-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdata_fetcher.py
More file actions
1663 lines (1314 loc) · 52.2 KB
/
data_fetcher.py
File metadata and controls
1663 lines (1314 loc) · 52.2 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
"""
Nunchi Dashboard - HyperEVM Data Fetcher
Queries blockchain events directly from HyperEVM RPC
Uses requests instead of web3.py to avoid asyncio issues with Streamlit
"""
import time
import requests
from datetime import datetime, timedelta
from typing import List, Dict, Optional
import pandas as pd
from cachetools import TTLCache
import json
import os
from config import (
RPC_URL, CONTRACTS, EVENTS, ZERO_ADDRESS, CACHE_TTL, TOKEN_DECIMALS, PENDLE_MARKETS
)
# Calculate divisor for token amounts
TOKEN_DIVISOR = 10 ** TOKEN_DECIMALS
# Cache for expensive queries
_cache = TTLCache(maxsize=100, ttl=CACHE_TTL)
# File path for persistent all-time totals cache
ALLTIME_CACHE_FILE = os.path.join(os.path.dirname(__file__), 'alltime_cache.json')
# Starting blocks for contracts (discovered via binary search)
CONTRACT_START_BLOCKS = {
'wNLP': 20000000,
'SY_wNLP': 20000000,
'PENDLE_MARKET_DEC': 20000000,
'PENDLE_MARKET_JUN': 24000000,
}
def rpc_call(method: str, params: list) -> dict:
"""Make a JSON-RPC call to HyperEVM"""
payload = {
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": 1,
}
try:
response = requests.post(RPC_URL, json=payload, timeout=30)
result = response.json()
if "error" in result:
print(f"RPC Error: {result['error']}")
return {}
return result.get("result", {})
except Exception as e:
print(f"RPC call failed: {e}")
return {}
def get_current_block() -> int:
"""Get current block number"""
result = rpc_call("eth_blockNumber", [])
if result:
return int(result, 16)
return 0
def get_block_timestamp(block_num: int) -> int:
"""Get timestamp for a specific block"""
result = rpc_call("eth_getBlockByNumber", [hex(block_num), False])
if result and "timestamp" in result:
return int(result["timestamp"], 16)
return int(time.time())
def get_block_by_timestamp(target_timestamp: int) -> int:
"""Estimate block number for a given timestamp"""
current_block = get_current_block()
if current_block == 0:
return 1
current_time = get_block_timestamp(current_block)
# Estimate blocks per second (HyperEVM ~2 second blocks)
blocks_per_second = 0.5
time_diff = current_time - target_timestamp
estimated_block = max(1, int(current_block - (time_diff * blocks_per_second)))
return estimated_block
def fetch_logs(
contract_address: str,
topics: List[str],
from_block: int,
to_block: int = None,
batch_size: int = 900
) -> List[Dict]:
"""Fetch event logs from HyperEVM"""
if to_block is None:
to_block = get_current_block()
if to_block == 0:
return []
all_logs = []
current_from = from_block
while current_from <= to_block:
current_to = min(current_from + batch_size, to_block)
params = [{
"fromBlock": hex(current_from),
"toBlock": hex(current_to),
"address": contract_address,
"topics": topics,
}]
result = rpc_call("eth_getLogs", params)
if isinstance(result, list):
for log in result:
all_logs.append({
'block_number': int(log['blockNumber'], 16),
'tx_hash': log['transactionHash'],
'log_index': int(log['logIndex'], 16),
'address': log['address'],
'topics': log['topics'],
'data': log.get('data', '0x'),
})
time.sleep(0.1) # Rate limiting
current_from = current_to + 1
return all_logs
def decode_uint256(hex_data: str, offset: int = 0) -> int:
"""Decode uint256 from hex data"""
if not hex_data or hex_data == '0x':
return 0
if hex_data.startswith('0x'):
hex_data = hex_data[2:]
start = offset * 64
end = start + 64
if len(hex_data) < end:
return 0
return int(hex_data[start:end], 16)
def decode_int256(hex_data: str, offset: int = 0) -> int:
"""Decode int256 from hex data (signed)"""
value = decode_uint256(hex_data, offset)
if value >= 2**255:
value -= 2**256
return value
def decode_address(topic: str) -> str:
"""Decode address from topic (last 40 chars)"""
if not topic:
return ZERO_ADDRESS
if topic.startswith('0x'):
topic = topic[2:]
return '0x' + topic[-40:]
def add_block_timestamps(logs: List[Dict]) -> List[Dict]:
"""Add timestamps to logs"""
block_times = {}
for log in logs:
block_num = log['block_number']
if block_num not in block_times:
ts = get_block_timestamp(block_num)
block_times[block_num] = datetime.fromtimestamp(ts)
time.sleep(0.05) # Rate limiting
for log in logs:
log['timestamp'] = block_times.get(log['block_number'], datetime.now())
return logs
# ============================================================================
# DATA FETCHING FUNCTIONS
# ============================================================================
def get_nlp_transfers(days: int = 30) -> pd.DataFrame:
"""Get wNLP token transfers"""
cache_key = f"nlp_transfers_{days}"
if cache_key in _cache:
return _cache[cache_key]
from_block = get_block_by_timestamp(
int((datetime.now() - timedelta(days=days)).timestamp())
)
logs = fetch_logs(
CONTRACTS['wNLP'],
[EVENTS['TRANSFER']],
from_block
)
if not logs:
return pd.DataFrame()
logs = add_block_timestamps(logs)
data = []
for log in logs:
from_addr = decode_address(log['topics'][1]) if len(log['topics']) > 1 else ZERO_ADDRESS
to_addr = decode_address(log['topics'][2]) if len(log['topics']) > 2 else ZERO_ADDRESS
amount = decode_uint256(log['data']) / TOKEN_DIVISOR
transfer_type = 'transfer'
if from_addr.lower() == ZERO_ADDRESS.lower():
transfer_type = 'mint'
elif to_addr.lower() == ZERO_ADDRESS.lower():
transfer_type = 'burn'
data.append({
'timestamp': log['timestamp'],
'block': log['block_number'],
'tx_hash': log['tx_hash'],
'from': from_addr,
'to': to_addr,
'amount': amount,
'type': transfer_type,
})
df = pd.DataFrame(data)
_cache[cache_key] = df
return df
def get_sy_transfers(days: int = 30) -> pd.DataFrame:
"""Get SY-wNLP transfers (Pendle deposits/withdrawals)"""
cache_key = f"sy_transfers_{days}"
if cache_key in _cache:
return _cache[cache_key]
from_block = get_block_by_timestamp(
int((datetime.now() - timedelta(days=days)).timestamp())
)
logs = fetch_logs(
CONTRACTS['SY_wNLP'],
[EVENTS['TRANSFER']],
from_block
)
if not logs:
return pd.DataFrame()
logs = add_block_timestamps(logs)
data = []
for log in logs:
from_addr = decode_address(log['topics'][1]) if len(log['topics']) > 1 else ZERO_ADDRESS
to_addr = decode_address(log['topics'][2]) if len(log['topics']) > 2 else ZERO_ADDRESS
amount = decode_uint256(log['data']) / TOKEN_DIVISOR
transfer_type = 'transfer'
if from_addr.lower() == ZERO_ADDRESS.lower():
transfer_type = 'deposit'
elif to_addr.lower() == ZERO_ADDRESS.lower():
transfer_type = 'withdrawal'
data.append({
'timestamp': log['timestamp'],
'block': log['block_number'],
'tx_hash': log['tx_hash'],
'from': from_addr,
'to': to_addr,
'amount': amount,
'type': transfer_type,
})
df = pd.DataFrame(data)
_cache[cache_key] = df
return df
def get_pendle_swaps(days: int = 30) -> pd.DataFrame:
"""Get Pendle market swap events from all markets"""
cache_key = f"pendle_swaps_{days}"
if cache_key in _cache:
return _cache[cache_key]
from_block = get_block_by_timestamp(
int((datetime.now() - timedelta(days=days)).timestamp())
)
all_logs = []
for market_name, market_info in PENDLE_MARKETS.items():
logs = fetch_logs(
market_info['market'],
[EVENTS['SWAP']],
from_block
)
for log in logs:
log['market'] = market_name
all_logs.extend(logs)
if not all_logs:
return pd.DataFrame()
all_logs = add_block_timestamps(all_logs)
data = []
for log in all_logs:
caller = decode_address(log['topics'][1]) if len(log['topics']) > 1 else ZERO_ADDRESS
receiver = decode_address(log['topics'][2]) if len(log['topics']) > 2 else ZERO_ADDRESS
net_pt_out = decode_int256(log['data'], 0) / TOKEN_DIVISOR
net_sy_out = decode_int256(log['data'], 1) / TOKEN_DIVISOR
sy_fee = decode_uint256(log['data'], 2) / TOKEN_DIVISOR
data.append({
'timestamp': log['timestamp'],
'block': log['block_number'],
'tx_hash': log['tx_hash'],
'market': log.get('market', 'unknown'),
'caller': caller,
'receiver': receiver,
'net_pt_out': net_pt_out,
'net_sy_out': net_sy_out,
'fee': sy_fee,
'volume': abs(net_sy_out),
})
df = pd.DataFrame(data)
_cache[cache_key] = df
return df
def get_pendle_lp_events(days: int = 30) -> pd.DataFrame:
"""Get Pendle LP mint/burn events from all markets"""
cache_key = f"pendle_lp_{days}"
if cache_key in _cache:
return _cache[cache_key]
from_block = get_block_by_timestamp(
int((datetime.now() - timedelta(days=days)).timestamp())
)
all_logs = []
for market_name, market_info in PENDLE_MARKETS.items():
mint_logs = fetch_logs(market_info['market'], [EVENTS['MINT']], from_block)
burn_logs = fetch_logs(market_info['market'], [EVENTS['BURN']], from_block)
for log in mint_logs + burn_logs:
log['market'] = market_name
all_logs.extend(mint_logs + burn_logs)
if not all_logs:
return pd.DataFrame()
all_logs = add_block_timestamps(all_logs)
data = []
for log in all_logs:
is_mint = log['topics'][0] == EVENTS['MINT']
user = decode_address(log['topics'][1]) if len(log['topics']) > 1 else ZERO_ADDRESS
lp_amount = decode_uint256(log['data'], 0) / TOKEN_DIVISOR
data.append({
'timestamp': log['timestamp'],
'block': log['block_number'],
'tx_hash': log['tx_hash'],
'market': log.get('market', 'unknown'),
'user': user,
'lp_amount': lp_amount,
'action': 'mint' if is_mint else 'burn',
})
df = pd.DataFrame(data)
_cache[cache_key] = df
return df
def get_reward_claims(days: int = 30) -> pd.DataFrame:
"""Get reward claim events"""
cache_key = f"rewards_{days}"
if cache_key in _cache:
return _cache[cache_key]
from_block = get_block_by_timestamp(
int((datetime.now() - timedelta(days=days)).timestamp())
)
logs = fetch_logs(CONTRACTS['PENDLE_MARKET'], [EVENTS['REDEEM_REWARDS']], from_block)
if not logs:
return pd.DataFrame()
logs = add_block_timestamps(logs)
data = []
for log in logs:
user = decode_address(log['topics'][1]) if len(log['topics']) > 1 else ZERO_ADDRESS
data.append({
'timestamp': log['timestamp'],
'block': log['block_number'],
'tx_hash': log['tx_hash'],
'user': user,
})
df = pd.DataFrame(data)
_cache[cache_key] = df
return df
# ============================================================================
# AGGREGATION FUNCTIONS
# ============================================================================
def get_daily_pendle_deposits(days: int = 30) -> pd.DataFrame:
"""Aggregate daily Pendle deposits and withdrawals"""
df = get_sy_transfers(days)
if df.empty:
return pd.DataFrame(columns=['date', 'deposits', 'withdrawals', 'net_flow'])
df['date'] = pd.to_datetime(df['timestamp']).dt.date
deposits = df[df['type'] == 'deposit'].groupby('date')['amount'].sum()
withdrawals = df[df['type'] == 'withdrawal'].groupby('date')['amount'].sum()
result = pd.DataFrame({
'deposits': deposits,
'withdrawals': withdrawals,
}).fillna(0)
result['net_flow'] = result['deposits'] - result['withdrawals']
return result.reset_index()
def get_daily_volume(days: int = 30) -> pd.DataFrame:
"""Aggregate daily Pendle swap volume"""
df = get_pendle_swaps(days)
if df.empty:
return pd.DataFrame(columns=['date', 'volume', 'fees', 'num_swaps', 'traders'])
df['date'] = pd.to_datetime(df['timestamp']).dt.date
result = df.groupby('date').agg({
'volume': 'sum',
'fee': 'sum',
'tx_hash': 'count',
'caller': 'nunique',
}).rename(columns={
'fee': 'fees',
'tx_hash': 'num_swaps',
'caller': 'traders',
})
return result.reset_index()
def get_nlp_tvl(days: int = 30) -> pd.DataFrame:
"""Calculate nLP TVL over time"""
df = get_nlp_transfers(days)
if df.empty:
return pd.DataFrame(columns=['date', 'daily_change', 'tvl'])
df['date'] = pd.to_datetime(df['timestamp']).dt.date
mints = df[df['type'] == 'mint'].groupby('date')['amount'].sum()
burns = df[df['type'] == 'burn'].groupby('date')['amount'].sum()
daily_change = (mints.fillna(0) - burns.fillna(0)).reset_index()
daily_change.columns = ['date', 'daily_change']
daily_change = daily_change.sort_values('date')
daily_change['tvl'] = daily_change['daily_change'].cumsum()
return daily_change
def get_daily_nlp_volume(days: int = 30) -> pd.DataFrame:
"""Aggregate daily nLP transfer volume"""
df = get_nlp_transfers(days)
if df.empty:
return pd.DataFrame(columns=['date', 'volume', 'num_transfers'])
transfers = df[df['type'] == 'transfer'].copy()
if transfers.empty:
return pd.DataFrame(columns=['date', 'volume', 'num_transfers'])
transfers['date'] = pd.to_datetime(transfers['timestamp']).dt.date
result = transfers.groupby('date').agg({
'amount': 'sum',
'tx_hash': 'count',
}).rename(columns={
'amount': 'volume',
'tx_hash': 'num_transfers',
})
return result.reset_index()
def get_top_holders(days: int = 90) -> pd.DataFrame:
"""Get current top nLP holders"""
df = get_nlp_transfers(days)
if df.empty:
return pd.DataFrame(columns=['holder', 'balance', 'pct_supply'])
received = df.groupby('to')['amount'].sum()
sent = df.groupby('from')['amount'].sum()
balances = (received.fillna(0) - sent.fillna(0)).reset_index()
balances.columns = ['holder', 'balance']
balances = balances[
(balances['holder'].str.lower() != ZERO_ADDRESS.lower()) &
(balances['balance'] > 0.01)
]
total_supply = balances['balance'].sum()
if total_supply > 0:
balances['pct_supply'] = (balances['balance'] / total_supply * 100).round(2)
else:
balances['pct_supply'] = 0
return balances.sort_values('balance', ascending=False).head(20)
def get_user_stats(days: int = 30) -> pd.DataFrame:
"""Get daily active users"""
nlp_df = get_nlp_transfers(days)
swap_df = get_pendle_swaps(days)
users = []
if not nlp_df.empty:
nlp_df['date'] = pd.to_datetime(nlp_df['timestamp']).dt.date
for _, row in nlp_df.iterrows():
if row['from'].lower() != ZERO_ADDRESS.lower():
users.append({'date': row['date'], 'user': row['from'].lower(), 'product': 'nLP'})
if row['to'].lower() != ZERO_ADDRESS.lower():
users.append({'date': row['date'], 'user': row['to'].lower(), 'product': 'nLP'})
if not swap_df.empty:
swap_df['date'] = pd.to_datetime(swap_df['timestamp']).dt.date
for _, row in swap_df.iterrows():
users.append({'date': row['date'], 'user': row['caller'].lower(), 'product': 'Pendle'})
if not users:
return pd.DataFrame(columns=['date', 'daily_users', 'nlp_users', 'pendle_users'])
users_df = pd.DataFrame(users).drop_duplicates()
result = users_df.groupby('date')['user'].nunique().reset_index()
result.columns = ['date', 'daily_users']
nlp_users = users_df[users_df['product'] == 'nLP'].groupby('date')['user'].nunique()
pendle_users = users_df[users_df['product'] == 'Pendle'].groupby('date')['user'].nunique()
result = result.set_index('date')
result['nlp_users'] = nlp_users
result['pendle_users'] = pendle_users
result = result.fillna(0).astype({'nlp_users': int, 'pendle_users': int})
return result.reset_index()
def get_kpi_summary(days: int = 30) -> Dict:
"""Get key performance indicators"""
nlp_df = get_nlp_transfers(days)
swap_df = get_pendle_swaps(days)
sy_df = get_sy_transfers(days)
# Calculate TVL
if not nlp_df.empty:
mints = nlp_df[nlp_df['type'] == 'mint']['amount'].sum()
burns = nlp_df[nlp_df['type'] == 'burn']['amount'].sum()
tvl = mints - burns
else:
tvl = 0
mints = 0
burns = 0
# nLP Volume = total deposits + withdrawals (mints + burns)
nlp_volume = mints + burns if not nlp_df.empty else 0
# Calculate swap volume (7d)
if not swap_df.empty:
seven_days_ago = datetime.now() - timedelta(days=7)
swap_df['timestamp'] = pd.to_datetime(swap_df['timestamp'])
recent_swaps = swap_df[swap_df['timestamp'] >= seven_days_ago]
swap_volume_7d = recent_swaps['volume'].sum() if not recent_swaps.empty else 0
total_swap_volume = swap_df['volume'].sum()
total_fees = swap_df['fee'].sum()
else:
swap_volume_7d = 0
total_swap_volume = 0
total_fees = 0
# Pendle deposits/withdrawals
if not sy_df.empty:
pendle_deposits = sy_df[sy_df['type'] == 'deposit']['amount'].sum()
pendle_withdrawals = sy_df[sy_df['type'] == 'withdrawal']['amount'].sum()
else:
pendle_deposits = 0
pendle_withdrawals = 0
# Total Pendle Volume = swap volume + deposits + withdrawals
pendle_total_volume = total_swap_volume + pendle_deposits + pendle_withdrawals
# Count users
all_users = set()
if not nlp_df.empty:
all_users.update(nlp_df['from'].str.lower().tolist())
all_users.update(nlp_df['to'].str.lower().tolist())
if not swap_df.empty:
all_users.update(swap_df['caller'].str.lower().tolist())
all_users.discard(ZERO_ADDRESS.lower())
return {
'tvl': round(tvl, 2),
'nlp_volume': round(nlp_volume, 2),
'swap_volume_7d': round(swap_volume_7d, 2),
'pendle_total_volume': round(pendle_total_volume, 2),
'pendle_deposits': round(pendle_deposits, 2),
'pendle_withdrawals': round(pendle_withdrawals, 2),
'total_fees': round(total_fees, 4),
'total_users': len(all_users),
}
def get_market_stats(days: int = 30) -> Dict:
"""Get stats per Pendle market"""
swap_df = get_pendle_swaps(days)
lp_df = get_pendle_lp_events(days)
market_stats = {}
for market_name in PENDLE_MARKETS.keys():
# Swap stats for this market
if not swap_df.empty:
market_swaps = swap_df[swap_df['market'] == market_name]
swap_volume = market_swaps['volume'].sum() if not market_swaps.empty else 0
swap_count = len(market_swaps)
fees = market_swaps['fee'].sum() if not market_swaps.empty else 0
else:
swap_volume = 0
swap_count = 0
fees = 0
# LP stats for this market
if not lp_df.empty:
market_lp = lp_df[lp_df['market'] == market_name]
mints = market_lp[market_lp['action'] == 'mint']['lp_amount'].sum() if not market_lp.empty else 0
burns = market_lp[market_lp['action'] == 'burn']['lp_amount'].sum() if not market_lp.empty else 0
else:
mints = 0
burns = 0
market_stats[market_name] = {
'swap_volume': round(swap_volume, 2),
'swap_count': swap_count,
'fees': round(fees, 4),
'lp_mints': round(mints, 2),
'lp_burns': round(burns, 2),
'net_lp': round(mints - burns, 2),
}
return market_stats
def get_total_supply(contract_address: str, decimals: int = TOKEN_DECIMALS) -> float:
"""Get total supply of a token (instant, accurate TVL)"""
# totalSupply() selector: 0x18160ddd
result = rpc_call("eth_call", [{"to": contract_address, "data": "0x18160ddd"}, "latest"])
if result:
return int(result, 16) / (10 ** decimals)
return 0
def get_accurate_tvl() -> Dict:
"""Get accurate TVL using totalSupply() - instant and accurate"""
cache_key = "accurate_tvl"
if cache_key in _cache:
return _cache[cache_key]
wNLP_supply = get_total_supply(CONTRACTS['wNLP'], decimals=6)
SY_supply = get_total_supply(CONTRACTS['SY_wNLP'], decimals=6)
nHYPE_supply = get_total_supply(CONTRACTS['nHYPE'], decimals=18)
result = {
'wNLP_tvl': round(wNLP_supply, 2),
'SY_tvl': round(SY_supply, 2),
'nHYPE_tvl': round(nHYPE_supply, 2),
}
_cache[cache_key] = result
return result
def load_alltime_cache() -> Dict:
"""Load all-time totals from disk cache"""
if os.path.exists(ALLTIME_CACHE_FILE):
try:
with open(ALLTIME_CACHE_FILE, 'r') as f:
return json.load(f)
except:
pass
return {}
def save_alltime_cache(data: Dict):
"""Save all-time totals to disk cache"""
try:
with open(ALLTIME_CACHE_FILE, 'w') as f:
json.dump(data, f)
except Exception as e:
print(f"Failed to save cache: {e}")
def fetch_alltime_totals(contract: str, start_block: int, progress_callback=None) -> Dict:
"""Fetch all-time transfer totals for a contract"""
current_block = get_current_block()
if current_block == 0:
return {'mints': 0, 'burns': 0, 'transfers': 0, 'last_block': 0}
total_mints = 0
total_burns = 0
total_transfers = 0
batch_size = 900
current_from = start_block
while current_from <= current_block:
current_to = min(current_from + batch_size, current_block)
params = [{
"fromBlock": hex(current_from),
"toBlock": hex(current_to),
"address": contract,
"topics": [EVENTS['TRANSFER']],
}]
result = rpc_call("eth_getLogs", params)
if isinstance(result, list):
for log in result:
from_addr = '0x' + log['topics'][1][-40:] if len(log['topics']) > 1 else ZERO_ADDRESS
to_addr = '0x' + log['topics'][2][-40:] if len(log['topics']) > 2 else ZERO_ADDRESS
data = log.get('data', '0x')
amount = int(data, 16) / TOKEN_DIVISOR if data and data != '0x' else 0
if from_addr.lower() == ZERO_ADDRESS.lower():
total_mints += amount
elif to_addr.lower() == ZERO_ADDRESS.lower():
total_burns += amount
else:
total_transfers += amount
if progress_callback:
progress = (current_from - start_block) / (current_block - start_block)
progress_callback(progress)
time.sleep(0.05) # Rate limiting
current_from = current_to + 1
return {
'mints': round(total_mints, 2),
'burns': round(total_burns, 2),
'transfers': round(total_transfers, 2),
'last_block': current_block,
}
def get_alltime_totals(force_refresh: bool = False) -> Dict:
"""Get all-time totals from cache or fetch if needed"""
cache = load_alltime_cache()
current_block = get_current_block()
# Check if we need to update (cache is empty or stale by >10000 blocks)
needs_update = {}
for name, contract in [('wNLP', CONTRACTS['wNLP']), ('SY_wNLP', CONTRACTS['SY_wNLP'])]:
if force_refresh or name not in cache:
needs_update[name] = CONTRACT_START_BLOCKS.get(name, 20000000)
elif current_block - cache[name].get('last_block', 0) > 10000:
# Just fetch from last block instead of from beginning
needs_update[name] = cache[name].get('last_block', CONTRACT_START_BLOCKS.get(name, 20000000))
# Return cached data if no update needed
if not needs_update and cache:
return cache
# Fetch missing/stale data
for name, start_block in needs_update.items():
contract = CONTRACTS['wNLP'] if name == 'wNLP' else CONTRACTS['SY_wNLP']
print(f"Fetching all-time data for {name} from block {start_block}...")
new_data = fetch_alltime_totals(contract, start_block)
if name in cache:
# Add to existing totals
cache[name]['mints'] = round(cache[name].get('mints', 0) + new_data['mints'], 2)
cache[name]['burns'] = round(cache[name].get('burns', 0) + new_data['burns'], 2)
cache[name]['transfers'] = round(cache[name].get('transfers', 0) + new_data['transfers'], 2)
cache[name]['last_block'] = new_data['last_block']
else:
cache[name] = new_data
save_alltime_cache(cache)
return cache
def get_apy_history(days: int = 7) -> pd.DataFrame:
"""Fetch historical APY data from Pendle API"""
cache_key = f"apy_history_{days}"
if cache_key in _cache:
return _cache[cache_key]
all_data = []
for market_name, market_info in PENDLE_MARKETS.items():
try:
response = requests.get(
f"https://api-v2.pendle.finance/core/v1/999/markets/{market_info['market']}/apy-history",
timeout=15
)
data = response.json()
for entry in data.get('results', []):
all_data.append({
'timestamp': pd.to_datetime(entry['timestamp']),
'market': market_name,
'underlying_apy': entry.get('underlyingApy', 0) * 100,
'implied_apy': entry.get('impliedApy', 0) * 100,
})
except Exception as e:
print(f"Failed to fetch APY history for {market_name}: {e}")
if not all_data:
return pd.DataFrame()
df = pd.DataFrame(all_data)
# Filter to requested days - convert timestamp to naive datetime for comparison
cutoff = datetime.now() - timedelta(days=days)
df['timestamp'] = pd.to_datetime(df['timestamp']).dt.tz_localize(None)
df = df[df['timestamp'] >= cutoff]
_cache[cache_key] = df
return df
def get_pendle_apy() -> Dict:
"""Fetch APY data from Pendle API"""
cache_key = "pendle_apy"
if cache_key in _cache:
return _cache[cache_key]
try:
response = requests.get(
"https://api-v2.pendle.finance/core/v1/999/markets",
timeout=10
)
data = response.json()
apy_data = {}
for market in data.get('results', []):
name = market.get('proName', market.get('name', ''))
if 'wNLP' in name or 'nLP' in name.lower():
addr = market.get('address', '').lower()
underlying_apy = market.get('underlyingInterestApy', 0) * 100
tvl_usd = market.get('liquidity', {}).get('usd', 0)
# Calculate distributed yield (APY × TVL)
daily_yield = (underlying_apy / 100 / 365) * tvl_usd
weekly_yield = daily_yield * 7
monthly_yield = daily_yield * 30
annual_yield = (underlying_apy / 100) * tvl_usd
apy_data[addr] = {
'name': name,
'implied_apy': round(market.get('impliedApy', 0) * 100, 2),
'underlying_apy': round(underlying_apy, 2),
'tvl_usd': round(tvl_usd, 2),
'pt_price': market.get('pt', {}).get('price', {}).get('usd', 0),
'yt_price': market.get('yt', {}).get('price', {}).get('usd', 0),
'expiry': market.get('expiry', ''),
# Distributed yield calculations
'daily_yield': round(daily_yield, 2),
'weekly_yield': round(weekly_yield, 2),
'monthly_yield': round(monthly_yield, 2),
'annual_yield': round(annual_yield, 2),
}
_cache[cache_key] = apy_data
return apy_data
except Exception as e:
print(f"Failed to fetch Pendle APY: {e}")
return {}
def clear_cache():
"""Clear all cached data"""
_cache.clear()
# ============================================================================
# HYPERSCAN API FUNCTIONS (for efficient all-time data fetching)
# ============================================================================
HYPERSCAN_API = "https://www.hyperscan.com/api/v2"
def fetch_all_token_transfers_hyperscan(token_address: str) -> Dict:
"""
Fetch all transfers of a token from Hyperscan API.
Returns totals for mints, burns, and regular transfers.
"""
url = f"{HYPERSCAN_API}/tokens/{token_address}/transfers"
all_transfers = []
next_params = None
page = 0
print(f"Fetching transfers for {token_address[:10]}... via Hyperscan API")
while True:
page += 1
params = next_params or {}
try:
resp = requests.get(url, params=params, timeout=30)
if resp.status_code != 200:
print(f" Error on page {page}: {resp.status_code}")
break
data = resp.json()
items = data.get('items', [])
all_transfers.extend(items)
if page % 20 == 0:
print(f" Page {page}: {len(all_transfers)} transfers...")
next_params = data.get('next_page_params')
if not next_params:
break
time.sleep(0.1) # Rate limiting
except Exception as e:
print(f" Request failed: {e}")
break
print(f" Total transfers: {len(all_transfers)}")
# Calculate totals and track unique users
mints = 0.0
burns = 0.0
transfers = 0.0
unique_users = set()
for tx in all_transfers:
from_addr = tx.get('from', {}).get('hash', '').lower()
to_addr = tx.get('to', {}).get('hash', '').lower()
value = int(tx.get('total', {}).get('value', '0'))
decimals = int(tx.get('total', {}).get('decimals', '6') or '6')
amount = value / (10 ** decimals)
# Track unique users (exclude zero address)
if from_addr != ZERO_ADDRESS.lower():
unique_users.add(from_addr)
if to_addr != ZERO_ADDRESS.lower():
unique_users.add(to_addr)
if from_addr == ZERO_ADDRESS.lower():
mints += amount
elif to_addr == ZERO_ADDRESS.lower():
burns += amount
else:
transfers += amount
return {
'mints': round(mints, 2),
'burns': round(burns, 2),
'transfers': round(transfers, 2),
'total_count': len(all_transfers),
'unique_users': len(unique_users),
'user_addresses': unique_users, # Keep for deduplication across tokens
}
def get_alltime_totals_hyperscan(force_refresh: bool = False) -> Dict:
"""
Get all-time totals using Hyperscan API (much faster than RPC).
Returns cached data if available, otherwise fetches from API.
"""
cache_key = "alltime_hyperscan"
# Check memory cache first
if not force_refresh and cache_key in _cache:
return _cache[cache_key]
# Check disk cache