-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui_field_config.py
More file actions
344 lines (308 loc) · 12 KB
/
ui_field_config.py
File metadata and controls
344 lines (308 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/env python3
"""
Bidirectional UI Field Configuration System
Automatically syncs database fields with UI columns
"""
import sqlite3
import json
from typing import Dict, List, Tuple
# Master field configuration - single source of truth
UI_FIELDS = [
{
'id': 'name',
'header': 'Token',
'db_field': 'name',
'sortable': True,
'type': 'text',
'display_format': 'token_name',
'width': 'auto'
},
{
'id': 'price',
'header': 'Price',
'db_field': 'price_usd',
'sortable': True,
'type': 'currency',
'display_format': 'price',
'width': '100px'
},
{
'id': 'change_5m',
'header': '5m',
'db_field': 'price_change_5m',
'sortable': True,
'type': 'percentage',
'display_format': 'price_change',
'width': '80px'
},
{
'id': 'change_1h',
'header': '1h',
'db_field': 'price_change_1h',
'sortable': True,
'type': 'percentage',
'display_format': 'price_change',
'width': '80px'
},
{
'id': 'change_24h',
'header': '24h',
'db_field': 'price_change_24h',
'sortable': True,
'type': 'percentage',
'display_format': 'price_change',
'width': '80px'
},
{
'id': 'market_cap',
'header': 'Market Cap',
'db_field': 'market_cap',
'sortable': True,
'type': 'currency',
'display_format': 'number',
'width': '120px'
},
{
'id': 'liquidity',
'header': 'Liquidity',
'db_field': 'liquidity',
'sortable': True,
'type': 'currency',
'display_format': 'number',
'width': '120px'
},
{
'id': 'volume24h',
'header': 'Volume 24h',
'db_field': 'volume24h',
'sortable': True,
'type': 'currency',
'display_format': 'number',
'width': '120px'
},
{
'id': 'holders',
'header': 'Holders',
'db_field': 'current_holder_count',
'sortable': True,
'type': 'number',
'display_format': 'number',
'width': '100px'
},
{
'id': 'holder_growth',
'header': 'Growth 24h',
'db_field': 'holder_growth_24h',
'sortable': True,
'type': 'percentage',
'display_format': 'price_change',
'width': '100px'
},
{
'id': 'risk',
'header': 'Risk',
'db_field': 'risk_score',
'sortable': True,
'type': 'number',
'display_format': 'risk',
'width': '80px'
},
{
'id': 'platform',
'header': 'Platform',
'db_field': 'is_pump_token',
'sortable': True,
'type': 'boolean',
'display_format': 'platform',
'width': '100px'
},
{
'id': 'score',
'header': 'Score',
'db_field': 'composite_score',
'sortable': True,
'type': 'number',
'display_format': 'score',
'width': '80px'
},
{
'id': 'links',
'header': 'Links',
'db_field': None, # Computed field
'sortable': False,
'type': 'links',
'display_format': 'links',
'width': '150px'
}
]
class UIFieldManager:
def __init__(self, database_file='raydium_pools.db'):
self.database_file = database_file
self.fields = UI_FIELDS.copy()
def add_field(self, field_config: Dict, position: int = None):
"""Add a new field to both database and UI"""
if position is None:
position = len(self.fields) - 1 # Before links column
# Add to database if needed
if field_config.get('db_field'):
self._add_db_field(field_config)
# Add to UI configuration
self.fields.insert(position, field_config)
# Regenerate UI components
self._update_ui_components()
print(f"✅ Added field '{field_config['id']}' at position {position}")
def remove_field(self, field_id: str):
"""Remove field from both database and UI"""
field = self.get_field_by_id(field_id)
if not field:
print(f"❌ Field '{field_id}' not found")
return
# Remove from UI
self.fields = [f for f in self.fields if f['id'] != field_id]
# Note: We don't drop DB columns for safety
print(f"✅ Removed field '{field_id}' from UI")
# Regenerate UI components
self._update_ui_components()
def get_field_by_id(self, field_id: str) -> Dict:
"""Get field configuration by ID"""
return next((f for f in self.fields if f['id'] == field_id), None)
def get_sortable_fields(self) -> List[Dict]:
"""Get all sortable fields"""
return [f for f in self.fields if f['sortable']]
def get_db_fields(self) -> List[str]:
"""Get list of database fields to query"""
return [f['db_field'] for f in self.fields if f['db_field']]
def _add_db_field(self, field_config: Dict):
"""Add field to database"""
if not field_config.get('db_field'):
return
db_field = field_config['db_field']
field_type = self._get_sql_type(field_config['type'])
conn = sqlite3.connect(self.database_file)
try:
# Check if field exists
cursor = conn.execute("PRAGMA table_info(pools)")
existing_fields = [row[1] for row in cursor.fetchall()]
if db_field not in existing_fields:
conn.execute(f'ALTER TABLE pools ADD COLUMN {db_field} {field_type}')
print(f"✅ Added database field: {db_field} {field_type}")
else:
print(f"📋 Database field already exists: {db_field}")
conn.commit()
except Exception as e:
print(f"❌ Database error: {e}")
finally:
conn.close()
def _get_sql_type(self, field_type: str) -> str:
"""Convert field type to SQL type"""
type_map = {
'text': 'TEXT',
'number': 'INTEGER',
'currency': 'REAL',
'percentage': 'REAL',
'boolean': 'INTEGER'
}
return type_map.get(field_type, 'TEXT')
def _update_ui_components(self):
"""Generate updated UI components"""
self.generate_table_headers()
self.generate_table_cells()
self.generate_sort_function()
self.generate_filter_fields()
def generate_table_headers(self) -> str:
"""Generate HTML table headers"""
headers = []
for i, field in enumerate(self.fields):
if field['sortable']:
headers.append(f'''<th onclick="sortTable({i})" class="sortable ${{currentSort.column === {i} ? 'sort-' + currentSort.direction : ''}}">{field['header']}</th>''')
else:
headers.append(f'''<th>{field['header']}</th>''')
return '\n '.join(headers)
def generate_table_cells(self) -> str:
"""Generate JavaScript table cell templates"""
cells = []
for field in self.fields:
cell_template = self._get_cell_template(field)
cells.append(cell_template)
return '\n '.join(cells)
def _get_cell_template(self, field: Dict) -> str:
"""Get cell template for field type"""
templates = {
'token_name': '''<td class="token-name-cell">
<div>${token.name || 'Unknown Token'}</div>
<div class="token-address" onclick="copyAddress('${token.token_address}')" title="Click to copy: ${token.token_address}">
${token.token_address?.substring(0, 4)}...${token.token_address?.substring(-4)}
<span class="copy-icon">📋</span>
</div>
</td>''',
'price': '''<td class="number-cell" data-value="${token.price_usd || 0}">$${token.price_usd?.toFixed(6) || 'N/A'}</td>''',
'price_change': f'''<td class="price-change-cell" data-value="${{token.{field['db_field']} || 0}}">
<span class="price-change ${{getPriceChangeClass(token.{field['db_field']})}}">
${{token.{field['db_field']} ? (token.{field['db_field']} > 0 ? '+' : '') + token.{field['db_field']}.toFixed(2) + '%' : 'N/A'}}
</span>
</td>''',
'number': f'''<td class="number-cell" data-value="${{token.{field['db_field']} || 0}}">${{token.{field['db_field']}?.toLocaleString() || 'N/A'}}</td>''',
'risk': '''<td class="risk-cell" data-value="${token.risk_score || 0}">
<span class="risk-badge ${getRiskClass(token.risk_score)}">
${getRiskLabel(token.risk_score)} (${token.risk_score}/10)
</span>
</td>''',
'platform': '''<td class="platform-cell">
${token.is_pump_token ?
'<span class="pump-badge">Pump.fun</span>' :
'<span class="regular-badge">Other</span>'
}
</td>''',
'score': '''<td class="score-cell" data-value="${token.composite_score || 0}">
<span class="composite-score ${scoreClass}">
${token.composite_score > 0 ? '+' : ''}${token.composite_score}
</span>
</td>''',
'links': '''<td class="links-cell">
<a href="${token.solscan_url}" target="_blank" rel="noopener noreferrer">Solscan</a>
<a href="${token.dexscreener_url}" target="_blank" rel="noopener noreferrer">DexScreener</a>
</td>'''
}
return templates.get(field['display_format'], f'''<td class="text-cell">${{token.{field['db_field']} || 'N/A'}}</td>''')
def generate_sort_function(self) -> str:
"""Generate JavaScript sort function cases"""
cases = []
for i, field in enumerate(self.fields):
if not field['sortable']:
continue
if field['type'] == 'text':
cases.append(f'''case {i}: // {field['header']}
aVal = (a.{field['db_field']} || '').toLowerCase();
bVal = (b.{field['db_field']} || '').toLowerCase();
break;''')
elif field['type'] == 'boolean':
cases.append(f'''case {i}: // {field['header']}
aVal = a.{field['db_field']} ? 1 : 0;
bVal = b.{field['db_field']} ? 1 : 0;
break;''')
else:
cases.append(f'''case {i}: // {field['header']}
aVal = a.{field['db_field']} || 0;
bVal = b.{field['db_field']} || 0;
break;''')
return '\n '.join(cases)
# Example usage
def demo_add_field():
"""Demo: Add a new field"""
manager = UIFieldManager()
# Add a new field: Trading Volume 1h
new_field = {
'id': 'volume_1h',
'header': 'Volume 1h',
'db_field': 'volume_1h',
'sortable': True,
'type': 'currency',
'display_format': 'number',
'width': '120px'
}
manager.add_field(new_field, position=8) # After Volume 24h
print("\n📋 Updated field configuration:")
for i, field in enumerate(manager.fields):
print(f"{i:2d}. {field['header']:15} -> {field['db_field']}")
if __name__ == "__main__":
demo_add_field()