-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1645 lines (1512 loc) · 78.9 KB
/
Copy pathserver.py
File metadata and controls
1645 lines (1512 loc) · 78.9 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
#!/usr/bin/env python3
"""
moneyapi server v0.4 with X402 (crypto-per-request) payment on premium endpoints.
Free tier (no payment):
/api/v1/health, /api/v1/fear-greed, /api/v1/gas, /api/v1/trending,
/api/v1/btc, /api/v1/eth, /api/v1/news, /api/v1/whale-alerts, /api/v1/signal
Premium tier (USDC on Base, $0.001 per call):
/api/v1/premium/btc, /api/v1/premium/eth, /api/v1/premium/signal,
/api/v1/premium/gas, /api/v1/premium/fear-greed
X402 protocol:
1. Client GET /api/v1/premium/btc
2. Server returns 402 + WWW-Authenticate header containing payment-required JSON
3. Client pays USDC to wallet address (visible in header)
4. Client retries with X-Payment-Tx header containing tx hash
5. Server verifies tx on-chain (Base) and serves the data
"""
import json
import os
import re
import threading
import time
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.request import urlopen, Request
from urllib.error import URLError, HTTPError
from urllib.parse import urlparse, parse_qs
import urllib.parse
import urllib.error
# -----------------------------------------------------------------------------
# Crypto payment layer
# -----------------------------------------------------------------------------
WALLET_PATH = "/data/.secrets/x402_wallet"
USDC_PRICE = "1000" # 0.001 USDC = 1000 micro-USDC = 6 decimals on USDC contract
PAYMENT_TTL_SEC = 600 # 10 min to pay after challenge
REQUIRED_CONFIRMATIONS = 1
# x402-standard network identifier (CAIP-2) + Bazaar discovery extension
NETWORK_CAIP2 = "eip155:8453" # Base mainnet
# Base mainnet USDC contract (verified from Coinbase docs)
USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
BASE_RPC = "https://base.drpc.org" # public RPC
# In-memory payment cache: {tx_hash_lower: {ts, payer, amount_micro_usdc, used}}
_payments = {}
_payments_lock = threading.Lock()
def load_wallet():
with open(WALLET_PATH) as f:
return json.load(f)
def verify_usdc_transfer(tx_hash, expected_to, expected_amount_micro):
"""Verify a USDC Transfer event on Base chain.
Returns dict with ok=True/False and details.
"""
# 1. Fetch the transaction receipt via JSON-RPC
payload = json.dumps({
"jsonrpc": "2.0",
"id": 1,
"method": "eth_getTransactionReceipt",
"params": [tx_hash],
}).encode()
req = Request(BASE_RPC, data=payload, headers={
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (moneyapi/x402)",
})
try:
with urlopen(req, timeout=15) as r:
data = json.loads(r.read().decode())
except Exception as e:
return {"ok": False, "reason": f"rpc_unreachable: {e}"}
receipt = data.get("result")
if not receipt:
return {"ok": False, "reason": "tx_not_found_or_pending"}
# Confirmations
payload = json.dumps({
"jsonrpc": "2.0",
"id": 1,
"method": "eth_blockNumber",
"params": [],
}).encode()
req = Request(BASE_RPC, data=payload, headers={
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0",
})
try:
with urlopen(req, timeout=10) as r:
cur_block = int(json.loads(r.read().decode())["result"], 16)
except Exception:
cur_block = 0
tx_block = int(receipt.get("blockNumber", "0x0"), 16)
confirms = cur_block - tx_block if cur_block and tx_block else 0
if confirms < REQUIRED_CONFIRMATIONS:
return {"ok": False, "reason": f"needs_more_confirms:={confirms}"}
# Decode logs for USDC Transfer event
# Transfer(address indexed from, address indexed to, uint256 value)
TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
found = None
for log in receipt.get("logs", []):
if log.get("address", "").lower() != USDC_BASE.lower():
continue
topics = log.get("topics", [])
if len(topics) < 3:
continue
if topics[0].lower() != TRANSFER_TOPIC:
continue
# topics[2] is the `to` address (padded to 32 bytes)
to_addr = "0x" + topics[2][-40:]
if to_addr.lower() != expected_to.lower():
continue
# data is the value (uint256, 32 bytes)
val = int(log.get("data", "0x0"), 16)
if val >= int(expected_amount_micro):
found = {
"to": to_addr,
"value_micro": val,
"block": tx_block,
"from": "0x" + topics[1][-40:],
}
break
if not found:
return {"ok": False, "reason": "no_matching_transfer_event"}
return {
"ok": True,
"value_micro": found["value_micro"],
"from": found["from"],
"to": found["to"],
"block": found["block"],
"confirmations": confirms,
}
# -----------------------------------------------------------------------------
# Existing TTL cache for upstream APIs
# -----------------------------------------------------------------------------
_cache = {}
_cache_lock = threading.Lock()
def cached_get(url, ttl=60, headers=None, timeout=10):
now = time.time()
with _cache_lock:
hit = _cache.get(url)
if hit and now - hit[0] < ttl:
return hit[1]
try:
req = Request(url, headers=headers or {"User-Agent": "MoneyAPI/0.4"})
with urlopen(req, timeout=timeout) as r:
data = r.read().decode()
except (URLError, HTTPError, TimeoutError) as e:
return json.dumps({"error": str(e), "url": url})
with _cache_lock:
_cache[url] = (now, data)
return data
def jsonrpc(url, method, params=None, timeout=10):
body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params or []}).encode()
req = Request(url, data=body, headers={
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
})
try:
with urlopen(req, timeout=timeout) as r:
d = json.loads(r.read().decode())
return d.get("result")
except Exception:
return None
# -----------------------------------------------------------------------------
# Free endpoints (unchanged from v0.3)
# -----------------------------------------------------------------------------
def ep_health(_q):
w = load_wallet()
return {
"ok": True,
"ts": int(time.time()),
"version": "1.1",
"x402_enabled": True,
"payment_address": w["address"],
"payment_asset": "USDC",
"payment_chain": w["chain"],
}
def ep_fear_greed(_q):
raw = cached_get("https://api.alternative.me/fng/?limit=1&format=json", ttl=300)
try:
d = json.loads(raw)
v = d.get("data", [{}])[0]
return {
"value": int(v.get("value", 0)),
"value_classification": v.get("value_classification"),
"timestamp": int(v.get("timestamp", 0)),
}
except Exception as e:
return {"error": "upstream_parse", "detail": str(e), "raw": raw[:200]}
def ep_gas(_q):
rpc = "https://ethereum-rpc.publicnode.com"
gp_hex = jsonrpc(rpc, "eth_gasPrice")
if not gp_hex:
return {"error": "rpc_unavailable", "ts": int(time.time())}
wei = int(gp_hex, 16)
gwei = round(wei / 1e9, 2)
return {
"safe_gas": round(gwei * 0.85, 1),
"propose_gas": gwei,
"fast_gas": round(gwei * 1.3, 1),
"unit": "gwei",
"rpc": rpc,
"ts": int(time.time()),
}
def ep_trending(_q):
raw = cached_get("https://api.coingecko.com/api/v3/search/trending", ttl=120,
headers={"User-Agent": "MoneyAPI/0.4", "Accept": "application/json"})
try:
d = json.loads(raw)
coins = d.get("coins", [])
return {
"count": len(coins),
"coins": [
{
"rank": c.get("item", {}).get("market_cap_rank"),
"id": c.get("item", {}).get("id"),
"name": c.get("item", {}).get("name"),
"symbol": c.get("item", {}).get("symbol"),
"price_btc": c.get("item", {}).get("price_btc"),
}
for c in coins[:15]
],
}
except Exception as e:
return {"error": "upstream_parse", "detail": str(e)}
def _price(symbol):
raw = cached_get(f"https://api.coingecko.com/api/v3/simple/price?ids={symbol}&vs_currencies=usd&include_24hr_change=true&include_market_cap=true", ttl=30)
try:
d = json.loads(raw)
r = d.get(symbol, {})
return {"symbol": symbol, "usd": r.get("usd"), "usd_24h_change": r.get("usd_24h_change"), "market_cap": r.get("usd_market_cap"), "ts": int(time.time())}
except Exception as e:
return {"error": "upstream_parse", "detail": str(e)}
def ep_btc(_q):
return _price("bitcoin")
def ep_eth(_q):
return _price("ethereum")
def ep_news(q):
limit = int(q.get("limit", ["10"])[0])
limit = min(max(limit, 1), 50)
raw = cached_get("https://cointelegraph.com/rss", ttl=300,
headers={"User-Agent": "Mozilla/5.0"})
try:
items = re.findall(r"<item>(.*?)</item>", raw, re.DOTALL)
out = []
for it in items[:limit]:
t = re.search(r"<title>(.*?)</title>", it, re.DOTALL)
l = re.search(r"<link>(.*?)</link>", it)
p = re.search(r"<pubDate>(.*?)</pubDate>", it)
out.append({
"title": (t.group(1).strip() if t else None),
"url": (l.group(1).strip() if l else None),
"published_at": (p.group(1).strip() if p else None),
"source": "cointelegraph",
})
return {"count": len(out), "news": out}
except Exception as e:
return {"error": "upstream_parse", "detail": str(e), "raw": raw[:200]}
def ep_whale_alerts(q):
limit = int(q.get("limit", ["5"])[0])
limit = min(max(limit, 1), 20)
raw = cached_get("https://whale-alert.io/rss.xml", ttl=300)
try:
items = re.findall(r"<item>(.*?)</item>", raw, re.DOTALL)
out = []
for it in items[:limit]:
title = re.search(r"<title>(.*?)</title>", it, re.DOTALL)
link = re.search(r"<link>(.*?)</link>", it)
pub = re.search(r"<pubDate>(.*?)</pubDate>", it)
if title:
out.append({
"title": title.group(1).strip(),
"link": link.group(1).strip() if link else None,
"published": pub.group(1).strip() if pub else None,
})
return {"count": len(out), "alerts": out}
except Exception as e:
return {"error": "upstream_parse", "detail": str(e)}
def ep_signal(q):
symbol = (q.get("symbol", ["bitcoin"])[0]).lower()
supported = ("bitcoin", "ethereum", "solana", "dogecoin", "cardano", "ripple", "polkadot", "tron")
sym = symbol if symbol in supported else "bitcoin"
price = _price(sym)
fg = ep_fear_greed({})
gas = ep_gas({})
score = 50
notes = []
if isinstance(price, dict):
ch = price.get("usd_24h_change")
if isinstance(ch, (int, float)):
score += max(min(ch * 4, 30), -30)
notes.append(f"24h change: {ch:.2f}%")
if isinstance(fg, dict) and "value" in fg:
v = fg["value"]
if v < 25:
score += 10
notes.append("extreme fear (contrarian buy)")
elif v > 75:
score -= 10
notes.append("extreme greed (contrarian sell)")
notes.append(f"fear&greed={v} ({fg.get('value_classification')})")
score = max(0, min(100, int(score)))
if score >= 70:
action = "buy_lean"
elif score <= 30:
action = "sell_lean"
else:
action = "neutral"
return {
"symbol": sym,
"price": price,
"fear_greed": fg,
"gas": gas,
"score": score,
"action": action,
"notes": notes,
"ts": int(time.time()),
}
def ep_erc20_balance(q):
address = (q.get("address", [""])[0]).strip()
contract = (q.get("contract", ["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"])[0]).strip()
if not address.startswith("0x") or len(address) != 42:
return {"error": "invalid_address"}
if not contract.startswith("0x") or len(contract) != 42:
return {"error": "invalid_contract"}
try:
data = "0x70a08231" + "0"*24 + address[2:].lower()
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{"to":contract,"data":data},"latest"]}).encode()
req = Request(BASE_RPC, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
result = json.loads(r.read().decode()).get("result")
if not result or result == "0x":
return {"address": address, "contract": contract, "balance_raw": "0x0", "balance_wei": 0, "ts": int(time.time())}
return {"address": address, "contract": contract, "balance_raw": result, "balance_wei": int(result, 16), "ts": int(time.time())}
except Exception as e:
return {"error": "rpc_failed", "detail": str(e)}
def ep_wiki(q):
topic = (q.get("topic", [""])[0]).strip()
if not topic:
return {"error": "missing_topic"}
url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + urllib.parse.quote(topic.replace(" ", "_"))
try:
req = Request(url, headers={"User-Agent":"moneyapi/1.0"})
with urlopen(req, timeout=10) as r:
data = json.loads(r.read().decode())
return {
"title": data.get("title"),
"description": data.get("description"),
"extract": (data.get("extract") or "")[:1000],
"url": data.get("content_urls",{}).get("desktop",{}).get("page"),
"ts": int(time.time()),
}
except urllib.error.HTTPError as e:
if e.code == 404:
return {"error": "not_found", "topic": topic}
return {"error": "wiki_failed", "detail": e.read().decode()[:200]}
except Exception as e:
return {"error": "wiki_failed", "detail": str(e)}
def ep_weather(q):
city = (q.get("city", [""])[0]).strip()
if not city:
return {"error": "missing_city"}
try:
geo_url = "https://geocoding-api.open-meteo.com/v1/search?name=" + urllib.parse.quote(city) + "&count=1"
req = Request(geo_url, headers={"User-Agent":"moneyapi/1.0"})
with urlopen(req, timeout=10) as r:
geo = json.loads(r.read().decode())
if not geo.get("results"):
return {"error": "city_not_found", "city": city}
g = geo["results"][0]
lat, lon = g["latitude"], g["longitude"]
wx_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t_weather=true&temperature_unit=celsius"
req = Request(wx_url, headers={"User-Agent":"moneyapi/1.0"})
with urlopen(req, timeout=10) as r:
wx = json.loads(r.read().decode())
return {
"city": g.get("name"),
"country": g.get("country"),
"lat": lat, "lon": lon,
"current": wx.get("current_weather", {}),
"ts": int(time.time()),
}
except Exception as e:
return {"error": "weather_failed", "detail": str(e)}
def ep_token(q):
contract = (q.get("contract", [""])[0]).strip()
if not contract.startswith("0x") or len(contract) != 42:
return {"error": "invalid_contract"}
out = {"contract": contract, "ts": int(time.time())}
try:
for k, sel in (("decimals", "0x313ce567"), ("total_supply", "0x18160ddd")):
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{"to":contract,"data":sel},"latest"]}).encode()
req = Request(BASE_RPC, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
rd = json.loads(r.read().decode()).get("result")
if rd and rd != "0x":
out[k] = int(rd, 16)
for field, sel in (("name", "0x06fdde03"), ("symbol", "0x95d89b41")):
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{"to":contract,"data":sel},"latest"]}).encode()
req = Request(BASE_RPC, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
rd = json.loads(r.read().decode()).get("result")
if rd and len(rd) >= 130:
hs = rd[2:]
if len(hs) >= 128:
sl = int(hs[64:128], 16)
if 0 < sl < 256:
try: out[field] = bytes.fromhex(hs[128:128+sl*2]).decode("utf8", errors="ignore").strip("\x00")
except: pass
return out
except Exception as e:
return {"error": "rpc_failed", "detail": str(e)}
def ep_holders(q):
contract = (q.get("contract", [""])[0]).strip()
if not contract.startswith("0x") or len(contract) != 42:
return {"error": "invalid_contract"}
try:
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}).encode(); req = Request(BASE_RPC, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"}); cur = int(json.loads(urlopen(req, timeout=10).read().decode())["result"], 16)
from_block = max(0, cur - 5000)
lf = {"fromBlock":hex(from_block),"toBlock":hex(cur),"address":contract,"topics":["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]}; body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_getLogs","params":[lf]}).encode(); req = Request(BASE_RPC, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"}); logs = json.loads(urlopen(req, timeout=20).read().decode()).get("result") or []
holders = {}
for log in logs:
if len(log.get("topics", [])) < 3: continue
frm = "0x" + log["topics"][1][-40:]
to = "0x" + log["topics"][2][-40:]
val = int(log.get("data", "0x0"), 16)
holders[frm] = holders.get(frm, 0) - val
holders[to] = holders.get(to, 0) + val
top = sorted(holders.items(), key=lambda x: -x[1])[:20]
return {"contract": contract, "from_block": from_block, "to_block": cur, "top_holders": [{"address":a, "balance":b} for a,b in top], "ts": int(time.time())}
except Exception as e:
return {"error": "holders_failed", "detail": str(e)}
def ep_balance(q):
address = (q.get("address", [""])[0]).strip()
chain = (q.get("chain", ["base"])[0]).strip()
if not address.startswith("0x") or len(address) != 42:
return {"error": "invalid_address"}
rpc_url = "https://base.drpc.org" if chain == "base" else "https://eth.drpc.org"
out = {"address": address, "chain": chain, "ts": int(time.time())}
try:
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_getBalance","params":[address,"latest"]}).encode()
req = Request(rpc_url, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
result = json.loads(r.read().decode()).get("result")
if result: out["balance_wei"] = int(result, 16)
if chain == "base":
usdc = "0x70a08231" + "0"*24 + address[2:].lower()
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{"to":"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913","data":usdc},"latest"]}).encode()
req = Request(rpc_url, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
usdc_result = json.loads(r.read().decode()).get("result")
if usdc_result: out["usdc_balance_raw"] = usdc_result
return out
except Exception as e:
return {"error": "balance_failed", "detail": str(e)}
def ep_tx(q):
tx_hash = (q.get("hash", [""])[0]).strip()
if not tx_hash.startswith("0x") or len(tx_hash) != 66:
return {"error": "invalid_hash"}
out = {"hash": tx_hash, "ts": int(time.time())}
try:
for field, method in (("tx", "eth_getTransactionByHash"), ("receipt", "eth_getTransactionReceipt")):
body = json.dumps({"jsonrpc":"2.0","id":1,"method":method,"params":[tx_hash]}).encode()
req = Request(BASE_RPC, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
result = json.loads(r.read().decode()).get("result")
if result: out[field] = result
return out
except Exception as e:
return {"error": "tx_failed", "detail": str(e)}
def ep_ts(q):
from datetime import datetime, timezone as tz
ts_str = (q.get("ts", [""])[0]).strip()
date_str = (q.get("date", [""])[0]).strip()
out = {"ts": int(time.time())}
try:
if ts_str:
ts = int(ts_str)
dt = datetime.fromtimestamp(ts, tz=tz.utc)
out["input_ts"] = ts
out["utc"] = dt.isoformat()
out["unix"] = ts
elif date_str:
dt = datetime.fromisoformat(date_str.replace("Z", "+00:00"))
out["input_date"] = date_str
out["unix"] = int(dt.timestamp())
out["utc"] = dt.isoformat()
else:
out["now_unix"] = int(time.time())
out["utc"] = datetime.now(tz=tz.utc).isoformat()
return out
except Exception as e:
return {"error": "ts_failed", "detail": str(e)}
def ep_rand(q):
import secrets
try:
lo = int(q.get("min", ["1"])[0])
hi = int(q.get("max", ["100"])[0])
count = min(int(q.get("count", ["1"])[0]), 100)
if lo >= hi or hi - lo > 1_000_000_000:
return {"error": "invalid_range"}
nums = [secrets.randbelow(hi - lo) + lo for _ in range(count)]
try:
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}).encode()
req = Request(BASE_RPC, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=5) as r:
block = int(json.loads(r.read().decode())["result"], 16)
except Exception:
block = 0
return {"numbers": nums, "min": lo, "max": hi, "count": count, "block": block, "ts": int(time.time())}
except Exception as e:
return {"error": "rand_failed", "detail": str(e)}
def ep_shorten(q):
import base64 as b64
url = (q.get("url", [""])[0]).strip()
if not url.startswith(("http://", "https://")):
return {"error": "invalid_url"}
import hashlib
h = hashlib.sha256(url.encode()).hexdigest()[:8]
short = b64.urlsafe_b64encode(h.encode()).decode().rstrip("=")[:10]
out = {"url": url, "short": f"https://mnyapi.xyz/{short}", "id": h, "ts": int(time.time())}
store = {}
try:
with open("/data/shortener.json") as f: store = json.load(f)
except Exception: pass
store[h] = url
with open("/data/shortener.json","w") as f: json.dump(store, f)
return out
# -----------------------------------------------------------------------------
def ep_nft(q):
"""NFT metadata for any ERC721 on Base or Ethereum.
Query: contract, tokenid, [chain=base|ethereum]"""
contract = (q.get("contract", [""])[0]).strip()
tokenid = (q.get("tokenid", [""])[0]).strip()
chain = (q.get("chain", ["base"])[0]).strip()
if not contract.startswith("0x") or len(contract) != 42:
return {"error": "invalid_contract"}
try:
tokenid_int = int(tokenid)
except (TypeError, ValueError):
return {"error": "invalid_tokenid"}
rpc_url = "https://base.drpc.org" if chain == "base" else "https://eth.drpc.org"
out = {"contract": contract, "tokenid": tokenid, "chain": chain, "ts": int(time.time())}
try:
# name() 0x06fdde03, symbol() 0x95d89b41, tokenURI(uint256) 0xc87b56dd
# First fetch tokenURI
tid_hex = format(tokenid_int, "x")
data_uri = "0xc87b56dd" + "0" * (64 - len(tid_hex)) + tid_hex
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{"to":contract,"data":data_uri},"latest"]}).encode()
req = Request(rpc_url, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
result = json.loads(r.read().decode()).get("result")
if result and len(result) >= 130:
hs = result[2:]
if len(hs) >= 128:
sl = int(hs[64:128], 16)
if 0 < sl < 8192:
try:
uri = bytes.fromhex(hs[128:128+sl*2]).decode("utf8", errors="ignore").strip("\x00")
if uri.startswith("ipfs://"):
uri = uri.replace("ipfs://", "https://ipfs.io/ipfs/", 1)
out["token_uri"] = uri
# Fetch the metadata
if uri.startswith("http"):
try:
req2 = Request(uri, headers={"User-Agent":"moneyapi/1.0"})
with urlopen(req2, timeout=10) as r2:
md = json.loads(r2.read().decode())
out["metadata"] = md
except Exception as e:
out["metadata_error"] = str(e)[:200]
except Exception: pass
# Owner of token
try:
data_owner = "0x6352211e" + "0" * (64 - len(tid_hex)) + tid_hex # ownerOf(uint256)
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{"to":contract,"data":data_owner},"latest"]}).encode()
req = Request(rpc_url, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
ores = json.loads(r.read().decode()).get("result")
if ores and len(ores) >= 66:
out["owner"] = "0x" + ores[-40:]
except Exception: pass
return out
except Exception as e:
return {"error": "nft_failed", "detail": str(e)}
def ep_gh(q):
"""GitHub user profile + repos. Query: user"""
user = (q.get("user", [""])[0]).strip()
if not user:
return {"error": "missing_user"}
try:
# Public API, no auth needed
req = Request(f"https://api.github.com/users/{user}", headers={"User-Agent":"moneyapi/1.0","Accept":"application/vnd.github+json"})
with urlopen(req, timeout=10) as r:
data = json.loads(r.read().decode())
if "message" in data and data.get("message") == "Not Found":
return {"error": "user_not_found", "user": user}
return {
"login": data.get("login"),
"name": data.get("name"),
"bio": data.get("bio"),
"public_repos": data.get("public_repos"),
"followers": data.get("followers"),
"following": data.get("following"),
"created_at": data.get("created_at"),
"avatar_url": data.get("avatar_url"),
"html_url": data.get("html_url"),
"company": data.get("company"),
"location": data.get("location"),
"ts": int(time.time()),
}
except urllib.error.HTTPError as e:
if e.code == 404: return {"error": "user_not_found", "user": user}
return {"error": "gh_failed", "detail": e.read().decode()[:200]}
except Exception as e:
return {"error": "gh_failed", "detail": str(e)}
def ep_block(q):
"""Latest Ethereum block info. Query: [tag=latest|finalized|pending]"""
tag = (q.get("tag", ["latest"])[0]).strip()
try:
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_getBlockByNumber","params":[tag, False]}).encode()
req = Request("https://eth.drpc.org", data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
data = json.loads(r.read().decode()).get("result")
if not data: return {"error": "block_not_found", "tag": tag}
return {
"number": int(data.get("number","0x0"), 16),
"hash": data.get("hash"),
"parent_hash": data.get("parentHash"),
"timestamp": int(data.get("timestamp","0x0"), 16),
"miner": data.get("miner"),
"gas_used": int(data.get("gasUsed","0x0"), 16),
"gas_limit": int(data.get("gasLimit","0x0"), 16),
"tx_count": len(data.get("transactions", [])),
"base_fee": int(data.get("baseFeePerGas","0x0"), 16) if data.get("baseFeePerGas") else 0,
"ts": int(time.time()),
}
except Exception as e:
return {"error": "block_failed", "detail": str(e)}
def ep_doge(q):
"""Dogecoin price (coingecko). No params."""
try:
req = Request("https://api.coingecko.com/api/v3/simple/price?ids=dogecoin&vs_currencies=usd&include_24hr_change=true&include_market_cap=true", headers={"User-Agent":"moneyapi/1.0"})
with urlopen(req, timeout=10) as r:
d = json.loads(r.read().decode())
out = {"doge": d.get("dogecoin", {}), "ts": int(time.time())}
return out
except Exception as e:
return {"error": "doge_failed", "detail": str(e)}
def ep_sol(q):
"""Solana RPC proxy. Query: method, [params=json-string].
Methods: getBalance, getAccountInfo, getRecentBlockhash, getHealth, getSlot, getBlockTime"""
method = (q.get("method", ["getSlot"])[0]).strip()
params_str = (q.get("params", ["[]"])[0]).strip() or "[]"
try:
params = json.loads(params_str) if params_str.startswith("[") else [params_str]
except Exception:
params = []
try:
body = json.dumps({"jsonrpc":"2.0","id":1,"method":method,"params":params}).encode()
req = Request("https://api.mainnet-beta.solana.com", data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=15) as r:
data = json.loads(r.read().decode())
return {"method": method, "result": data.get("result"), "error": data.get("error"), "ts": int(time.time())}
except Exception as e:
return {"error": "sol_failed", "detail": str(e)}
def ep_x(q):
"""Twitter/X user lookup. Query: handle (no @). Returns public profile data via nitter fallback chain.
Note: X API is paywalled; this is best-effort public data via syndication."""
handle = (q.get("handle", [""])[0]).strip().lstrip("@")
if not handle: return {"error": "missing_handle"}
try:
# Twitter's public syndication API
req = Request(f"https://cdn.syndication.twimg.com/widgets/followbutton/info.json?user_names={handle}", headers={"User-Agent":"moneyapi/1.0"})
with urlopen(req, timeout=10) as r:
d = json.loads(r.read().decode())
if not d or not isinstance(d, list):
return {"error": "user_not_found", "handle": handle}
u = d[0]
return {
"handle": u.get("screen_name"),
"name": u.get("name"),
"followers": u.get("followers_count"),
"description": u.get("description"),
"profile_image": u.get("profile_image_url"),
"verified": u.get("verified", False),
"ts": int(time.time()),
}
except urllib.error.HTTPError as e:
if e.code == 404: return {"error": "user_not_found", "handle": handle}
return {"error": "x_failed", "detail": e.read().decode()[:200]}
except Exception as e:
return {"error": "x_failed", "detail": str(e)}
def ep_meme(q):
"""Trending Base memecoins. No params. Returns top 10 by 24h volume."""
try:
# Use coingecko categories
req = Request("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&category=meme-token&order=volume_desc&per_page=10&page=1&sparkline=false&price_change_percentage=24h", headers={"User-Agent":"moneyapi/1.0"})
with urlopen(req, timeout=10) as r:
d = json.loads(r.read().decode())
out = []
for c in d:
out.append({
"rank": c.get("market_cap_rank"),
"id": c.get("id"),
"symbol": c.get("symbol"),
"name": c.get("name"),
"price": c.get("current_price"),
"change_24h": c.get("price_change_percentage_24h"),
"volume_24h": c.get("total_volume"),
"market_cap": c.get("market_cap"),
"image": c.get("image"),
})
return {"trending": out, "count": len(out), "ts": int(time.time())}
except Exception as e:
return {"error": "meme_failed", "detail": str(e)}
def ep_yield(q):
"""DeFi yield opportunities. Query: [chain=ethereum|base|polygon], [min_tvl=1000000]"""
chain = (q.get("chain", ["ethereum"])[0]).strip()
try:
min_tvl = int(q.get("min_tvl", ["1000000"])[0])
except: min_tvl = 1_000_000
try:
url = f"https://yields.llama.fi/pools"
req = Request(url, headers={"User-Agent":"moneyapi/1.0"})
with urlopen(req, timeout=15) as r:
d = json.loads(r.read().decode())
pools = d.get("data", [])
out = []
for p in pools:
if p.get("chain", "").lower() != chain.lower(): continue
tvl = p.get("tvlUsd", 0) or 0
if tvl < min_tvl: continue
out.append({
"pool": p.get("pool"),
"project": p.get("project"),
"symbol": p.get("symbol"),
"apy": p.get("apy"),
"apyBase": p.get("apyBase"),
"apyReward": p.get("apyReward"),
"tvlUsd": tvl,
})
if len(out) >= 15: break
# Sort by APY desc
out.sort(key=lambda x: -(x.get("apy") or 0))
return {"chain": chain, "min_tvl": min_tvl, "pools": out, "ts": int(time.time())}
except Exception as e:
return {"error": "yield_failed", "detail": str(e)}
# =============================================================================
# Bazaar discovery endpoints (v0.8)
# =============================================================================
def ep_security_audit(q):
"""Security audit for an ERC20 contract. Returns risk score + flags.
Premium endpoint: $0.01 USDC per scan (Bankr model).
Query: contract (required), [chain=base|ethereum]"""
contract = (q.get("contract", [""])[0]).strip()
chain = (q.get("chain", ["base"])[0]).strip()
if not contract.startswith("0x") or len(contract) != 42:
return {"error": "invalid_contract", "expected": "0x... 20-byte hex"}
rpc_url = "https://base.drpc.org" if chain == "base" else "https://eth.drpc.org"
findings = []
risk_score = 0
info = {"contract": contract, "chain": chain, "ts": int(time.time())}
try:
for method, sel in (("decimals", "0x313ce567"), ("total_supply", "0x18160ddd")):
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{"to":contract,"data":sel},"latest"]}).encode()
req = Request(rpc_url, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
rd = json.loads(r.read().decode()).get("result")
if rd and rd != "0x":
info[method] = int(rd, 16)
for field, sel in (("name", "0x06fdde03"), ("symbol", "0x95d89b41")):
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{"to":contract,"data":sel},"latest"]}).encode()
req = Request(rpc_url, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
rd = json.loads(r.read().decode()).get("result")
if rd and len(rd) >= 130:
hs = rd[2:]
if len(hs) >= 128:
sl = int(hs[64:128], 16)
if 0 < sl < 256:
try:
info[field] = bytes.fromhex(hs[128:128+sl*2]).decode("utf8", errors="ignore").strip("\x00")
except Exception: pass
owner_sel = "0x8da5cb5b"
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{"to":contract,"data":owner_sel},"latest"]}).encode()
req = Request(rpc_url, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
rd = json.loads(r.read().decode()).get("result")
if rd and rd != "0x" and len(rd) >= 66:
owner = "0x" + rd[-40:]
if owner != "0x" + "0" * 40:
info["owner"] = owner
findings.append({"flag": "has_owner", "severity": "info", "detail": "Contract has an owner address"})
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}).encode()
req = Request(rpc_url, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=10) as r:
cur = int(json.loads(r.read().decode())["result"], 16)
from_block = max(0, cur - 5000)
log_filter = {"fromBlock":hex(from_block),"toBlock":hex(cur),"address":contract,"topics":["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]}
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_getLogs","params":[log_filter]}).encode()
req = Request(rpc_url, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
with urlopen(req, timeout=20) as r:
logs = json.loads(r.read().decode()).get("result") or []
holders = {}
for log in logs:
if len(log.get("topics", [])) < 3: continue
frm = "0x" + log["topics"][1][-40:]
to = "0x" + log["topics"][2][-40:]
val = int(log.get("data", "0x0"), 16)
holders[frm] = holders.get(frm, 0) - val
holders[to] = holders.get(to, 0) + val
total = sum(max(0, v) for v in holders.values())
info["transfer_count"] = len(logs)
info["unique_addresses"] = len(holders)
if total > 0:
top_holder = max(holders.values())
top_pct = top_holder / total * 100
info["top_holder_pct"] = round(top_pct, 2)
if top_pct > 50:
findings.append({"flag": "concentrated_ownership", "severity": "high", "detail": f"Top holder owns {top_pct:.1f}% of supply"})
risk_score += 30
elif top_pct > 20:
findings.append({"flag": "moderate_concentration", "severity": "medium", "detail": f"Top holder owns {top_pct:.1f}% of supply"})
risk_score += 15
if risk_score == 0 and not findings:
findings.append({"flag": "no_immediate_red_flags", "severity": "info", "detail": "No high-risk patterns detected"})
if info.get("owner"):
risk_score += 5
risk_score = min(100, risk_score)
info["risk_score"] = risk_score
info["risk_level"] = "low" if risk_score < 30 else "medium" if risk_score < 60 else "high"
info["findings"] = findings
return info
except Exception as e:
return {"error": "audit_failed", "detail": str(e), "contract": contract, "chain": chain}
def ep_swap_quote(q):
"""Get a Uniswap V3 quote for swapping tokens on Base.
Query: token_in, token_out, amount_in (in wei), [fee=3000]"""
token_in = (q.get("token_in", [""])[0]).strip()
token_out = (q.get("token_out", [""])[0]).strip()
try:
fee = int(q.get("fee", ["3000"])[0])
amount_in = int(q.get("amount_in", ["0"])[0])
except:
return {"error": "invalid_params"}
if not all([token_in.startswith("0x"), token_out.startswith("0x"), len(token_in) == 42, len(token_out) == 42, amount_in > 0]):
return {"error": "missing_params", "required": ["token_in (0x...)", "token_out (0x...)", "amount_in (wei)"]}
quoter = "0xb27308f9F90F607684bbF5c6402d072838B0B10A" # Uniswap V3 quoter on Base
rpc_url = "https://base.drpc.org"
def encode_addr(a):
return a.lower().replace("0x", "").zfill(64)
data = "0xf7729d43" + encode_addr(token_in) + encode_addr(token_out) + format(fee, "x").zfill(64) + format(amount_in, "x").zfill(64) + "00" * 32
body = json.dumps({"jsonrpc":"2.0","id":1,"method":"eth_call","params":[{"to":quoter,"data":data},"latest"]}).encode()
req = Request(rpc_url, data=body, headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0"})
try:
with urlopen(req, timeout=15) as r:
result = json.loads(r.read().decode())
if "error" in result:
return {"error": "quoter_failed", "detail": str(result["error"])}
amount_out = int(result.get("result", "0x0"), 16)
return {"token_in": token_in, "token_out": token_out, "amount_in": str(amount_in), "amount_out": str(amount_out), "fee": fee, "chain": "base", "ts": int(time.time())}
except Exception as e:
return {"error": "quote_failed", "detail": str(e)}
def ep_research(q):
"""Generate a research brief on any crypto topic.
Query: topic (required), [symbol=bitcoin]"""
topic = (q.get("topic", [""])[0]).strip()
symbol = (q.get("symbol", ["bitcoin"])[0]).strip()
if not topic:
return {"error": "missing_topic"}
brief = {"topic": topic, "symbol": symbol, "ts": int(time.time()), "sections": {}}
try:
req = Request(f"https://api.coingecko.com/api/v3/simple/price?ids={symbol}&vs_currencies=usd&include_24hr_change=true&include_market_cap=true", headers={"User-Agent":"moneyapi/1.0"})
with urlopen(req, timeout=10) as r:
brief["sections"]["price"] = json.loads(r.read().decode())
except Exception as e:
brief["sections"]["price_error"] = str(e)
try:
req = Request(f"https://en.wikipedia.org/api/rest_v1/page/summary/{urllib.parse.quote(topic.replace(chr(32), chr(95)))}", headers={"User-Agent":"moneyapi/1.0"})
with urlopen(req, timeout=10) as r:
d = json.loads(r.read().decode())
brief["sections"]["context"] = {"title": d.get("title"), "extract": (d.get("extract") or "")[:500], "url": d.get("content_urls",{}).get("desktop",{}).get("page")}
except Exception as e:
brief["sections"]["context_error"] = str(e)
try:
req = Request("https://api.alternative.me/fng/", headers={"User-Agent":"moneyapi/1.0"})
with urlopen(req, timeout=10) as r:
d = json.loads(r.read().decode())
brief["sections"]["sentiment"] = d.get("data", [{}])[0]
except Exception as e:
brief["sections"]["sentiment_error"] = str(e)
md = f"# Research Brief: {topic}\n\n_Generated: {time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime())}_\n\n"
if "price" in brief["sections"] and isinstance(brief["sections"]["price"], dict):
p = brief["sections"]["price"].get(symbol, {})
if p:
md += f"## Price\n\n- USD: ${p.get('usd', '?')}\n- 24h change: {p.get('usd_24h_change', 0):.2f}%\n- Market cap: ${p.get('usd_market_cap', 0):,.0f}\n\n"
if "context" in brief["sections"] and isinstance(brief["sections"]["context"], dict):
ctx = brief["sections"]["context"]
md += f"## Background\n\n{ctx.get('extract', '')}\n\n"
if ctx.get("url"):
md += f"Source: {ctx['url']}\n\n"
if "sentiment" in brief["sections"] and isinstance(brief["sections"]["sentiment"], dict):
s = brief["sections"]["sentiment"]
md += f"## Market Sentiment\n\nFear & Greed Index: **{s.get('value', '?')}** ({s.get('value_classification', '?')})\n\n"
brief["markdown"] = md
return brief
def ep_meme_analyze(q):
"""Memecoin launch risk analyzer. Returns risk score for a token.
Query: contract (required)"""
contract = (q.get("contract", [""])[0]).strip()
if not contract.startswith("0x") or len(contract) != 42:
return {"error": "invalid_contract"}
audit = ep_security_audit(q)
if "error" in audit:
return audit