-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
4598 lines (4081 loc) · 188 KB
/
Copy pathapp.js
File metadata and controls
4598 lines (4081 loc) · 188 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
import { createAppKit } from "https://esm.sh/@reown/appkit@1.8.20";
import { EthersAdapter } from "https://esm.sh/@reown/appkit-adapter-ethers@1.8.20";
import { defineChain } from "https://esm.sh/@reown/appkit@1.8.20/networks";
import { ethers } from "https://esm.sh/ethers@6.16.0";
const LUST_CHAIN_ID_DECIMAL = 6923;
const LUST_CHAIN_ID_HEX = "0x1b0b";
const LUST_REOWN_PROJECT_ID = "abda6475ac4aba59197da882facababc";
const lustNetwork = defineChain({
id: LUST_CHAIN_ID_DECIMAL,
caipNetworkId: "eip155:6923",
chainNamespace: "eip155",
name: "LUST Chain",
nativeCurrency: { decimals: 18, name: "LST", symbol: "LST" },
rpcUrls: {
default: { http: ["https://rpc.lustchain.org"] },
public: { http: ["https://rpc.lustchain.org"] }
},
blockExplorers: {
default: { name: "LUST Explorer", url: "https://explorer.lustchain.org" }
}
});
const ethereumNetwork = defineChain({
id: 1,
caipNetworkId: "eip155:1",
chainNamespace: "eip155",
name: "Ethereum",
nativeCurrency: { decimals: 18, name: "Ether", symbol: "ETH" },
rpcUrls: {
default: { http: ["https://ethereum-rpc.publicnode.com"] },
public: { http: ["https://ethereum-rpc.publicnode.com"] }
},
blockExplorers: {
default: { name: "Etherscan", url: "https://etherscan.io" }
}
});
const polygonNetwork = defineChain({
id: 137,
caipNetworkId: "eip155:137",
chainNamespace: "eip155",
name: "Polygon",
nativeCurrency: { decimals: 18, name: "POL", symbol: "POL" },
rpcUrls: {
default: { http: ["https://polygon-rpc.com"] },
public: { http: ["https://polygon-rpc.com"] }
},
blockExplorers: {
default: { name: "PolygonScan", url: "https://polygonscan.com" }
}
});
const bscNetwork = defineChain({
id: 56,
caipNetworkId: "eip155:56",
chainNamespace: "eip155",
name: "BNB Smart Chain",
nativeCurrency: { decimals: 18, name: "BNB", symbol: "BNB" },
rpcUrls: {
default: { http: ["https://bsc-rpc.publicnode.com"] },
public: { http: ["https://bsc-rpc.publicnode.com"] }
},
blockExplorers: {
default: { name: "BscScan", url: "https://bscscan.com" }
}
});
const appKit = createAppKit({
adapters: [new EthersAdapter()],
networks: [lustNetwork, ethereumNetwork, polygonNetwork, bscNetwork],
defaultNetwork: lustNetwork,
defaultAccountTypes: { eip155: "eoa" },
projectId: LUST_REOWN_PROJECT_ID,
metadata: {
name: "LUST Platform",
description: "Official LUST Chain platform",
url: window.location.origin,
icons: [`${window.location.origin}/icon.png`]
},
customRpcUrls: {
"eip155:6923": [{ url: "https://rpc.lustchain.org" }],
"eip155:1": [{ url: "https://ethereum-rpc.publicnode.com" }],
"eip155:137": [{ url: "https://polygon-bor-rpc.publicnode.com" }],
"eip155:56": [{ url: "https://bsc-rpc.publicnode.com" }]
},
themeMode: "dark",
themeVariables: {
"--w3m-accent": "#f70375",
"--w3m-border-radius-master": "12px"
},
allWallets: "SHOW",
enableWallets: true,
enableWalletGuide: true,
enableNetworkSwitch: true,
enableReconnect: true,
enableMobileFullScreen: true,
allowUnsupportedChain: true,
enableCoinbase: true,
coinbasePreference: "eoaOnly",
features: {
analytics: true,
email: false,
socials: false,
swaps: false,
onramp: false,
connectMethodsOrder: ["wallet"]
}
});
window.lustAppKit = appKit;
let walletState = { address: "", chainId: "", connected: false };
function normalizeChainId(value) {
if (value === null || value === undefined || value === "") return "";
if (typeof value === "number" && Number.isFinite(value)) return `0x${value.toString(16)}`;
const raw = String(value).trim().toLowerCase();
if (!raw) return "";
if (raw.startsWith("0x")) return raw;
if (raw.startsWith("eip155:")) {
const parsed = Number(raw.replace("eip155:", ""));
return Number.isFinite(parsed) ? `0x${parsed.toString(16)}` : "";
}
const parsed = Number(raw);
return Number.isFinite(parsed) ? `0x${parsed.toString(16)}` : raw;
}
function shortAddress(address) {
return address ? `${address.slice(0, 6)}...${address.slice(-4)}` : "Connect wallet";
}
function disconnectedHtml() {
return `
<div class="connect-icon">◫</div>
<div class="connect-copy">
<strong>Connect wallet</strong>
<span>Wallet not connected</span>
</div>
<div class="connect-caret">⌄</div>
`;
}
function connectedHtml() {
const normalized = normalizeChainId(walletState.chainId);
const isBridgePage = Boolean(document.querySelector("[data-lusdt-bridge]"));
const allowedBridgeChains = new Set([LUST_CHAIN_ID_HEX, "0x89", "0x38"]);
const ready = isBridgePage ? allowedBridgeChains.has(normalized) : normalized === LUST_CHAIN_ID_HEX;
const label = normalized === LUST_CHAIN_ID_HEX ? "LUST CHAIN · LST"
: normalized === "0x89" ? "POLYGON · USDT"
: normalized === "0x38" ? "BSC · USDT"
: isBridgePage ? "SELECT BRIDGE NETWORK" : "SWITCH TO LUST CHAIN";
return `
<div class="connect-icon ${ready ? "ready" : "warn"}">${ready ? "✓" : "!"}</div>
<div class="connect-copy">
<strong>${shortAddress(walletState.address)}</strong>
<span>${label}</span>
</div>
<div class="connect-caret">⌄</div>
`;
}
function renderWalletButton() {
document.querySelectorAll("[data-connect-wallet]").forEach((btn) => {
btn.innerHTML = walletState.connected && walletState.address ? connectedHtml() : disconnectedHtml();
});
}
function readState() {
try {
const address = appKit.getAddress?.() || "";
const chainId = normalizeChainId(appKit.getChainId?.() || "");
const connected = Boolean(appKit.getIsConnected?.() || address);
walletState = { address, chainId, connected };
} catch (err) {
console.warn(err);
}
renderWalletButton();
if (document.querySelector("[data-lusdt-bridge]")) {
setTimeout(refreshBridgeWalletUi, 60);
}
}
async function switchToLust() {
try {
await appKit.switchNetwork(lustNetwork);
} catch (err) {
console.warn("Switch rejected or failed", err);
}
setTimeout(readState, 350);
setTimeout(readState, 1200);
}
async function openLustWallet(event) {
event?.preventDefault?.();
event?.stopPropagation?.();
readState();
try {
if (walletState.connected && walletState.address) {
await appKit.open({ view: "Account" });
} else {
await appKit.open({ view: "Connect", namespace: "eip155" });
}
} catch (err) {
console.error(err);
}
setTimeout(readState, 400);
setTimeout(readState, 1200);
setTimeout(readState, 2500);
}
window.openLustWallet = openLustWallet;
appKit.subscribeProvider?.((state) => {
walletState = {
address: state?.address || appKit.getAddress?.() || "",
chainId: normalizeChainId(state?.chainId || appKit.getChainId?.() || ""),
connected: Boolean(state?.isConnected || state?.address || appKit.getIsConnected?.())
};
renderWalletButton();
if (document.querySelector("[data-lusdt-bridge]")) {
setTimeout(refreshBridgeWalletUi, 60);
}
const isBridgePage = Boolean(document.querySelector("[data-lusdt-bridge]"));
if (!isBridgePage && walletState.connected && walletState.address && normalizeChainId(walletState.chainId) !== LUST_CHAIN_ID_HEX) {
setTimeout(switchToLust, 350);
}
});
appKit.subscribeState?.(() => {
setTimeout(readState, 100);
setTimeout(readState, 900);
});
appKit.subscribeEvents?.(() => {
setTimeout(readState, 120);
setTimeout(readState, 900);
});
document.addEventListener("click", (event) => {
const btn = event.target.closest("[data-connect-wallet]");
if (btn) openLustWallet(event);
});
function bridgeCalc() {
const amountEl = document.querySelector("#bridgeAmount");
const feeEl = document.querySelector("#bridgeFee");
const receiveEl = document.querySelector("#bridgeReceive");
if (!amountEl || !feeEl || !receiveEl) return;
const amount = Number(amountEl.value || 0);
const fee = amount * 0.002;
const receive = Math.max(amount - fee, 0);
feeEl.textContent = `${fee.toFixed(4)} LUSDT`;
receiveEl.textContent = `${receive.toFixed(4)} LUSDT`;
}
document.querySelector("#bridgeAmount")?.addEventListener("input", bridgeCalc);
bridgeCalc();
document.querySelectorAll("[data-tab]").forEach((tab) => {
tab.addEventListener("click", () => {
document.querySelectorAll("[data-tab]").forEach((t) => t.classList.remove("active"));
tab.classList.add("active");
const mode = tab.getAttribute("data-tab");
const route = document.querySelector("#bridgeRoute");
if (route) {
route.textContent = mode === "buy"
? "Polygon/BSC → LUST Chain"
: "LUST Chain → Polygon/BSC";
}
});
});
renderWalletButton();
readState();
setTimeout(readState, 900);
setTimeout(readState, 2500);
// Back to top button
const backToTopButton = document.querySelector("#backToTop");
function syncBackToTopButton() {
if (!backToTopButton) return;
if (window.scrollY > 360) {
backToTopButton.classList.add("show");
} else {
backToTopButton.classList.remove("show");
}
}
backToTopButton?.addEventListener("click", () => {
window.scrollTo({ top: 0, behavior: "smooth" });
});
window.addEventListener("scroll", syncBackToTopButton, { passive: true });
syncBackToTopButton();
// LUST miner registration + mining page helpers v20260611-txfeed-v3-final
const LUST_REGISTRY_ADDRESS = "0x0000000000000000000000000000000000006923";
const LUST_REGISTER_MAGIC_V2 = "0x4c5143525f5632"; // LQCR_V2 + 20-byte operator address
const LUST_RPC_URL = "https://rpc.lustchain.org";
const LUST_EXPLORER_URL = "https://explorer.lustchain.org";
const LUST_SNAPSHOT_INFO_URL = "https://snapshot.lustchain.org/snapshot/snapshot-info.json";
const LUST_FAUCET_STATUS_URL = "https://downloads.lustchain.org/faucet/status";
const LUST_FAUCET_CLAIM_URL = "https://downloads.lustchain.org/faucet/claim";
const LUST_MINING_STATS_URL = "https://rpc.lustchain.org/mining-stats";
const LUST_PENDING_RAW_URL = "https://rpc.lustchain.org/pending-raw";
const LUST_V7A25_REGISTRY_BLOCK = 138282;
const LUST_V7A25_SIGNATURE_BLOCK = 139082;
const LUST_V7A25_AUTONOMY_BLOCK = 999999999999;
function setMinerLog(message, tone = "") {
document.querySelectorAll("[data-miner-log]").forEach((el) => {
el.textContent = message;
el.dataset.tone = tone;
});
}
function setText(selector, text) {
document.querySelectorAll(selector).forEach((el) => { el.textContent = text; });
}
function setMiningStatsLog(message, tone = "") {
document.querySelectorAll("[data-mining-stats-log]").forEach((el) => {
el.textContent = message;
el.dataset.tone = tone;
});
}
function fmtNumber(value) {
const n = Number(value || 0);
if (!Number.isFinite(n)) return "0";
return new Intl.NumberFormat("en-US").format(n);
}
function fmtAddress(value) {
return value ? shortAddress(value) : "--";
}
function getInjectedEthereum() {
return window.ethereum || null;
}
async function getBestWalletAddress() {
readState();
if (walletState.address) return walletState.address;
const eth = getInjectedEthereum();
if (!eth?.request) return "";
try {
const accounts = await eth.request({ method: "eth_accounts" });
const account = Array.isArray(accounts) && accounts.length ? accounts[0] : "";
if (account) {
walletState = { ...walletState, address: account, connected: true };
renderWalletButton();
return account;
}
} catch (_) {}
return "";
}
function localRegistrationKey(address) {
return `lustMinerRegistered:${String(address || "").toLowerCase()}`;
}
async function lustRpc(method, params = []) {
const res = await fetch(LUST_RPC_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params })
});
const json = await res.json();
if (json.error) throw new Error(json.error.message || "RPC error");
return json.result;
}
function parseRpcBlockNumber(value) {
if (typeof value === "number") return value;
const v = String(value || "").trim();
if (!v) return 0;
if (v.startsWith("0x")) return Number.parseInt(v, 16) || 0;
return Number.parseInt(v, 10) || 0;
}
async function getLustCurrentBlock() {
return parseRpcBlockNumber(await lustRpc("eth_blockNumber", []));
}
function updateV7A25GateDisplay(currentBlock) {
const block = Number(currentBlock || 0);
const remaining = Math.max(0, LUST_V7A25_REGISTRY_BLOCK - block);
const isOpen = block >= LUST_V7A25_REGISTRY_BLOCK;
setText("[data-current-block]", block > 0 ? fmtNumber(block) : "Loading...");
setText("[data-blocks-to-registry]", block > 0 ? fmtNumber(remaining) : "Loading...");
setText("[data-registration-open]", isOpen ? "Open" : `Locked until ${fmtNumber(LUST_V7A25_REGISTRY_BLOCK)}`);
setText("[data-registry-countdown-note]", isOpen ? "Registration is open now." : `Wait ${fmtNumber(remaining)} blocks before registering.`);
document.querySelectorAll("[data-register-miner]").forEach((btn) => {
btn.disabled = !isOpen;
btn.textContent = isOpen ? "Register V7A25 Miner now" : `Registration opens at block ${fmtNumber(LUST_V7A25_REGISTRY_BLOCK)}`;
btn.title = isOpen ? "Send V7A25 LQCR_V2 registration" : `Current block ${fmtNumber(block)}. Wait until ${fmtNumber(LUST_V7A25_REGISTRY_BLOCK)}.`;
});
return { block, remaining, isOpen };
}
function weiHexToLst(hexValue) {
try {
const raw = BigInt(hexValue || "0x0");
const whole = raw / 1000000000000000000n;
const frac = raw % 1000000000000000000n;
return `${whole}.${frac.toString().padStart(18, "0").slice(0, 6)} LST`;
} catch (_) {
return "--";
}
}
async function addLustChainToWallet() {
const eth = getInjectedEthereum();
if (!eth) {
setMinerLog("MetaMask or an injected wallet was not found. Install MetaMask and try again.", "warn");
return false;
}
try {
await eth.request({
method: "wallet_addEthereumChain",
params: [{
chainId: LUST_CHAIN_ID_HEX,
chainName: "LUST Chain",
nativeCurrency: { name: "LST", symbol: "LST", decimals: 18 },
rpcUrls: ["https://rpc.lustchain.org"],
blockExplorerUrls: ["https://explorer.lustchain.org"]
}]
});
await eth.request({ method: "wallet_switchEthereumChain", params: [{ chainId: LUST_CHAIN_ID_HEX }] });
setMinerLog("LUST Chain is selected in your wallet.", "ok");
setTimeout(readState, 300);
setTimeout(updateMinerPage, 700);
return true;
} catch (err) {
console.error(err);
setMinerLog(err?.message || "Could not add/switch to LUST Chain.", "warn");
return false;
}
}
async function getWalletAccount() {
const eth = getInjectedEthereum();
if (!eth) throw new Error("MetaMask or injected wallet not found.");
const accounts = await eth.request({ method: "eth_requestAccounts" });
const account = accounts?.[0] || "";
if (!account) throw new Error("No wallet account selected.");
return account;
}
async function waitForTxReceipt(txHash, timeoutMs = 180000) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const receipt = await lustRpc("eth_getTransactionReceipt", [txHash]).catch(() => null);
if (receipt) return receipt;
await new Promise((resolve) => setTimeout(resolve, 2500));
}
return null;
}
async function registerMinerWallet() {
try {
setMinerLog("Abrindo confirmação da carteira para registro V7A25...", "");
const eth = getInjectedEthereum();
if (!eth) throw new Error("MetaMask or injected wallet not found.");
const operatorInput = document.querySelector("[data-operator-address]");
const operator = String(operatorInput?.value || "").trim();
if (!/^0x[0-9a-fA-F]{40}$/.test(operator)) {
throw new Error("Cole o operator address V7A25 do operator-address.txt antes de registrar.");
}
const account = await getWalletAccount();
await addLustChainToWallet();
const chainId = normalizeChainId(await eth.request({ method: "eth_chainId" }));
if (chainId !== LUST_CHAIN_ID_HEX) {
throw new Error("Troque para LUST Chain antes de registrar.");
}
const currentBlock = await getLustCurrentBlock();
const gate = updateV7A25GateDisplay(currentBlock);
if (!gate.isOpen) {
throw new Error(`Registro V7A25 ainda bloqueado. Bloco atual ${fmtNumber(currentBlock)}. Espere o bloco ${fmtNumber(LUST_V7A25_REGISTRY_BLOCK)}. Faltam ${fmtNumber(gate.remaining)} blocos.`);
}
const registerData = `${LUST_REGISTER_MAGIC_V2}${operator.slice(2).toLowerCase()}`;
const txHash = await eth.request({
method: "eth_sendTransaction",
params: [{
from: account,
to: LUST_REGISTRY_ADDRESS,
value: "0x0",
data: registerData,
gas: "0x249f0"
}]
});
setMinerLog(`V7A25 registration sent. Waiting confirmation: ${txHash}`, "");
const receipt = await waitForTxReceipt(txHash);
if (receipt?.status === "0x1") {
localStorage.setItem(localRegistrationKey(account), JSON.stringify({ txHash, operator, mode: "LQCR_V2", time: Date.now() }));
setMinerLog(`Miner V7A25 registrado com sucesso. Operator: ${shortAddress(operator)} · Tx: ${txHash}`, "ok");
} else if (receipt) {
setMinerLog(`Registration transaction failed. Tx: ${txHash}`, "warn");
} else {
setMinerLog(`Transaction sent but confirmation is still pending. Check explorer: ${txHash}`, "warn");
}
updateMinerPage();
} catch (err) {
console.error(err);
setMinerLog(err?.message || "Registration rejected or failed.", "warn");
}
}
async function updateMinerPage() {
const hasMinerPage = document.querySelector("[data-registration-state]") || document.querySelector("[data-snapshot-block]");
if (!hasMinerPage) return;
readState();
try {
const currentBlock = await getLustCurrentBlock();
updateV7A25GateDisplay(currentBlock);
} catch (_) {
updateV7A25GateDisplay(0);
}
const address = walletState.address || "";
const chain = normalizeChainId(walletState.chainId || "");
setText("[data-connected-address]", address ? shortAddress(address) : "Not connected");
setText("[data-chain-state]", chain === LUST_CHAIN_ID_HEX ? "LUST Chain" : (address ? "Wrong network" : "Not connected"));
if (address) {
try {
const bal = await lustRpc("eth_getBalance", [address, "latest"]);
setText("[data-lust-balance]", weiHexToLst(bal));
} catch (_) {
setText("[data-lust-balance]", "--");
}
const saved = localStorage.getItem(localRegistrationKey(address));
if (saved) {
const parsed = JSON.parse(saved);
setText("[data-registration-state]", parsed.operator ? `V7A25 ${shortAddress(parsed.operator)} · ${shortAddress(parsed.txHash || "")}` : `Saved tx ${shortAddress(parsed.txHash || "")}`);
} else {
setText("[data-registration-state]", "Ready to register");
}
} else {
setText("[data-lust-balance]", "--");
setText("[data-registration-state]", "Connect wallet first");
}
try {
const snap = await fetch(LUST_SNAPSHOT_INFO_URL, { cache: "no-store" }).then((r) => r.json());
if (snap?.block) setText("[data-snapshot-block]", String(snap.block));
if (snap?.sha256) setText("[data-snapshot-sha]", snap.sha256);
} catch (_) {
// HTTP snapshot info may be blocked by HTTPS pages until final HTTPS snapshot domain is live.
}
}
function fetchJsonp(url, timeoutMs = 9000) {
return new Promise((resolve, reject) => {
const cb = `__lustJsonp_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const script = document.createElement("script");
const sep = url.includes("?") ? "&" : "?";
const timer = setTimeout(() => {
cleanup();
reject(new Error("Mining stats JSONP timeout"));
}, timeoutMs);
function cleanup() {
clearTimeout(timer);
try { delete window[cb]; } catch (_) { window[cb] = undefined; }
if (script.parentNode) script.parentNode.removeChild(script);
}
window[cb] = (data) => {
cleanup();
resolve(data);
};
script.onerror = () => {
cleanup();
reject(new Error("Mining stats JSONP failed"));
};
script.src = `${url}${sep}callback=${encodeURIComponent(cb)}&t=${Date.now()}`;
document.head.appendChild(script);
});
}
async function fetchMiningStatsLive() {
const ts = Date.now();
try {
const res = await fetch(`${LUST_MINING_STATS_URL}?t=${ts}`, { cache: "no-store", mode: "cors" });
if (!res.ok) throw new Error(`Mining stats HTTP ${res.status}`);
return await res.json();
} catch (fetchErr) {
console.warn("Mining stats fetch failed, trying JSONP fallback", fetchErr);
return await fetchJsonp("https://rpc.lustchain.org/mining-stats.js");
}
}
async function updateMiningStatsPanel() {
const hasPanel = document.querySelector("[data-mining-registered]") || document.querySelector("[data-mining-pending]");
if (!hasPanel) return;
try {
const ts = Date.now();
const [statsRes, feedRes] = await Promise.allSettled([
fetchMiningStatsLive(),
fetch(`${LUST_PENDING_RAW_URL}?t=${ts}`, { cache: "no-store", mode: "cors" }).then((r) => {
if (!r.ok) throw new Error(`TX-FEED HTTP ${r.status}`);
return r.json();
})
]);
const stats = statsRes.status === "fulfilled" ? statsRes.value : null;
const feed = feedRes.status === "fulfilled" ? feedRes.value : null;
if (!stats || stats.ok === false) throw new Error(stats?.error || statsRes.reason?.message || "Mining stats API unavailable");
setText("[data-mining-registered]", fmtNumber(stats.registeredMiners));
setText("[data-mining-active]", fmtNumber(stats.activePublicMinersLast200));
setText("[data-mining-public-blocks]", fmtNumber(stats.publicBlocksLast200));
setText("[data-mining-official-blocks]", fmtNumber(stats.officialBlocksLast200));
setText("[data-mining-last-public]", fmtAddress(stats.lastPublicMiner));
const lastPublicBlock = stats.lastPublicMinerBlock ? `Last public block: ${fmtNumber(stats.lastPublicMinerBlock)}` : "Indexer is still scanning public blocks...";
setText("[data-mining-last-public-block]", lastPublicBlock);
if (feed && feed.ok !== false) {
setText("[data-mining-pending]", fmtNumber(feed.count || 0));
} else if (stats.pendingTxCount !== undefined) {
setText("[data-mining-pending]", fmtNumber(stats.pendingTxCount));
} else {
setText("[data-mining-pending]", "0");
}
const head = Number(stats.head || 0);
const scannedTo = Number(stats.scannedTo || 0);
const pct = head > 0 ? Math.min(100, Math.max(0, (scannedTo / head) * 100)) : 0;
const progress = stats.scanComplete
? "Registry scan complete"
: `Registry scan ${pct.toFixed(1)}% · scanned ${fmtNumber(scannedTo)} / ${fmtNumber(head)} blocks`;
setText("[data-mining-scan-progress]", progress);
const updated = stats.updatedAt ? new Date(stats.updatedAt).toLocaleString() : "now";
const tone = stats.scanComplete ? "ok" : "warn";
setMiningStatsLog(`${progress} · updated ${updated} · registration txs: ${fmtNumber(stats.registrationTxs || 0)} · TX-FEED V3 active`, tone);
} catch (err) {
console.error(err);
setText("[data-mining-registered]", "--");
setText("[data-mining-active]", "--");
setText("[data-mining-public-blocks]", "--");
setText("[data-mining-official-blocks]", "--");
setText("[data-mining-last-public]", "--");
setText("[data-mining-pending]", "--");
setText("[data-mining-scan-progress]", "Mining stats API unavailable");
setMiningStatsLog(`${err?.message || "Could not load live mining stats."} · Open the API button below; if it opens, refresh with Ctrl+F5.`, "warn");
}
}
function setFaucetLog(message, tone = "") {
document.querySelectorAll("[data-faucet-log]").forEach((el) => {
el.textContent = message;
el.dataset.tone = tone;
});
}
async function updateFaucetPanel() {
const hasFaucet = document.querySelector("[data-faucet-eligibility]") || document.querySelector("[data-faucet-balance]");
if (!hasFaucet) return;
const address = await getBestWalletAddress();
const url = address ? `${LUST_FAUCET_STATUS_URL}?address=${encodeURIComponent(address)}` : LUST_FAUCET_STATUS_URL;
try {
const res = await fetch(url, { method: "GET", mode: "cors", cache: "no-store", headers: { "Accept": "application/json" } });
const json = await res.json();
if (!json.ok) throw new Error(json.message || "Faucet status failed");
setText("[data-faucet-amount]", `${json.amountLST || "0.01"} LST`);
setText("[data-faucet-balance]", `${json.faucetBalanceLST || "--"} LST`);
setText("[data-faucet-wallet-balance]", json.walletBalanceLST ? `${json.walletBalanceLST} LST` : "Connect wallet");
setText("[data-faucet-eligibility]", json.eligible ? "Eligible" : (json.reason || "Not eligible"));
if (!address) {
setFaucetLog("Connect your wallet to check faucet eligibility.", "");
} else if (json.eligible) {
setFaucetLog("Your wallet can claim 0.01 LST for its first LUST Chain transaction.", "ok");
} else {
setFaucetLog(json.reason || "This wallet is not eligible for the faucet.", "warn");
}
} catch (err) {
console.error(err);
setFaucetLog(err?.message || "Could not read faucet status. Hard refresh the page and try again.", "warn");
}
}
async function claimLustFaucet() {
try {
const eth = getInjectedEthereum();
if (!eth) throw new Error("MetaMask or injected wallet not found.");
setFaucetLog("Checking wallet and official faucet eligibility...", "");
const account = await getWalletAccount();
await addLustChainToWallet();
const res = await fetch(LUST_FAUCET_CLAIM_URL, {
method: "POST",
mode: "cors",
cache: "no-store",
headers: { "Content-Type": "application/json", "Accept": "application/json" },
body: JSON.stringify({ address: account })
});
const json = await res.json().catch(() => ({}));
if (!res.ok || !json.ok) {
throw new Error(json.message || json.reason || "Faucet claim failed.");
}
setFaucetLog(`Faucet sent ${json.amountLST || "0.01"} LST. Tx: ${json.txHash}`, "ok");
setTimeout(updateFaucetPanel, 2500);
setTimeout(updateMinerPage, 3500);
} catch (err) {
console.error(err);
setFaucetLog(err?.message || "Faucet claim rejected or failed.", "warn");
}
}
window.addLustChainToWallet = addLustChainToWallet;
window.registerMinerWallet = registerMinerWallet;
window.updateMinerPage = updateMinerPage;
window.updateFaucetPanel = updateFaucetPanel;
window.updateMiningStatsPanel = updateMiningStatsPanel;
window.claimLustFaucet = claimLustFaucet;
document.addEventListener("click", (event) => {
if (event.target.closest("[data-add-lust-chain]")) {
event.preventDefault();
addLustChainToWallet();
}
if (event.target.closest("[data-register-miner]")) {
event.preventDefault();
registerMinerWallet();
}
if (event.target.closest("[data-refresh-miner]")) {
event.preventDefault();
updateMinerPage();
updateFaucetPanel();
updateMiningStatsPanel();
}
if (event.target.closest("[data-claim-faucet]")) {
event.preventDefault();
claimLustFaucet();
}
if (event.target.closest("[data-refresh-faucet]")) {
event.preventDefault();
updateFaucetPanel();
}
});
setTimeout(updateMinerPage, 800);
setTimeout(updateFaucetPanel, 1200);
setTimeout(updateMiningStatsPanel, 1500);
setInterval(updateMinerPage, 15000);
setInterval(updateFaucetPanel, 20000);
setInterval(updateMiningStatsPanel, 15000);
// LUSDT Bridge app v20260612-lusdt-bridge-v3-cors-bsc
const LUSDT_BRIDGE_API_URL = "https://lusdt-bridge.lustchain.org";
const LUSDT_BRIDGE_API_BACKUP_URLS = ["https://lusdt-bridge.lustchain.org"];
const LUSDT_TOKEN_ADDRESS = "0x1E8636066d7e86De0A8Bd6Acb1e54BE129aC19AE";
const LUSDT_EXECUTOR_ADDRESS = "0xbBC818f161D1B7190f85bE258CDB568a5A63f380";
const LUSDT_POLYGON_LOCKBOX = "0x273cC6A72aF97381daa07332Df768a05cb30CE47";
const LUSDT_BSC_LOCKBOX = "0x273cC6A72aF97381daa07332Df768a05cb30CE47";
const POLYGON_USDT_ADDRESS = "0xc2132D05D31c914a87C6611C10748AEb04B58e8F";
const BSC_USDT_ADDRESS = "0x55d398326f99059fF775485246999027B3197955";
const BRIDGE_FEE_BPS = 20n;
const BRIDGE_CHAINS = {
lust: {
key: "lust",
chainId: 6923,
chainIdHex: "0x1b0b",
name: "LUST Chain",
nativeCurrency: { name: "LST", symbol: "LST", decimals: 18 },
rpcUrls: ["https://rpc.lustchain.org"],
blockExplorerUrls: ["https://explorer.lustchain.org"]
},
polygon: {
key: "polygon",
chainId: 137,
chainIdHex: "0x89",
name: "Polygon",
nativeCurrency: { name: "POL", symbol: "POL", decimals: 18 },
rpcUrls: ["https://polygon-bor-rpc.publicnode.com"],
blockExplorerUrls: ["https://polygonscan.com"]
},
bsc: {
key: "bsc",
chainId: 56,
chainIdHex: "0x38",
name: "BNB Smart Chain",
nativeCurrency: { name: "BNB", symbol: "BNB", decimals: 18 },
rpcUrls: ["https://bsc-rpc.publicnode.com"],
blockExplorerUrls: ["https://bscscan.com"]
}
};
const ERC20_ABI = [
"function decimals() view returns (uint8)",
"function balanceOf(address) view returns (uint256)",
"function allowance(address owner,address spender) view returns (uint256)",
"function approve(address spender,uint256 amount) returns (bool)"
];
const LOCKBOX_POLYGON_ABI = [
"function depositsEnabled() view returns (bool)",
"function usedNonce(address,uint256) view returns (bool)",
"function deposit(uint256 amount)",
"function release(address recipient,uint256 amount,uint256 nonce,uint256 deadline,bytes[] signatures)",
"event Deposited(address indexed user,uint256 amount,bytes32 indexed depositId,uint256 indexed sourceChainId,uint256 destinationChainId)"
];
const LOCKBOX_BSC_ABI = [
"function depositsEnabled() view returns (bool)",
"function usedNonce(address,uint256) view returns (bool)",
"function deposit(uint256 rawAmount18)",
"function release(address recipient,uint256 amount6,uint256 nonce,uint256 deadline,bytes[] signatures)",
"event Deposited(address indexed user,uint256 rawAmount18,uint256 normalizedAmount6,bytes32 indexed depositId,uint256 indexed sourceChainId,uint256 destinationChainId)"
];
const EXECUTOR_ABI = [
"function mintFromExternalDeposit(address recipient,uint256 amount,bytes32 depositId,uint256 sourceChainId,uint256 deadline,bytes[] signatures)",
"function burnForExternalRelease(address recipientExternal,uint256 amount,uint256 destinationChainId,uint256 nonce,uint256 deadline)",
"function quoteNetAmount(uint256 amount) view returns (uint256 fee,uint256 net)",
"function mintIdUsed(bytes32 depositId) view returns (bool)",
"event BurnRequested(address indexed burner,address indexed recipientExternal,uint256 grossAmount,uint256 netAmount,uint256 feeAmount,uint256 nonce,uint256 indexed destinationChainId,uint256 sourceChainId)"
];
let activeClaim = null;
let activeRelease = null;
let pendingBridgeClaims = [];
let pendingBridgeReleases = [];
let bridgeLiquidity = { polygon: null, bsc: null };
function bridgeLog(message, tone = "", scope = "active") {
let selector = "[data-bridge-claim-log]";
if (scope === "release") selector = "[data-bridge-release-log]";
else if (scope === "claim") selector = "[data-bridge-claim-log]";
else if (typeof activeBridgeMode === "function" && activeBridgeMode() === "withdraw") selector = "[data-bridge-release-log]";
document.querySelectorAll(selector).forEach((el) => {
el.textContent = message;
el.dataset.tone = tone;
});
}
function bridgeClaimLog(message, tone = "") {
bridgeLog(message, tone, "claim");
}
function bridgeReleaseLog(message, tone = "") {
bridgeLog(message, tone, "release");
}
function bridgeButtonBaseLabel(selector) {
if (selector.includes("deposit")) return "Deposit USDT";
if (selector.includes("mint") && selector.includes("recover")) return "Mint recovered claim";
if (selector.includes("mint")) return "Mint on LUST";
if (selector.includes("burn")) return "Burn LUSDT";
if (selector.includes("release")) return "Release USDT";
if (selector.includes("recover")) return "Recover claim";
return "Continue";
}
function bridgeButtonBusyLabel(selector) {
if (selector.includes("deposit")) return "Depositing...";
if (selector.includes("mint")) return "Minting...";
if (selector.includes("burn")) return "Burning...";
if (selector.includes("release")) return "Releasing...";
if (selector.includes("recover")) return "Recovering...";
return "Processing...";
}
function setBridgeButtonState(selector, state = "default", label = "") {
const btn = document.querySelector(selector);
if (!btn) return;
const baseLabel = bridgeButtonBaseLabel(selector);
if (!btn.dataset.defaultText) btn.dataset.defaultText = baseLabel;
btn.classList.remove("is-ready", "is-waiting", "is-loading");
if (state === "ready") {
btn.classList.add("is-ready");
btn.removeAttribute("disabled");
btn.textContent = baseLabel;
return;
}
if (state === "waiting") {
btn.classList.add("is-waiting");
btn.setAttribute("disabled", "disabled");
btn.textContent = baseLabel;
return;
}
if (state === "loading") {
btn.classList.add("is-loading");
btn.setAttribute("disabled", "disabled");
btn.textContent = bridgeButtonBusyLabel(selector);
return;
}
if (state === "disabled") {
btn.setAttribute("disabled", "disabled");
btn.textContent = baseLabel;
return;
}
btn.removeAttribute("disabled");
btn.textContent = baseLabel;
}
function setBridgeActionReady(selector, ready) {
setBridgeButtonState(selector, ready ? "ready" : "disabled");
}
function setLiquidityStatus(selector, message, tone = "") {
document.querySelectorAll(selector).forEach((el) => {
el.textContent = message;
el.classList.remove("ok", "warn", "bad", "info");
if (tone) el.classList.add(tone);
});
}
function amount6ToDestinationUnits(amount6, destination) {
const raw = BigInt(amount6 || 0);
return destination === "bsc" ? raw * 1000000000000n : raw;
}
async function fetchLockboxLiquidity(kind) {
const tokenCfg = sourceToken(kind);
const chain = bridgeChainFor(kind);
const provider = new ethers.JsonRpcProvider(chain.rpcUrls[0]);
const token = new ethers.Contract(tokenCfg.address, ERC20_ABI, provider);
const balance = await token.balanceOf(tokenCfg.lockbox);
return { kind, balance, decimals: tokenCfg.decimals };
}
function describeLiquidity(kind, balance) {
const decimals = kind === "bsc" ? 18 : 6;
const formatted = formatUnitsSafe(balance, decimals, 6);
const numeric = Number(ethers.formatUnits(balance, decimals));
const tone = numeric <= 0 ? "bad" : numeric < 100 ? "warn" : "ok";
const message = numeric <= 0
? "No USDT currently available for releases on this network."
: numeric < 100
? `Low available reserve on ${kind.toUpperCase()}. Large withdrawals may fail until more USDT is added.`
: `Reserve available on ${kind.toUpperCase()} for normal bridge releases.`;
return { formatted: `${formatted} USDT`, tone, message };
}
function updateDestinationLiquidityNotice() {
const destination = selectedDestination();
const amountText = document.querySelector("[data-withdraw-amount]")?.value || "0";
const q = bridgeQuote(amountText);
const liq = bridgeLiquidity[destination];
if (!liq) {
setText("[data-bridge-destination-balance]", "Loading...");
setText("[data-bridge-destination-liquidity-status]", "Checking...");
setLiquidityStatus("[data-bridge-destination-warning]", "Checking destination reserve before burn...", "info");