-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathdexter_phase2.py
More file actions
2407 lines (2246 loc) · 84.5 KB
/
dexter_phase2.py
File metadata and controls
2407 lines (2246 loc) · 84.5 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
from dataclasses import dataclass
import datetime as dt
from decimal import Decimal
import hashlib
import json
import math
from pathlib import Path
from typing import Any, Protocol
import uuid
import asyncpg
PHASE2_SCHEMA_STATEMENTS = [
"""
CREATE TABLE IF NOT EXISTS phase2_raw_events (
fingerprint TEXT PRIMARY KEY,
source TEXT NOT NULL,
program TEXT NOT NULL,
signature TEXT NOT NULL,
slot BIGINT NOT NULL DEFAULT 0,
log_index INTEGER NOT NULL DEFAULT 0,
event_type TEXT NOT NULL,
is_mint BOOLEAN NOT NULL DEFAULT FALSE,
mint_id TEXT,
owner TEXT,
observed_at TIMESTAMPTZ NOT NULL,
raw_logs JSONB NOT NULL DEFAULT '[]'::jsonb,
parsed_payload JSONB NOT NULL DEFAULT '{}'::jsonb
);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_raw_events_signature
ON phase2_raw_events(signature);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_raw_events_mint_observed
ON phase2_raw_events(mint_id, observed_at DESC);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_raw_events_owner_observed
ON phase2_raw_events(owner, observed_at DESC);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_mints (
mint_id TEXT PRIMARY KEY,
owner TEXT,
name TEXT,
symbol TEXT,
bonding_curve TEXT,
status TEXT NOT NULL DEFAULT 'active',
mint_sig TEXT,
created_at TIMESTAMPTZ,
last_event_fingerprint TEXT,
last_event_slot BIGINT,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_mint_snapshots (
snapshot_id BIGSERIAL PRIMARY KEY,
mint_id TEXT NOT NULL REFERENCES phase2_mints(mint_id) ON DELETE CASCADE,
lifecycle_state TEXT NOT NULL,
recorded_at TIMESTAMPTZ NOT NULL,
owner TEXT,
name TEXT,
symbol TEXT,
bonding_curve TEXT,
market_cap DOUBLE PRECISION,
price_usd DOUBLE PRECISION,
liquidity DOUBLE PRECISION,
open_price DOUBLE PRECISION,
high_price DOUBLE PRECISION,
low_price DOUBLE PRECISION,
current_price DOUBLE PRECISION,
age_seconds DOUBLE PRECISION,
tx_counts JSONB NOT NULL DEFAULT '{}'::jsonb,
volume JSONB NOT NULL DEFAULT '{}'::jsonb,
holders JSONB NOT NULL DEFAULT '{}'::jsonb,
price_history JSONB NOT NULL DEFAULT '{}'::jsonb,
last_event_fingerprint TEXT,
last_event_slot BIGINT,
snapshot_payload JSONB NOT NULL DEFAULT '{}'::jsonb
);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_mint_snapshots_mint_time
ON phase2_mint_snapshots(mint_id, recorded_at DESC);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_leaderboard_generations (
version TEXT PRIMARY KEY,
generated_at TIMESTAMPTZ NOT NULL,
source TEXT NOT NULL,
creator_count INTEGER NOT NULL,
ranking_hash TEXT NOT NULL,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_creator_snapshots (
snapshot_id BIGSERIAL PRIMARY KEY,
leaderboard_version TEXT NOT NULL REFERENCES phase2_leaderboard_generations(version) ON DELETE CASCADE,
creator TEXT NOT NULL,
rank INTEGER NOT NULL,
mint_count INTEGER NOT NULL DEFAULT 0,
total_swaps INTEGER NOT NULL DEFAULT 0,
success_count INTEGER NOT NULL DEFAULT 0,
unsuccess_count INTEGER NOT NULL DEFAULT 0,
median_peak_market_cap DOUBLE PRECISION NOT NULL DEFAULT 0,
median_market_cap DOUBLE PRECISION NOT NULL DEFAULT 0,
median_open_price DOUBLE PRECISION NOT NULL DEFAULT 0,
median_high_price DOUBLE PRECISION NOT NULL DEFAULT 0,
trust_factor DOUBLE PRECISION NOT NULL DEFAULT 0,
avg_success_ratio DOUBLE PRECISION NOT NULL DEFAULT 0,
median_success_ratio DOUBLE PRECISION NOT NULL DEFAULT 0,
performance_score DOUBLE PRECISION NOT NULL DEFAULT 0,
entry_payload JSONB NOT NULL DEFAULT '{}'::jsonb,
UNIQUE (leaderboard_version, creator)
);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_creator_snapshots_creator_version
ON phase2_creator_snapshots(creator, leaderboard_version DESC);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_trade_sessions (
session_id TEXT PRIMARY KEY,
mint_id TEXT NOT NULL,
owner TEXT NOT NULL,
runtime_mode TEXT NOT NULL,
trust_level INTEGER,
leaderboard_version TEXT REFERENCES phase2_leaderboard_generations(version),
open_reason TEXT,
status TEXT NOT NULL DEFAULT 'open',
session_context JSONB NOT NULL DEFAULT '{}'::jsonb,
buy_cost_lamports BIGINT,
sell_proceeds_lamports BIGINT,
realized_profit_lamports BIGINT,
opened_at TIMESTAMPTZ NOT NULL,
closed_at TIMESTAMPTZ,
close_reason TEXT
);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_trade_sessions_mint_time
ON phase2_trade_sessions(mint_id, opened_at DESC);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_orders (
order_id BIGSERIAL PRIMARY KEY,
session_id TEXT NOT NULL REFERENCES phase2_trade_sessions(session_id) ON DELETE CASCADE,
mint_id TEXT NOT NULL,
side TEXT NOT NULL,
venue TEXT NOT NULL,
status TEXT NOT NULL,
requested_token_amount BIGINT,
requested_lamports BIGINT,
tx_id TEXT,
order_context JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_orders_session_side
ON phase2_orders(session_id, side, created_at);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_fills (
fill_id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES phase2_orders(order_id) ON DELETE CASCADE,
session_id TEXT NOT NULL REFERENCES phase2_trade_sessions(session_id) ON DELETE CASCADE,
mint_id TEXT NOT NULL,
side TEXT NOT NULL,
tx_id TEXT,
fill_price TEXT,
token_amount BIGINT,
cost_lamports BIGINT,
proceeds_lamports BIGINT,
fee_lamports BIGINT,
wallet_delta_lamports BIGINT,
wallet_balance BIGINT,
fill_context JSONB NOT NULL DEFAULT '{}'::jsonb,
filled_at TIMESTAMPTZ NOT NULL
);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_fills_session_time
ON phase2_fills(session_id, filled_at);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_holding_snapshots (
snapshot_id BIGSERIAL PRIMARY KEY,
session_id TEXT NOT NULL REFERENCES phase2_trade_sessions(session_id) ON DELETE CASCADE,
mint_id TEXT NOT NULL,
owner TEXT,
status TEXT NOT NULL,
token_balance BIGINT NOT NULL DEFAULT 0,
buy_price TEXT,
cost_basis_lamports BIGINT,
buy_fee_lamports BIGINT,
buy_wallet_balance BIGINT,
snapshot_payload JSONB NOT NULL DEFAULT '{}'::jsonb,
recorded_at TIMESTAMPTZ NOT NULL
);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_holding_snapshots_session_time
ON phase2_holding_snapshots(session_id, recorded_at);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_strategy_decisions (
decision_id BIGSERIAL PRIMARY KEY,
session_id TEXT REFERENCES phase2_trade_sessions(session_id) ON DELETE CASCADE,
mint_id TEXT NOT NULL,
owner TEXT,
decision_type TEXT NOT NULL,
reason TEXT NOT NULL,
raw_event_fingerprint TEXT,
decision_inputs JSONB NOT NULL DEFAULT '{}'::jsonb,
decision_outcome JSONB NOT NULL DEFAULT '{}'::jsonb,
decided_at TIMESTAMPTZ NOT NULL
);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_strategy_decisions_session_time
ON phase2_strategy_decisions(session_id, decided_at);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_strategy_profiles (
profile_key TEXT PRIMARY KEY,
profile_name TEXT NOT NULL,
version TEXT NOT NULL,
definition JSONB NOT NULL DEFAULT '{}'::jsonb,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL
);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_position_journal (
session_id TEXT PRIMARY KEY REFERENCES phase2_trade_sessions(session_id) ON DELETE CASCADE,
mint_id TEXT NOT NULL,
owner TEXT,
strategy_profile TEXT,
status TEXT NOT NULL,
intended_size_lamports BIGINT,
intended_token_amount BIGINT,
executed_size_lamports BIGINT,
executed_token_amount BIGINT,
actual_buy_price TEXT,
exit_reason TEXT,
realized_profit_lamports BIGINT,
journal_context JSONB NOT NULL DEFAULT '{}'::jsonb,
opened_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
closed_at TIMESTAMPTZ
);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_position_journal_status_time
ON phase2_position_journal(status, updated_at DESC);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_backtest_runs (
run_id TEXT PRIMARY KEY,
profile_key TEXT NOT NULL REFERENCES phase2_strategy_profiles(profile_key) ON DELETE RESTRICT,
input_source TEXT NOT NULL,
summary_payload JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL
);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_backtest_trades (
trade_id BIGSERIAL PRIMARY KEY,
run_id TEXT NOT NULL REFERENCES phase2_backtest_runs(run_id) ON DELETE CASCADE,
mint_id TEXT NOT NULL,
owner TEXT,
entered BOOLEAN NOT NULL DEFAULT FALSE,
score DOUBLE PRECISION NOT NULL DEFAULT 0,
realized_return_pct DOUBLE PRECISION NOT NULL DEFAULT 0,
trade_payload JSONB NOT NULL DEFAULT '{}'::jsonb
);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_backtest_trades_run
ON phase2_backtest_trades(run_id, entered DESC, score DESC);
""",
"""
CREATE TABLE IF NOT EXISTS phase2_risk_events (
event_id BIGSERIAL PRIMARY KEY,
session_id TEXT REFERENCES phase2_trade_sessions(session_id) ON DELETE CASCADE,
mint_id TEXT NOT NULL,
owner TEXT,
event_type TEXT NOT NULL,
severity TEXT NOT NULL,
detail TEXT NOT NULL,
event_context JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL
);
""",
"""
CREATE INDEX IF NOT EXISTS idx_phase2_risk_events_session_time
ON phase2_risk_events(session_id, created_at DESC);
""",
]
def _utc_now() -> dt.datetime:
return dt.datetime.now(dt.timezone.utc)
def _ensure_utc(value: dt.datetime | None) -> dt.datetime:
if value is None:
return _utc_now()
if value.tzinfo is None:
return value.replace(tzinfo=dt.timezone.utc)
return value.astimezone(dt.timezone.utc)
def _json_safe(value: Any) -> Any:
if isinstance(value, Decimal):
if not value.is_finite():
return None
return str(value)
if isinstance(value, float):
if not math.isfinite(value):
return None
return value
if isinstance(value, Path):
return str(value)
if isinstance(value, dt.datetime):
return _ensure_utc(value).isoformat()
if isinstance(value, bytes):
return value.hex()
if isinstance(value, dict):
return {str(key): _json_safe(item) for key, item in value.items()}
if isinstance(value, (list, tuple, set)):
return [_json_safe(item) for item in value]
return value
def _jsonb_param(value: Any) -> str:
return json.dumps(_json_safe(value), sort_keys=True, allow_nan=False)
def _canonical_payload(value: Any) -> str:
return json.dumps(_json_safe(value), sort_keys=True, separators=(",", ":"), allow_nan=False)
def _finite_float_or(value: Any, default: float | None = None) -> float | None:
if value is None:
return default
if isinstance(value, Decimal):
if not value.is_finite():
return default
return float(value)
try:
result = float(value)
except (TypeError, ValueError):
return default
if not math.isfinite(result):
return default
return result
def compute_event_fingerprint(
*,
source: str,
signature: str,
log_index: int,
event_type: str,
mint_id: str | None,
payload: Any,
) -> str:
seed = "|".join(
[
source,
signature or "",
str(log_index),
event_type,
mint_id or "",
_canonical_payload(payload),
]
)
return hashlib.sha256(seed.encode("utf-8")).hexdigest()
def compute_leaderboard_version(leaderboard: dict[str, dict[str, Any]]) -> str:
entries = prepare_leaderboard_entries(leaderboard)
payload = _canonical_payload(entries)
digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()
return f"lgd_{digest[:20]}"
def prepare_leaderboard_entries(leaderboard: dict[str, dict[str, Any]]) -> list[dict[str, Any]]:
ranked = sorted(
leaderboard.items(),
key=lambda item: (item[1].get("performance_score", 0), item[0]),
reverse=True,
)
entries: list[dict[str, Any]] = []
for rank, (creator, entry) in enumerate(ranked, start=1):
normalized = dict(_json_safe(entry))
normalized["creator"] = creator
normalized["rank"] = rank
entries.append(normalized)
return entries
def _default_export_dir(config: Any) -> Path:
if getattr(config, "phase2", None) is not None:
export_dir = getattr(config.phase2, "export_dir", None)
if export_dir is not None:
return Path(export_dir)
return Path(config.project_root) / "dev" / "exports"
def _default_retention_days(config: Any) -> int:
if getattr(config, "phase2", None) is not None:
return int(getattr(config.phase2, "raw_event_retention_days", 30))
return 30
def _default_mint_snapshot_interval_seconds(config: Any) -> int:
if getattr(config, "phase2", None) is not None:
return int(getattr(config.phase2, "mint_snapshot_interval_seconds", 15))
return 15
def _default_mint_snapshot_retention_per_mint(config: Any) -> int:
if getattr(config, "phase2", None) is not None:
return int(getattr(config.phase2, "mint_snapshot_retention_per_mint", 4))
return 4
def _default_maintenance_interval_seconds(config: Any) -> int:
if getattr(config, "phase2", None) is not None:
return int(getattr(config.phase2, "maintenance_interval_seconds", 60))
return 60
def _default_max_database_size_bytes(config: Any) -> int:
if getattr(config, "phase2", None) is not None:
return int(getattr(config.phase2, "max_database_size_bytes", 2147483648))
return 2147483648
def _container_length(value: Any) -> int:
if isinstance(value, (dict, list, tuple, set)):
return len(value)
return 0
def _compact_mint_snapshot(snapshot: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
tx_counts = snapshot.get("tx_counts") or {}
volume = snapshot.get("volume") or {}
holders = snapshot.get("holders") or {}
price_history = snapshot.get("price_history") or {}
compact_payload = {
"mint_sig": snapshot.get("mint_sig"),
"created_at": snapshot.get("created_at"),
"holder_count": _container_length(holders),
"price_point_count": _container_length(price_history),
"swap_count": int((tx_counts or {}).get("swaps", 0) or 0) if isinstance(tx_counts, dict) else 0,
"buy_count": int((tx_counts or {}).get("buys", 0) or 0) if isinstance(tx_counts, dict) else 0,
"sell_count": int((tx_counts or {}).get("sells", 0) or 0) if isinstance(tx_counts, dict) else 0,
"volume_windows": sorted(str(key) for key in volume.keys()) if isinstance(volume, dict) else [],
}
sanitized_snapshot = dict(snapshot)
sanitized_snapshot["holders"] = {}
sanitized_snapshot["price_history"] = {}
return sanitized_snapshot, _json_safe(compact_payload)
@dataclass(frozen=True)
class ReplayInvariant:
name: str
status: str
detail: str
class SessionReplayRepository(Protocol):
async def fetch_session_bundle(
self,
*,
session_id: str | None = None,
mint_id: str | None = None,
) -> dict[str, Any]:
...
class Phase2Store:
def __init__(self, db_dsn: str, config: Any | None = None):
self.db_dsn = db_dsn
self.config = config
self.pool: asyncpg.Pool | None = None
self._last_retention_prune: dt.datetime | None = None
self._last_snapshot_prune: dt.datetime | None = None
self._last_vacuum_at: dt.datetime | None = None
self._last_mint_snapshot_recorded: dict[str, tuple[str, dt.datetime]] = {}
def bind_pool(self, pool: asyncpg.Pool) -> None:
self.pool = pool
async def _with_connection(self, operation):
if self.pool is not None:
async with self.pool.acquire() as conn:
return await operation(conn)
conn = await asyncpg.connect(self.db_dsn)
try:
return await operation(conn)
finally:
await conn.close()
async def ensure_schema(self) -> None:
async def _operation(conn):
for statement in PHASE2_SCHEMA_STATEMENTS:
await conn.execute(statement)
await self._with_connection(_operation)
async def record_raw_event(
self,
*,
source: str,
program: str,
signature: str,
slot: int,
log_index: int,
event_type: str,
is_mint: bool,
payload: dict[str, Any],
raw_logs: list[str] | None = None,
observed_at: dt.datetime | None = None,
) -> str:
mint_id = str(payload.get("mint", "") or "")
owner = str(payload.get("user") or payload.get("owner") or "")
fingerprint = compute_event_fingerprint(
source=source,
signature=signature,
log_index=log_index,
event_type=event_type,
mint_id=mint_id or None,
payload=payload,
)
observed_at = _ensure_utc(observed_at)
async def _operation(conn):
await conn.execute(
"""
INSERT INTO phase2_raw_events (
fingerprint,
source,
program,
signature,
slot,
log_index,
event_type,
is_mint,
mint_id,
owner,
observed_at,
raw_logs,
parsed_payload
)
VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, NULLIF($9, ''), NULLIF($10, ''),
$11, $12::jsonb, $13::jsonb
)
ON CONFLICT (fingerprint) DO NOTHING
""",
fingerprint,
source,
program,
signature,
int(slot or 0),
int(log_index),
event_type,
bool(is_mint),
mint_id,
owner,
observed_at,
_jsonb_param(raw_logs or []),
_jsonb_param(payload),
)
await self._with_connection(_operation)
return fingerprint
async def upsert_mint_record(
self,
*,
mint_id: str,
owner: str | None = None,
name: str | None = None,
symbol: str | None = None,
bonding_curve: str | None = None,
status: str = "active",
mint_sig: str | None = None,
created_at: dt.datetime | None = None,
last_event_fingerprint: str | None = None,
last_event_slot: int | None = None,
) -> None:
async def _operation(conn):
await conn.execute(
"""
INSERT INTO phase2_mints (
mint_id,
owner,
name,
symbol,
bonding_curve,
status,
mint_sig,
created_at,
last_event_fingerprint,
last_event_slot,
updated_at
)
VALUES (
$1, NULLIF($2, ''), NULLIF($3, ''), NULLIF($4, ''), NULLIF($5, ''),
$6, NULLIF($7, ''), $8, NULLIF($9, ''), $10, $11
)
ON CONFLICT (mint_id) DO UPDATE SET
owner = COALESCE(EXCLUDED.owner, phase2_mints.owner),
name = COALESCE(EXCLUDED.name, phase2_mints.name),
symbol = COALESCE(EXCLUDED.symbol, phase2_mints.symbol),
bonding_curve = COALESCE(EXCLUDED.bonding_curve, phase2_mints.bonding_curve),
status = EXCLUDED.status,
mint_sig = COALESCE(EXCLUDED.mint_sig, phase2_mints.mint_sig),
created_at = COALESCE(EXCLUDED.created_at, phase2_mints.created_at),
last_event_fingerprint = COALESCE(EXCLUDED.last_event_fingerprint, phase2_mints.last_event_fingerprint),
last_event_slot = COALESCE(EXCLUDED.last_event_slot, phase2_mints.last_event_slot),
updated_at = EXCLUDED.updated_at
""",
mint_id,
owner or "",
name or "",
symbol or "",
bonding_curve or "",
status,
mint_sig or "",
_ensure_utc(created_at) if created_at is not None else None,
last_event_fingerprint or "",
int(last_event_slot) if last_event_slot is not None else None,
_utc_now(),
)
await self._with_connection(_operation)
async def record_mint_snapshot(
self,
*,
mint_id: str,
lifecycle_state: str,
snapshot: dict[str, Any],
recorded_at: dt.datetime | None = None,
last_event_fingerprint: str | None = None,
last_event_slot: int | None = None,
) -> None:
await self.upsert_mint_record(
mint_id=mint_id,
owner=str(snapshot.get("owner") or ""),
name=str(snapshot.get("name") or ""),
symbol=str(snapshot.get("symbol") or ""),
bonding_curve=str(snapshot.get("bonding_curve") or ""),
status=lifecycle_state,
mint_sig=str(snapshot.get("mint_sig") or ""),
created_at=snapshot.get("created_at"),
last_event_fingerprint=last_event_fingerprint,
last_event_slot=last_event_slot,
)
recorded_at = _ensure_utc(recorded_at)
if not self._should_record_mint_snapshot(
mint_id=mint_id,
lifecycle_state=lifecycle_state,
recorded_at=recorded_at,
):
return
compact_snapshot, compact_payload = _compact_mint_snapshot(snapshot)
async def _operation(conn):
await conn.execute(
"""
INSERT INTO phase2_mint_snapshots (
mint_id,
lifecycle_state,
recorded_at,
owner,
name,
symbol,
bonding_curve,
market_cap,
price_usd,
liquidity,
open_price,
high_price,
low_price,
current_price,
age_seconds,
tx_counts,
volume,
holders,
price_history,
last_event_fingerprint,
last_event_slot,
snapshot_payload
)
VALUES (
$1, $2, $3, NULLIF($4, ''), NULLIF($5, ''), NULLIF($6, ''), NULLIF($7, ''),
$8, $9, $10, $11, $12, $13, $14, $15,
$16::jsonb, $17::jsonb, $18::jsonb, $19::jsonb,
NULLIF($20, ''), $21, $22::jsonb
)
""",
mint_id,
lifecycle_state,
recorded_at,
str(compact_snapshot.get("owner") or ""),
str(compact_snapshot.get("name") or ""),
str(compact_snapshot.get("symbol") or ""),
str(compact_snapshot.get("bonding_curve") or ""),
_finite_float_or(compact_snapshot.get("market_cap"), 0.0),
_finite_float_or(compact_snapshot.get("price_usd"), 0.0),
_finite_float_or(compact_snapshot.get("liquidity"), 0.0),
_finite_float_or(compact_snapshot.get("open_price"), 0.0),
_finite_float_or(compact_snapshot.get("high_price"), 0.0),
_finite_float_or(compact_snapshot.get("low_price")),
_finite_float_or(compact_snapshot.get("current_price"), 0.0),
_finite_float_or(compact_snapshot.get("age"), 0.0),
_jsonb_param(compact_snapshot.get("tx_counts") or {}),
_jsonb_param(compact_snapshot.get("volume") or {}),
_jsonb_param({}),
_jsonb_param({}),
last_event_fingerprint or "",
int(last_event_slot) if last_event_slot is not None else None,
_jsonb_param(compact_payload),
)
await self._with_connection(_operation)
def _should_record_mint_snapshot(
self,
*,
mint_id: str,
lifecycle_state: str,
recorded_at: dt.datetime,
) -> bool:
if lifecycle_state not in {"active", "migrated"}:
self._last_mint_snapshot_recorded[mint_id] = (lifecycle_state, recorded_at)
return True
interval_seconds = _default_mint_snapshot_interval_seconds(self.config)
previous = self._last_mint_snapshot_recorded.get(mint_id)
if previous is None:
self._last_mint_snapshot_recorded[mint_id] = (lifecycle_state, recorded_at)
return True
previous_state, previous_recorded_at = previous
if previous_state != lifecycle_state:
self._last_mint_snapshot_recorded[mint_id] = (lifecycle_state, recorded_at)
return True
should_record = (recorded_at - previous_recorded_at) >= dt.timedelta(seconds=interval_seconds)
if should_record:
self._last_mint_snapshot_recorded[mint_id] = (lifecycle_state, recorded_at)
return should_record
async def record_leaderboard_generation(
self,
leaderboard: dict[str, dict[str, Any]],
*,
source: str,
generated_at: dt.datetime | None = None,
metadata: dict[str, Any] | None = None,
) -> str:
generated_at = _ensure_utc(generated_at)
entries = prepare_leaderboard_entries(leaderboard)
version = compute_leaderboard_version(leaderboard)
ranking_hash = hashlib.sha256(_canonical_payload(entries).encode("utf-8")).hexdigest()
async def _operation(conn):
async with conn.transaction():
await conn.execute(
"""
INSERT INTO phase2_leaderboard_generations (
version,
generated_at,
source,
creator_count,
ranking_hash,
metadata
)
VALUES ($1, $2, $3, $4, $5, $6::jsonb)
ON CONFLICT (version) DO NOTHING
""",
version,
generated_at,
source,
len(entries),
ranking_hash,
_jsonb_param(metadata or {}),
)
await conn.execute(
"DELETE FROM phase2_creator_snapshots WHERE leaderboard_version = $1",
version,
)
for entry in entries:
await conn.execute(
"""
INSERT INTO phase2_creator_snapshots (
leaderboard_version,
creator,
rank,
mint_count,
total_swaps,
success_count,
unsuccess_count,
median_peak_market_cap,
median_market_cap,
median_open_price,
median_high_price,
trust_factor,
avg_success_ratio,
median_success_ratio,
performance_score,
entry_payload
)
VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11,
$12, $13, $14, $15, $16::jsonb
)
""",
version,
entry["creator"],
int(entry["rank"]),
int(entry.get("mint_count", 0) or 0),
int(entry.get("total_swaps", 0) or 0),
int(entry.get("success_count", 0) or 0),
int(entry.get("unsuccess_count", 0) or 0),
float(entry.get("median_peak_market_cap", 0) or 0),
float(entry.get("median_market_cap", 0) or 0),
float(entry.get("median_open_price", 0) or 0),
float(entry.get("median_high_price", 0) or 0),
float(entry.get("trust_factor", 0) or 0),
float(entry.get("avg_success_ratio", 0) or 0),
float(entry.get("median_success_ratio", 0) or 0),
float(entry.get("performance_score", 0) or 0),
_jsonb_param(entry),
)
await self._with_connection(_operation)
return version
async def start_trade_session(
self,
*,
mint_id: str,
owner: str,
runtime_mode: str,
trust_level: int | None = None,
leaderboard_version: str | None = None,
open_reason: str | None = None,
opened_at: dt.datetime | None = None,
session_context: dict[str, Any] | None = None,
session_id: str | None = None,
) -> str:
opened_at = _ensure_utc(opened_at)
session_id = session_id or f"session_{uuid.uuid4().hex}"
async def _operation(conn):
await conn.execute(
"""
INSERT INTO phase2_trade_sessions (
session_id,
mint_id,
owner,
runtime_mode,
trust_level,
leaderboard_version,
open_reason,
status,
session_context,
opened_at
)
VALUES (
$1, $2, $3, $4, $5, NULLIF($6, ''), NULLIF($7, ''),
'open', $8::jsonb, $9
)
ON CONFLICT (session_id) DO NOTHING
""",
session_id,
mint_id,
owner,
runtime_mode,
trust_level,
leaderboard_version or "",
open_reason or "",
_jsonb_param(session_context or {}),
opened_at,
)
await self._with_connection(_operation)
return session_id
async def close_trade_session(
self,
session_id: str,
*,
status: str,
close_reason: str | None = None,
buy_cost_lamports: int | None = None,
sell_proceeds_lamports: int | None = None,
realized_profit_lamports: int | None = None,
closed_at: dt.datetime | None = None,
) -> None:
async def _operation(conn):
await conn.execute(
"""
UPDATE phase2_trade_sessions
SET status = $2,
close_reason = NULLIF($3, ''),
buy_cost_lamports = COALESCE($4, buy_cost_lamports),
sell_proceeds_lamports = COALESCE($5, sell_proceeds_lamports),
realized_profit_lamports = COALESCE($6, realized_profit_lamports),
closed_at = $7
WHERE session_id = $1
""",
session_id,
status,
close_reason or "",
buy_cost_lamports,
sell_proceeds_lamports,
realized_profit_lamports,
_ensure_utc(closed_at),
)
await self._with_connection(_operation)
async def record_order(
self,
*,
session_id: str,
mint_id: str,
side: str,
venue: str,
status: str,
requested_token_amount: int | None = None,
requested_lamports: int | None = None,
tx_id: str | None = None,
context: dict[str, Any] | None = None,
created_at: dt.datetime | None = None,
) -> int:
created_at = _ensure_utc(created_at)
async def _operation(conn):
row = await conn.fetchrow(
"""
INSERT INTO phase2_orders (
session_id,
mint_id,
side,
venue,
status,
requested_token_amount,
requested_lamports,
tx_id,
order_context,
created_at,
updated_at
)
VALUES (
$1, $2, $3, $4, $5, $6, $7, NULLIF($8, ''), $9::jsonb, $10, $10
)
RETURNING order_id
""",
session_id,
mint_id,
side,
venue,
status,
requested_token_amount,
requested_lamports,
tx_id or "",
_jsonb_param(context or {}),
created_at,
)
return int(row["order_id"])
return await self._with_connection(_operation)
async def update_order(
self,
order_id: int,