-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathwrtc_bridge_blueprint.py.bak_dns
More file actions
721 lines (610 loc) · 23.9 KB
/
wrtc_bridge_blueprint.py.bak_dns
File metadata and controls
721 lines (610 loc) · 23.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
"""
BoTTube wRTC Bridge — Solana SPL Token ↔ Platform RTC Credits
Deposit wRTC from Solana wallet → credit rtc_balance (activates tipping).
Withdraw rtc_balance → send wRTC to user's Solana wallet.
Blueprint pattern matches paypal_packages.py / usdc_blueprint.py.
"""
import json
import os
import subprocess
import sqlite3
import time
import requests as http_requests
from flask import Blueprint, request, jsonify, g, render_template
# ---------------------------------------------------------------------------
# CONFIGURATION
# ---------------------------------------------------------------------------
SOLANA_RPC = os.environ.get("SOLANA_RPC", "https://api.mainnet-beta.solana.com")
WRTC_MINT = "12TAdKXxcGf6oCv4rqDz2NkgxjyHq6HQKoxKZYGf5i4X"
WRTC_DECIMALS = 6
RESERVE_WALLET = "3n7RJanhRghRzW2PBg1UbkV9syiod8iUMugTvLzwTRkW"
RAYDIUM_SWAP_URL = (
"https://raydium.io/swap/"
"?inputMint=sol"
"&outputMint=12TAdKXxcGf6oCv4rqDz2NkgxjyHq6HQKoxKZYGf5i4X"
)
MIN_DEPOSIT = 1.0 # Minimum 1 wRTC deposit
MIN_WITHDRAW = 10.0 # Minimum 10 wRTC withdrawal
WITHDRAW_FEE = 0.5 # 0.5 wRTC flat fee per withdrawal
WITHDRAW_COOLDOWN = 3600 # 1 hour between withdrawals per user
ADMIN_KEY = os.environ.get("BOTTUBE_ADMIN_KEY", "")
# Path to Node.js withdrawal helper
SEND_WRTC_SCRIPT = os.path.join(os.path.dirname(__file__), "send_wrtc.mjs")
# ---------------------------------------------------------------------------
# BLUEPRINT
# ---------------------------------------------------------------------------
wrtc_bp = Blueprint("wrtc_bridge", __name__)
# ---------------------------------------------------------------------------
# DATABASE
# ---------------------------------------------------------------------------
WRTC_SCHEMA = """
CREATE TABLE IF NOT EXISTS wrtc_deposits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tx_signature TEXT UNIQUE NOT NULL,
from_address TEXT NOT NULL,
amount_wrtc REAL NOT NULL,
agent_id INTEGER,
status TEXT DEFAULT 'credited',
created_at REAL NOT NULL,
FOREIGN KEY (agent_id) REFERENCES agents(id)
);
CREATE TABLE IF NOT EXISTS wrtc_withdrawals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id INTEGER NOT NULL,
amount_wrtc REAL NOT NULL,
fee_wrtc REAL NOT NULL,
net_wrtc REAL NOT NULL,
to_address TEXT NOT NULL,
tx_signature TEXT,
status TEXT DEFAULT 'pending',
created_at REAL NOT NULL,
completed_at REAL,
FOREIGN KEY (agent_id) REFERENCES agents(id)
);
CREATE INDEX IF NOT EXISTS idx_wrtc_deposits_agent ON wrtc_deposits(agent_id);
CREATE INDEX IF NOT EXISTS idx_wrtc_deposits_tx ON wrtc_deposits(tx_signature);
CREATE INDEX IF NOT EXISTS idx_wrtc_withdrawals_agent ON wrtc_withdrawals(agent_id);
CREATE INDEX IF NOT EXISTS idx_wrtc_withdrawals_status ON wrtc_withdrawals(status);
"""
def init_wrtc_tables(db_or_path=None):
"""Create wRTC bridge tables. Accepts sqlite3.Connection or path string."""
if db_or_path is None:
db_or_path = "/root/bottube/bottube.db"
if isinstance(db_or_path, str):
conn = sqlite3.connect(db_or_path)
own = True
else:
conn = db_or_path
own = False
conn.executescript(WRTC_SCHEMA)
cursor = conn.execute("PRAGMA table_info(wrtc_deposits)")
existing_cols = {row[1] for row in cursor.fetchall()}
if "status" not in existing_cols:
conn.execute("ALTER TABLE wrtc_deposits ADD COLUMN status TEXT DEFAULT 'credited'")
conn.commit()
if own:
conn.close()
# ---------------------------------------------------------------------------
# HELPERS
# ---------------------------------------------------------------------------
def _get_db():
"""Get database connection from Flask g context (matches main app pattern)."""
if "db" not in g:
g.db = sqlite3.connect("/root/bottube/bottube.db")
g.db.row_factory = sqlite3.Row
g.db.execute("PRAGMA journal_mode=WAL")
g.db.execute("PRAGMA foreign_keys=ON")
return g.db
def _get_authenticated_agent():
"""Get agent from session (web UI) or X-API-Key header."""
# Web session
if g.get("user"):
return dict(g.user)
# API key
api_key = request.headers.get("X-API-Key", "")
if api_key:
db = _get_db()
row = db.execute(
"SELECT * FROM agents WHERE api_key = ?", (api_key,)
).fetchone()
if row:
return dict(row)
return None
def _is_admin():
"""Check if request has valid admin key."""
key = request.headers.get("X-Admin-Key", "") or request.args.get("key", "")
return key and key == ADMIN_KEY
def _award_rtc(db, agent_id: int, amount: float, reason: str, video_id: str = ""):
"""Credit RTC to an agent's balance and log earning (mirrors bottube_server.award_rtc)."""
db.execute(
"UPDATE agents SET rtc_balance = rtc_balance + ? WHERE id = ?",
(amount, agent_id),
)
db.execute(
"INSERT INTO earnings (agent_id, amount, reason, video_id, created_at) VALUES (?, ?, ?, ?, ?)",
(agent_id, amount, reason, video_id, time.time()),
)
def _debit_rtc(db, agent_id: int, amount: float):
"""Debit RTC from an agent's balance. Returns True if sufficient funds."""
row = db.execute("SELECT rtc_balance FROM agents WHERE id = ?", (agent_id,)).fetchone()
if not row or row["rtc_balance"] < amount:
return False
db.execute(
"UPDATE agents SET rtc_balance = rtc_balance - ? WHERE id = ?",
(amount, agent_id),
)
return True
# ---------------------------------------------------------------------------
# SOLANA TX VERIFICATION
# ---------------------------------------------------------------------------
def verify_solana_deposit(tx_signature: str):
"""
Verify a Solana transaction is a valid wRTC deposit to our reserve wallet.
Returns (info_dict, error_string). On success info_dict is populated and
error_string is None. On failure info_dict is None.
"""
try:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "getTransaction",
"params": [
tx_signature,
{"encoding": "jsonParsed", "maxSupportedTransactionVersion": 0}
],
}
resp = http_requests.post(SOLANA_RPC, json=payload, timeout=30)
if not resp.ok:
return None, f"Solana RPC error: HTTP {resp.status_code}"
result = resp.json().get("result")
if not result:
return None, "Transaction not found — it may still be confirming. Try again in a minute."
# Check confirmation
meta = result.get("meta", {})
if meta.get("err"):
return None, f"Transaction failed on-chain: {meta['err']}"
# Walk through inner + outer instructions looking for transferChecked
all_instructions = []
tx = result.get("transaction", {})
msg = tx.get("message", {})
all_instructions.extend(msg.get("instructions", []))
for inner in meta.get("innerInstructions", []):
all_instructions.extend(inner.get("instructions", []))
for ix in all_instructions:
parsed = ix.get("parsed")
if not parsed:
continue
ix_type = parsed.get("type", "")
info = parsed.get("info", {})
# Match transferChecked (standard for SPL tokens with decimals)
if ix_type == "transferChecked":
if info.get("mint") != WRTC_MINT:
continue
token_amount = info.get("tokenAmount", {})
ui_amount = float(token_amount.get("uiAmount", 0))
dest_ata = info.get("destination", "")
source_ata = info.get("source", "")
authority = info.get("authority", "")
# Verify destination is our reserve wallet's ATA
if not _is_reserve_ata(dest_ata):
continue
return {
"tx_signature": tx_signature,
"from_address": authority,
"from_ata": source_ata,
"to_ata": dest_ata,
"amount_wrtc": ui_amount,
"slot": result.get("slot"),
}, None
# Also match plain "transfer" (some wallets use this)
if ix_type == "transfer" and ix.get("program") == "spl-token":
dest_ata = info.get("destination", "")
source_ata = info.get("source", "")
authority = info.get("authority", "")
raw_amount = int(info.get("amount", 0))
ui_amount = raw_amount / (10 ** WRTC_DECIMALS)
if not _is_reserve_ata(dest_ata):
continue
# For plain transfer, we need to verify the token account holds wRTC
if _verify_token_account_mint(dest_ata):
return {
"tx_signature": tx_signature,
"from_address": authority,
"from_ata": source_ata,
"to_ata": dest_ata,
"amount_wrtc": ui_amount,
"slot": result.get("slot"),
}, None
return None, "No wRTC transfer to reserve wallet found in this transaction."
except http_requests.Timeout:
return None, "Solana RPC timeout — try again."
except Exception as e:
return None, f"Verification error: {str(e)}"
# Cache the reserve ATA address (it's deterministic and never changes)
_reserve_ata_cache = None
def _get_reserve_ata():
"""Get the Associated Token Account for our reserve wallet + wRTC mint."""
global _reserve_ata_cache
if _reserve_ata_cache:
return _reserve_ata_cache
try:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "getTokenAccountsByOwner",
"params": [
RESERVE_WALLET,
{"mint": WRTC_MINT},
{"encoding": "jsonParsed"}
],
}
resp = http_requests.post(SOLANA_RPC, json=payload, timeout=15)
data = resp.json().get("result", {}).get("value", [])
if data:
_reserve_ata_cache = data[0]["pubkey"]
return _reserve_ata_cache
except Exception:
pass
return None
def _is_reserve_ata(account_address: str) -> bool:
"""Check if a token account belongs to our reserve wallet."""
ata = _get_reserve_ata()
if ata and account_address == ata:
return True
# Fallback: query the account owner
return _check_account_owner(account_address, RESERVE_WALLET)
def _check_account_owner(token_account: str, expected_owner: str) -> bool:
"""Check if a token account is owned by the expected wallet."""
try:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "getAccountInfo",
"params": [token_account, {"encoding": "jsonParsed"}],
}
resp = http_requests.post(SOLANA_RPC, json=payload, timeout=10)
info = resp.json().get("result", {}).get("value", {})
if not info:
return False
parsed = info.get("data", {}).get("parsed", {}).get("info", {})
return parsed.get("owner", "").lower() == expected_owner.lower()
except Exception:
return False
def _verify_token_account_mint(token_account: str) -> bool:
"""Verify that a token account holds wRTC tokens."""
try:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "getAccountInfo",
"params": [token_account, {"encoding": "jsonParsed"}],
}
resp = http_requests.post(SOLANA_RPC, json=payload, timeout=10)
info = resp.json().get("result", {}).get("value", {})
if not info:
return False
parsed = info.get("data", {}).get("parsed", {}).get("info", {})
return parsed.get("mint", "") == WRTC_MINT
except Exception:
return False
# ---------------------------------------------------------------------------
# API ENDPOINTS
# ---------------------------------------------------------------------------
@wrtc_bp.route("/api/bridge/info", methods=["GET"])
def bridge_info():
"""Public endpoint — token info, fees, links."""
balance = None
try:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "getTokenAccountsByOwner",
"params": [
RESERVE_WALLET,
{"mint": WRTC_MINT},
{"encoding": "jsonParsed"},
],
}
resp = http_requests.post(SOLANA_RPC, json=payload, timeout=10)
accounts = resp.json().get("result", {}).get("value", [])
if accounts:
parsed = accounts[0]["account"]["data"]["parsed"]["info"]
balance = float(parsed["tokenAmount"]["uiAmount"])
except Exception:
pass
return jsonify({
"ok": True,
"token": {
"name": "Wrapped RustChain Token",
"symbol": "wRTC",
"mint": WRTC_MINT,
"decimals": WRTC_DECIMALS,
"total_supply": 8_300_000,
},
"reserve_wallet": RESERVE_WALLET,
"reserve_balance_wrtc": balance,
"swap_url": RAYDIUM_SWAP_URL,
"fees": {
"deposit_fee": 0,
"withdraw_fee": WITHDRAW_FEE,
"min_deposit": MIN_DEPOSIT,
"min_withdraw": MIN_WITHDRAW,
},
})
@wrtc_bp.route("/api/bridge/deposit", methods=["POST"])
def bridge_deposit():
"""
Verify a Solana TX and credit the user's rtc_balance.
POST /api/bridge/deposit
{
"tx_signature": "5abc..."
}
Auth: session (web) or X-API-Key header.
"""
agent = _get_authenticated_agent()
if not agent:
return jsonify({"error": "Login required"}), 401
data = request.get_json(silent=True) or {}
tx_sig = (data.get("tx_signature") or "").strip()
if not tx_sig:
return jsonify({"error": "tx_signature required"}), 400
if len(tx_sig) < 60 or len(tx_sig) > 120:
return jsonify({"error": "Invalid transaction signature format"}), 400
db = _get_db()
# Dedup check
existing = db.execute(
"SELECT id FROM wrtc_deposits WHERE tx_signature = ?", (tx_sig,)
).fetchone()
if existing:
return jsonify({"error": "This transaction has already been claimed"}), 409
# Verify on-chain
info, err = verify_solana_deposit(tx_sig)
if err:
return jsonify({"error": err}), 400
amount = info["amount_wrtc"]
if amount < MIN_DEPOSIT:
return jsonify({
"error": f"Minimum deposit is {MIN_DEPOSIT} wRTC (got {amount})"
}), 400
# Credit balance
_award_rtc(db, agent["id"], amount, "bridge_deposit")
# Record deposit
db.execute(
"INSERT INTO wrtc_deposits (tx_signature, from_address, amount_wrtc, agent_id, status, created_at) "
"VALUES (?, ?, ?, ?, 'credited', ?)",
(tx_sig, info["from_address"], amount, agent["id"], time.time()),
)
db.commit()
# Get updated balance
updated = db.execute(
"SELECT rtc_balance FROM agents WHERE id = ?", (agent["id"],)
).fetchone()
return jsonify({
"ok": True,
"credited": amount,
"new_balance": round(updated["rtc_balance"], 6) if updated else amount,
"tx_signature": tx_sig,
"from_address": info["from_address"],
})
@wrtc_bp.route("/api/bridge/withdraw", methods=["POST"])
def bridge_withdraw():
"""
Queue a wRTC withdrawal to user's Solana address.
POST /api/bridge/withdraw
{
"amount": 50.0,
"sol_address": "ABC..."
}
"""
agent = _get_authenticated_agent()
if not agent:
return jsonify({"error": "Login required"}), 401
data = request.get_json(silent=True) or {}
amount = float(data.get("amount", 0))
sol_address = (data.get("sol_address") or "").strip()
if not sol_address or len(sol_address) < 32 or len(sol_address) > 50:
return jsonify({"error": "Valid Solana wallet address required"}), 400
if amount < MIN_WITHDRAW:
return jsonify({
"error": f"Minimum withdrawal is {MIN_WITHDRAW} wRTC"
}), 400
total_debit = amount # We debit the full amount, fee comes from it
net = amount - WITHDRAW_FEE
if net <= 0:
return jsonify({"error": "Amount too small after fee"}), 400
db = _get_db()
# Rate limit: 1 withdrawal per hour
recent = db.execute(
"SELECT created_at FROM wrtc_withdrawals WHERE agent_id = ? ORDER BY created_at DESC LIMIT 1",
(agent["id"],),
).fetchone()
if recent and (time.time() - recent["created_at"]) < WITHDRAW_COOLDOWN:
wait = int(WITHDRAW_COOLDOWN - (time.time() - recent["created_at"]))
return jsonify({
"error": f"Withdrawal cooldown — try again in {wait // 60} minutes"
}), 429
# Debit balance
if not _debit_rtc(db, agent["id"], total_debit):
return jsonify({"error": "Insufficient balance"}), 400
# Record withdrawal as pending
db.execute(
"INSERT INTO wrtc_withdrawals (agent_id, amount_wrtc, fee_wrtc, net_wrtc, to_address, status, created_at) "
"VALUES (?, ?, ?, ?, ?, 'pending', ?)",
(agent["id"], amount, WITHDRAW_FEE, net, sol_address, time.time()),
)
db.commit()
# Log the debit as a negative earning
db.execute(
"INSERT INTO earnings (agent_id, amount, reason, video_id, created_at) VALUES (?, ?, ?, '', ?)",
(agent["id"], -amount, "bridge_withdrawal", time.time()),
)
db.commit()
return jsonify({
"ok": True,
"amount": amount,
"fee": WITHDRAW_FEE,
"net": round(net, 6),
"to_address": sol_address,
"status": "pending",
"message": "Withdrawal queued. Processing usually completes within 1 hour.",
})
@wrtc_bp.route("/api/bridge/history", methods=["GET"])
def bridge_history():
"""Get deposit/withdrawal history for the authenticated user."""
agent = _get_authenticated_agent()
if not agent:
return jsonify({"error": "Login required"}), 401
db = _get_db()
deposits = db.execute(
"SELECT tx_signature, from_address, amount_wrtc, status, created_at "
"FROM wrtc_deposits WHERE agent_id = ? ORDER BY created_at DESC LIMIT 50",
(agent["id"],),
).fetchall()
withdrawals = db.execute(
"SELECT amount_wrtc, fee_wrtc, net_wrtc, to_address, tx_signature, status, created_at, completed_at "
"FROM wrtc_withdrawals WHERE agent_id = ? ORDER BY created_at DESC LIMIT 50",
(agent["id"],),
).fetchall()
return jsonify({
"ok": True,
"deposits": [
{
"tx_signature": d["tx_signature"],
"from_address": d["from_address"],
"amount": d["amount_wrtc"],
"status": d["status"],
"created_at": d["created_at"],
}
for d in deposits
],
"withdrawals": [
{
"amount": w["amount_wrtc"],
"fee": w["fee_wrtc"],
"net": w["net_wrtc"],
"to_address": w["to_address"],
"tx_signature": w["tx_signature"],
"status": w["status"],
"created_at": w["created_at"],
"completed_at": w["completed_at"],
}
for w in withdrawals
],
})
@wrtc_bp.route("/api/bridge/process-withdrawals", methods=["POST"])
def process_withdrawals():
"""
Admin endpoint: process pending withdrawals by sending wRTC on-chain.
POST /api/bridge/process-withdrawals
X-Admin-Key: <key>
"""
if not _is_admin():
return jsonify({"error": "Unauthorized"}), 401
db = _get_db()
pending = db.execute(
"SELECT id, agent_id, net_wrtc, to_address FROM wrtc_withdrawals "
"WHERE status = 'pending' ORDER BY created_at ASC LIMIT 10"
).fetchall()
if not pending:
return jsonify({"ok": True, "processed": 0, "message": "No pending withdrawals"})
results = []
for w in pending:
wid = w["id"]
try:
result = subprocess.run(
[
"node", SEND_WRTC_SCRIPT,
"--to", w["to_address"],
"--amount", str(w["net_wrtc"]),
],
capture_output=True,
text=True,
timeout=90,
cwd=os.path.dirname(SEND_WRTC_SCRIPT),
)
if result.returncode != 0:
error_msg = result.stderr.strip() or result.stdout.strip() or "Unknown error"
results.append({"id": wid, "ok": False, "error": error_msg})
db.execute(
"UPDATE wrtc_withdrawals SET status = 'failed' WHERE id = ?",
(wid,),
)
# Refund the agent
db.execute(
"UPDATE agents SET rtc_balance = rtc_balance + ? WHERE id = ?",
(w["net_wrtc"] + WITHDRAW_FEE, w["agent_id"]),
)
continue
out = json.loads(result.stdout.strip())
if out.get("ok"):
tx_sig = out.get("tx", "")
db.execute(
"UPDATE wrtc_withdrawals SET status = 'completed', tx_signature = ?, completed_at = ? WHERE id = ?",
(tx_sig, time.time(), wid),
)
results.append({"id": wid, "ok": True, "tx": tx_sig})
else:
err = out.get("error", "Send failed")
results.append({"id": wid, "ok": False, "error": err})
db.execute(
"UPDATE wrtc_withdrawals SET status = 'failed' WHERE id = ?",
(wid,),
)
# Refund
db.execute(
"UPDATE agents SET rtc_balance = rtc_balance + ? WHERE id = ?",
(w["net_wrtc"] + WITHDRAW_FEE, w["agent_id"]),
)
except subprocess.TimeoutExpired:
results.append({"id": wid, "ok": False, "error": "Timeout"})
except Exception as e:
results.append({"id": wid, "ok": False, "error": str(e)})
db.commit()
return jsonify({
"ok": True,
"processed": len(results),
"results": results,
})
@wrtc_bp.route("/api/bridge/stats", methods=["GET"])
def bridge_stats():
"""Public stats — total deposits, withdrawals, volume."""
db = _get_db()
dep = db.execute(
"SELECT COUNT(*), COALESCE(SUM(amount_wrtc), 0) FROM wrtc_deposits WHERE status = 'credited'"
).fetchone()
wd = db.execute(
"SELECT COUNT(*), COALESCE(SUM(net_wrtc), 0), COALESCE(SUM(fee_wrtc), 0) "
"FROM wrtc_withdrawals WHERE status = 'completed'"
).fetchone()
return jsonify({
"ok": True,
"deposits": {"count": dep[0], "total_wrtc": round(dep[1], 6)},
"withdrawals": {"count": wd[0], "total_wrtc": round(wd[1], 6), "total_fees": round(wd[2], 6)},
})
# ---------------------------------------------------------------------------
# PAGE ROUTES (HTML)
# ---------------------------------------------------------------------------
@wrtc_bp.route("/bridge")
@wrtc_bp.route("/bridge/wrtc")
@wrtc_bp.route("/bridge/ergo")
@wrtc_bp.route("/bridge/btc")
@wrtc_bp.route("/bridge/ltc")
@wrtc_bp.route("/bridge/doge")
def bridge_page():
"""Render the multi-chain Bridge page (wRTC, ERG, BTC, LTC, DOGE)."""
import os as _os
user_balance = 0
user_sol = ""
if g.user:
user_balance = g.user.get("rtc_balance", 0) or 0
user_sol = g.user.get("sol_address", "") or ""
ergo_addr = _os.environ.get("ERGO_PLATFORM_ADDRESS", "")
return render_template(
"bridge.html",
user_balance=round(user_balance, 6),
user_sol_address=user_sol,
reserve_wallet=RESERVE_WALLET,
swap_url=RAYDIUM_SWAP_URL,
wrtc_mint=WRTC_MINT,
ergo_address=ergo_addr,
)