@glacislabs/stablegenie-zerodelta 4.18.1 → 4.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/{chunk-NXEWSGMY.js → chunk-NLXQVXZ5.js} +1513 -182
- package/dist/{chunk-MB7R66M7.js → chunk-NS444RZM.js} +130 -83
- package/dist/core/index.cjs +1547 -181
- package/dist/core/index.d.cts +26 -5
- package/dist/core/index.d.ts +26 -5
- package/dist/core/index.js +1 -1
- package/dist/index.cjs +1598 -353
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/{mount-BdxMZC70.d.ts → mount-A24qHOI0.d.ts} +1 -1
- package/dist/{mount-BSXfSSP2.d.cts → mount-BsoZvwCl.d.cts} +1 -1
- package/dist/mount.cjs +1598 -353
- package/dist/mount.d.cts +2 -2
- package/dist/mount.d.ts +2 -2
- package/dist/mount.js +2 -2
- package/dist/standalone.global.js +9 -9
- package/dist/{verify-BBREdvIM.d.cts → verify-BzTQQMc8.d.cts} +466 -2
- package/dist/{verify-BBREdvIM.d.ts → verify-BzTQQMc8.d.ts} +466 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -575,12 +575,64 @@ var init_ed255192 = __esm({
|
|
|
575
575
|
});
|
|
576
576
|
|
|
577
577
|
// src/core/delivery.ts
|
|
578
|
-
var FAILED = /* @__PURE__ */ new Set(["cancelled", "fill_failed", "delivery_failed", "
|
|
579
|
-
var ATTENTION = /* @__PURE__ */ new Set(["cancel_pending", "awaiting_claim"]);
|
|
578
|
+
var FAILED = /* @__PURE__ */ new Set(["cancelled", "fill_failed", "delivery_failed", "failed"]);
|
|
579
|
+
var ATTENTION = /* @__PURE__ */ new Set(["cancel_pending", "awaiting_claim", "expired"]);
|
|
580
580
|
var TRACKING = Object.freeze({ phase: "tracking", status: "", steps: [] });
|
|
581
581
|
var word = (v) => typeof v === "string" ? v.trim().toLowerCase() : "";
|
|
582
582
|
var STEP_ORDER = { submitted: 0, arrived: 1, filled: 2, delivered: 3 };
|
|
583
583
|
var STATUS_REACHED = { in_progress: 1, outbound_bridging: 2, delivery_failed: 2, delivered: 3 };
|
|
584
|
+
var ZDH_FIRST_STEP = 20;
|
|
585
|
+
var ZDH_STEP = {
|
|
586
|
+
paid_out: "delivered",
|
|
587
|
+
cancelled: "cancellation_requested",
|
|
588
|
+
refunded: "refunded"
|
|
589
|
+
};
|
|
590
|
+
var ROUTE_MECHANICS = /* @__PURE__ */ new Set(["consumed", "step_executed", "step_filled", "returned"]);
|
|
591
|
+
var PROGRESS = /* @__PURE__ */ new Set(["pending", "in_progress", "outbound_bridging"]);
|
|
592
|
+
var MAX_STEPS = 8;
|
|
593
|
+
function isZdHeavy(r, steps) {
|
|
594
|
+
return r.protocol === "zdheavy" || steps.some((s) => Number(s.stepNumber ?? 0) >= ZDH_FIRST_STEP);
|
|
595
|
+
}
|
|
596
|
+
function zdHeavyDelivery(own, rawSteps) {
|
|
597
|
+
const named = rawSteps.filter((s) => s && typeof s === "object" && typeof s.stepName === "string");
|
|
598
|
+
const lite = (name) => named.some((s) => Number(s.stepNumber ?? 0) < ZDH_FIRST_STEP && s.stepName === name && s.stepStatus === "completed");
|
|
599
|
+
const events = named.map((s, i) => ({ s, i })).filter(({ s }) => Number(s.stepNumber ?? 0) >= ZDH_FIRST_STEP).sort((a, b) => (Date.parse(String(a.s.blockTimestamp ?? "")) || 0) - (Date.parse(String(b.s.blockTimestamp ?? "")) || 0) || a.i - b.i).map(({ s }) => s);
|
|
600
|
+
const has = (name) => events.some((e) => e.stepName === name);
|
|
601
|
+
const cancelled = has("cancelled");
|
|
602
|
+
const status = PROGRESS.has(own) && has("paid_out") && !cancelled ? "delivered" : own;
|
|
603
|
+
const steps = [];
|
|
604
|
+
const push = (name, done) => {
|
|
605
|
+
const last = steps[steps.length - 1];
|
|
606
|
+
if (last && last.name === name && last.done === done) return;
|
|
607
|
+
steps.push({ name, done });
|
|
608
|
+
};
|
|
609
|
+
if (lite("submitted")) push("submitted", true);
|
|
610
|
+
const terminal = cancelled || FAILED.has(status) || ATTENTION.has(status) || status === "delivered";
|
|
611
|
+
if (!cancelled && !FAILED.has(status) && !ATTENTION.has(status)) {
|
|
612
|
+
if (status === "delivered") {
|
|
613
|
+
push("route_completed", true);
|
|
614
|
+
} else {
|
|
615
|
+
push("route", false);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
for (const e of events) {
|
|
619
|
+
const name = String(e.stepName);
|
|
620
|
+
if (ROUTE_MECHANICS.has(name)) continue;
|
|
621
|
+
if (name === "refund_parked") {
|
|
622
|
+
push(e.stepStatus === "recovered" ? "claimed" : "ready_to_claim", e.stepStatus === "recovered");
|
|
623
|
+
continue;
|
|
624
|
+
}
|
|
625
|
+
push(ZDH_STEP[name] ?? name.slice(0, 32), true);
|
|
626
|
+
}
|
|
627
|
+
if (!terminal) push("delivered", false);
|
|
628
|
+
const capped = steps.length > MAX_STEPS ? [...steps.slice(0, MAX_STEPS - 1), steps[steps.length - 1]] : steps;
|
|
629
|
+
const refunded = cancelled && has("refunded");
|
|
630
|
+
if (!status) return TRACKING;
|
|
631
|
+
if (FAILED.has(status)) return { phase: "failed", status, steps: capped, ...refunded ? { refunded } : {} };
|
|
632
|
+
if (ATTENTION.has(status)) return { phase: "attention", status, steps: capped };
|
|
633
|
+
if (status === "delivered") return { phase: "delivered", status, steps: capped };
|
|
634
|
+
return { phase: "in-progress", status, steps: capped };
|
|
635
|
+
}
|
|
584
636
|
function normalizeDelivery(raw2) {
|
|
585
637
|
const row = raw2 && typeof raw2 === "object" && !Array.isArray(raw2) ? raw2.data ?? raw2 : null;
|
|
586
638
|
if (!row || typeof row !== "object" || Array.isArray(row)) return TRACKING;
|
|
@@ -590,6 +642,7 @@ function normalizeDelivery(raw2) {
|
|
|
590
642
|
const own = word(r.status);
|
|
591
643
|
const status = journey || own;
|
|
592
644
|
const rawSteps = Array.isArray(r.steps) ? r.steps : [];
|
|
645
|
+
if (isZdHeavy(r, rawSteps) && !chained) return zdHeavyDelivery(own, rawSteps);
|
|
593
646
|
const listed = rawSteps.filter((s) => s && typeof s === "object" && typeof s.stepName === "string").sort((a, b) => Number(a.stepNumber ?? 0) - Number(b.stepNumber ?? 0)).slice(0, 8).map((s) => ({ name: String(s.stepName).slice(0, 32), done: s.stepStatus === "completed" }));
|
|
594
647
|
const reached = Math.max(STATUS_REACHED[own] ?? -1, ...listed.filter((s) => s.done).map((s) => STEP_ORDER[s.name] ?? -1));
|
|
595
648
|
const steps = listed.map((s) => (STEP_ORDER[s.name] ?? Infinity) <= reached ? { ...s, done: true } : s);
|
|
@@ -633,11 +686,15 @@ function useDelivery(engine, hash2) {
|
|
|
633
686
|
let alive = true;
|
|
634
687
|
let timer2;
|
|
635
688
|
let answered = false;
|
|
689
|
+
let waitsOnOwner = false;
|
|
636
690
|
let unanswered = 0;
|
|
637
691
|
const started2 = Date.now();
|
|
638
692
|
setState({ hash: hash2, value: TRACKING });
|
|
639
693
|
const schedule = () => {
|
|
640
|
-
if (Date.now() - started2 > DELIVERY_GIVE_UP_MS)
|
|
694
|
+
if (Date.now() - started2 > DELIVERY_GIVE_UP_MS) {
|
|
695
|
+
if (waitsOnOwner) return;
|
|
696
|
+
return setState({ hash: hash2, value: UNAVAILABLE });
|
|
697
|
+
}
|
|
641
698
|
timer2 = setTimeout(tick, deliveryPollDelay(Date.now() - started2));
|
|
642
699
|
};
|
|
643
700
|
const tick = async () => {
|
|
@@ -650,6 +707,7 @@ function useDelivery(engine, hash2) {
|
|
|
650
707
|
return schedule();
|
|
651
708
|
}
|
|
652
709
|
answered = true;
|
|
710
|
+
waitsOnOwner = next.phase === "attention";
|
|
653
711
|
setState({ hash: hash2, value: next });
|
|
654
712
|
if (next.phase === "delivered" || next.phase === "failed") return;
|
|
655
713
|
schedule();
|
|
@@ -674,7 +732,15 @@ var STEP_LABEL = {
|
|
|
674
732
|
arrived: "Arrived",
|
|
675
733
|
filled: "Filled",
|
|
676
734
|
outbound_bridging: "Bridging",
|
|
677
|
-
delivered: "Delivered"
|
|
735
|
+
delivered: "Delivered",
|
|
736
|
+
// ZD Heavy (core/delivery.ts; mirrors zd-dapp src/lib/zdHeavyTimeline.ts). How the order was filled
|
|
737
|
+
// (netted, partly netted, swapped) is the protocol's business, so the holder reads one "Filled".
|
|
738
|
+
route_completed: "Filled",
|
|
739
|
+
route: "Filled",
|
|
740
|
+
cancellation_requested: "Cancellation requested",
|
|
741
|
+
refunded: "Refunded",
|
|
742
|
+
ready_to_claim: "Ready to claim",
|
|
743
|
+
claimed: "Claimed"
|
|
678
744
|
};
|
|
679
745
|
var label = (name) => STEP_LABEL[name] ?? name.replace(/_/g, " ");
|
|
680
746
|
function deliveryHeadline(delivery, sourceConfirmed, direct2 = false) {
|
|
@@ -683,12 +749,14 @@ function deliveryHeadline(delivery, sourceConfirmed, direct2 = false) {
|
|
|
683
749
|
case "delivered":
|
|
684
750
|
return "Delivered";
|
|
685
751
|
case "failed":
|
|
752
|
+
if (delivery.status === "cancelled" && delivery.refunded) return "Cancelled \u2014 refunded to the owner";
|
|
686
753
|
return delivery.status === "cancelled" ? "Cancelled \u2014 not delivered" : `Not delivered (${delivery.status.replace(/_/g, " ")}) \u2014 open the transaction for details`;
|
|
687
754
|
case "attention":
|
|
688
755
|
return delivery.status === "cancel_pending" ? "Being cancelled \u2014 not delivered" : "Waiting to be claimed \u2014 open the transaction";
|
|
689
756
|
case "in-progress": {
|
|
690
757
|
if (delivery.status === "continuing") return "On its way \u2014 final leg next";
|
|
691
758
|
const next = delivery.steps.find((s) => !s.done);
|
|
759
|
+
if (next?.name === "route") return "On its way";
|
|
692
760
|
return next ? `On its way \u2014 ${label(next.name).toLowerCase()} next` : "On its way";
|
|
693
761
|
}
|
|
694
762
|
case "unavailable":
|
|
@@ -913,7 +981,7 @@ var CHAIN_DISPLAY_NAMES = Object.freeze({
|
|
|
913
981
|
8453: "Base",
|
|
914
982
|
9745: "Plasma",
|
|
915
983
|
34443: "Mode",
|
|
916
|
-
42161: "Arbitrum
|
|
984
|
+
42161: "Arbitrum",
|
|
917
985
|
// "Avalanche", as the dApp prints it since zd-dapp#582 (from ZD Heavy's /chains). The widget's
|
|
918
986
|
// registry read lists no row for a payout-only chain, so this table is what names it here.
|
|
919
987
|
43114: "Avalanche",
|
|
@@ -989,8 +1057,8 @@ var SOLANA_DESTINATION_ASSETS = Object.freeze({
|
|
|
989
1057
|
AymATz4TCL9sWNEEV9Kvyz45CHVhDZ6kUgjTJPzLpU9P: pin("XAUT", 6, "layerzero", TOKEN_PROGRAM)
|
|
990
1058
|
});
|
|
991
1059
|
function solanaDestinationAsset(mint) {
|
|
992
|
-
const
|
|
993
|
-
return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS,
|
|
1060
|
+
const key2 = typeof mint === "string" ? mint.trim() : "";
|
|
1061
|
+
return Object.prototype.hasOwnProperty.call(SOLANA_DESTINATION_ASSETS, key2) ? SOLANA_DESTINATION_ASSETS[key2] : null;
|
|
994
1062
|
}
|
|
995
1063
|
function solanaBridgeOf(token) {
|
|
996
1064
|
const pinned = solanaDestinationAsset(token.address);
|
|
@@ -1364,9 +1432,9 @@ function hexBytes(hex) {
|
|
|
1364
1432
|
if (h2.length % 2 || !/^[a-fA-F0-9]*$/.test(h2)) throw new Error("Invalid hex bytes.");
|
|
1365
1433
|
return Uint8Array.from(h2.match(/../g) || [], (v) => Number.parseInt(v, 16));
|
|
1366
1434
|
}
|
|
1367
|
-
function solanaKeyBytes(
|
|
1368
|
-
if (!isSolanaAddress(
|
|
1369
|
-
return base58Decode(
|
|
1435
|
+
function solanaKeyBytes(key2) {
|
|
1436
|
+
if (!isSolanaAddress(key2) || key2 !== key2.trim()) throw new Error("Invalid Solana public key.");
|
|
1437
|
+
return base58Decode(key2);
|
|
1370
1438
|
}
|
|
1371
1439
|
var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
1372
1440
|
function base64Decode(text) {
|
|
@@ -1712,16 +1780,16 @@ function tokenTicker(token) {
|
|
|
1712
1780
|
}
|
|
1713
1781
|
function tickerOn(tokens, chainId, symbol) {
|
|
1714
1782
|
if (!symbol || !chainId || !tokens?.length) return symbol;
|
|
1715
|
-
const
|
|
1716
|
-
const deployment = tokens.find((t) => Number(t.chainId) === Number(chainId) && symbolKey(t.symbol) ===
|
|
1783
|
+
const key2 = symbolKey(symbol);
|
|
1784
|
+
const deployment = tokens.find((t) => Number(t.chainId) === Number(chainId) && symbolKey(t.symbol) === key2);
|
|
1717
1785
|
return deployment ? tokenTicker(deployment) : symbol;
|
|
1718
1786
|
}
|
|
1719
1787
|
|
|
1720
1788
|
// src/core/availability.ts
|
|
1721
1789
|
function assetClassOf(symbol) {
|
|
1722
|
-
const
|
|
1723
|
-
if (TRADEABLE_RWA_ASSETS.has(
|
|
1724
|
-
if (STABLE_ASSETS.has(
|
|
1790
|
+
const key2 = symbolKey(symbol);
|
|
1791
|
+
if (TRADEABLE_RWA_ASSETS.has(key2)) return "rwa";
|
|
1792
|
+
if (STABLE_ASSETS.has(key2)) return "stable";
|
|
1725
1793
|
return null;
|
|
1726
1794
|
}
|
|
1727
1795
|
var NEST_VAULT_SHARES = /* @__PURE__ */ new Set(["NALPHA", "NTBILL", "NBASIS", "NCREDIT", "NOPAL", "NWISDOM", "NACRDX", "NLCRD", "NAXI", "NCLOA", "NFALCON"]);
|
|
@@ -1830,8 +1898,8 @@ function buildCatalogue(input) {
|
|
|
1830
1898
|
if (product === "rwa") return true;
|
|
1831
1899
|
if (execution.has(chainId) || token.isChainedDestination === true) return true;
|
|
1832
1900
|
if (!isExecutableBridge(token)) return false;
|
|
1833
|
-
const
|
|
1834
|
-
return source2.has(
|
|
1901
|
+
const key2 = tokenKey(token.chainId, token.address);
|
|
1902
|
+
return source2.has(key2) || destination.has(key2);
|
|
1835
1903
|
});
|
|
1836
1904
|
const ready = chains.length > 0 && routes.length > 0 && projectedCatalogue.length > 0;
|
|
1837
1905
|
const catalogue = ready ? projectedCatalogue : allowed;
|
|
@@ -1875,8 +1943,8 @@ function tokenEnabled(token) {
|
|
|
1875
1943
|
return token?.isEnabled !== false && isChainAddress(token?.chainId, token?.address) && Number.isFinite(Number(token?.chainId));
|
|
1876
1944
|
}
|
|
1877
1945
|
function findToken(tokens, chainId, symbol) {
|
|
1878
|
-
const
|
|
1879
|
-
return tokens.find((token) => tokenEnabled(token) && Number(token.chainId) === Number(chainId) && symbolKey(token.symbol) ===
|
|
1946
|
+
const key2 = symbolKey(symbol);
|
|
1947
|
+
return tokens.find((token) => tokenEnabled(token) && Number(token.chainId) === Number(chainId) && symbolKey(token.symbol) === key2) || null;
|
|
1880
1948
|
}
|
|
1881
1949
|
function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains, walletChainId, catalogue }) {
|
|
1882
1950
|
const invoiceKey = symbolKey(invoiceAsset);
|
|
@@ -1910,10 +1978,10 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
|
|
|
1910
1978
|
const chainId = Number(token.chainId);
|
|
1911
1979
|
const chain2 = chainById(chains, chainId);
|
|
1912
1980
|
if (!chainSelectable(chain2, chainId)) continue;
|
|
1913
|
-
const
|
|
1914
|
-
if (seen.has(
|
|
1981
|
+
const key2 = tokenKey(chainId, token.address);
|
|
1982
|
+
if (seen.has(key2)) continue;
|
|
1915
1983
|
if (refusal(token)) continue;
|
|
1916
|
-
seen.add(
|
|
1984
|
+
seen.add(key2);
|
|
1917
1985
|
const payKey = symbolKey(token.symbol);
|
|
1918
1986
|
const direct2 = chainId === invoiceChain && payKey === invoiceKey;
|
|
1919
1987
|
options.push({
|
|
@@ -2099,7 +2167,7 @@ function normalizePreview(request, quote, to, amount) {
|
|
|
2099
2167
|
async function quoteSolanaSource(api, input) {
|
|
2100
2168
|
const { from, to, amount } = selections(input, await api.fetchTokens());
|
|
2101
2169
|
const request = makeRequest(input, from, to, amount);
|
|
2102
|
-
const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
|
|
2170
|
+
const quote = await api.apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
|
|
2103
2171
|
const preview = normalizePreview(request, quote, to, input.amountIn);
|
|
2104
2172
|
quoteRequests.set(preview, { api, request: clone(request) });
|
|
2105
2173
|
return preview;
|
|
@@ -2113,7 +2181,7 @@ async function previewSolanaSource(api, input) {
|
|
|
2113
2181
|
raw(amount, "input amount", true);
|
|
2114
2182
|
const body = { inputChain: SOLANA_CHAIN_ID, outputChain: input.toChainId, inputToken: from.symbol, outputToken: to.symbol, inputAmount: amount };
|
|
2115
2183
|
const request = body;
|
|
2116
|
-
const quote = await api.apiRequest("/quote", { method: "POST", body: JSON.stringify(request), timeoutMs: 18e3 });
|
|
2184
|
+
const quote = await api.apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
|
|
2117
2185
|
const option = quote?.options?.[0];
|
|
2118
2186
|
if (!option) throw new Error("Native quote returned no options.");
|
|
2119
2187
|
const receive = raw(option.finalAmount, "quoted output", true);
|
|
@@ -2470,8 +2538,8 @@ function historyKey(value) {
|
|
|
2470
2538
|
var str = (v) => typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
|
|
2471
2539
|
function tokenAt(tokens, chainId, address) {
|
|
2472
2540
|
if (!address) return void 0;
|
|
2473
|
-
const
|
|
2474
|
-
return tokens.find((t) => Number(t.chainId) === chainId && historyKey(String(t.address)) ===
|
|
2541
|
+
const key2 = historyKey(address);
|
|
2542
|
+
return tokens.find((t) => Number(t.chainId) === chainId && historyKey(String(t.address)) === key2);
|
|
2475
2543
|
}
|
|
2476
2544
|
function amountOf(raw2, token, rowDecimals, rowAmount) {
|
|
2477
2545
|
const decimals = token ? Number(token.decimals) : Number(rowDecimals);
|
|
@@ -2557,13 +2625,13 @@ function mergeHistory(local, remote, limit = WALLET_HISTORY_LIMIT) {
|
|
|
2557
2625
|
const out = [];
|
|
2558
2626
|
const seen = /* @__PURE__ */ new Set();
|
|
2559
2627
|
for (const entry of local) {
|
|
2560
|
-
const
|
|
2561
|
-
if (seen.has(
|
|
2562
|
-
seen.add(
|
|
2563
|
-
const known = byHash.get(
|
|
2628
|
+
const key2 = historyKey(entry.hash);
|
|
2629
|
+
if (seen.has(key2)) continue;
|
|
2630
|
+
seen.add(key2);
|
|
2631
|
+
const known = byHash.get(key2);
|
|
2564
2632
|
out.push(known ? { ...entry, delivery: known.delivery, legs: entry.legs ?? known.legs } : entry);
|
|
2565
2633
|
}
|
|
2566
|
-
for (const [
|
|
2634
|
+
for (const [key2, entry] of byHash) if (!seen.has(key2)) out.push(entry);
|
|
2567
2635
|
return out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, limit);
|
|
2568
2636
|
}
|
|
2569
2637
|
|
|
@@ -2674,12 +2742,12 @@ function suppressedLanes(health) {
|
|
|
2674
2742
|
const out = /* @__PURE__ */ new Map();
|
|
2675
2743
|
for (const lane of health.lanes) {
|
|
2676
2744
|
if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
|
|
2677
|
-
const
|
|
2678
|
-
if (!
|
|
2745
|
+
const key2 = healthLaneKey(lane.laneKey);
|
|
2746
|
+
if (!key2) continue;
|
|
2679
2747
|
const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
|
|
2680
2748
|
const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
|
|
2681
2749
|
const message = typeof availability?.message === "string" && availability.message ? availability.message : lane.message;
|
|
2682
|
-
out.set(
|
|
2750
|
+
out.set(key2, {
|
|
2683
2751
|
route: typeof lane.route === "string" ? lane.route : "",
|
|
2684
2752
|
code: typeof code === "string" ? code : "",
|
|
2685
2753
|
message: typeof message === "string" ? message : "",
|
|
@@ -2694,15 +2762,15 @@ function limitedLanes(health) {
|
|
|
2694
2762
|
const out = /* @__PURE__ */ new Map();
|
|
2695
2763
|
for (const lane of health.lanes) {
|
|
2696
2764
|
if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
|
|
2697
|
-
const
|
|
2765
|
+
const key2 = healthLaneKey(lane.laneKey);
|
|
2698
2766
|
const limit = lane.availability?.limit;
|
|
2699
|
-
if (!
|
|
2767
|
+
if (!key2 || !limit || typeof limit !== "object") continue;
|
|
2700
2768
|
const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
|
|
2701
2769
|
const maxAmount = typeof limit.maxAmount === "string" ? limit.maxAmount.trim() : "";
|
|
2702
2770
|
const decimals = limit.decimals;
|
|
2703
2771
|
if (!side || !BASE_UNITS.test(maxAmount) || typeof decimals !== "number" || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) continue;
|
|
2704
2772
|
const code = lane.availability?.code;
|
|
2705
|
-
out.set(
|
|
2773
|
+
out.set(key2, {
|
|
2706
2774
|
side,
|
|
2707
2775
|
token: typeof limit.token === "string" ? limit.token : "",
|
|
2708
2776
|
fromChainId: Number(limit.fromChainId) || 0,
|
|
@@ -2765,10 +2833,10 @@ function resolveVaultIcon(apiBase, iconPath) {
|
|
|
2765
2833
|
function vaultIconsBySymbol(apiBase, vaults) {
|
|
2766
2834
|
const out = /* @__PURE__ */ new Map();
|
|
2767
2835
|
for (const vault of vaults) {
|
|
2768
|
-
const
|
|
2769
|
-
if (!
|
|
2836
|
+
const key2 = symbolKey(vault?.symbol);
|
|
2837
|
+
if (!key2 || out.has(key2)) continue;
|
|
2770
2838
|
const url = resolveVaultIcon(apiBase, vault?.iconMiniUrl) ?? resolveVaultIcon(apiBase, vault?.iconUrl);
|
|
2771
|
-
if (url) out.set(
|
|
2839
|
+
if (url) out.set(key2, url);
|
|
2772
2840
|
}
|
|
2773
2841
|
return out;
|
|
2774
2842
|
}
|
|
@@ -2865,7 +2933,7 @@ var CATEGORY_PHRASES = {
|
|
|
2865
2933
|
UNKNOWN: "an unrecognized risk"
|
|
2866
2934
|
};
|
|
2867
2935
|
function categoryLabel(code) {
|
|
2868
|
-
const
|
|
2936
|
+
const key2 = code.trim().toUpperCase();
|
|
2869
2937
|
const LABELS = {
|
|
2870
2938
|
SANCTIONS: "Sanctions",
|
|
2871
2939
|
TERRORISM_FINANCING: "Terrorist financing",
|
|
@@ -2880,7 +2948,7 @@ function categoryLabel(code) {
|
|
|
2880
2948
|
UNCLASSIFIED: "Unclassified risk",
|
|
2881
2949
|
UNKNOWN: "Unclassified risk"
|
|
2882
2950
|
};
|
|
2883
|
-
return LABELS[
|
|
2951
|
+
return LABELS[key2] ?? key2.toLowerCase().replace(/_/g, " ");
|
|
2884
2952
|
}
|
|
2885
2953
|
function cleanJurisdiction(code) {
|
|
2886
2954
|
return code.replace(/^(OFAC|TIER\d+|SANCTIONED)_/i, "").trim();
|
|
@@ -2993,9 +3061,9 @@ function distinctScreenedWallets(compliance) {
|
|
|
2993
3061
|
for (const raw2 of compliance?.screenedWallets ?? []) {
|
|
2994
3062
|
const address = raw2?.trim();
|
|
2995
3063
|
if (!address) continue;
|
|
2996
|
-
const
|
|
2997
|
-
if (seen.has(
|
|
2998
|
-
seen.add(
|
|
3064
|
+
const key2 = /^0x[0-9a-fA-F]+$/.test(address) ? address.toLowerCase() : address;
|
|
3065
|
+
if (seen.has(key2)) continue;
|
|
3066
|
+
seen.add(key2);
|
|
2999
3067
|
wallets.push(address);
|
|
3000
3068
|
}
|
|
3001
3069
|
return wallets;
|
|
@@ -3122,9 +3190,9 @@ var TUNED_OUTCOMES = {
|
|
|
3122
3190
|
UNCLASSIFIED: "flagged"
|
|
3123
3191
|
};
|
|
3124
3192
|
function screeningOutcomeOf(category) {
|
|
3125
|
-
const
|
|
3126
|
-
if (FLOOR_CATEGORIES.includes(
|
|
3127
|
-
return TUNED_OUTCOMES[
|
|
3193
|
+
const key2 = category.trim().toUpperCase();
|
|
3194
|
+
if (FLOOR_CATEGORIES.includes(key2)) return "always-blocked";
|
|
3195
|
+
return TUNED_OUTCOMES[key2] ?? null;
|
|
3128
3196
|
}
|
|
3129
3197
|
var labelsFor = (outcome) => [...FLOOR_CATEGORIES, ...TUNABLE_CATEGORIES].filter((c) => screeningOutcomeOf(c) === outcome).map(categoryLabel);
|
|
3130
3198
|
var SCREENING_BUCKETS = [
|
|
@@ -3133,6 +3201,91 @@ var SCREENING_BUCKETS = [
|
|
|
3133
3201
|
{ outcome: "flagged", title: "Flagged", detail: "A warning is shown.", categories: labelsFor("flagged") }
|
|
3134
3202
|
];
|
|
3135
3203
|
|
|
3204
|
+
// src/core/zdheavy-routers.ts
|
|
3205
|
+
var ZDHEAVY_ROUTER_TEST05 = "0x94c5cC7f4689AD7B0Abd0975F4C8E159e4633251";
|
|
3206
|
+
var ZDHEAVY_ROUTER_TEST04 = "0x72EA420DCE5BE939062E527b49388479d7171379";
|
|
3207
|
+
var ZDHEAVY_ROUTER_DEV = "0xD813690937324417cFBE12E742dD53054F90dF04";
|
|
3208
|
+
var ZDHEAVY_ROUTER_DEV_V6 = "0xa6155b1505378e6C9871483c55375dcBBB16f897";
|
|
3209
|
+
var ZDHEAVY_ROUTER_PROD = "0x7D50305f2855Bf2225FE51E15858b4BA0C0844e1";
|
|
3210
|
+
var ZDHEAVY_DEV_CHAINS = [1, 10, 56, 130, 137, 143, 146, 1329, 1672, 4663, 5e3, 8453, 9745, 42161, 43114, 57073, 98866];
|
|
3211
|
+
var ZDHEAVY_SANDBOX_CHAINS = [8453, 9745, 42161];
|
|
3212
|
+
var ZDHEAVY_ROUTER_ADDRESSES = Object.fromEntries(
|
|
3213
|
+
ZDHEAVY_DEV_CHAINS.map((id) => [
|
|
3214
|
+
id,
|
|
3215
|
+
ZDHEAVY_SANDBOX_CHAINS.includes(id) ? [ZDHEAVY_ROUTER_TEST05, ZDHEAVY_ROUTER_TEST04, ZDHEAVY_ROUTER_DEV, ZDHEAVY_ROUTER_DEV_V6, ZDHEAVY_ROUTER_PROD] : [ZDHEAVY_ROUTER_DEV, ZDHEAVY_ROUTER_DEV_V6, ZDHEAVY_ROUTER_PROD]
|
|
3216
|
+
])
|
|
3217
|
+
);
|
|
3218
|
+
function zdHeavyRouterPinned(chainId, router) {
|
|
3219
|
+
if (typeof router !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(router)) return false;
|
|
3220
|
+
const want = router.toLowerCase();
|
|
3221
|
+
return (ZDHEAVY_ROUTER_ADDRESSES[chainId] ?? []).some((a) => a.toLowerCase() === want);
|
|
3222
|
+
}
|
|
3223
|
+
|
|
3224
|
+
// src/core/quote-option.ts
|
|
3225
|
+
function zdHeavyExecutable(q) {
|
|
3226
|
+
const order = q.execution?.order;
|
|
3227
|
+
const chainId = typeof q.fromChainId === "number" ? q.fromChainId : Number(order?.chainNumber);
|
|
3228
|
+
return q.protocol === "zdheavy" && q.payloadStatus === "resolved-offchain-signed" && !!order && !!q.rootHash && Array.isArray(q.txData) && q.txData.some((tx) => (tx.actionType === "submit" || tx.actionType === "submitOrder") && typeof tx.to === "string" && typeof tx.data === "string") && zdHeavyRouterPinned(chainId, order.router);
|
|
3229
|
+
}
|
|
3230
|
+
function liteExecutable(q) {
|
|
3231
|
+
return q.protocol !== "zdheavy" && Array.isArray(q.orderRequests) && q.orderRequests.length > 0;
|
|
3232
|
+
}
|
|
3233
|
+
function selectQuoteOption(quote) {
|
|
3234
|
+
if (!Array.isArray(quote.options)) return quote;
|
|
3235
|
+
const option = quote.options.find(zdHeavyExecutable) ?? quote.options.find((q) => q.protocol !== "zdheavy" && !!q.orderRequests?.length);
|
|
3236
|
+
if (!option) throw new Error("ZeroDelta quote has no executable option.");
|
|
3237
|
+
const gatewayOptions = [];
|
|
3238
|
+
let gatewayOptionIndex = -1;
|
|
3239
|
+
for (const o of quote.options) {
|
|
3240
|
+
if (!o || typeof o !== "object" || Array.isArray(o)) continue;
|
|
3241
|
+
if (o === option) gatewayOptionIndex = gatewayOptions.length;
|
|
3242
|
+
gatewayOptions.push(projectOption(quote, o));
|
|
3243
|
+
}
|
|
3244
|
+
return { ...projectOption(quote, option), gatewayOptions, gatewayOptionIndex };
|
|
3245
|
+
}
|
|
3246
|
+
function projectOption(quote, option) {
|
|
3247
|
+
const { fromChainId, toChainId, fromToken, toToken: toToken2, fromAmount } = quote;
|
|
3248
|
+
const last = option.orderRequests?.[option.orderRequests.length - 1];
|
|
3249
|
+
const { entersNetting, gasSponsored, gatewayOptions: _g, gatewayOptionIndex: _i, ...rest } = option;
|
|
3250
|
+
return {
|
|
3251
|
+
...rest,
|
|
3252
|
+
...entersNetting === true ? { entersNetting: true } : {},
|
|
3253
|
+
...gasSponsored === true ? { gasSponsored: true } : {},
|
|
3254
|
+
fromChainId,
|
|
3255
|
+
toChainId,
|
|
3256
|
+
fromToken,
|
|
3257
|
+
toToken: toToken2,
|
|
3258
|
+
fromAmount,
|
|
3259
|
+
quoteId: quote.quoteId,
|
|
3260
|
+
toAmount: String(last?.askTokenAmount ?? option.outputAmount ?? option.toAmount ?? ""),
|
|
3261
|
+
finalAmount: String(option.finalAmount || last?.askTokenAmount || option.outputAmount || ""),
|
|
3262
|
+
compliance: complianceDecision(quote),
|
|
3263
|
+
estimatedDuration: option.estimatedTimeSec ?? option.estimatedDuration
|
|
3264
|
+
};
|
|
3265
|
+
}
|
|
3266
|
+
function complianceDecision(quote) {
|
|
3267
|
+
const decision = quote.complianceDecision ?? quote.compliance;
|
|
3268
|
+
return decision && typeof decision === "object" && !Array.isArray(decision) ? decision : void 0;
|
|
3269
|
+
}
|
|
3270
|
+
function normalizeQuoteResponse(response, request) {
|
|
3271
|
+
const quote = Array.isArray(response?.options) ? selectQuoteOption({
|
|
3272
|
+
...response,
|
|
3273
|
+
fromChainId: request.inputChain,
|
|
3274
|
+
toChainId: request.outputChain,
|
|
3275
|
+
fromToken: request.inputToken,
|
|
3276
|
+
toToken: request.outputToken,
|
|
3277
|
+
fromAmount: request.inputAmount
|
|
3278
|
+
}) : response;
|
|
3279
|
+
if (quote?.gatewayOptions) quote.gatewayOptions = quote.gatewayOptions.map(numericExecutionChain);
|
|
3280
|
+
return numericExecutionChain(quote);
|
|
3281
|
+
}
|
|
3282
|
+
function numericExecutionChain(quote) {
|
|
3283
|
+
return quote && quote.executionChainId != null ? { ...quote, executionChainId: Number(quote.executionChainId) } : quote;
|
|
3284
|
+
}
|
|
3285
|
+
function deliveredAmount(quote, solanaDestination) {
|
|
3286
|
+
return BigInt(quote.protocol === "zdheavy" || solanaDestination ? quote.finalAmount || quote.toAmount || "0" : quote.toAmount || "0");
|
|
3287
|
+
}
|
|
3288
|
+
|
|
3136
3289
|
// src/core/solve.ts
|
|
3137
3290
|
async function solveExactOut({ option, destination, destinationToken, payer, fetchQuote }) {
|
|
3138
3291
|
const destDecimals = assetDecimals(destinationToken);
|
|
@@ -3179,7 +3332,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
3179
3332
|
let bestGuess = guess;
|
|
3180
3333
|
for (let i = 0; i < 3; i += 1) {
|
|
3181
3334
|
const guessSent = guess;
|
|
3182
|
-
const quote = await fetchQuote({
|
|
3335
|
+
const quote = selectQuoteOption(await fetchQuote({
|
|
3183
3336
|
fromChainId: option.chainId,
|
|
3184
3337
|
toChainId: Number(destination.chainId),
|
|
3185
3338
|
fromToken: option.symbol,
|
|
@@ -3187,11 +3340,11 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
3187
3340
|
fromAmount: guessSent.toString(),
|
|
3188
3341
|
owner: payer,
|
|
3189
3342
|
destinationReceiver: destination.address
|
|
3190
|
-
});
|
|
3343
|
+
}));
|
|
3191
3344
|
if (BigInt(quote?.fromAmount || "0") !== guessSent) {
|
|
3192
3345
|
throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
3193
3346
|
}
|
|
3194
|
-
const guaranteed = isSolanaChainId(destination.chainId)
|
|
3347
|
+
const guaranteed = deliveredAmount(quote, isSolanaChainId(destination.chainId));
|
|
3195
3348
|
const final = finalOf(quote);
|
|
3196
3349
|
if (final > bestFinal) {
|
|
3197
3350
|
bestFinal = final;
|
|
@@ -3228,7 +3381,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
3228
3381
|
directTransfer: false,
|
|
3229
3382
|
quote: best,
|
|
3230
3383
|
youPayRaw: bestGuess.toString(),
|
|
3231
|
-
recipientReceivesRaw: (isSolanaChainId(destination.chainId)
|
|
3384
|
+
recipientReceivesRaw: deliveredAmount(best, isSolanaChainId(destination.chainId)).toString(),
|
|
3232
3385
|
targetRaw: targetRaw.toString(),
|
|
3233
3386
|
overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
|
|
3234
3387
|
meetsTarget: bestFinal >= targetRaw,
|
|
@@ -3238,7 +3391,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
3238
3391
|
async function solveExactIn({ option, destination, destinationToken, payer, fetchQuote, amountInRaw }) {
|
|
3239
3392
|
const fromRaw = BigInt(amountInRaw || "0");
|
|
3240
3393
|
if (fromRaw <= 0n) throw new Error("Swap amount must be greater than zero.");
|
|
3241
|
-
const quote = await fetchQuote({
|
|
3394
|
+
const quote = selectQuoteOption(await fetchQuote({
|
|
3242
3395
|
fromChainId: option.chainId,
|
|
3243
3396
|
toChainId: Number(destination.chainId),
|
|
3244
3397
|
fromToken: option.symbol,
|
|
@@ -3246,11 +3399,11 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
|
|
|
3246
3399
|
fromAmount: fromRaw.toString(),
|
|
3247
3400
|
owner: payer,
|
|
3248
3401
|
destinationReceiver: destination.address
|
|
3249
|
-
});
|
|
3402
|
+
}));
|
|
3250
3403
|
if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
|
|
3251
3404
|
throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
3252
3405
|
}
|
|
3253
|
-
const guaranteed = isSolanaChainId(destination.chainId)
|
|
3406
|
+
const guaranteed = deliveredAmount(quote, isSolanaChainId(destination.chainId));
|
|
3254
3407
|
if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
|
|
3255
3408
|
return {
|
|
3256
3409
|
directTransfer: false,
|
|
@@ -3263,6 +3416,24 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
|
|
|
3263
3416
|
iterations: 1
|
|
3264
3417
|
};
|
|
3265
3418
|
}
|
|
3419
|
+
function resultForOption(result, option, mode, destinationChainId) {
|
|
3420
|
+
if (result.directTransfer) throw new Error("A direct transfer has no other option.");
|
|
3421
|
+
if (BigInt(option.fromAmount || "0") !== BigInt(result.youPayRaw)) throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
3422
|
+
const guaranteed = deliveredAmount(option, isSolanaChainId(destinationChainId));
|
|
3423
|
+
if (mode === "exact-in") {
|
|
3424
|
+
if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
|
|
3425
|
+
return { ...result, quote: option, recipientReceivesRaw: guaranteed.toString(), targetRaw: guaranteed.toString(), overageBps: 0, meetsTarget: true };
|
|
3426
|
+
}
|
|
3427
|
+
const targetRaw = BigInt(result.targetRaw);
|
|
3428
|
+
const final = finalOf(option);
|
|
3429
|
+
return {
|
|
3430
|
+
...result,
|
|
3431
|
+
quote: option,
|
|
3432
|
+
recipientReceivesRaw: guaranteed.toString(),
|
|
3433
|
+
overageBps: targetRaw > 0n ? Number((final - targetRaw) * 10000n / targetRaw) : 0,
|
|
3434
|
+
meetsTarget: final >= targetRaw
|
|
3435
|
+
};
|
|
3436
|
+
}
|
|
3266
3437
|
|
|
3267
3438
|
// src/core/order.ts
|
|
3268
3439
|
var DEFAULT_DEADLINE_SECONDS = 1800;
|
|
@@ -3382,6 +3553,954 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
|
|
|
3382
3553
|
}
|
|
3383
3554
|
}
|
|
3384
3555
|
|
|
3556
|
+
// src/core/checksum.ts
|
|
3557
|
+
var RC = [
|
|
3558
|
+
0x0000000000000001n,
|
|
3559
|
+
0x0000000000008082n,
|
|
3560
|
+
0x800000000000808an,
|
|
3561
|
+
0x8000000080008000n,
|
|
3562
|
+
0x000000000000808bn,
|
|
3563
|
+
0x0000000080000001n,
|
|
3564
|
+
0x8000000080008081n,
|
|
3565
|
+
0x8000000000008009n,
|
|
3566
|
+
0x000000000000008an,
|
|
3567
|
+
0x0000000000000088n,
|
|
3568
|
+
0x0000000080008009n,
|
|
3569
|
+
0x000000008000000an,
|
|
3570
|
+
0x000000008000808bn,
|
|
3571
|
+
0x800000000000008bn,
|
|
3572
|
+
0x8000000000008089n,
|
|
3573
|
+
0x8000000000008003n,
|
|
3574
|
+
0x8000000000008002n,
|
|
3575
|
+
0x8000000000000080n,
|
|
3576
|
+
0x000000000000800an,
|
|
3577
|
+
0x800000008000000an,
|
|
3578
|
+
0x8000000080008081n,
|
|
3579
|
+
0x8000000000008080n,
|
|
3580
|
+
0x0000000080000001n,
|
|
3581
|
+
0x8000000080008008n
|
|
3582
|
+
];
|
|
3583
|
+
var ROT = [0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14];
|
|
3584
|
+
var MASK = (1n << 64n) - 1n;
|
|
3585
|
+
var rotl = (x, n) => n === 0 ? x : (x << BigInt(n) | x >> BigInt(64 - n)) & MASK;
|
|
3586
|
+
function keccakF(s) {
|
|
3587
|
+
for (let round = 0; round < 24; round++) {
|
|
3588
|
+
const c = [0, 1, 2, 3, 4].map((x) => s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]);
|
|
3589
|
+
for (let x = 0; x < 5; x++) {
|
|
3590
|
+
const d = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1);
|
|
3591
|
+
for (let y = 0; y < 25; y += 5) s[y + x] = s[y + x] ^ d;
|
|
3592
|
+
}
|
|
3593
|
+
const b = new Array(25);
|
|
3594
|
+
for (let x = 0; x < 5; x++) for (let y = 0; y < 5; y++) b[y + 5 * ((2 * x + 3 * y) % 5)] = rotl(s[x + 5 * y], ROT[x + 5 * y]);
|
|
3595
|
+
for (let x = 0; x < 5; x++) for (let y = 0; y < 25; y += 5) s[y + x] = b[y + x] ^ ~b[y + (x + 1) % 5] & MASK & b[y + (x + 2) % 5];
|
|
3596
|
+
s[0] = s[0] ^ RC[round];
|
|
3597
|
+
}
|
|
3598
|
+
}
|
|
3599
|
+
function keccak256Hex(bytes) {
|
|
3600
|
+
const rate = 136;
|
|
3601
|
+
const padded = new Uint8Array(Math.ceil((bytes.length + 1) / rate) * rate);
|
|
3602
|
+
padded.set(bytes);
|
|
3603
|
+
padded[bytes.length] = padded[bytes.length] ^ 1;
|
|
3604
|
+
padded[padded.length - 1] = padded[padded.length - 1] ^ 128;
|
|
3605
|
+
const s = new Array(25).fill(0n);
|
|
3606
|
+
for (let off = 0; off < padded.length; off += rate) {
|
|
3607
|
+
for (let i = 0; i < rate / 8; i++) {
|
|
3608
|
+
let lane = 0n;
|
|
3609
|
+
for (let j = 7; j >= 0; j--) lane = lane << 8n | BigInt(padded[off + i * 8 + j]);
|
|
3610
|
+
s[i] = s[i] ^ lane;
|
|
3611
|
+
}
|
|
3612
|
+
keccakF(s);
|
|
3613
|
+
}
|
|
3614
|
+
let out = "";
|
|
3615
|
+
for (let i = 0; i < 4; i++) for (let j = 0; j < 8; j++) out += Number(s[i] >> BigInt(8 * j) & 0xffn).toString(16).padStart(2, "0");
|
|
3616
|
+
return out;
|
|
3617
|
+
}
|
|
3618
|
+
function toChecksumAddress(address) {
|
|
3619
|
+
const lower3 = address.slice(2).toLowerCase();
|
|
3620
|
+
const hash2 = keccak256Hex(new TextEncoder().encode(lower3));
|
|
3621
|
+
let out = "0x";
|
|
3622
|
+
for (let i = 0; i < 40; i++) out += Number.parseInt(hash2[i], 16) >= 8 ? lower3[i].toUpperCase() : lower3[i];
|
|
3623
|
+
return out;
|
|
3624
|
+
}
|
|
3625
|
+
function hasValidChecksum(address) {
|
|
3626
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return false;
|
|
3627
|
+
const body = address.slice(2);
|
|
3628
|
+
if (body === body.toLowerCase() || body === body.toUpperCase()) return true;
|
|
3629
|
+
return toChecksumAddress(address) === address;
|
|
3630
|
+
}
|
|
3631
|
+
|
|
3632
|
+
// src/core/zdheavy-codec.ts
|
|
3633
|
+
var concat = (parts) => "0x" + parts.map((p) => p.slice(2)).join("");
|
|
3634
|
+
var hexToBytes2 = (h2) => Uint8Array.from(h2.slice(2).match(/../g) ?? [], (b) => Number.parseInt(b, 16));
|
|
3635
|
+
var toBytes = (s) => new TextEncoder().encode(s);
|
|
3636
|
+
var toHex = (v, opts) => "0x" + (typeof v === "bigint" ? v.toString(16).padStart((opts?.size ?? 0) * 2, "0") : Array.from(v, (b) => b.toString(16).padStart(2, "0")).join(""));
|
|
3637
|
+
var keccak256 = (h2) => "0x" + keccak256Hex(hexToBytes2(h2));
|
|
3638
|
+
var STEP_VERSION = 5;
|
|
3639
|
+
var MAX_STEPS2 = 8;
|
|
3640
|
+
var StepKind = {
|
|
3641
|
+
LOCAL_PAYOUT: 1,
|
|
3642
|
+
REMOTE_PAYOUT: 2,
|
|
3643
|
+
SEND: 3,
|
|
3644
|
+
SWAP: 4,
|
|
3645
|
+
EXECUTE: 5,
|
|
3646
|
+
NET: 6,
|
|
3647
|
+
SUBSIDY: 7
|
|
3648
|
+
};
|
|
3649
|
+
var ZdHeavyCodecError = class extends Error {
|
|
3650
|
+
constructor(message) {
|
|
3651
|
+
super(message);
|
|
3652
|
+
this.name = "ZdHeavyCodecError";
|
|
3653
|
+
}
|
|
3654
|
+
};
|
|
3655
|
+
function checkedHex(value, length) {
|
|
3656
|
+
if (typeof value !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(value) || length !== void 0 && value.length !== 2 + length * 2) {
|
|
3657
|
+
throw new ZdHeavyCodecError(`Expected ${length === void 0 ? "byte-aligned" : length + "-byte"} hex`);
|
|
3658
|
+
}
|
|
3659
|
+
return value.toLowerCase();
|
|
3660
|
+
}
|
|
3661
|
+
function uint(value, bytes) {
|
|
3662
|
+
if (typeof value !== "bigint" || value < 0n || value >= 1n << BigInt(bytes * 8)) {
|
|
3663
|
+
throw new ZdHeavyCodecError(`Value outside uint${bytes * 8}`);
|
|
3664
|
+
}
|
|
3665
|
+
return toHex(value, { size: bytes });
|
|
3666
|
+
}
|
|
3667
|
+
var Reader2 = class {
|
|
3668
|
+
bytes;
|
|
3669
|
+
offset = 0;
|
|
3670
|
+
constructor(step) {
|
|
3671
|
+
this.bytes = hexToBytes2(checkedHex(step));
|
|
3672
|
+
}
|
|
3673
|
+
take(n) {
|
|
3674
|
+
if (this.offset + n > this.bytes.length) throw new ZdHeavyCodecError("Short step");
|
|
3675
|
+
const result = this.bytes.slice(this.offset, this.offset + n);
|
|
3676
|
+
this.offset += n;
|
|
3677
|
+
return result;
|
|
3678
|
+
}
|
|
3679
|
+
hex(n) {
|
|
3680
|
+
return toHex(this.take(n));
|
|
3681
|
+
}
|
|
3682
|
+
uint(n) {
|
|
3683
|
+
let result = 0n;
|
|
3684
|
+
for (const byte of this.take(n)) result = result << 8n | BigInt(byte);
|
|
3685
|
+
return result;
|
|
3686
|
+
}
|
|
3687
|
+
number(n) {
|
|
3688
|
+
return Number(this.uint(n));
|
|
3689
|
+
}
|
|
3690
|
+
address() {
|
|
3691
|
+
const n = this.number(1);
|
|
3692
|
+
if (n === 0 || n > 64) throw new ZdHeavyCodecError("Address length must be 1..64");
|
|
3693
|
+
return this.hex(n);
|
|
3694
|
+
}
|
|
3695
|
+
bytes16() {
|
|
3696
|
+
return this.hex(this.number(2));
|
|
3697
|
+
}
|
|
3698
|
+
adapters() {
|
|
3699
|
+
const count = this.number(1);
|
|
3700
|
+
if (count > 8) throw new ZdHeavyCodecError("Too many bridge adapters");
|
|
3701
|
+
return Array.from({ length: count }, () => this.number(2));
|
|
3702
|
+
}
|
|
3703
|
+
end() {
|
|
3704
|
+
if (this.offset !== this.bytes.length) throw new ZdHeavyCodecError("Trailing step bytes");
|
|
3705
|
+
}
|
|
3706
|
+
};
|
|
3707
|
+
function decodeStep(step) {
|
|
3708
|
+
const r = new Reader2(step);
|
|
3709
|
+
if (r.number(1) !== STEP_VERSION) throw new ZdHeavyCodecError("Unsupported step version");
|
|
3710
|
+
const kind = r.number(2);
|
|
3711
|
+
if (kind < 1 || kind > 7) throw new ZdHeavyCodecError("Unknown step kind");
|
|
3712
|
+
const chainId = r.uint(8);
|
|
3713
|
+
const count = r.number(1);
|
|
3714
|
+
if (kind !== StepKind.SWAP && count !== 0) throw new ZdHeavyCodecError("Unexpected allowances");
|
|
3715
|
+
const allowances = Array.from({ length: count }, () => ({
|
|
3716
|
+
pathwayId: r.number(1),
|
|
3717
|
+
maxShareBps: r.number(2),
|
|
3718
|
+
params: r.bytes16()
|
|
3719
|
+
}));
|
|
3720
|
+
const base = { chainId, allowances };
|
|
3721
|
+
let result;
|
|
3722
|
+
switch (kind) {
|
|
3723
|
+
case StepKind.LOCAL_PAYOUT:
|
|
3724
|
+
result = { ...base, kind: "LOCAL_PAYOUT", token: r.address(), receiver: r.address(), minAmountOut: r.uint(16) };
|
|
3725
|
+
break;
|
|
3726
|
+
case StepKind.REMOTE_PAYOUT:
|
|
3727
|
+
result = {
|
|
3728
|
+
...base,
|
|
3729
|
+
kind: "REMOTE_PAYOUT",
|
|
3730
|
+
token: r.address(),
|
|
3731
|
+
receiverChainId: r.uint(8),
|
|
3732
|
+
receiver: r.address(),
|
|
3733
|
+
bridgeAdapters: r.adapters(),
|
|
3734
|
+
maxFee: r.uint(16),
|
|
3735
|
+
minAmountOut: r.uint(16)
|
|
3736
|
+
};
|
|
3737
|
+
break;
|
|
3738
|
+
case StepKind.SEND:
|
|
3739
|
+
result = {
|
|
3740
|
+
...base,
|
|
3741
|
+
kind: "SEND",
|
|
3742
|
+
token: r.address(),
|
|
3743
|
+
dstChainId: r.uint(8),
|
|
3744
|
+
bridgeAdapters: r.adapters(),
|
|
3745
|
+
maxFee: r.uint(16),
|
|
3746
|
+
inUnit: r.uint(16),
|
|
3747
|
+
outUnit: r.uint(16)
|
|
3748
|
+
};
|
|
3749
|
+
break;
|
|
3750
|
+
case StepKind.SWAP:
|
|
3751
|
+
result = { ...base, kind: "SWAP", tokenIn: r.address(), tokenOut: r.address(), expectedIn: r.uint(16), minOut: r.uint(16) };
|
|
3752
|
+
break;
|
|
3753
|
+
case StepKind.EXECUTE:
|
|
3754
|
+
result = { ...base, kind: "EXECUTE", token: r.address(), receiver: r.address(), minAmountOut: r.uint(16), gasLimit: r.uint(8), data: r.bytes16() };
|
|
3755
|
+
break;
|
|
3756
|
+
case StepKind.NET: {
|
|
3757
|
+
const token = r.address(), pathwayId = r.number(1), arriveStep = r.number(1);
|
|
3758
|
+
const params = r.hex(78);
|
|
3759
|
+
const t = new Reader2(params);
|
|
3760
|
+
const terms = {
|
|
3761
|
+
nettingDeadline: t.uint(8),
|
|
3762
|
+
dstDomain: t.number(4),
|
|
3763
|
+
dstAsset: t.hex(32),
|
|
3764
|
+
inUnit: t.uint(16),
|
|
3765
|
+
outUnit: t.uint(16),
|
|
3766
|
+
complianceClass: t.number(2)
|
|
3767
|
+
};
|
|
3768
|
+
result = { chainId, allowances: [{ pathwayId, maxShareBps: 0, params }], kind: "NET", token, pathwayId, arriveStep, terms };
|
|
3769
|
+
break;
|
|
3770
|
+
}
|
|
3771
|
+
case StepKind.SUBSIDY:
|
|
3772
|
+
result = { ...base, kind: "SUBSIDY", token: r.address(), minIn: r.uint(16), amountOut: r.uint(16) };
|
|
3773
|
+
break;
|
|
3774
|
+
default:
|
|
3775
|
+
throw new ZdHeavyCodecError("Unknown step kind");
|
|
3776
|
+
}
|
|
3777
|
+
r.end();
|
|
3778
|
+
return result;
|
|
3779
|
+
}
|
|
3780
|
+
function routerWord(addr) {
|
|
3781
|
+
return concat([toHex(new Uint8Array(12)), checkedHex(addr, 20)]);
|
|
3782
|
+
}
|
|
3783
|
+
function ownerWord(addr) {
|
|
3784
|
+
return routerWord(addr);
|
|
3785
|
+
}
|
|
3786
|
+
function encodeOrderHeader(serial, router, ownerType, owner) {
|
|
3787
|
+
if (!Number.isInteger(ownerType) || ownerType < 0 || ownerType > 255) throw new ZdHeavyCodecError("Invalid ownerType");
|
|
3788
|
+
return concat(["0x050000", uint(serial, 8), routerWord(router), uint(BigInt(ownerType), 1), checkedHex(owner, 32)]);
|
|
3789
|
+
}
|
|
3790
|
+
function orderIdOf(expiryDate, header, steps) {
|
|
3791
|
+
if (steps.length < 1 || steps.length > MAX_STEPS2) throw new ZdHeavyCodecError("Step count must be 1..8");
|
|
3792
|
+
return keccak256(
|
|
3793
|
+
concat([toHex(toBytes("ZD/ORDER")), uint(expiryDate, 8), keccak256(checkedHex(header)), ...steps.map((step) => keccak256(checkedHex(step)))])
|
|
3794
|
+
);
|
|
3795
|
+
}
|
|
3796
|
+
var ZDHEAVY_SUBMIT_SELECTOR = "0x1a579a0c";
|
|
3797
|
+
var ZDHEAVY_PARTNER_SUBMIT_SELECTOR = "0xdd3d9749";
|
|
3798
|
+
var ZDHEAVY_QUOTE_SELECTOR = "0x3cfc3141";
|
|
3799
|
+
function decodeZdHeavySubmit(data) {
|
|
3800
|
+
const hex = checkedHex(data);
|
|
3801
|
+
const selector = hex.slice(0, 10);
|
|
3802
|
+
if (selector !== ZDHEAVY_SUBMIT_SELECTOR && selector !== ZDHEAVY_PARTNER_SUBMIT_SELECTOR) {
|
|
3803
|
+
throw new ZdHeavyCodecError("Expected submitOrder");
|
|
3804
|
+
}
|
|
3805
|
+
const body = hex.slice(10);
|
|
3806
|
+
const size = body.length / 2;
|
|
3807
|
+
const fail = () => {
|
|
3808
|
+
throw new ZdHeavyCodecError("Invalid submitOrder calldata");
|
|
3809
|
+
};
|
|
3810
|
+
const word2 = (at, bits = 256) => {
|
|
3811
|
+
if (!Number.isSafeInteger(at) || at < 0 || at + 32 > size) return fail();
|
|
3812
|
+
const n2 = BigInt(`0x${body.slice(at * 2, (at + 32) * 2)}`);
|
|
3813
|
+
if (n2 >= 1n << BigInt(bits)) return fail();
|
|
3814
|
+
return n2;
|
|
3815
|
+
};
|
|
3816
|
+
const fixed = (at) => {
|
|
3817
|
+
word2(at);
|
|
3818
|
+
return `0x${body.slice(at * 2, (at + 32) * 2)}`;
|
|
3819
|
+
};
|
|
3820
|
+
const offset = (at, expected) => {
|
|
3821
|
+
if (word2(at) !== BigInt(expected)) fail();
|
|
3822
|
+
};
|
|
3823
|
+
const bytes = (at) => {
|
|
3824
|
+
const n2 = word2(at);
|
|
3825
|
+
if (n2 > BigInt(size - at - 32)) return fail();
|
|
3826
|
+
const length = Number(n2);
|
|
3827
|
+
const end = at + 32 + Math.ceil(length / 32) * 32;
|
|
3828
|
+
if (end > size || /[^0]/.test(body.slice((at + 32 + length) * 2, end * 2))) return fail();
|
|
3829
|
+
return { value: `0x${body.slice((at + 32) * 2, (at + 32 + length) * 2)}`, end };
|
|
3830
|
+
};
|
|
3831
|
+
const base = selector === ZDHEAVY_SUBMIT_SELECTOR ? 32 : 64;
|
|
3832
|
+
offset(0, base);
|
|
3833
|
+
const partnerId = base === 64 ? fixed(32) : null;
|
|
3834
|
+
const serial = word2(base, 64);
|
|
3835
|
+
const ownerType = Number(word2(base + 32, 8));
|
|
3836
|
+
const owner = fixed(base + 64);
|
|
3837
|
+
const expiryDate = word2(base + 160, 64);
|
|
3838
|
+
offset(base + 96, 224);
|
|
3839
|
+
const ownerSignature = bytes(base + 224);
|
|
3840
|
+
offset(base + 128, ownerSignature.end - base);
|
|
3841
|
+
const array = ownerSignature.end;
|
|
3842
|
+
const count = word2(array);
|
|
3843
|
+
if (count > BigInt(Math.floor((size - array - 32) / 32))) return fail();
|
|
3844
|
+
const n = Number(count);
|
|
3845
|
+
const arrayBase = array + 32;
|
|
3846
|
+
let next = arrayBase + n * 32;
|
|
3847
|
+
const steps = [];
|
|
3848
|
+
for (let i = 0; i < n; i++) {
|
|
3849
|
+
offset(arrayBase + i * 32, next - arrayBase);
|
|
3850
|
+
const step = bytes(next);
|
|
3851
|
+
steps.push(step.value);
|
|
3852
|
+
next = step.end;
|
|
3853
|
+
}
|
|
3854
|
+
offset(base + 192, next - base);
|
|
3855
|
+
const q = next;
|
|
3856
|
+
const amountIn = word2(q, 128);
|
|
3857
|
+
const fee = { input: word2(q + 32, 128), native: word2(q + 64, 128) };
|
|
3858
|
+
const quoteId = fixed(q + 96);
|
|
3859
|
+
const requestId = fixed(q + 128);
|
|
3860
|
+
const expiresAt = word2(q + 160, 64);
|
|
3861
|
+
offset(q + 192, 224);
|
|
3862
|
+
const signature = bytes(q + 224);
|
|
3863
|
+
if (signature.end !== size) return fail();
|
|
3864
|
+
return {
|
|
3865
|
+
submission: {
|
|
3866
|
+
serial,
|
|
3867
|
+
ownerType,
|
|
3868
|
+
owner,
|
|
3869
|
+
ownerSignature: ownerSignature.value,
|
|
3870
|
+
steps,
|
|
3871
|
+
expiryDate,
|
|
3872
|
+
quote: { amountIn, fee, quoteId, requestId, expiresAt, signature: signature.value }
|
|
3873
|
+
},
|
|
3874
|
+
partnerId
|
|
3875
|
+
};
|
|
3876
|
+
}
|
|
3877
|
+
function quoteSubmitCalldata(data) {
|
|
3878
|
+
decodeZdHeavySubmit(data);
|
|
3879
|
+
const tuple = data.slice(data.slice(0, 10).toLowerCase() === ZDHEAVY_SUBMIT_SELECTOR ? 74 : 138);
|
|
3880
|
+
return `${ZDHEAVY_QUOTE_SELECTOR}${uintWord(32)}${tuple}`;
|
|
3881
|
+
}
|
|
3882
|
+
|
|
3883
|
+
// src/core/zdheavy-check.ts
|
|
3884
|
+
var isAddress2 = hasValidChecksum;
|
|
3885
|
+
var getAddress = (s) => toChecksumAddress(s);
|
|
3886
|
+
var refuse = (what) => ({
|
|
3887
|
+
ok: false,
|
|
3888
|
+
reason: `The ZD Heavy order the gateway built does not match the order shown (${what}) \u2014 refusing to sign.`
|
|
3889
|
+
});
|
|
3890
|
+
var lower = (v) => typeof v === "string" ? v.toLowerCase() : "";
|
|
3891
|
+
function big2(v) {
|
|
3892
|
+
if (v === void 0 || v === null || v === "") return null;
|
|
3893
|
+
try {
|
|
3894
|
+
return BigInt(v);
|
|
3895
|
+
} catch {
|
|
3896
|
+
return null;
|
|
3897
|
+
}
|
|
3898
|
+
}
|
|
3899
|
+
var sameBig = (a, b) => big2(b) === a;
|
|
3900
|
+
var sameAddr = (a, b) => !!b && lower(a) === lower(b);
|
|
3901
|
+
function checkZdHeavyRouter(chainId, router) {
|
|
3902
|
+
if (!router || !isAddress2(router)) return { ok: false, reason: "No valid ZD Heavy router address for this chain \u2014 refusing to sign." };
|
|
3903
|
+
const address = getAddress(router);
|
|
3904
|
+
const pinned = (ZDHEAVY_ROUTER_ADDRESSES[chainId] ?? []).map((a) => getAddress(a));
|
|
3905
|
+
if (!pinned.includes(address)) {
|
|
3906
|
+
return { ok: false, reason: `Router ${address} is not a trusted ZD Heavy router on this chain \u2014 refusing to sign.` };
|
|
3907
|
+
}
|
|
3908
|
+
return { ok: true, address };
|
|
3909
|
+
}
|
|
3910
|
+
function checkZdHeavyValue(txValue, quotedSubmit) {
|
|
3911
|
+
if (quotedSubmit === void 0) return { ok: false, reason: "The router\u2019s submit fee could not be read \u2014 refusing to sign." };
|
|
3912
|
+
if (big2(txValue) !== quotedSubmit) return { ok: false, reason: "The transaction carries a native value the router did not quote \u2014 refusing to sign." };
|
|
3913
|
+
return { ok: true };
|
|
3914
|
+
}
|
|
3915
|
+
function sameAllowances(d, j) {
|
|
3916
|
+
if (d.kind !== "SWAP") return true;
|
|
3917
|
+
const want = j.allowances ?? [];
|
|
3918
|
+
if (want.length !== d.allowances.length) return false;
|
|
3919
|
+
return d.allowances.every((a, i) => {
|
|
3920
|
+
const w = want[i];
|
|
3921
|
+
return a.pathwayId === w.pathwayId && a.maxShareBps === w.maxShareBps && lower(a.params) === lower(w.params && w.params !== "" ? w.params : "0x");
|
|
3922
|
+
});
|
|
3923
|
+
}
|
|
3924
|
+
function sameAdapters(a, b) {
|
|
3925
|
+
const w = b ?? [];
|
|
3926
|
+
return a.length === w.length && a.every((x, i) => x === w[i]);
|
|
3927
|
+
}
|
|
3928
|
+
function sameStep(d, j) {
|
|
3929
|
+
if (d.kind !== String(j.kind).toUpperCase()) return false;
|
|
3930
|
+
if (!sameBig(d.chainId, j.chainId)) return false;
|
|
3931
|
+
if (!sameAllowances(d, j)) return false;
|
|
3932
|
+
switch (d.kind) {
|
|
3933
|
+
case "SWAP":
|
|
3934
|
+
return sameAddr(d.tokenIn, j.tokenIn) && sameAddr(d.tokenOut, j.tokenOut) && sameBig(d.expectedIn, j.expectedIn) && sameBig(d.minOut, j.minOut);
|
|
3935
|
+
case "LOCAL_PAYOUT":
|
|
3936
|
+
return sameAddr(d.token, j.token) && sameAddr(d.receiver, j.receiver) && sameBig(d.minAmountOut, j.minAmountOut);
|
|
3937
|
+
case "REMOTE_PAYOUT":
|
|
3938
|
+
return sameAddr(d.token, j.token) && sameBig(d.receiverChainId, j.receiverChainId) && sameAddr(d.receiver, j.receiver) && sameAdapters(d.bridgeAdapters, j.bridgeAdapters) && sameBig(d.maxFee, j.maxFee) && sameBig(d.minAmountOut, j.minAmountOut);
|
|
3939
|
+
case "SEND":
|
|
3940
|
+
return sameAddr(d.token, j.token) && sameBig(d.dstChainId, j.dstChainId) && sameAdapters(d.bridgeAdapters, j.bridgeAdapters) && sameBig(d.maxFee, j.maxFee) && sameBig(d.inUnit, j.inUnit) && sameBig(d.outUnit, j.outUnit);
|
|
3941
|
+
case "SUBSIDY":
|
|
3942
|
+
return sameAddr(d.token, j.token) && sameBig(d.minIn, j.minIn) && sameBig(d.amountOut, j.amountOut);
|
|
3943
|
+
case "NET": {
|
|
3944
|
+
const t = j.terms;
|
|
3945
|
+
if (!t) return false;
|
|
3946
|
+
const domainOfAsset = Number(BigInt(t.dstAsset) >> 224n);
|
|
3947
|
+
return sameAddr(d.token, j.token) && d.pathwayId === j.pathwayId && d.arriveStep === j.arriveStep && sameBig(d.terms.nettingDeadline, t.nettingDeadline) && d.terms.dstDomain === domainOfAsset && lower(d.terms.dstAsset) === lower(t.dstAsset) && sameBig(d.terms.inUnit, t.inUnit) && sameBig(d.terms.outUnit, t.outUnit);
|
|
3948
|
+
}
|
|
3949
|
+
default:
|
|
3950
|
+
return false;
|
|
3951
|
+
}
|
|
3952
|
+
}
|
|
3953
|
+
function checkSubmit(tx, e) {
|
|
3954
|
+
if (tx.chainId !== String(e.chainId)) return refuse("chain");
|
|
3955
|
+
if (!sameAddr(e.router, tx.to)) return refuse("router");
|
|
3956
|
+
let decoded;
|
|
3957
|
+
try {
|
|
3958
|
+
decoded = decodeZdHeavySubmit(tx.data);
|
|
3959
|
+
} catch {
|
|
3960
|
+
return refuse("not a router submitOrder");
|
|
3961
|
+
}
|
|
3962
|
+
const { submission: s, partnerId } = decoded;
|
|
3963
|
+
const order = e.order;
|
|
3964
|
+
if (!order) return refuse("no order");
|
|
3965
|
+
const wantPartner = typeof e.partnerId === "string" && /^0x[0-9a-fA-F]{64}$/.test(e.partnerId) ? lower(e.partnerId) : null;
|
|
3966
|
+
if ((partnerId ? lower(partnerId) : null) !== wantPartner) return refuse("partner id");
|
|
3967
|
+
if (!isAddress2(e.owner)) return refuse("owner");
|
|
3968
|
+
if (s.ownerType !== 1 || lower(s.owner) !== lower(ownerWord(e.owner))) return refuse("owner");
|
|
3969
|
+
if (s.ownerSignature !== "0x") return refuse("owner signature");
|
|
3970
|
+
if (!s.quote.signature || s.quote.signature === "0x") return refuse("no API signature");
|
|
3971
|
+
if (order.chainNumber !== e.chainId || !sameAddr(e.router, order.router)) return refuse("router");
|
|
3972
|
+
if (s.steps.length < 1 || s.steps.length > MAX_STEPS2 || s.steps.length !== order.steps.length) return refuse("number of steps");
|
|
3973
|
+
const steps = [];
|
|
3974
|
+
for (let i = 0; i < s.steps.length; i++) {
|
|
3975
|
+
let d;
|
|
3976
|
+
try {
|
|
3977
|
+
d = decodeStep(s.steps[i]);
|
|
3978
|
+
} catch {
|
|
3979
|
+
return refuse(`step ${i} encoding`);
|
|
3980
|
+
}
|
|
3981
|
+
if (d.kind === "EXECUTE") return refuse(`step ${i} kind EXECUTE`);
|
|
3982
|
+
if (!sameStep(d, order.steps[i])) return refuse(`step ${i}`);
|
|
3983
|
+
steps.push(d);
|
|
3984
|
+
}
|
|
3985
|
+
const first = steps[0];
|
|
3986
|
+
if (first.chainId !== BigInt(e.chainId)) return refuse("source chain");
|
|
3987
|
+
const firstToken = first.kind === "SWAP" ? first.tokenIn : "token" in first ? first.token : "";
|
|
3988
|
+
if (!sameAddr(e.fromToken, firstToken) || !sameAddr(e.fromToken, order.tokenIn)) return refuse("source token");
|
|
3989
|
+
const last = steps[steps.length - 1];
|
|
3990
|
+
if (steps.slice(0, -1).some((d) => d.kind === "LOCAL_PAYOUT" || d.kind === "REMOTE_PAYOUT")) return refuse("payout before the last step");
|
|
3991
|
+
if (last.kind !== "LOCAL_PAYOUT" && last.kind !== "REMOTE_PAYOUT") return refuse("no payout");
|
|
3992
|
+
const deliveryChain = last.kind === "LOCAL_PAYOUT" ? last.chainId : last.receiverChainId;
|
|
3993
|
+
if (deliveryChain !== BigInt(e.toChainId)) return refuse("destination chain");
|
|
3994
|
+
if (last.kind === "LOCAL_PAYOUT") {
|
|
3995
|
+
if (!sameAddr(e.toToken, last.token)) return refuse("destination token");
|
|
3996
|
+
} else {
|
|
3997
|
+
if (!e.remotePayoutToken?.(last.token, Number(last.chainId))) return refuse("destination token of a cross-chain payout");
|
|
3998
|
+
}
|
|
3999
|
+
if (!sameAddr(e.receiver, last.receiver)) return refuse("receiver");
|
|
4000
|
+
const amountIn = big2(order.amountIn);
|
|
4001
|
+
const feeInput = big2(order.fee.input);
|
|
4002
|
+
const feeNative = big2(order.fee.native);
|
|
4003
|
+
if (amountIn === null || feeInput === null || feeNative === null) return refuse("amount");
|
|
4004
|
+
if (s.quote.amountIn !== amountIn || s.quote.fee.input !== feeInput || s.quote.fee.native !== feeNative) return refuse("amount");
|
|
4005
|
+
if (amountIn + feeInput !== e.amountRaw || big2(order.grossIn) !== e.amountRaw) return refuse("amount");
|
|
4006
|
+
if (s.expiryDate !== BigInt(order.expiryDate) || s.quote.expiresAt !== BigInt(order.expiresAt)) return refuse("expiry");
|
|
4007
|
+
if (s.expiryDate <= BigInt(e.nowSec) || s.quote.expiresAt <= BigInt(e.nowSec)) return refuse("expired");
|
|
4008
|
+
if (last.kind === "REMOTE_PAYOUT" && last.maxFee >= last.minAmountOut) return refuse("minimum out");
|
|
4009
|
+
const floor = last.kind === "REMOTE_PAYOUT" ? last.minAmountOut - last.maxFee : last.minAmountOut;
|
|
4010
|
+
if (floor <= 0n || floor !== e.finalAmount) return refuse("minimum out");
|
|
4011
|
+
let orderId;
|
|
4012
|
+
try {
|
|
4013
|
+
orderId = orderIdOf(s.expiryDate, encodeOrderHeader(s.serial, getAddress(e.router), 1, s.owner), s.steps);
|
|
4014
|
+
} catch {
|
|
4015
|
+
return refuse("order id");
|
|
4016
|
+
}
|
|
4017
|
+
if (!e.rootHash || lower(orderId) !== lower(e.rootHash)) return refuse("order id");
|
|
4018
|
+
return { ok: true, floor, orderId };
|
|
4019
|
+
}
|
|
4020
|
+
function checkZdHeavySubmit(tx, e) {
|
|
4021
|
+
try {
|
|
4022
|
+
return checkSubmit(tx, e);
|
|
4023
|
+
} catch {
|
|
4024
|
+
return refuse("malformed order");
|
|
4025
|
+
}
|
|
4026
|
+
}
|
|
4027
|
+
|
|
4028
|
+
// src/core/asset-identity.ts
|
|
4029
|
+
function key(chainId, address) {
|
|
4030
|
+
const id = Number(chainId);
|
|
4031
|
+
return Number.isSafeInteger(id) && id > 0 && typeof address === "string" && isChainAddress(id, address) ? tokenKey(id, address) : null;
|
|
4032
|
+
}
|
|
4033
|
+
function sameAssetDeployment(tokens, routes, a, b) {
|
|
4034
|
+
const ka = key(a.chainId, a.address);
|
|
4035
|
+
const kb = key(b.chainId, b.address);
|
|
4036
|
+
if (!ka || !kb) return false;
|
|
4037
|
+
const parent = /* @__PURE__ */ new Map();
|
|
4038
|
+
const find = (k) => {
|
|
4039
|
+
const p = parent.get(k);
|
|
4040
|
+
if (p === void 0) {
|
|
4041
|
+
parent.set(k, k);
|
|
4042
|
+
return k;
|
|
4043
|
+
}
|
|
4044
|
+
if (p === k) return k;
|
|
4045
|
+
const root = find(p);
|
|
4046
|
+
parent.set(k, root);
|
|
4047
|
+
return root;
|
|
4048
|
+
};
|
|
4049
|
+
const join = (x, y) => {
|
|
4050
|
+
if (x && y) parent.set(find(y), find(x));
|
|
4051
|
+
};
|
|
4052
|
+
for (const r of routes) {
|
|
4053
|
+
if (r.isEnabled === false) continue;
|
|
4054
|
+
const from = key(r.fromChainId, r.fromAddress);
|
|
4055
|
+
const to = key(r.toChainId, r.toAddress);
|
|
4056
|
+
join(from, to);
|
|
4057
|
+
const home = key(r.homeChainId, r.homeTokenAddress);
|
|
4058
|
+
join(from, home);
|
|
4059
|
+
join(to, home);
|
|
4060
|
+
}
|
|
4061
|
+
for (const t of tokens) join(key(t.chainId, t.address), key(t.homeChainId, t.homeTokenAddress));
|
|
4062
|
+
return parent.has(ka) && parent.has(kb) && find(ka) === find(kb);
|
|
4063
|
+
}
|
|
4064
|
+
|
|
4065
|
+
// src/core/validate-tx.ts
|
|
4066
|
+
var lower2 = (v) => String(v || "").toLowerCase();
|
|
4067
|
+
function isHexAddress(value) {
|
|
4068
|
+
return /^0x[a-fA-F0-9]{40}$/.test(String(value || ""));
|
|
4069
|
+
}
|
|
4070
|
+
function isHexData(value) {
|
|
4071
|
+
return /^0x(?:[a-fA-F0-9]{2})*$/.test(String(value || "0x"));
|
|
4072
|
+
}
|
|
4073
|
+
function isHexQuantity(value) {
|
|
4074
|
+
return /^0x[0-9a-fA-F]+$/.test(String(value || "0x0"));
|
|
4075
|
+
}
|
|
4076
|
+
function dataWord(data, index) {
|
|
4077
|
+
const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
|
|
4078
|
+
return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
|
|
4079
|
+
}
|
|
4080
|
+
function dataAddress(data, index) {
|
|
4081
|
+
const word2 = dataWord(data, index);
|
|
4082
|
+
return word2 ? `0x${word2.slice(24)}` : "";
|
|
4083
|
+
}
|
|
4084
|
+
function dataUint(data, index) {
|
|
4085
|
+
const word2 = dataWord(data, index);
|
|
4086
|
+
return word2 ? BigInt(`0x${word2}`) : null;
|
|
4087
|
+
}
|
|
4088
|
+
function rawEquals(value, expected) {
|
|
4089
|
+
try {
|
|
4090
|
+
return value === BigInt(expected || "0");
|
|
4091
|
+
} catch {
|
|
4092
|
+
return false;
|
|
4093
|
+
}
|
|
4094
|
+
}
|
|
4095
|
+
function planMsgValueHex(route) {
|
|
4096
|
+
try {
|
|
4097
|
+
const raw2 = route?.quote?.msgValue;
|
|
4098
|
+
if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
|
|
4099
|
+
return "0x" + BigInt(raw2).toString(16);
|
|
4100
|
+
} catch {
|
|
4101
|
+
return null;
|
|
4102
|
+
}
|
|
4103
|
+
}
|
|
4104
|
+
function validatePlannedTransaction(tx, route, expectedRecipient, heavyExpected) {
|
|
4105
|
+
if (!tx || tx.mock) return true;
|
|
4106
|
+
if (!isHexAddress(tx.to) || !isHexData(tx.data || "0x") || !isHexQuantity(tx.value || "0x0")) return false;
|
|
4107
|
+
const data = String(tx.data || "0x").toLowerCase();
|
|
4108
|
+
const selector = data.slice(0, 10);
|
|
4109
|
+
const value = lower2(tx.value || "0x0");
|
|
4110
|
+
if (tx.kind === "transfer") {
|
|
4111
|
+
if (value !== "0x0") return false;
|
|
4112
|
+
return selector === "0xa9059cbb" && isHexAddress(tx.token) && lower2(tx.to) === lower2(tx.token) && lower2(dataAddress(data, 0)) === lower2(expectedRecipient) && rawEquals(dataUint(data, 1), tx.amountRaw);
|
|
4113
|
+
}
|
|
4114
|
+
if (tx.kind === "approve") {
|
|
4115
|
+
if (route.zdHeavy) {
|
|
4116
|
+
return !!heavyExpected && tx.chainId === heavyExpected.chainId && lower2(tx.to) === lower2(heavyExpected.fromToken) && lower2(data) === lower2(encodeApprove(heavyExpected.router, heavyExpected.amountRaw)) && BigInt(value) === 0n;
|
|
4117
|
+
}
|
|
4118
|
+
if (value !== "0x0") return false;
|
|
4119
|
+
return selector === "0x095ea7b3" && isHexAddress(tx.token) && isHexAddress(tx.spender) && lower2(tx.to) === lower2(tx.token) && lower2(dataAddress(data, 0)) === lower2(tx.spender) && rawEquals(dataUint(data, 1), tx.amountRaw);
|
|
4120
|
+
}
|
|
4121
|
+
if (tx.kind === "submitOrder") {
|
|
4122
|
+
if (route.zdHeavy) {
|
|
4123
|
+
const expectedValue = planMsgValueHex(route);
|
|
4124
|
+
return expectedValue !== null && value === lower2(expectedValue) && !!heavyExpected && checkZdHeavySubmit({ ...tx, chainId: String(tx.chainId) }, heavyExpected).ok;
|
|
4125
|
+
}
|
|
4126
|
+
const expected = planMsgValueHex(route);
|
|
4127
|
+
if (expected === null || value !== lower2(expected)) return false;
|
|
4128
|
+
if (selector !== SUBMIT_ORDER_SELECTOR || !isHexAddress(tx.escrow) || lower2(tx.to) !== lower2(tx.escrow)) return false;
|
|
4129
|
+
const decoded = decodeSubmitOrderCalldata(data);
|
|
4130
|
+
if (!decoded) return false;
|
|
4131
|
+
const first = decoded.orders[0];
|
|
4132
|
+
const last = decoded.orders[decoded.orders.length - 1];
|
|
4133
|
+
return decoded.partnerId === lower2(route.quote?.partnerId || NO_PARTNER_ID) && lower2(first.bidToken) === lower2(route.source.tokenAddress) && rawEquals(first.bidTokenAmount, tx.amountRaw) && lower2(last.askToken) === lower2(isSolanaChainId(route.receive.chainId) ? solanaKeyHex(route.receive.tokenAddress || "") : route.receive.tokenAddress) && Number(last.destinationChainId) === Number(route.receive.chainId) && (isSolanaChainId(route.receive.chainId) ? solanaDeliveryMatches(last.destinationReceiver, expectedRecipient, route.receive.tokenAddress) : lower2(last.destinationReceiver) === lower2(expectedRecipient));
|
|
4134
|
+
}
|
|
4135
|
+
return false;
|
|
4136
|
+
}
|
|
4137
|
+
function solanaDeliveryMatches(encoded, recipient2, mint) {
|
|
4138
|
+
try {
|
|
4139
|
+
return lower2(encoded) === expectedSolanaDelivery(recipient2, mint || "");
|
|
4140
|
+
} catch {
|
|
4141
|
+
return false;
|
|
4142
|
+
}
|
|
4143
|
+
}
|
|
4144
|
+
async function allowanceCovers(tx, account, ethCall2) {
|
|
4145
|
+
if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
|
|
4146
|
+
try {
|
|
4147
|
+
const raw2 = await ethCall2(tx.token, encodeAllowance(account, tx.spender));
|
|
4148
|
+
return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
|
|
4149
|
+
} catch {
|
|
4150
|
+
return false;
|
|
4151
|
+
}
|
|
4152
|
+
}
|
|
4153
|
+
|
|
4154
|
+
// src/core/zdheavy-route.ts
|
|
4155
|
+
function zdHeavyExpected(route, owner, receiver, tokens, routes) {
|
|
4156
|
+
const heavy = route.zdHeavy;
|
|
4157
|
+
if (!heavy) throw new Error("Missing ZD Heavy order.");
|
|
4158
|
+
const pin2 = checkZdHeavyRouter(route.source.chainId, heavy.order.router);
|
|
4159
|
+
if (!pin2.ok) throw new Error(pin2.reason);
|
|
4160
|
+
if (route.source.amount !== formatUnits(heavy.amountRaw, route.source.decimals) || route.source.payAmount !== route.source.amount || route.receive.amount !== formatUnits(heavy.finalAmount, route.receive.decimals))
|
|
4161
|
+
throw new Error("ZD Heavy display amount mismatch.");
|
|
4162
|
+
return {
|
|
4163
|
+
chainId: route.source.chainId,
|
|
4164
|
+
router: pin2.address,
|
|
4165
|
+
owner,
|
|
4166
|
+
receiver,
|
|
4167
|
+
fromToken: route.source.tokenAddress,
|
|
4168
|
+
toToken: route.receive.tokenAddress,
|
|
4169
|
+
toChainId: route.receive.chainId,
|
|
4170
|
+
amountRaw: BigInt(heavy.amountRaw),
|
|
4171
|
+
finalAmount: BigInt(heavy.finalAmount),
|
|
4172
|
+
order: heavy.order,
|
|
4173
|
+
rootHash: heavy.rootHash,
|
|
4174
|
+
partnerId: route.quote.partnerId,
|
|
4175
|
+
nowSec: Math.floor(Date.now() / 1e3),
|
|
4176
|
+
remotePayoutToken: (token, chainId) => sameAssetDeployment(tokens, routes, { chainId, address: token }, { chainId: route.receive.chainId, address: route.receive.tokenAddress })
|
|
4177
|
+
};
|
|
4178
|
+
}
|
|
4179
|
+
function validateZdHeavyPlan(route, expected) {
|
|
4180
|
+
if (route.transactions.length !== 2 || route.transactions[0].kind !== "approve" || route.transactions[1].kind !== "submitOrder") {
|
|
4181
|
+
throw new Error("ZD Heavy requires exactly approve then submitOrder; refusing to sign.");
|
|
4182
|
+
}
|
|
4183
|
+
for (const tx of route.transactions) {
|
|
4184
|
+
if (tx.mock || tx.chainId !== expected.chainId || !validatePlannedTransaction(tx, route, expected.receiver, expected)) {
|
|
4185
|
+
throw new Error("ZD Heavy transaction does not match the reviewed plan; refusing to sign.");
|
|
4186
|
+
}
|
|
4187
|
+
}
|
|
4188
|
+
const submit = route.transactions[1];
|
|
4189
|
+
const checked = checkZdHeavySubmit({ ...submit, chainId: String(submit.chainId) }, expected);
|
|
4190
|
+
if (!checked.ok) throw new Error(checked.reason);
|
|
4191
|
+
return checked.floor;
|
|
4192
|
+
}
|
|
4193
|
+
async function preflightZdHeavyPlan(route, expected, readFee) {
|
|
4194
|
+
validateZdHeavyPlan(route, expected);
|
|
4195
|
+
const tx = route.transactions[1];
|
|
4196
|
+
const value = checkZdHeavyValue(tx.value, await readFee(expected.chainId, expected.router, tx.data));
|
|
4197
|
+
if (!value.ok) throw new Error(value.reason);
|
|
4198
|
+
}
|
|
4199
|
+
|
|
4200
|
+
// src/core/zdheavy-build.ts
|
|
4201
|
+
function buildZdHeavyRoute(ctx) {
|
|
4202
|
+
const { option, destination, destinationToken, chains, result } = ctx;
|
|
4203
|
+
const q = result.quote;
|
|
4204
|
+
if (!zdHeavyExecutable(q)) throw new Error("ZD Heavy quote is not signed and executable.");
|
|
4205
|
+
const order = q.execution.order;
|
|
4206
|
+
const sourceAmount = formatUnits(result.youPayRaw, option.decimals);
|
|
4207
|
+
const decimals = assetDecimals(destinationToken);
|
|
4208
|
+
const receiveAmount = formatUnits(result.recipientReceivesRaw, decimals);
|
|
4209
|
+
const partnerId = typeof q.partnerId === "string" && /^0x[0-9a-fA-F]{64}$/.test(q.partnerId) ? q.partnerId : void 0;
|
|
4210
|
+
const route = {
|
|
4211
|
+
id: `zdh-${option.chainId}-${option.symbolKey}-${destination.chainId}-${destinationToken.symbol}`,
|
|
4212
|
+
recommended: false,
|
|
4213
|
+
state: result.meetsTarget ? "ROUTE" : "SHORT",
|
|
4214
|
+
source: {
|
|
4215
|
+
asset: option.symbol,
|
|
4216
|
+
ticker: option.ticker || option.symbol,
|
|
4217
|
+
chainId: option.chainId,
|
|
4218
|
+
chainName: option.chainName,
|
|
4219
|
+
tokenAddress: option.address,
|
|
4220
|
+
decimals: option.decimals,
|
|
4221
|
+
amount: sourceAmount,
|
|
4222
|
+
payAmount: sourceAmount
|
|
4223
|
+
},
|
|
4224
|
+
receive: {
|
|
4225
|
+
asset: destinationToken.symbol,
|
|
4226
|
+
ticker: tokenTicker(destinationToken),
|
|
4227
|
+
chainId: Number(destination.chainId),
|
|
4228
|
+
chainName: chainNameOf(Number(destination.chainId), chains),
|
|
4229
|
+
tokenAddress: destinationToken.address,
|
|
4230
|
+
decimals,
|
|
4231
|
+
amount: receiveAmount
|
|
4232
|
+
},
|
|
4233
|
+
routeLabel: "Settle on ZeroDelta via ZD Heavy.",
|
|
4234
|
+
deltaLabel: result.meetsTarget ? "~0" : "Below requested amount",
|
|
4235
|
+
legs: [
|
|
4236
|
+
{
|
|
4237
|
+
index: 1,
|
|
4238
|
+
fromAsset: option.symbol,
|
|
4239
|
+
fromTicker: option.ticker || option.symbol,
|
|
4240
|
+
fromChainId: option.chainId,
|
|
4241
|
+
fromChainName: option.chainName,
|
|
4242
|
+
fromAmount: sourceAmount,
|
|
4243
|
+
toAsset: destinationToken.symbol,
|
|
4244
|
+
toTicker: tokenTicker(destinationToken),
|
|
4245
|
+
toChainId: Number(destination.chainId),
|
|
4246
|
+
toChainName: chainNameOf(Number(destination.chainId), chains),
|
|
4247
|
+
toAmount: receiveAmount,
|
|
4248
|
+
executionChainId: option.chainId,
|
|
4249
|
+
executionChainName: option.chainName
|
|
4250
|
+
}
|
|
4251
|
+
],
|
|
4252
|
+
transactions: q.txData.map((tx, i) => {
|
|
4253
|
+
const submit = tx.actionType === "submit" || tx.actionType === "submitOrder";
|
|
4254
|
+
if (tx.actionType !== "approve" && !submit) throw new Error("Unexpected ZD Heavy transaction action.");
|
|
4255
|
+
if (typeof tx.value !== "string" || !/^(?:[0-9]+|0x[0-9a-fA-F]+)$/.test(tx.value)) throw new Error("Invalid ZD Heavy native value.");
|
|
4256
|
+
return {
|
|
4257
|
+
id: submit ? "submit-order" : `approve-${i}`,
|
|
4258
|
+
kind: submit ? "submitOrder" : "approve",
|
|
4259
|
+
label: submit ? "Submit ZeroDelta order" : `Approve ${option.ticker || option.symbol}`,
|
|
4260
|
+
chainId: Number(tx.chainId),
|
|
4261
|
+
to: tx.to,
|
|
4262
|
+
data: tx.data,
|
|
4263
|
+
// The gateway publishes decimal wei; EIP-1193 requires a hex quantity.
|
|
4264
|
+
// Calldata and targets remain the gateway's exact bytes.
|
|
4265
|
+
value: toHexQuantity(tx.value),
|
|
4266
|
+
token: option.address,
|
|
4267
|
+
spender: order.router,
|
|
4268
|
+
amountRaw: result.youPayRaw
|
|
4269
|
+
};
|
|
4270
|
+
}),
|
|
4271
|
+
quote: {
|
|
4272
|
+
bridge: q.bridge,
|
|
4273
|
+
feeBps: q.feeBps,
|
|
4274
|
+
estimatedDuration: q.estimatedDuration,
|
|
4275
|
+
gasCostSource: q.gasCostSource,
|
|
4276
|
+
iterations: result.iterations,
|
|
4277
|
+
compliance: q.compliance,
|
|
4278
|
+
partnerId,
|
|
4279
|
+
zeroDeltaFeeCentibips: q.zeroDeltaFeeCentibips,
|
|
4280
|
+
zeroDeltaFeeNative: q.zeroDeltaFeeNative
|
|
4281
|
+
},
|
|
4282
|
+
zdHeavy: { order, rootHash: q.rootHash, amountRaw: result.youPayRaw, finalAmount: result.recipientReceivesRaw, floor: "" }
|
|
4283
|
+
};
|
|
4284
|
+
if (route.transactions.length === 2) route.quote.msgValue = BigInt(route.transactions[1].value).toString();
|
|
4285
|
+
const expected = zdHeavyExpected(route, ctx.payer, destination.address, ctx.tokens, ctx.routes);
|
|
4286
|
+
route.zdHeavy.floor = validateZdHeavyPlan(route, expected).toString();
|
|
4287
|
+
return route;
|
|
4288
|
+
}
|
|
4289
|
+
|
|
4290
|
+
// src/core/quote-compare.ts
|
|
4291
|
+
var WAIT_MIN_SEC = 180;
|
|
4292
|
+
var WAIT_MAX_SEC = 7200;
|
|
4293
|
+
function clampWait(sec) {
|
|
4294
|
+
if (!Number.isFinite(sec)) return WAIT_MIN_SEC;
|
|
4295
|
+
return Math.min(WAIT_MAX_SEC, Math.max(WAIT_MIN_SEC, sec));
|
|
4296
|
+
}
|
|
4297
|
+
var hasTime = (o) => Number.isFinite(o.estimatedDuration) && o.estimatedDuration > 0;
|
|
4298
|
+
function selectableOptions(options) {
|
|
4299
|
+
return options.filter((o) => !o.unavailable);
|
|
4300
|
+
}
|
|
4301
|
+
function bestOutputOption(options) {
|
|
4302
|
+
return selectableOptions(options).reduce((best, o) => !best || o.amount > best.amount ? o : best, void 0);
|
|
4303
|
+
}
|
|
4304
|
+
function fastestOption(options) {
|
|
4305
|
+
const selectable = selectableOptions(options);
|
|
4306
|
+
const labelled = selectable.find((o) => o.label?.toLowerCase() === "fastest");
|
|
4307
|
+
if (labelled) return labelled;
|
|
4308
|
+
return selectable.filter(hasTime).reduce((f, o) => !f || o.estimatedDuration < f.estimatedDuration ? o : f, void 0);
|
|
4309
|
+
}
|
|
4310
|
+
function proposedWait(options) {
|
|
4311
|
+
const best = bestOutputOption(options);
|
|
4312
|
+
return clampWait(best && hasTime(best) ? best.estimatedDuration : WAIT_MIN_SEC);
|
|
4313
|
+
}
|
|
4314
|
+
function pickForWait(options, waitSec) {
|
|
4315
|
+
const within = selectableOptions(options).filter((o) => hasTime(o) && o.estimatedDuration <= waitSec);
|
|
4316
|
+
return bestOutputOption(within) ?? fastestOption(options);
|
|
4317
|
+
}
|
|
4318
|
+
var MAX_QUOTE_CARDS = 3;
|
|
4319
|
+
function visibleOptions(options, waitSec, selectedId) {
|
|
4320
|
+
if (options.length <= MAX_QUOTE_CARDS) return [...options];
|
|
4321
|
+
const selectable = selectableOptions(options);
|
|
4322
|
+
if (selectable.length === 0) return options.slice(0, MAX_QUOTE_CARDS);
|
|
4323
|
+
const chosen = selectable.find((o) => o.id === selectedId) ?? pickForWait(options, waitSec);
|
|
4324
|
+
const gasless = bestOutputOption(selectable.filter((o) => o.gasSponsored));
|
|
4325
|
+
const netting = bestOutputOption(selectable.filter((o) => o.entersNetting));
|
|
4326
|
+
const ids = new Set([chosen?.id, fastestOption(options)?.id, gasless?.id, netting?.id].filter((id) => !!id));
|
|
4327
|
+
const keep = new Set([...ids].slice(0, MAX_QUOTE_CARDS));
|
|
4328
|
+
return options.filter((o) => keep.has(o.id));
|
|
4329
|
+
}
|
|
4330
|
+
function parity(options, inputUsd, toUnitUsd) {
|
|
4331
|
+
const priced = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
4332
|
+
if (!priced(inputUsd) || !priced(toUnitUsd)) return { kind: "unknown" };
|
|
4333
|
+
const reaching = selectableOptions(options).filter((o) => hasTime(o) && o.amount * toUnitUsd >= inputUsd);
|
|
4334
|
+
const earliest = reaching.reduce(
|
|
4335
|
+
(e, o) => !e || o.estimatedDuration < e.estimatedDuration || o.estimatedDuration === e.estimatedDuration && o.amount > e.amount ? o : e,
|
|
4336
|
+
void 0
|
|
4337
|
+
);
|
|
4338
|
+
return earliest ? { kind: "at", option: earliest, timeSec: earliest.estimatedDuration } : { kind: "unavailable" };
|
|
4339
|
+
}
|
|
4340
|
+
function extraVsFastest(options, selectedId) {
|
|
4341
|
+
const selected = selectableOptions(options).find((o) => o.id === selectedId);
|
|
4342
|
+
const fastest = fastestOption(options);
|
|
4343
|
+
if (!selected || !fastest) return null;
|
|
4344
|
+
const extra = selected.amount - fastest.amount;
|
|
4345
|
+
return extra > 1e-9 ? extra : null;
|
|
4346
|
+
}
|
|
4347
|
+
function routeBadges(options) {
|
|
4348
|
+
const field = options.filter((o) => !o.unavailable);
|
|
4349
|
+
const out = /* @__PURE__ */ new Map();
|
|
4350
|
+
if (field.length < 2) return out;
|
|
4351
|
+
const best = (pick, better) => field.reduce((acc, o) => {
|
|
4352
|
+
const value = pick(o);
|
|
4353
|
+
if (value === null) return acc;
|
|
4354
|
+
const accValue = acc ? pick(acc) : null;
|
|
4355
|
+
return accValue === null || better(value, accValue) ? o : acc;
|
|
4356
|
+
}, null);
|
|
4357
|
+
const bestReturn = best(
|
|
4358
|
+
(o) => o.amount,
|
|
4359
|
+
(a, b) => a > b
|
|
4360
|
+
);
|
|
4361
|
+
const fastest = best(
|
|
4362
|
+
(o) => o.estimatedDuration,
|
|
4363
|
+
(a, b) => a < b
|
|
4364
|
+
);
|
|
4365
|
+
const lowestFee = best(
|
|
4366
|
+
(o) => o.feeUsd,
|
|
4367
|
+
(a, b) => a < b
|
|
4368
|
+
);
|
|
4369
|
+
if (bestReturn) out.set(bestReturn.id, "Best return");
|
|
4370
|
+
if (fastest && !out.has(fastest.id)) out.set(fastest.id, "Fastest");
|
|
4371
|
+
if (lowestFee && !out.has(lowestFee.id)) out.set(lowestFee.id, "Lowest fee");
|
|
4372
|
+
return out;
|
|
4373
|
+
}
|
|
4374
|
+
function routeShapeLabel(option) {
|
|
4375
|
+
if (!option) return null;
|
|
4376
|
+
if (option.kind === "transfer") return "Transfer";
|
|
4377
|
+
const middle = option.hops.slice(1, -1);
|
|
4378
|
+
if (middle.length === 0) return "Direct";
|
|
4379
|
+
return `Via ${middle.map((h2) => h2.ticker).join(" \xB7 ")}`;
|
|
4380
|
+
}
|
|
4381
|
+
function cornerTags(options, option, parityState) {
|
|
4382
|
+
if (option.unavailable) return [];
|
|
4383
|
+
if (option.kind === "transfer") return [{ text: "Transfer", tone: "brand" }];
|
|
4384
|
+
const tags = [];
|
|
4385
|
+
const labelledFastest = selectableOptions(options).some((o) => o.label?.toLowerCase() === "fastest");
|
|
4386
|
+
if (parityState.kind === "at" && parityState.option.id === option.id) tags.push({ text: "Target 1:1", tone: "brand" });
|
|
4387
|
+
else if (option.entersNetting) tags.push({ text: "Potential best return", tone: "brand" });
|
|
4388
|
+
else if (option.label?.toLowerCase() === "fastest") tags.push({ text: "Fastest", tone: "brand" });
|
|
4389
|
+
else if (option.gasSponsored) tags.push({ text: "Gasless", tone: "purple" });
|
|
4390
|
+
else {
|
|
4391
|
+
const badge = routeBadges(options).get(option.id);
|
|
4392
|
+
const text = badge === "Fastest" && labelledFastest ? void 0 : badge ?? routeShapeLabel(option) ?? void 0;
|
|
4393
|
+
if (text) tags.push({ text, tone: "brand" });
|
|
4394
|
+
}
|
|
4395
|
+
if (option.entersNetting) tags.push({ text: "Netting", tone: "green" });
|
|
4396
|
+
return tags;
|
|
4397
|
+
}
|
|
4398
|
+
function compareFeeUsd(option, fromUsd) {
|
|
4399
|
+
const centibips = option.feeCentibips;
|
|
4400
|
+
if (centibips === void 0 || option.feeNative) return null;
|
|
4401
|
+
if (centibips === 0) return 0;
|
|
4402
|
+
return typeof fromUsd === "number" && Number.isFinite(fromUsd) && fromUsd > 0 ? fromUsd * centibips / 1e6 : null;
|
|
4403
|
+
}
|
|
4404
|
+
function priceCompareOptions(options, fromUsd) {
|
|
4405
|
+
return options.map((o) => ({ ...o, feeUsd: compareFeeUsd(o, fromUsd) }));
|
|
4406
|
+
}
|
|
4407
|
+
var ZD_HEAVY_KEY_PREFIX = "zdheavy:";
|
|
4408
|
+
function zdHeavyOptionKey(q) {
|
|
4409
|
+
return q.label ? `${ZD_HEAVY_KEY_PREFIX}${q.label}:${String(q.escrowAddress ?? "").toLowerCase()}` : `${ZD_HEAVY_KEY_PREFIX}id:${q.optionId ?? ""}`;
|
|
4410
|
+
}
|
|
4411
|
+
function zdHeavyUnavailableStatus(q) {
|
|
4412
|
+
return zdHeavyExecutable(q) ? void 0 : typeof q.payloadStatus === "string" && q.payloadStatus ? q.payloadStatus : "unknown";
|
|
4413
|
+
}
|
|
4414
|
+
function tokenAt2(tokens, chainId, address) {
|
|
4415
|
+
const key2 = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
|
|
4416
|
+
const wanted = isChainAddress(chainId, key2) ? chainAddressKey(chainId, key2) : null;
|
|
4417
|
+
if (!wanted || !tokens?.length) return void 0;
|
|
4418
|
+
return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
|
|
4419
|
+
}
|
|
4420
|
+
function hopFor(tokens, address, chainId, fallback) {
|
|
4421
|
+
const token = tokenAt2(tokens, chainId, address);
|
|
4422
|
+
return { address, chainId, ticker: token ? tokenTicker(token) : fallback ?? "Unknown" };
|
|
4423
|
+
}
|
|
4424
|
+
function compareHops(quote, ctx) {
|
|
4425
|
+
if (quote.protocol === "zdheavy") {
|
|
4426
|
+
const order = quote.execution?.order;
|
|
4427
|
+
if (!order || !Array.isArray(order.steps) || !order.steps.length) return [];
|
|
4428
|
+
const first = order.steps[0];
|
|
4429
|
+
const hops2 = [hopFor(ctx.tokens, String(first.tokenIn ?? first.token ?? order.tokenIn ?? ""), Number(order.chainNumber), ctx.from.ticker)];
|
|
4430
|
+
const push = (address, chainId, fallback) => {
|
|
4431
|
+
if (!address || chainId === void 0) return;
|
|
4432
|
+
const previous = hops2[hops2.length - 1];
|
|
4433
|
+
if (previous.address.toLowerCase() === address.toLowerCase() && previous.chainId === Number(chainId)) return;
|
|
4434
|
+
hops2.push(hopFor(ctx.tokens, address, Number(chainId), fallback));
|
|
4435
|
+
};
|
|
4436
|
+
order.steps.forEach((s, i) => {
|
|
4437
|
+
const n = order.steps[i + 1];
|
|
4438
|
+
const p = hops2[hops2.length - 1];
|
|
4439
|
+
if (s.kind === "SWAP") push(s.tokenOut, s.chainId);
|
|
4440
|
+
else if (s.kind === "SEND") push(n?.tokenIn ?? n?.token, s.dstChainId, p.ticker);
|
|
4441
|
+
else if (s.kind === "LOCAL_PAYOUT") push(s.token, s.chainId, ctx.to.ticker);
|
|
4442
|
+
else if (s.kind === "REMOTE_PAYOUT") push(ctx.to.address, s.receiverChainId, ctx.to.ticker);
|
|
4443
|
+
});
|
|
4444
|
+
return hops2;
|
|
4445
|
+
}
|
|
4446
|
+
const requests = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
|
|
4447
|
+
if (!requests.length) return [];
|
|
4448
|
+
const hops = [hopFor(ctx.tokens, String(requests[0].bidToken ?? ""), Number(quote.fromChainId), ctx.from.ticker)];
|
|
4449
|
+
requests.forEach((request, i) => {
|
|
4450
|
+
const last = i === requests.length - 1;
|
|
4451
|
+
hops.push(hopFor(ctx.tokens, String(request.askToken ?? ""), Number(request.destinationChainId || quote.toChainId), last ? ctx.to.ticker : void 0));
|
|
4452
|
+
});
|
|
4453
|
+
return hops;
|
|
4454
|
+
}
|
|
4455
|
+
var shortAddress2 = (address) => address.slice(0, 10).toLowerCase();
|
|
4456
|
+
function compareOptionOf(quote, ctx) {
|
|
4457
|
+
const heavy = quote.protocol === "zdheavy";
|
|
4458
|
+
if (!heavy && !liteExecutable(quote)) return null;
|
|
4459
|
+
const hops = compareHops(quote, ctx);
|
|
4460
|
+
if (hops.length < 2 && !heavy) return null;
|
|
4461
|
+
let amountRaw;
|
|
4462
|
+
let amount;
|
|
4463
|
+
try {
|
|
4464
|
+
amountRaw = BigInt(quote.finalAmount || quote.toAmount || "");
|
|
4465
|
+
amount = Number(formatUnits(amountRaw, ctx.to.decimals, ctx.to.decimals));
|
|
4466
|
+
} catch {
|
|
4467
|
+
return null;
|
|
4468
|
+
}
|
|
4469
|
+
const centibips = quote.zeroDeltaFeeCentibips;
|
|
4470
|
+
const native = quote.zeroDeltaFeeNative;
|
|
4471
|
+
const feeNative = typeof native === "string" && /^\d+$/.test(native) && BigInt(native) > 0n;
|
|
4472
|
+
const feeCentibips = typeof centibips === "number" && Number.isSafeInteger(centibips) && centibips >= 0 ? centibips : void 0;
|
|
4473
|
+
const unavailable = heavy ? zdHeavyUnavailableStatus(quote) : void 0;
|
|
4474
|
+
const option = {
|
|
4475
|
+
// The path, not the amount: the amount moves on every re-quote, and a key that changes would drop a pick.
|
|
4476
|
+
id: heavy ? zdHeavyOptionKey(quote) : hops.map((h2) => `${h2.chainId}:${shortAddress2(h2.address)}`).join(">"),
|
|
4477
|
+
...typeof quote.label === "string" && quote.label ? { label: quote.label } : {},
|
|
4478
|
+
...unavailable ? { unavailable } : {},
|
|
4479
|
+
amount,
|
|
4480
|
+
amountRaw: amountRaw.toString(),
|
|
4481
|
+
estimatedDuration: Number(quote.estimatedDuration) || 0,
|
|
4482
|
+
feeUsd: null,
|
|
4483
|
+
...feeCentibips !== void 0 ? { feeCentibips } : {},
|
|
4484
|
+
...feeNative ? { feeNative: true } : {},
|
|
4485
|
+
hops,
|
|
4486
|
+
...quote.entersNetting === true ? { entersNetting: true } : {},
|
|
4487
|
+
...quote.gasSponsored === true ? { gasSponsored: true } : {}
|
|
4488
|
+
};
|
|
4489
|
+
option.feeUsd = compareFeeUsd(option);
|
|
4490
|
+
return option;
|
|
4491
|
+
}
|
|
4492
|
+
function compareOptionsOf(quote, ctx) {
|
|
4493
|
+
const all = quote.gatewayOptions?.length ? quote.gatewayOptions : [quote];
|
|
4494
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4495
|
+
const byIndex = all.map((q) => {
|
|
4496
|
+
const row = compareOptionOf(q, ctx);
|
|
4497
|
+
if (!row || seen.has(row.id)) return null;
|
|
4498
|
+
seen.add(row.id);
|
|
4499
|
+
return row;
|
|
4500
|
+
});
|
|
4501
|
+
return { options: byIndex.filter((o) => !!o), byIndex };
|
|
4502
|
+
}
|
|
4503
|
+
|
|
3385
4504
|
// src/core/route.ts
|
|
3386
4505
|
function routeDeltaLabel(result, quote) {
|
|
3387
4506
|
if (result.directTransfer) return "~0";
|
|
@@ -3402,9 +4521,9 @@ function routeLabelFor(option, destinationToken, result) {
|
|
|
3402
4521
|
const bridge = result.quote.bridge ? ` via ${result.quote.bridge}` : "";
|
|
3403
4522
|
return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
|
|
3404
4523
|
}
|
|
3405
|
-
function
|
|
3406
|
-
const
|
|
3407
|
-
const wanted = isChainAddress(chainId,
|
|
4524
|
+
function tokenAt3(tokens, chainId, address) {
|
|
4525
|
+
const key2 = isSolanaChainId(chainId) ? hexToSolanaKey(address) || address : address;
|
|
4526
|
+
const wanted = isChainAddress(chainId, key2) ? chainAddressKey(chainId, key2) : null;
|
|
3408
4527
|
if (!wanted || !tokens?.length) return void 0;
|
|
3409
4528
|
return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
|
|
3410
4529
|
}
|
|
@@ -3426,7 +4545,7 @@ function buildLegs(orders, ctx) {
|
|
|
3426
4545
|
const order = orders[index];
|
|
3427
4546
|
const isLast = index === orders.length - 1;
|
|
3428
4547
|
const toChainId = Number(order.destinationChainId);
|
|
3429
|
-
const askToken = isLast ? ctx.destinationToken :
|
|
4548
|
+
const askToken = isLast ? ctx.destinationToken : tokenAt3(ctx.tokens, toChainId, order.askToken);
|
|
3430
4549
|
const toAsset = isLast ? ctx.destinationToken.symbol : askToken?.symbol ?? "";
|
|
3431
4550
|
const toTicker = askToken ? tokenTicker(askToken) : "";
|
|
3432
4551
|
const toDecimals = askToken ? assetDecimals(askToken) : void 0;
|
|
@@ -3453,19 +4572,42 @@ function buildLegs(orders, ctx) {
|
|
|
3453
4572
|
}
|
|
3454
4573
|
return legs;
|
|
3455
4574
|
}
|
|
3456
|
-
async function buildRoute({
|
|
3457
|
-
option,
|
|
3458
|
-
|
|
3459
|
-
destinationToken,
|
|
3460
|
-
chains,
|
|
3461
|
-
tokens,
|
|
3462
|
-
payer,
|
|
3463
|
-
fetchQuote,
|
|
3464
|
-
solve = solveExactOut,
|
|
3465
|
-
amountInRaw,
|
|
3466
|
-
compliance
|
|
3467
|
-
}) {
|
|
4575
|
+
async function buildRoute(args) {
|
|
4576
|
+
const { option, destination, destinationToken, payer, fetchQuote, amountInRaw } = args;
|
|
4577
|
+
const solve = args.solve ?? solveExactOut;
|
|
3468
4578
|
const result = await solve({ option, destination, destinationToken, payer, fetchQuote, amountInRaw });
|
|
4579
|
+
const route = routeFromResult(args, result);
|
|
4580
|
+
return result.directTransfer ? route : withQuoteOptions(route, args, result, solve === solveExactIn ? "exact-in" : "exact-out");
|
|
4581
|
+
}
|
|
4582
|
+
function withQuoteOptions(route, args, result, mode) {
|
|
4583
|
+
const { option, destination, destinationToken } = args;
|
|
4584
|
+
const quote = result.quote;
|
|
4585
|
+
const { byIndex } = compareOptionsOf(quote, {
|
|
4586
|
+
tokens: args.tokens,
|
|
4587
|
+
from: { chainId: option.chainId, address: option.address, ticker: optionTicker(option) },
|
|
4588
|
+
to: { chainId: Number(destination.chainId), address: destinationToken.address, ticker: tokenTicker(destinationToken), decimals: assetDecimals(destinationToken) }
|
|
4589
|
+
});
|
|
4590
|
+
const selectedIndex = quote.gatewayOptions?.length ? quote.gatewayOptionIndex ?? -1 : 0;
|
|
4591
|
+
const built = [];
|
|
4592
|
+
const refused = /* @__PURE__ */ new Set();
|
|
4593
|
+
(quote.gatewayOptions ?? []).forEach((candidate, index) => {
|
|
4594
|
+
const row = byIndex[index];
|
|
4595
|
+
if (!row || row.unavailable || index === selectedIndex) return;
|
|
4596
|
+
try {
|
|
4597
|
+
built.push({ index, route: routeFromResult(args, resultForOption(result, candidate, mode, destination.chainId)) });
|
|
4598
|
+
} catch {
|
|
4599
|
+
refused.add(index);
|
|
4600
|
+
}
|
|
4601
|
+
});
|
|
4602
|
+
const options = [];
|
|
4603
|
+
byIndex.forEach((row, index) => {
|
|
4604
|
+
if (row) options.push(refused.has(index) ? { ...row, unavailable: "refused-by-widget" } : row);
|
|
4605
|
+
});
|
|
4606
|
+
const selectedOptionId = byIndex[selectedIndex]?.id;
|
|
4607
|
+
const alternatives = built.map(({ index, route: alt }) => ({ ...alt, id: route.id, options, selectedOptionId: byIndex[index].id }));
|
|
4608
|
+
return { ...route, options, ...selectedOptionId ? { selectedOptionId } : {}, ...alternatives.length ? { alternatives } : {} };
|
|
4609
|
+
}
|
|
4610
|
+
function routeFromResult({ option, destination, destinationToken, chains, tokens, routes, payer, compliance }, result) {
|
|
3469
4611
|
const quote = result.quote;
|
|
3470
4612
|
const destDecimals = assetDecimals(destinationToken);
|
|
3471
4613
|
const receiveAmount = formatUnits(result.recipientReceivesRaw, destDecimals);
|
|
@@ -3540,6 +4682,9 @@ async function buildRoute({
|
|
|
3540
4682
|
}
|
|
3541
4683
|
};
|
|
3542
4684
|
}
|
|
4685
|
+
if (quote.protocol === "zdheavy") {
|
|
4686
|
+
return buildZdHeavyRoute({ option, destination, destinationToken, chains, tokens: tokens ?? [], routes: routes ?? [], payer, result });
|
|
4687
|
+
}
|
|
3543
4688
|
const requestList = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
|
|
3544
4689
|
if (!requestList.length) throw new Error("ZeroDelta quote did not include an order request.");
|
|
3545
4690
|
const sourceChain = chainById(chains, option.chainId);
|
|
@@ -3641,12 +4786,134 @@ async function buildRoute({
|
|
|
3641
4786
|
};
|
|
3642
4787
|
}
|
|
3643
4788
|
|
|
4789
|
+
// src/core/promotions.ts
|
|
4790
|
+
var CENTIBIPS_PER_UNIT = 1e6;
|
|
4791
|
+
function toToken(raw2) {
|
|
4792
|
+
if (!raw2 || typeof raw2 !== "object") return void 0;
|
|
4793
|
+
const r = raw2;
|
|
4794
|
+
const chainId = Number(r.chainId);
|
|
4795
|
+
if (!Number.isSafeInteger(chainId) || chainId <= 0) return void 0;
|
|
4796
|
+
if (typeof r.address !== "string" || !r.address) return void 0;
|
|
4797
|
+
if (typeof r.symbol !== "string" || !r.symbol) return void 0;
|
|
4798
|
+
return { chainId, address: r.address, symbol: r.symbol };
|
|
4799
|
+
}
|
|
4800
|
+
function parsePromotion(raw2, now = Date.now()) {
|
|
4801
|
+
if (!raw2 || typeof raw2 !== "object") return void 0;
|
|
4802
|
+
const r = raw2;
|
|
4803
|
+
if (typeof r.id !== "string" || !r.id) return void 0;
|
|
4804
|
+
if (r.kind !== "token" && r.kind !== "pair") return void 0;
|
|
4805
|
+
const destination = toToken(r.destination);
|
|
4806
|
+
if (!destination) return void 0;
|
|
4807
|
+
const source2 = r.kind === "pair" ? toToken(r.source) : void 0;
|
|
4808
|
+
if (r.kind === "pair" && !source2) return void 0;
|
|
4809
|
+
const bonusCentibips = Number(r.bonusCentibips);
|
|
4810
|
+
if (!Number.isSafeInteger(bonusCentibips) || bonusCentibips <= 0) return void 0;
|
|
4811
|
+
if (r.fundedBy !== "issuer" && r.fundedBy !== "zerodelta") return void 0;
|
|
4812
|
+
if (typeof r.startsAt !== "string" || typeof r.endsAt !== "string") return void 0;
|
|
4813
|
+
const starts = Date.parse(r.startsAt);
|
|
4814
|
+
const ends = Date.parse(r.endsAt);
|
|
4815
|
+
if (!Number.isFinite(starts) || !Number.isFinite(ends) || !(starts <= now && now < ends)) return void 0;
|
|
4816
|
+
let maxBonusAmount;
|
|
4817
|
+
if (r.maxBonusAmount !== void 0) {
|
|
4818
|
+
if (typeof r.maxBonusAmount !== "string" || !/^[1-9]\d*$/.test(r.maxBonusAmount)) return void 0;
|
|
4819
|
+
maxBonusAmount = r.maxBonusAmount;
|
|
4820
|
+
}
|
|
4821
|
+
return {
|
|
4822
|
+
id: r.id,
|
|
4823
|
+
kind: r.kind,
|
|
4824
|
+
destination,
|
|
4825
|
+
...source2 ? { source: source2 } : {},
|
|
4826
|
+
bonusCentibips,
|
|
4827
|
+
...maxBonusAmount ? { maxBonusAmount } : {},
|
|
4828
|
+
fundedBy: r.fundedBy,
|
|
4829
|
+
...typeof r.funderName === "string" && r.funderName ? { funderName: r.funderName } : {},
|
|
4830
|
+
startsAt: r.startsAt,
|
|
4831
|
+
endsAt: r.endsAt
|
|
4832
|
+
};
|
|
4833
|
+
}
|
|
4834
|
+
function parsePromotions(rows, now = Date.now()) {
|
|
4835
|
+
if (!Array.isArray(rows)) return [];
|
|
4836
|
+
return rows.map((row) => parsePromotion(row, now)).filter((p) => !!p);
|
|
4837
|
+
}
|
|
4838
|
+
function sameAddress(a, b) {
|
|
4839
|
+
return a.startsWith("0x") && b.startsWith("0x") ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
4840
|
+
}
|
|
4841
|
+
function sameToken(t, chainId, address) {
|
|
4842
|
+
return t.chainId === chainId && sameAddress(t.address, address);
|
|
4843
|
+
}
|
|
4844
|
+
function promotedAssets(promotions) {
|
|
4845
|
+
const bySymbol = /* @__PURE__ */ new Map();
|
|
4846
|
+
for (const p of promotions) {
|
|
4847
|
+
if (p.kind !== "token") continue;
|
|
4848
|
+
const key2 = p.destination.symbol.toUpperCase();
|
|
4849
|
+
const asset = bySymbol.get(key2) ?? { symbol: p.destination.symbol, maxCentibips: 0, networks: [], fundedBy: p.fundedBy };
|
|
4850
|
+
asset.networks.push({ promotion: p, chainId: p.destination.chainId, address: p.destination.address, bonusCentibips: p.bonusCentibips });
|
|
4851
|
+
if (p.bonusCentibips > asset.maxCentibips) {
|
|
4852
|
+
asset.maxCentibips = p.bonusCentibips;
|
|
4853
|
+
asset.fundedBy = p.fundedBy;
|
|
4854
|
+
}
|
|
4855
|
+
bySymbol.set(key2, asset);
|
|
4856
|
+
}
|
|
4857
|
+
const assets = [...bySymbol.values()];
|
|
4858
|
+
for (const a of assets) a.networks.sort((x, y) => y.bonusCentibips - x.bonusCentibips || x.chainId - y.chainId);
|
|
4859
|
+
return assets.sort((a, b) => b.maxCentibips - a.maxCentibips || a.symbol.localeCompare(b.symbol));
|
|
4860
|
+
}
|
|
4861
|
+
function promotionFor(promotions, ends) {
|
|
4862
|
+
let best;
|
|
4863
|
+
for (const p of promotions) {
|
|
4864
|
+
if (!sameToken(p.destination, ends.toChainId, ends.toAddress)) continue;
|
|
4865
|
+
if (p.kind === "pair") {
|
|
4866
|
+
if (!p.source || ends.fromChainId === void 0 || !ends.fromAddress) continue;
|
|
4867
|
+
if (!sameToken(p.source, ends.fromChainId, ends.fromAddress)) continue;
|
|
4868
|
+
}
|
|
4869
|
+
if (!best || p.bonusCentibips > best.bonusCentibips) best = p;
|
|
4870
|
+
}
|
|
4871
|
+
return best;
|
|
4872
|
+
}
|
|
4873
|
+
function pairPromotionsInto(promotions, chainId, address) {
|
|
4874
|
+
return promotions.filter((p) => p.kind === "pair" && sameToken(p.destination, chainId, address));
|
|
4875
|
+
}
|
|
4876
|
+
function estimateBonus(amount, promotion) {
|
|
4877
|
+
if (amount <= 0n) return 0n;
|
|
4878
|
+
const bonus = amount * BigInt(promotion.bonusCentibips) / BigInt(CENTIBIPS_PER_UNIT);
|
|
4879
|
+
if (promotion.maxBonusAmount) {
|
|
4880
|
+
const cap = BigInt(promotion.maxBonusAmount);
|
|
4881
|
+
return bonus > cap ? cap : bonus;
|
|
4882
|
+
}
|
|
4883
|
+
return bonus;
|
|
4884
|
+
}
|
|
4885
|
+
/* @__PURE__ */ new Set([...STABLE_ASSETS, "GHO", "USD0", "USDF"]);
|
|
4886
|
+
|
|
4887
|
+
// src/core/quote-request.ts
|
|
4888
|
+
function nativeQuoteRequest(body) {
|
|
4889
|
+
const inputChain = Number(body.fromChainId);
|
|
4890
|
+
const owner = typeof body.owner === "string" && body.owner ? body.owner : void 0;
|
|
4891
|
+
const destinationWallet = typeof body.destinationReceiver === "string" && body.destinationReceiver ? body.destinationReceiver : void 0;
|
|
4892
|
+
const owners = owner ? isSolanaChainId(inputChain) && isSolanaAddress(owner) ? { svm: owner } : { evm: owner } : void 0;
|
|
4893
|
+
const sender = typeof body.sender === "string" ? body.sender : !isSolanaChainId(inputChain) ? owner : void 0;
|
|
4894
|
+
return {
|
|
4895
|
+
inputChain,
|
|
4896
|
+
outputChain: Number(body.toChainId),
|
|
4897
|
+
inputToken: String(body.fromToken ?? ""),
|
|
4898
|
+
outputToken: String(body.toToken ?? ""),
|
|
4899
|
+
inputAmount: String(body.fromAmount ?? ""),
|
|
4900
|
+
...owners ? { owners } : {},
|
|
4901
|
+
...destinationWallet ? { destinationWallet } : {},
|
|
4902
|
+
...sender && owners && destinationWallet ? { sender } : {},
|
|
4903
|
+
// No new deadline, latency limit or subject is invented for EVM quoting. The
|
|
4904
|
+
// gateway derives the subject from owners when this caller has no explicit one.
|
|
4905
|
+
...body.deadline !== void 0 ? { deadline: String(body.deadline) } : {},
|
|
4906
|
+
...typeof body.maxTimeSec === "number" ? { maxTimeSec: body.maxTimeSec } : {},
|
|
4907
|
+
...typeof body.subjectId === "string" ? { subjectId: body.subjectId } : {}
|
|
4908
|
+
};
|
|
4909
|
+
}
|
|
4910
|
+
|
|
3644
4911
|
// src/core/channel.ts
|
|
3645
4912
|
var CHANNEL_HEADER = "x-zd-channel";
|
|
3646
4913
|
var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
|
|
3647
4914
|
var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
|
|
3648
4915
|
var WIDGET_CHANNEL = "widget";
|
|
3649
|
-
var WIDGET_VERSION = "4.
|
|
4916
|
+
var WIDGET_VERSION = "4.19.0" ;
|
|
3650
4917
|
var MAX_CHANNEL_VERSION_LEN = 32;
|
|
3651
4918
|
function sanitizeVersion(raw2) {
|
|
3652
4919
|
const v = String(raw2).trim();
|
|
@@ -3738,7 +5005,7 @@ function classifyQuoteError(error) {
|
|
|
3738
5005
|
function amountFieldError(error) {
|
|
3739
5006
|
const fieldErrors = error?.fieldErrors;
|
|
3740
5007
|
if (!Array.isArray(fieldErrors)) return null;
|
|
3741
|
-
const entry = fieldErrors.find((e) => e && typeof e === "object" && e.field === "fromAmount" && typeof e.message === "string");
|
|
5008
|
+
const entry = fieldErrors.find((e) => e && typeof e === "object" && (e.field === "fromAmount" || e.field === "inputAmount") && typeof e.message === "string");
|
|
3742
5009
|
const message = entry ? sanitizeMessage(entry.message, "") : "";
|
|
3743
5010
|
return message || null;
|
|
3744
5011
|
}
|
|
@@ -3754,7 +5021,7 @@ function wait(ms) {
|
|
|
3754
5021
|
}
|
|
3755
5022
|
var PAGE_LIMIT = 500;
|
|
3756
5023
|
var MAX_PAGES = 10;
|
|
3757
|
-
var newRegistryCache = () => ({ chains: null, tokens: null, routes: null, health: null, vaults: null, inflight: /* @__PURE__ */ new Map() });
|
|
5024
|
+
var newRegistryCache = () => ({ chains: null, tokens: null, routes: null, health: null, vaults: null, promotions: null, inflight: /* @__PURE__ */ new Map() });
|
|
3758
5025
|
var SHARED_REGISTRY = /* @__PURE__ */ new WeakMap();
|
|
3759
5026
|
function registryCacheFor(scope) {
|
|
3760
5027
|
if (!scope) return newRegistryCache();
|
|
@@ -3911,6 +5178,20 @@ function createApiClient(cfg) {
|
|
|
3911
5178
|
return value;
|
|
3912
5179
|
});
|
|
3913
5180
|
}
|
|
5181
|
+
function fetchPromotions() {
|
|
5182
|
+
if (nowFresh(cache.promotions)) return Promise.resolve(parsePromotions(cache.promotions.value));
|
|
5183
|
+
return once("promotions", async () => {
|
|
5184
|
+
let value = [];
|
|
5185
|
+
try {
|
|
5186
|
+
const rows = await apiRequest("/promotions", { timeoutMs: 8e3 });
|
|
5187
|
+
value = Array.isArray(rows) ? rows : [];
|
|
5188
|
+
} catch {
|
|
5189
|
+
value = [];
|
|
5190
|
+
}
|
|
5191
|
+
cache.promotions = { at: Date.now(), value };
|
|
5192
|
+
return parsePromotions(value);
|
|
5193
|
+
});
|
|
5194
|
+
}
|
|
3914
5195
|
const priceCache = /* @__PURE__ */ new Map();
|
|
3915
5196
|
async function fetchPrices(symbols) {
|
|
3916
5197
|
const wanted = [...new Set(symbols.map((s) => String(s || "").toUpperCase()).filter((s) => /^[A-Z0-9]{1,16}$/.test(s)))];
|
|
@@ -3941,11 +5222,12 @@ function createApiClient(cfg) {
|
|
|
3941
5222
|
return out;
|
|
3942
5223
|
}
|
|
3943
5224
|
async function fetchQuote(body, retries = 1) {
|
|
5225
|
+
const request = nativeQuoteRequest(body);
|
|
3944
5226
|
let lastError;
|
|
3945
5227
|
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
|
3946
5228
|
try {
|
|
3947
|
-
const quote = await apiRequest("/quote", { method: "POST", body: JSON.stringify(
|
|
3948
|
-
return quote
|
|
5229
|
+
const quote = await apiRequest("/quote", { method: "POST", headers: { "X-ZD-Shape": "native" }, body: JSON.stringify(request), timeoutMs: 18e3 });
|
|
5230
|
+
return normalizeQuoteResponse(quote, request);
|
|
3949
5231
|
} catch (error) {
|
|
3950
5232
|
lastError = error;
|
|
3951
5233
|
if (attempt >= retries || !isTransientQuoteError(error)) throw error;
|
|
@@ -3959,10 +5241,10 @@ function createApiClient(cfg) {
|
|
|
3959
5241
|
if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
|
|
3960
5242
|
const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
|
|
3961
5243
|
if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
|
|
3962
|
-
const
|
|
3963
|
-
const hit = screenCache.get(
|
|
5244
|
+
const key2 = solana ? "solana|" + addr : (/^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr) + "|" + (chainId ?? "");
|
|
5245
|
+
const hit = screenCache.get(key2);
|
|
3964
5246
|
if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
|
|
3965
|
-
const inflight = screenInflight.get(
|
|
5247
|
+
const inflight = screenInflight.get(key2);
|
|
3966
5248
|
if (inflight) return inflight;
|
|
3967
5249
|
const request = apiRequest("/screen/wallet", {
|
|
3968
5250
|
method: "POST",
|
|
@@ -3973,12 +5255,12 @@ function createApiClient(cfg) {
|
|
|
3973
5255
|
throw apiError("Compliance screening returned an unusable result.", { code: "bad_response" });
|
|
3974
5256
|
}
|
|
3975
5257
|
const value = { ...screen, address: screen.address || addr };
|
|
3976
|
-
screenCache.set(
|
|
5258
|
+
screenCache.set(key2, { at: Date.now(), value });
|
|
3977
5259
|
return value;
|
|
3978
5260
|
}).finally(() => {
|
|
3979
|
-
screenInflight.delete(
|
|
5261
|
+
screenInflight.delete(key2);
|
|
3980
5262
|
});
|
|
3981
|
-
screenInflight.set(
|
|
5263
|
+
screenInflight.set(key2, request);
|
|
3982
5264
|
return request;
|
|
3983
5265
|
}
|
|
3984
5266
|
async function reportSubmission(report) {
|
|
@@ -4001,7 +5283,7 @@ function createApiClient(cfg) {
|
|
|
4001
5283
|
return false;
|
|
4002
5284
|
}
|
|
4003
5285
|
}
|
|
4004
|
-
return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchRouteHealth, fetchRwaVaults, fetchPrices, fetchQuote, screenWallet, reportSubmission, apiBase };
|
|
5286
|
+
return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchRouteHealth, fetchRwaVaults, fetchPrices, fetchPromotions, fetchQuote, screenWallet, reportSubmission, apiBase };
|
|
4005
5287
|
}
|
|
4006
5288
|
|
|
4007
5289
|
// src/core/plan.ts
|
|
@@ -4064,9 +5346,9 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
|
|
|
4064
5346
|
const balanceTargets = [];
|
|
4065
5347
|
const seenTargets = /* @__PURE__ */ new Set();
|
|
4066
5348
|
for (const option of options) {
|
|
4067
|
-
const
|
|
4068
|
-
if (seenTargets.has(
|
|
4069
|
-
seenTargets.add(
|
|
5349
|
+
const key2 = optionBalanceKey(option);
|
|
5350
|
+
if (seenTargets.has(key2)) continue;
|
|
5351
|
+
seenTargets.add(key2);
|
|
4070
5352
|
balanceTargets.push({ chainId: option.chainId, tokenAddress: option.address, decimals: option.decimals });
|
|
4071
5353
|
}
|
|
4072
5354
|
const walletBalances = readBalances ? await readBalances(payer, balanceTargets).catch(() => ({})) : {};
|
|
@@ -4078,9 +5360,9 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
|
|
|
4078
5360
|
for (const raw2 of [payer, destination.address]) {
|
|
4079
5361
|
const addr = String(raw2 || "").trim();
|
|
4080
5362
|
if (!addr) continue;
|
|
4081
|
-
const
|
|
4082
|
-
if (seenParty.has(
|
|
4083
|
-
seenParty.add(
|
|
5363
|
+
const key2 = /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
|
|
5364
|
+
if (seenParty.has(key2)) continue;
|
|
5365
|
+
seenParty.add(key2);
|
|
4084
5366
|
parties.push(addr);
|
|
4085
5367
|
}
|
|
4086
5368
|
try {
|
|
@@ -4127,6 +5409,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
|
|
|
4127
5409
|
destinationToken,
|
|
4128
5410
|
chains,
|
|
4129
5411
|
tokens,
|
|
5412
|
+
routes,
|
|
4130
5413
|
payer,
|
|
4131
5414
|
fetchQuote: api.fetchQuote,
|
|
4132
5415
|
compliance: option.direct ? directCompliance ?? void 0 : void 0
|
|
@@ -4187,7 +5470,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
|
|
|
4187
5470
|
(o) => !o.direct && Number(o.chainId) === Number(picked.chainId) && chainAddressKey(o.chainId, o.address) === chainAddressKey(picked.chainId, picked.address) && (!allowedFunding || allowedFunding.has(o.symbolKey))
|
|
4188
5471
|
);
|
|
4189
5472
|
if (!option) throw new Error("That funding option is not available for this payment right now.");
|
|
4190
|
-
return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
|
|
5473
|
+
return buildRoute({ option, destination, destinationToken, chains, tokens, routes, payer, fetchQuote: api.fetchQuote });
|
|
4191
5474
|
}
|
|
4192
5475
|
|
|
4193
5476
|
// src/core/swap.ts
|
|
@@ -4195,13 +5478,13 @@ function validateSwap(swap = {}) {
|
|
|
4195
5478
|
const fromChainId = Number(swap.fromChainId);
|
|
4196
5479
|
const toChainId = Number(swap.toChainId);
|
|
4197
5480
|
const fromToken = symbolKey(swap.fromToken);
|
|
4198
|
-
const
|
|
5481
|
+
const toToken2 = symbolKey(swap.toToken);
|
|
4199
5482
|
if (!SUPPORTED_CHAIN_IDS.has(fromChainId)) throw new Error("Unsupported swap chain.");
|
|
4200
5483
|
if (!Number.isSafeInteger(toChainId) || toChainId <= 0) throw new Error("Unsupported swap chain.");
|
|
4201
|
-
if (!SUPPORTED_ASSETS.has(fromToken) || !SUPPORTED_ASSETS.has(
|
|
5484
|
+
if (!SUPPORTED_ASSETS.has(fromToken) || !SUPPORTED_ASSETS.has(toToken2)) throw new Error("Unsupported swap asset.");
|
|
4202
5485
|
const amountIn = normalizeDecimalText(swap.amountIn);
|
|
4203
5486
|
if (!/^\d+(\.\d+)?$/.test(amountIn) || Number(amountIn) <= 0 || Number(amountIn) > 1e9) throw new Error("Enter a valid swap amount.");
|
|
4204
|
-
return { fromChainId, toChainId, fromToken, toToken, amountIn };
|
|
5487
|
+
return { fromChainId, toChainId, fromToken, toToken: toToken2, amountIn };
|
|
4205
5488
|
}
|
|
4206
5489
|
function viaOf(quote, tokens) {
|
|
4207
5490
|
const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
|
|
@@ -4251,7 +5534,7 @@ async function quoteSwapPreview(api, swap, owner) {
|
|
|
4251
5534
|
async function buildSwapPlan(api, swap, payer, wallet = {}) {
|
|
4252
5535
|
const v = validateSwap(swap);
|
|
4253
5536
|
const account = assertAddress(payer, "Swap wallet");
|
|
4254
|
-
const [chains, tokens] = await Promise.all([api.fetchChains(), api.fetchTokens()]);
|
|
5537
|
+
const [chains, tokens, routes] = await Promise.all([api.fetchChains(), api.fetchTokens(), api.fetchRoutes()]);
|
|
4255
5538
|
const sourceToken = findToken(tokens, v.fromChainId, v.fromToken);
|
|
4256
5539
|
const destToken = findToken(tokens, v.toChainId, v.toToken);
|
|
4257
5540
|
if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
|
|
@@ -4274,7 +5557,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
|
|
|
4274
5557
|
direct: false
|
|
4275
5558
|
};
|
|
4276
5559
|
const destination = { address: receiver, chainId: v.toChainId, asset: destToken.symbol };
|
|
4277
|
-
const route = await buildRoute({ option, destination, destinationToken: destToken, chains, tokens, payer: account, fetchQuote: api.fetchQuote, solve: solveExactIn, amountInRaw });
|
|
5560
|
+
const route = await buildRoute({ option, destination, destinationToken: destToken, chains, tokens, routes, payer: account, fetchQuote: api.fetchQuote, solve: solveExactIn, amountInRaw });
|
|
4278
5561
|
if (route.state === "SHORT") throw new Error("ZeroDelta could not price this swap right now.");
|
|
4279
5562
|
route.recommended = true;
|
|
4280
5563
|
return {
|
|
@@ -4295,88 +5578,6 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
|
|
|
4295
5578
|
};
|
|
4296
5579
|
}
|
|
4297
5580
|
|
|
4298
|
-
// src/core/validate-tx.ts
|
|
4299
|
-
var lower = (v) => String(v || "").toLowerCase();
|
|
4300
|
-
function isHexAddress(value) {
|
|
4301
|
-
return /^0x[a-fA-F0-9]{40}$/.test(String(value || ""));
|
|
4302
|
-
}
|
|
4303
|
-
function isHexData(value) {
|
|
4304
|
-
return /^0x(?:[a-fA-F0-9]{2})*$/.test(String(value));
|
|
4305
|
-
}
|
|
4306
|
-
function isHexQuantity(value) {
|
|
4307
|
-
return /^0x[0-9a-fA-F]+$/.test(String(value));
|
|
4308
|
-
}
|
|
4309
|
-
function dataWord(data, index) {
|
|
4310
|
-
const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
|
|
4311
|
-
return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
|
|
4312
|
-
}
|
|
4313
|
-
function dataAddress(data, index) {
|
|
4314
|
-
const word2 = dataWord(data, index);
|
|
4315
|
-
return word2 ? `0x${word2.slice(24)}` : "";
|
|
4316
|
-
}
|
|
4317
|
-
function dataUint(data, index) {
|
|
4318
|
-
const word2 = dataWord(data, index);
|
|
4319
|
-
return word2 ? BigInt(`0x${word2}`) : null;
|
|
4320
|
-
}
|
|
4321
|
-
function rawEquals(value, expected) {
|
|
4322
|
-
try {
|
|
4323
|
-
return value === BigInt(expected || "0");
|
|
4324
|
-
} catch {
|
|
4325
|
-
return false;
|
|
4326
|
-
}
|
|
4327
|
-
}
|
|
4328
|
-
function planMsgValueHex(route) {
|
|
4329
|
-
try {
|
|
4330
|
-
const raw2 = route?.quote?.msgValue;
|
|
4331
|
-
if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
|
|
4332
|
-
return "0x" + BigInt(raw2).toString(16);
|
|
4333
|
-
} catch {
|
|
4334
|
-
return null;
|
|
4335
|
-
}
|
|
4336
|
-
}
|
|
4337
|
-
function validatePlannedTransaction(tx, route, expectedRecipient) {
|
|
4338
|
-
if (!tx || tx.mock) return true;
|
|
4339
|
-
if (!isHexAddress(tx.to) || !isHexData(tx.data || "0x") || !isHexQuantity(tx.value || "0x0")) return false;
|
|
4340
|
-
const data = String(tx.data || "0x").toLowerCase();
|
|
4341
|
-
const selector = data.slice(0, 10);
|
|
4342
|
-
const value = lower(tx.value || "0x0");
|
|
4343
|
-
if (tx.kind === "transfer") {
|
|
4344
|
-
if (value !== "0x0") return false;
|
|
4345
|
-
return selector === "0xa9059cbb" && isHexAddress(tx.token) && lower(tx.to) === lower(tx.token) && lower(dataAddress(data, 0)) === lower(expectedRecipient) && rawEquals(dataUint(data, 1), tx.amountRaw);
|
|
4346
|
-
}
|
|
4347
|
-
if (tx.kind === "approve") {
|
|
4348
|
-
if (value !== "0x0") return false;
|
|
4349
|
-
return selector === "0x095ea7b3" && isHexAddress(tx.token) && isHexAddress(tx.spender) && lower(tx.to) === lower(tx.token) && lower(dataAddress(data, 0)) === lower(tx.spender) && rawEquals(dataUint(data, 1), tx.amountRaw);
|
|
4350
|
-
}
|
|
4351
|
-
if (tx.kind === "submitOrder") {
|
|
4352
|
-
const expected = planMsgValueHex(route);
|
|
4353
|
-
if (expected === null || value !== lower(expected)) return false;
|
|
4354
|
-
if (selector !== SUBMIT_ORDER_SELECTOR || !isHexAddress(tx.escrow) || lower(tx.to) !== lower(tx.escrow)) return false;
|
|
4355
|
-
const decoded = decodeSubmitOrderCalldata(data);
|
|
4356
|
-
if (!decoded) return false;
|
|
4357
|
-
const first = decoded.orders[0];
|
|
4358
|
-
const last = decoded.orders[decoded.orders.length - 1];
|
|
4359
|
-
return decoded.partnerId === lower(route.quote?.partnerId || NO_PARTNER_ID) && lower(first.bidToken) === lower(route.source.tokenAddress) && rawEquals(first.bidTokenAmount, tx.amountRaw) && lower(last.askToken) === lower(isSolanaChainId(route.receive.chainId) ? solanaKeyHex(route.receive.tokenAddress || "") : route.receive.tokenAddress) && Number(last.destinationChainId) === Number(route.receive.chainId) && (isSolanaChainId(route.receive.chainId) ? solanaDeliveryMatches(last.destinationReceiver, expectedRecipient, route.receive.tokenAddress) : lower(last.destinationReceiver) === lower(expectedRecipient));
|
|
4360
|
-
}
|
|
4361
|
-
return false;
|
|
4362
|
-
}
|
|
4363
|
-
function solanaDeliveryMatches(encoded, recipient2, mint) {
|
|
4364
|
-
try {
|
|
4365
|
-
return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
|
|
4366
|
-
} catch {
|
|
4367
|
-
return false;
|
|
4368
|
-
}
|
|
4369
|
-
}
|
|
4370
|
-
async function allowanceCovers(tx, account, ethCall2) {
|
|
4371
|
-
if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
|
|
4372
|
-
try {
|
|
4373
|
-
const raw2 = await ethCall2(tx.token, encodeAllowance(account, tx.spender));
|
|
4374
|
-
return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
|
|
4375
|
-
} catch {
|
|
4376
|
-
return false;
|
|
4377
|
-
}
|
|
4378
|
-
}
|
|
4379
|
-
|
|
4380
5581
|
// src/core/verify.ts
|
|
4381
5582
|
var TX_VERIFY_ATTEMPTS = 5;
|
|
4382
5583
|
var TX_VERIFY_INTERVAL_MS = 2500;
|
|
@@ -4521,9 +5722,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
4521
5722
|
const seen = /* @__PURE__ */ new Set();
|
|
4522
5723
|
for (const target of targets) {
|
|
4523
5724
|
if (!target || !isAddress(target.tokenAddress)) continue;
|
|
4524
|
-
const
|
|
4525
|
-
if (seen.has(
|
|
4526
|
-
seen.add(
|
|
5725
|
+
const key2 = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
|
|
5726
|
+
if (seen.has(key2)) continue;
|
|
5727
|
+
seen.add(key2);
|
|
4527
5728
|
const chainId = Number(target.chainId);
|
|
4528
5729
|
const group = groups.get(chainId) || [];
|
|
4529
5730
|
group.push(target);
|
|
@@ -4532,8 +5733,8 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
4532
5733
|
function record(target, hex) {
|
|
4533
5734
|
if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
|
|
4534
5735
|
const raw2 = BigInt(hex || "0x0").toString();
|
|
4535
|
-
const
|
|
4536
|
-
out[
|
|
5736
|
+
const key2 = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
|
|
5737
|
+
out[key2] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
|
|
4537
5738
|
return true;
|
|
4538
5739
|
}
|
|
4539
5740
|
async function readOne(rpcUrl, target) {
|
|
@@ -4579,7 +5780,18 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
4579
5780
|
return null;
|
|
4580
5781
|
}
|
|
4581
5782
|
}
|
|
4582
|
-
|
|
5783
|
+
async function readZdHeavySubmitFee(chainId, to, data) {
|
|
5784
|
+
try {
|
|
5785
|
+
const override = rpcOverrides[Number(chainId)];
|
|
5786
|
+
const rpc = override && /^https?:\/\//i.test(override) ? override : BUNDLED_RPC[Number(chainId)];
|
|
5787
|
+
if (!rpc) return void 0;
|
|
5788
|
+
const result = await rpcCall(rpc, "eth_call", [{ to, data: quoteSubmitCalldata(data) }, "latest"]);
|
|
5789
|
+
return typeof result === "string" && /^0x[0-9a-fA-F]{64}$/.test(result) ? BigInt(result) : void 0;
|
|
5790
|
+
} catch {
|
|
5791
|
+
return void 0;
|
|
5792
|
+
}
|
|
5793
|
+
}
|
|
5794
|
+
return { payerNonceBaseline, verifySubmittedTx, readBalances, readNativeBalance, readZdHeavySubmitFee };
|
|
4583
5795
|
}
|
|
4584
5796
|
|
|
4585
5797
|
// src/core/config.ts
|
|
@@ -4700,6 +5912,7 @@ function createEngine(config = {}) {
|
|
|
4700
5912
|
fetchRouteHealth: api.fetchRouteHealth,
|
|
4701
5913
|
fetchQuote: api.fetchQuote,
|
|
4702
5914
|
fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
|
|
5915
|
+
fetchPromotions: () => api.fetchPromotions ? api.fetchPromotions() : Promise.resolve([]),
|
|
4703
5916
|
fetchCatalogue: async (allowedAssets, product, options) => {
|
|
4704
5917
|
const [chains, registryTokens, routes, health, vaults] = await Promise.all([
|
|
4705
5918
|
api.fetchChains().catch(() => []),
|
|
@@ -5143,7 +6356,13 @@ function useFlow(args) {
|
|
|
5143
6356
|
statusRef.current = status;
|
|
5144
6357
|
const { idle: idle2, returnedAt: returnedAt2 } = useUserPresence();
|
|
5145
6358
|
const routes = plan?.routes ?? [];
|
|
5146
|
-
const
|
|
6359
|
+
const baseSelected = react.useMemo(() => routes.find((r) => r.id === selectedId) ?? routes.find((r) => r.recommended) ?? routes[0] ?? null, [routes, selectedId]);
|
|
6360
|
+
const [pickedOptionId, setPickedOptionId] = react.useState(null);
|
|
6361
|
+
const selected = react.useMemo(() => {
|
|
6362
|
+
if (!baseSelected || !pickedOptionId || pickedOptionId === baseSelected.selectedOptionId) return baseSelected;
|
|
6363
|
+
const alt = baseSelected.alternatives?.find((r) => r.selectedOptionId === pickedOptionId);
|
|
6364
|
+
return alt ? { ...alt, recommended: baseSelected.recommended } : baseSelected;
|
|
6365
|
+
}, [baseSelected, pickedOptionId]);
|
|
5147
6366
|
const reload = react.useCallback(() => setNonce((n) => n + 1), []);
|
|
5148
6367
|
const addRoute = react.useCallback((route) => {
|
|
5149
6368
|
setPlan((p) => p ? { ...p, routes: [...p.routes.filter((r) => r.id !== route.id), route] } : p);
|
|
@@ -5198,11 +6417,11 @@ function useFlow(args) {
|
|
|
5198
6417
|
if (!wallet.account || !src?.tokenAddress || src.decimals == null) return;
|
|
5199
6418
|
(async () => {
|
|
5200
6419
|
try {
|
|
5201
|
-
const
|
|
6420
|
+
const key2 = `${Number(src.chainId)}:${String(src.tokenAddress).toLowerCase()}`;
|
|
5202
6421
|
const balances = await engine.readBalances(wallet.account, [
|
|
5203
6422
|
{ chainId: Number(src.chainId), tokenAddress: src.tokenAddress, decimals: Number(src.decimals) }
|
|
5204
6423
|
]);
|
|
5205
|
-
const entry = balances[
|
|
6424
|
+
const entry = balances[key2];
|
|
5206
6425
|
if (!entry) return;
|
|
5207
6426
|
const need = parseUnitsDecimal(src.payAmount || src.amount, src.decimals);
|
|
5208
6427
|
if (alive) setInsufficient(BigInt(entry.raw) < need);
|
|
@@ -5266,6 +6485,8 @@ function useFlow(args) {
|
|
|
5266
6485
|
throw new Error(nativeFeeShortMessage(check2, nativeSymbol(Number(sourceChainId), chains), route.source.chainName));
|
|
5267
6486
|
}
|
|
5268
6487
|
}
|
|
6488
|
+
const heavyExpected = route.zdHeavy ? zdHeavyExpected(route, account, recipient2, ...await Promise.all([engine.fetchTokens(), engine.fetchRoutes()])) : void 0;
|
|
6489
|
+
if (heavyExpected) await preflightZdHeavyPlan(route, heavyExpected, engine.verifier.readZdHeavySubmitFee);
|
|
5269
6490
|
const minNonce = await engine.payerNonceBaseline(Number(sourceChainId), account);
|
|
5270
6491
|
const txs = route.transactions;
|
|
5271
6492
|
let settleHash = "";
|
|
@@ -5281,7 +6502,7 @@ function useFlow(args) {
|
|
|
5281
6502
|
patch(tx.id, "done");
|
|
5282
6503
|
continue;
|
|
5283
6504
|
}
|
|
5284
|
-
if (!validatePlannedTransaction(tx, route, recipient2)) {
|
|
6505
|
+
if (!validatePlannedTransaction(tx, route, recipient2, heavyExpected ? { ...heavyExpected, nowSec: Math.floor(Date.now() / 1e3) } : void 0)) {
|
|
5285
6506
|
throw new Error(`Refusing to sign a ${tx.kind} that does not match the reviewed plan.`);
|
|
5286
6507
|
}
|
|
5287
6508
|
patch(tx.id, "active");
|
|
@@ -5352,6 +6573,98 @@ function useFlow(args) {
|
|
|
5352
6573
|
busyRef.current = false;
|
|
5353
6574
|
}
|
|
5354
6575
|
}, [selected, wallet.provider, wallet.account, engine, kind, recipientFor, onSuccess, onError]);
|
|
6576
|
+
const [prices, setPrices] = react.useState(null);
|
|
6577
|
+
const priceKey = baseSelected?.options?.length ? `${baseSelected.source.asset}|${baseSelected.receive.asset}` : "";
|
|
6578
|
+
react.useEffect(() => {
|
|
6579
|
+
if (!priceKey || typeof engine.fetchPrices !== "function") return;
|
|
6580
|
+
let alive = true;
|
|
6581
|
+
const [from, to] = priceKey.split("|");
|
|
6582
|
+
(async () => {
|
|
6583
|
+
try {
|
|
6584
|
+
const p = await engine.fetchPrices([from, to]);
|
|
6585
|
+
const next = { key: priceKey, from: p[from.toUpperCase()], to: p[to.toUpperCase()] };
|
|
6586
|
+
if (alive) setPrices((prev) => prev && prev.key === next.key && prev.from === next.from && prev.to === next.to ? prev : next);
|
|
6587
|
+
} catch {
|
|
6588
|
+
}
|
|
6589
|
+
})();
|
|
6590
|
+
return () => {
|
|
6591
|
+
alive = false;
|
|
6592
|
+
};
|
|
6593
|
+
}, [engine, priceKey]);
|
|
6594
|
+
const compare = react.useMemo(() => {
|
|
6595
|
+
const base = baseSelected;
|
|
6596
|
+
if (!base?.options?.length) return null;
|
|
6597
|
+
const priced = prices?.key === priceKey ? prices : null;
|
|
6598
|
+
const inputAmount = Number(base.source.payAmount || base.source.amount);
|
|
6599
|
+
const fromUsd = priced?.from && Number.isFinite(inputAmount) ? inputAmount * priced.from : null;
|
|
6600
|
+
const options = priceCompareOptions(base.options, fromUsd);
|
|
6601
|
+
const selectedOptionId = selected?.selectedOptionId ?? null;
|
|
6602
|
+
const parityState = parity(options, fromUsd, priced?.to ?? null);
|
|
6603
|
+
return {
|
|
6604
|
+
options,
|
|
6605
|
+
visibleOptions: visibleOptions(options, proposedWait(options), selectedOptionId),
|
|
6606
|
+
selectedId: selectedOptionId,
|
|
6607
|
+
proposedWait: proposedWait(options),
|
|
6608
|
+
parity: parityState,
|
|
6609
|
+
extraVsFastest: extraVsFastest(options, selectedOptionId),
|
|
6610
|
+
tags: Object.fromEntries(options.map((o) => [o.id, cornerTags(options, o, parityState)])),
|
|
6611
|
+
pickForWait: (waitSec) => pickForWait(options, waitSec)
|
|
6612
|
+
};
|
|
6613
|
+
}, [baseSelected, selected, prices, priceKey]);
|
|
6614
|
+
const selectOption = react.useCallback(
|
|
6615
|
+
(optionId) => {
|
|
6616
|
+
if (busyRef.current || !baseSelected) return false;
|
|
6617
|
+
const signable = optionId === baseSelected.selectedOptionId || !!baseSelected.alternatives?.some((r) => r.selectedOptionId === optionId);
|
|
6618
|
+
if (!signable) return false;
|
|
6619
|
+
setPickedOptionId(optionId === baseSelected.selectedOptionId ? null : optionId);
|
|
6620
|
+
return true;
|
|
6621
|
+
},
|
|
6622
|
+
[baseSelected]
|
|
6623
|
+
);
|
|
6624
|
+
const [promotionList, setPromotionList] = react.useState([]);
|
|
6625
|
+
react.useEffect(() => {
|
|
6626
|
+
if (!enabled) return;
|
|
6627
|
+
let alive = true;
|
|
6628
|
+
(async () => {
|
|
6629
|
+
try {
|
|
6630
|
+
if (typeof engine.fetchPromotions !== "function") return;
|
|
6631
|
+
const read = await engine.fetchPromotions();
|
|
6632
|
+
const list = Array.isArray(read) ? read : [];
|
|
6633
|
+
if (alive) setPromotionList((prev) => JSON.stringify(prev) === JSON.stringify(list) ? prev : list);
|
|
6634
|
+
} catch {
|
|
6635
|
+
}
|
|
6636
|
+
})();
|
|
6637
|
+
return () => {
|
|
6638
|
+
alive = false;
|
|
6639
|
+
};
|
|
6640
|
+
}, [engine, enabled]);
|
|
6641
|
+
const promotions = react.useMemo(() => {
|
|
6642
|
+
const route = selected;
|
|
6643
|
+
const toAddress = route?.receive.tokenAddress;
|
|
6644
|
+
const forSelection = route && toAddress ? promotionFor(promotionList, {
|
|
6645
|
+
fromChainId: Number(route.source.chainId),
|
|
6646
|
+
...route.source.tokenAddress ? { fromAddress: route.source.tokenAddress } : {},
|
|
6647
|
+
toChainId: Number(route.receive.chainId),
|
|
6648
|
+
toAddress
|
|
6649
|
+
}) : void 0;
|
|
6650
|
+
let bonusEstimateRaw = null;
|
|
6651
|
+
if (forSelection && route) {
|
|
6652
|
+
const pickedRow = route.options?.find((o) => o.id === route.selectedOptionId);
|
|
6653
|
+
try {
|
|
6654
|
+
const delivered = pickedRow ? BigInt(pickedRow.amountRaw) : parseUnitsDecimal(route.receive.amount, Number(route.receive.decimals));
|
|
6655
|
+
bonusEstimateRaw = estimateBonus(delivered, forSelection).toString();
|
|
6656
|
+
} catch {
|
|
6657
|
+
bonusEstimateRaw = null;
|
|
6658
|
+
}
|
|
6659
|
+
}
|
|
6660
|
+
return {
|
|
6661
|
+
all: promotionList,
|
|
6662
|
+
promotedAssets: promotedAssets(promotionList),
|
|
6663
|
+
forSelection,
|
|
6664
|
+
pairsInto: route && toAddress ? pairPromotionsInto(promotionList, Number(route.receive.chainId), toAddress) : [],
|
|
6665
|
+
bonusEstimateRaw
|
|
6666
|
+
};
|
|
6667
|
+
}, [promotionList, selected]);
|
|
5355
6668
|
const quoteReady = status === "ready" && !!plan;
|
|
5356
6669
|
const quotePaused = quoteReady && idle2;
|
|
5357
6670
|
const quoteStale = quoteReady && (idle2 || planAt < returnedAt2);
|
|
@@ -5373,7 +6686,10 @@ function useFlow(args) {
|
|
|
5373
6686
|
quoteStale,
|
|
5374
6687
|
submit,
|
|
5375
6688
|
reload,
|
|
5376
|
-
addRoute
|
|
6689
|
+
addRoute,
|
|
6690
|
+
compare,
|
|
6691
|
+
selectOption,
|
|
6692
|
+
promotions
|
|
5377
6693
|
};
|
|
5378
6694
|
}
|
|
5379
6695
|
var RETRY_DELAYS_MS = [800, 2400, 6e3];
|
|
@@ -5441,9 +6757,9 @@ function useHoldings(engine, account, routes, initialBalances) {
|
|
|
5441
6757
|
const seeded = {};
|
|
5442
6758
|
const missing = [];
|
|
5443
6759
|
for (const target of targets) {
|
|
5444
|
-
const
|
|
5445
|
-
const balance = initialBalances?.[
|
|
5446
|
-
if (balance) seeded[
|
|
6760
|
+
const key2 = balanceKey(target.chainId, target.tokenAddress);
|
|
6761
|
+
const balance = initialBalances?.[key2];
|
|
6762
|
+
if (balance) seeded[key2] = balance;
|
|
5447
6763
|
else missing.push(target);
|
|
5448
6764
|
}
|
|
5449
6765
|
setBalances(seeded);
|
|
@@ -6967,7 +8283,7 @@ function priceOf(prices, symbol) {
|
|
|
6967
8283
|
const p = prices?.[String(symbol).toUpperCase()];
|
|
6968
8284
|
return typeof p === "number" && Number.isFinite(p) ? p : void 0;
|
|
6969
8285
|
}
|
|
6970
|
-
function buildGroup(
|
|
8286
|
+
function buildGroup(key2, members, prices) {
|
|
6971
8287
|
const tokens = members.map((m) => m.token);
|
|
6972
8288
|
let amount = null;
|
|
6973
8289
|
let usd2 = null;
|
|
@@ -6979,7 +8295,7 @@ function buildGroup(key, members, prices) {
|
|
|
6979
8295
|
}
|
|
6980
8296
|
const first = members[0].token;
|
|
6981
8297
|
return {
|
|
6982
|
-
key,
|
|
8298
|
+
key: key2,
|
|
6983
8299
|
symbol: dominantSymbol(tokens),
|
|
6984
8300
|
name: String(first.name || first.symbol),
|
|
6985
8301
|
logoUrl: first.logoUrl,
|
|
@@ -7000,15 +8316,15 @@ function groupDeployments(deployments, prices) {
|
|
|
7000
8316
|
const order = [];
|
|
7001
8317
|
const members = /* @__PURE__ */ new Map();
|
|
7002
8318
|
for (const d of [...deployments].sort(byDeployment)) {
|
|
7003
|
-
const
|
|
7004
|
-
const list = members.get(
|
|
8319
|
+
const key2 = String(d.token.symbol).toUpperCase();
|
|
8320
|
+
const list = members.get(key2);
|
|
7005
8321
|
if (list) list.push(d);
|
|
7006
8322
|
else {
|
|
7007
|
-
members.set(
|
|
7008
|
-
order.push(
|
|
8323
|
+
members.set(key2, [d]);
|
|
8324
|
+
order.push(key2);
|
|
7009
8325
|
}
|
|
7010
8326
|
}
|
|
7011
|
-
return order.map((
|
|
8327
|
+
return order.map((key2) => buildGroup(key2, members.get(key2), prices)).sort(byPickability);
|
|
7012
8328
|
}
|
|
7013
8329
|
var CHAIN_ALIASES = {
|
|
7014
8330
|
56: ["bsc", "binance"],
|
|
@@ -7016,10 +8332,10 @@ var CHAIN_ALIASES = {
|
|
|
7016
8332
|
43114: ["avax"]
|
|
7017
8333
|
};
|
|
7018
8334
|
function labelForms(label2) {
|
|
7019
|
-
const
|
|
7020
|
-
if (!
|
|
7021
|
-
const compact =
|
|
7022
|
-
return compact && compact !==
|
|
8335
|
+
const lower3 = label2.trim().toLowerCase();
|
|
8336
|
+
if (!lower3) return [];
|
|
8337
|
+
const compact = lower3.replace(/[^a-z0-9]/g, "");
|
|
8338
|
+
return compact && compact !== lower3 ? [lower3, compact] : [lower3];
|
|
7023
8339
|
}
|
|
7024
8340
|
function buildChainSearchTerms(chains) {
|
|
7025
8341
|
const byId = /* @__PURE__ */ new Map();
|
|
@@ -7282,14 +8598,14 @@ function TokenSelect(props) {
|
|
|
7282
8598
|
const groups = react.useMemo(() => {
|
|
7283
8599
|
const deployments = [];
|
|
7284
8600
|
for (const token of props.tokens) {
|
|
7285
|
-
const
|
|
7286
|
-
const n = Number(props.balances?.[
|
|
7287
|
-
const st = props.optionStates?.[
|
|
8601
|
+
const key2 = rowKey(token);
|
|
8602
|
+
const n = Number(props.balances?.[key2]?.formatted);
|
|
8603
|
+
const st = props.optionStates?.[key2];
|
|
7288
8604
|
if (st?.disabled && !WALLET_STATE_REASONS.has(String(st.reason))) continue;
|
|
7289
8605
|
deployments.push({
|
|
7290
8606
|
token,
|
|
7291
|
-
key,
|
|
7292
|
-
balance: showBalances && props.balances?.[
|
|
8607
|
+
key: key2,
|
|
8608
|
+
balance: showBalances && props.balances?.[key2] && Number.isFinite(n) ? n : null,
|
|
7293
8609
|
disabled: !!st?.disabled,
|
|
7294
8610
|
// The line under a greyed row says why. Callers send either a sentence in `reason` (the
|
|
7295
8611
|
// exchange's "cannot be delivered on this chain") or a machine code there with the words in
|
|
@@ -7661,7 +8977,7 @@ function WidgetShell(props) {
|
|
|
7661
8977
|
}
|
|
7662
8978
|
);
|
|
7663
8979
|
}
|
|
7664
|
-
function
|
|
8980
|
+
function shortAddress3(a) {
|
|
7665
8981
|
if (!a) return "";
|
|
7666
8982
|
return `${a.slice(0, 6)}\u2026${a.slice(-4)}`;
|
|
7667
8983
|
}
|
|
@@ -7930,13 +9246,13 @@ function useTxHistory(account) {
|
|
|
7930
9246
|
react.useEffect(() => {
|
|
7931
9247
|
setEntries(readTxHistory(account));
|
|
7932
9248
|
if (typeof window === "undefined" || !account) return;
|
|
7933
|
-
const
|
|
9249
|
+
const key2 = txHistoryKey(account);
|
|
7934
9250
|
const onLocal = (e) => {
|
|
7935
9251
|
const detail = e.detail;
|
|
7936
9252
|
if (!detail?.account || detail.account === account.toLowerCase()) setEntries(readTxHistory(account));
|
|
7937
9253
|
};
|
|
7938
9254
|
const onStorage = (e) => {
|
|
7939
|
-
if (e.key ===
|
|
9255
|
+
if (e.key === key2) setEntries(readTxHistory(account));
|
|
7940
9256
|
};
|
|
7941
9257
|
window.addEventListener(TX_HISTORY_EVENT, onLocal);
|
|
7942
9258
|
window.addEventListener("storage", onStorage);
|
|
@@ -7952,32 +9268,37 @@ var hidden2 = () => typeof document !== "undefined" && document.visibilityState
|
|
|
7952
9268
|
var travelling = (entries) => !!entries?.some((e) => e.delivery === "in-progress" || e.delivery === "attention");
|
|
7953
9269
|
function useWalletHistory(engine, wallets) {
|
|
7954
9270
|
const [entries, setEntries] = react.useState(null);
|
|
7955
|
-
const
|
|
9271
|
+
const key2 = wallets.filter((w) => !!w).join("|");
|
|
7956
9272
|
react.useEffect(() => {
|
|
7957
9273
|
setEntries(null);
|
|
7958
|
-
if (!engine || !
|
|
9274
|
+
if (!engine || !key2) return;
|
|
7959
9275
|
let alive = true;
|
|
7960
9276
|
let timer2;
|
|
9277
|
+
let started2 = Date.now();
|
|
7961
9278
|
const read = async () => {
|
|
7962
9279
|
if (timer2) clearTimeout(timer2);
|
|
7963
9280
|
timer2 = void 0;
|
|
7964
9281
|
if (!hidden2()) {
|
|
7965
|
-
const next = await engine.fetchWalletHistory(
|
|
9282
|
+
const next = await engine.fetchWalletHistory(key2.split("|"));
|
|
7966
9283
|
if (!alive) return;
|
|
7967
9284
|
if (next) setEntries(next);
|
|
7968
9285
|
if (!travelling(next)) return;
|
|
7969
9286
|
}
|
|
9287
|
+
if (Date.now() - started2 > DELIVERY_GIVE_UP_MS) return;
|
|
7970
9288
|
timer2 = setTimeout(read, WALLET_HISTORY_REFRESH_MS);
|
|
7971
9289
|
};
|
|
7972
9290
|
void read();
|
|
7973
|
-
const onRecorded = () =>
|
|
9291
|
+
const onRecorded = () => {
|
|
9292
|
+
started2 = Date.now();
|
|
9293
|
+
void read();
|
|
9294
|
+
};
|
|
7974
9295
|
if (typeof window !== "undefined") window.addEventListener(TX_HISTORY_EVENT, onRecorded);
|
|
7975
9296
|
return () => {
|
|
7976
9297
|
alive = false;
|
|
7977
9298
|
if (timer2) clearTimeout(timer2);
|
|
7978
9299
|
if (typeof window !== "undefined") window.removeEventListener(TX_HISTORY_EVENT, onRecorded);
|
|
7979
9300
|
};
|
|
7980
|
-
}, [engine,
|
|
9301
|
+
}, [engine, key2]);
|
|
7981
9302
|
return entries;
|
|
7982
9303
|
}
|
|
7983
9304
|
function BackGlyph() {
|
|
@@ -8114,15 +9435,15 @@ function TxPair(props) {
|
|
|
8114
9435
|
] });
|
|
8115
9436
|
}
|
|
8116
9437
|
function logoFor(art, symbol, chainId) {
|
|
8117
|
-
const
|
|
8118
|
-
if (!
|
|
9438
|
+
const key2 = symbolKey(symbol);
|
|
9439
|
+
if (!key2) return void 0;
|
|
8119
9440
|
const tokens = art.tokens;
|
|
8120
9441
|
if (tokens?.length) {
|
|
8121
|
-
const sameChain = chainId == null ? void 0 : tokens.find((t) => Number(t.chainId) === chainId && symbolKey(t.symbol) ===
|
|
8122
|
-
const found = (sameChain ?? tokens.find((t) => symbolKey(t.symbol) ===
|
|
9442
|
+
const sameChain = chainId == null ? void 0 : tokens.find((t) => Number(t.chainId) === chainId && symbolKey(t.symbol) === key2);
|
|
9443
|
+
const found = (sameChain ?? tokens.find((t) => symbolKey(t.symbol) === key2))?.logoUrl;
|
|
8123
9444
|
if (found) return found;
|
|
8124
9445
|
}
|
|
8125
|
-
return art.vaultIcons?.get(
|
|
9446
|
+
return art.vaultIcons?.get(key2);
|
|
8126
9447
|
}
|
|
8127
9448
|
function TxHistoryList(props) {
|
|
8128
9449
|
if (!props.entries.length) {
|
|
@@ -8199,7 +9520,7 @@ function TxDetail(props) {
|
|
|
8199
9520
|
] }),
|
|
8200
9521
|
e.recipient ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta-row", children: [
|
|
8201
9522
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Recipient" }),
|
|
8202
|
-
/* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", children:
|
|
9523
|
+
/* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", children: shortAddress3(e.recipient) })
|
|
8203
9524
|
] }) : null,
|
|
8204
9525
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta-row", children: [
|
|
8205
9526
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Settlement" }),
|
|
@@ -8236,7 +9557,7 @@ function TxHistoryPanel(props) {
|
|
|
8236
9557
|
/* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", autoFocus: true, ref: backRef, className: "sg-back", onClick: selected ? () => setSelectedHash(null) : props.onBack, "aria-label": "Back", children: /* @__PURE__ */ jsxRuntime.jsx(BackGlyph, {}) }),
|
|
8237
9558
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-sel-title", children: [
|
|
8238
9559
|
selected ? "Transaction" : "Transaction history",
|
|
8239
|
-
account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sel-sub sg-mono", children:
|
|
9560
|
+
account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sel-sub sg-mono", children: shortAddress3(account) }) : null
|
|
8240
9561
|
] })
|
|
8241
9562
|
] }),
|
|
8242
9563
|
selected ? /* @__PURE__ */ jsxRuntime.jsx(TxDetail, { entry: selected, tokens: props.tokens, vaultIcons: props.vaultIcons }) : /* @__PURE__ */ jsxRuntime.jsx(TxHistoryList, { entries, tokens: props.tokens, vaultIcons: props.vaultIcons, onPick: pick })
|
|
@@ -8418,8 +9739,8 @@ function onSolanaAccountChange(info, cb) {
|
|
|
8418
9739
|
}
|
|
8419
9740
|
}) ?? (() => {
|
|
8420
9741
|
});
|
|
8421
|
-
const changed = (
|
|
8422
|
-
const address = validAddress(
|
|
9742
|
+
const changed = (key2) => {
|
|
9743
|
+
const address = validAddress(key2);
|
|
8423
9744
|
connected.set(provider, address ? [{ address }] : []);
|
|
8424
9745
|
cb(address);
|
|
8425
9746
|
};
|
|
@@ -8591,82 +9912,6 @@ function useRecipient(destinationChainId, hostRecipient, opts = {}) {
|
|
|
8591
9912
|
const recipientFor = (account) => required ? recipient2 || "" : hostRecipient || custom.evm || account;
|
|
8592
9913
|
return { recipientFamily, recipientChainId: destinationChainId, recipient: recipient2, shown, typed, recipientFor, managed, missing, error, wallet, familyWallet, wallets, open: open && managed, show: () => setOpen(true), close, selectAddress, connect, triggerRef };
|
|
8593
9914
|
}
|
|
8594
|
-
|
|
8595
|
-
// src/core/checksum.ts
|
|
8596
|
-
var RC = [
|
|
8597
|
-
0x0000000000000001n,
|
|
8598
|
-
0x0000000000008082n,
|
|
8599
|
-
0x800000000000808an,
|
|
8600
|
-
0x8000000080008000n,
|
|
8601
|
-
0x000000000000808bn,
|
|
8602
|
-
0x0000000080000001n,
|
|
8603
|
-
0x8000000080008081n,
|
|
8604
|
-
0x8000000000008009n,
|
|
8605
|
-
0x000000000000008an,
|
|
8606
|
-
0x0000000000000088n,
|
|
8607
|
-
0x0000000080008009n,
|
|
8608
|
-
0x000000008000000an,
|
|
8609
|
-
0x000000008000808bn,
|
|
8610
|
-
0x800000000000008bn,
|
|
8611
|
-
0x8000000000008089n,
|
|
8612
|
-
0x8000000000008003n,
|
|
8613
|
-
0x8000000000008002n,
|
|
8614
|
-
0x8000000000000080n,
|
|
8615
|
-
0x000000000000800an,
|
|
8616
|
-
0x800000008000000an,
|
|
8617
|
-
0x8000000080008081n,
|
|
8618
|
-
0x8000000000008080n,
|
|
8619
|
-
0x0000000080000001n,
|
|
8620
|
-
0x8000000080008008n
|
|
8621
|
-
];
|
|
8622
|
-
var ROT = [0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14];
|
|
8623
|
-
var MASK = (1n << 64n) - 1n;
|
|
8624
|
-
var rotl = (x, n) => n === 0 ? x : (x << BigInt(n) | x >> BigInt(64 - n)) & MASK;
|
|
8625
|
-
function keccakF(s) {
|
|
8626
|
-
for (let round = 0; round < 24; round++) {
|
|
8627
|
-
const c = [0, 1, 2, 3, 4].map((x) => s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]);
|
|
8628
|
-
for (let x = 0; x < 5; x++) {
|
|
8629
|
-
const d = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1);
|
|
8630
|
-
for (let y = 0; y < 25; y += 5) s[y + x] = s[y + x] ^ d;
|
|
8631
|
-
}
|
|
8632
|
-
const b = new Array(25);
|
|
8633
|
-
for (let x = 0; x < 5; x++) for (let y = 0; y < 5; y++) b[y + 5 * ((2 * x + 3 * y) % 5)] = rotl(s[x + 5 * y], ROT[x + 5 * y]);
|
|
8634
|
-
for (let x = 0; x < 5; x++) for (let y = 0; y < 25; y += 5) s[y + x] = b[y + x] ^ ~b[y + (x + 1) % 5] & MASK & b[y + (x + 2) % 5];
|
|
8635
|
-
s[0] = s[0] ^ RC[round];
|
|
8636
|
-
}
|
|
8637
|
-
}
|
|
8638
|
-
function keccak256Hex(bytes) {
|
|
8639
|
-
const rate = 136;
|
|
8640
|
-
const padded = new Uint8Array(Math.ceil((bytes.length + 1) / rate) * rate);
|
|
8641
|
-
padded.set(bytes);
|
|
8642
|
-
padded[bytes.length] = padded[bytes.length] ^ 1;
|
|
8643
|
-
padded[padded.length - 1] = padded[padded.length - 1] ^ 128;
|
|
8644
|
-
const s = new Array(25).fill(0n);
|
|
8645
|
-
for (let off = 0; off < padded.length; off += rate) {
|
|
8646
|
-
for (let i = 0; i < rate / 8; i++) {
|
|
8647
|
-
let lane = 0n;
|
|
8648
|
-
for (let j = 7; j >= 0; j--) lane = lane << 8n | BigInt(padded[off + i * 8 + j]);
|
|
8649
|
-
s[i] = s[i] ^ lane;
|
|
8650
|
-
}
|
|
8651
|
-
keccakF(s);
|
|
8652
|
-
}
|
|
8653
|
-
let out = "";
|
|
8654
|
-
for (let i = 0; i < 4; i++) for (let j = 0; j < 8; j++) out += Number(s[i] >> BigInt(8 * j) & 0xffn).toString(16).padStart(2, "0");
|
|
8655
|
-
return out;
|
|
8656
|
-
}
|
|
8657
|
-
function toChecksumAddress(address) {
|
|
8658
|
-
const lower2 = address.slice(2).toLowerCase();
|
|
8659
|
-
const hash2 = keccak256Hex(new TextEncoder().encode(lower2));
|
|
8660
|
-
let out = "0x";
|
|
8661
|
-
for (let i = 0; i < 40; i++) out += Number.parseInt(hash2[i], 16) >= 8 ? lower2[i].toUpperCase() : lower2[i];
|
|
8662
|
-
return out;
|
|
8663
|
-
}
|
|
8664
|
-
function hasValidChecksum(address) {
|
|
8665
|
-
if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return false;
|
|
8666
|
-
const body = address.slice(2);
|
|
8667
|
-
if (body === body.toLowerCase() || body === body.toUpperCase()) return true;
|
|
8668
|
-
return toChecksumAddress(address) === address;
|
|
8669
|
-
}
|
|
8670
9915
|
function ArrowLeft() {
|
|
8671
9916
|
return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
|
|
8672
9917
|
/* @__PURE__ */ jsxRuntime.jsx("path", { d: "M6.38 3.95312L2.33333 7.99979L6.38 12.0465", stroke: "currentColor", strokeWidth: "1.2", strokeMiterlimit: "10", strokeLinecap: "round", strokeLinejoin: "round" }),
|
|
@@ -9347,7 +10592,7 @@ function IdentityLine(props) {
|
|
|
9347
10592
|
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-link-id", children: [
|
|
9348
10593
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-icon", children: /* @__PURE__ */ jsxRuntime.jsx(WalletGlyph, {}) }),
|
|
9349
10594
|
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-link-id-text", children: [
|
|
9350
|
-
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-primary", children: props.account ?
|
|
10595
|
+
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-primary", children: props.account ? shortAddress3(props.account) : "ZeroDelta Link" }),
|
|
9351
10596
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-secondary", children: props.email ? props.email : props.account ? "Connected wallet" : "Connect your wallet to continue" })
|
|
9352
10597
|
] }),
|
|
9353
10598
|
props.account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }) : null
|
|
@@ -9494,9 +10739,9 @@ function PaymentIsland(props) {
|
|
|
9494
10739
|
const optionStates = react.useMemo(() => {
|
|
9495
10740
|
const map = {};
|
|
9496
10741
|
for (const a of annotated) {
|
|
9497
|
-
const
|
|
10742
|
+
const key2 = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
|
|
9498
10743
|
if (!a.balance || holdings.loading) {
|
|
9499
|
-
map[
|
|
10744
|
+
map[key2] = { disabled: false, reason: "checking" };
|
|
9500
10745
|
continue;
|
|
9501
10746
|
}
|
|
9502
10747
|
let zero = false;
|
|
@@ -9505,9 +10750,9 @@ function PaymentIsland(props) {
|
|
|
9505
10750
|
} catch {
|
|
9506
10751
|
zero = false;
|
|
9507
10752
|
}
|
|
9508
|
-
if (zero) map[
|
|
9509
|
-
else if (a.affordable === false) map[
|
|
9510
|
-
else map[
|
|
10753
|
+
if (zero) map[key2] = { disabled: true, reason: "no-balance", hint: "No balance on this chain" };
|
|
10754
|
+
else if (a.affordable === false) map[key2] = { disabled: true, reason: "insufficient", hint: `Need ${a.route.source.payAmount} ${a.route.source.ticker || a.route.source.asset}` };
|
|
10755
|
+
else map[key2] = { disabled: false };
|
|
9511
10756
|
}
|
|
9512
10757
|
return map;
|
|
9513
10758
|
}, [annotated, holdings.loading]);
|
|
@@ -9547,19 +10792,19 @@ function PaymentIsland(props) {
|
|
|
9547
10792
|
if (!catalogue?.ready) return void 0;
|
|
9548
10793
|
const states2 = {};
|
|
9549
10794
|
for (const token of catalogue.tokens) {
|
|
9550
|
-
const
|
|
10795
|
+
const key2 = balanceKey(Number(token.chainId), token.address);
|
|
9551
10796
|
const measured = exFromToken ? brokenLaneFor(token, exFromToken, catalogue.brokenLanes) : void 0;
|
|
9552
10797
|
if (measured) {
|
|
9553
|
-
states2[
|
|
10798
|
+
states2[key2] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
|
|
9554
10799
|
continue;
|
|
9555
10800
|
}
|
|
9556
10801
|
const verdict = destinationAvailability(token, catalogue, exFromToken);
|
|
9557
10802
|
if (verdict === "available") {
|
|
9558
10803
|
const limit = laneLimitFor(token, exFromToken, catalogue.limitedLanes);
|
|
9559
|
-
if (limit) states2[
|
|
10804
|
+
if (limit) states2[key2] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, exFromToken ? tokenTicker(exFromToken) : void 0)) };
|
|
9560
10805
|
continue;
|
|
9561
10806
|
}
|
|
9562
|
-
states2[
|
|
10807
|
+
states2[key2] = {
|
|
9563
10808
|
disabled: true,
|
|
9564
10809
|
reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain.` : "ZeroDelta cannot deliver this asset here.",
|
|
9565
10810
|
hint: verdict === "hub-only" ? "Not here" : "Unavailable"
|
|
@@ -9572,9 +10817,9 @@ function PaymentIsland(props) {
|
|
|
9572
10817
|
const seen = /* @__PURE__ */ new Set();
|
|
9573
10818
|
const list = [];
|
|
9574
10819
|
for (const r of visibleRoutes) {
|
|
9575
|
-
const
|
|
9576
|
-
if (seen.has(
|
|
9577
|
-
seen.add(
|
|
10820
|
+
const key2 = balanceKey(r.source.chainId, r.source.tokenAddress);
|
|
10821
|
+
if (seen.has(key2)) continue;
|
|
10822
|
+
seen.add(key2);
|
|
9578
10823
|
const reg = registryTokens.find((t) => Number(t.chainId) === r.source.chainId && addrEq(t.address, r.source.tokenAddress));
|
|
9579
10824
|
list.push(
|
|
9580
10825
|
reg ?? {
|
|
@@ -9914,7 +11159,7 @@ function PaymentIsland(props) {
|
|
|
9914
11159
|
] }),
|
|
9915
11160
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-receipt-sub", children: [
|
|
9916
11161
|
deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
|
|
9917
|
-
(flow.lastTxEntry?.recipient || recipient2) && (isPay || recipientState.recipientFamily === "solana") ? ` \xB7 ${
|
|
11162
|
+
(flow.lastTxEntry?.recipient || recipient2) && (isPay || recipientState.recipientFamily === "solana") ? ` \xB7 ${shortAddress3(flow.lastTxEntry?.recipient || recipient2)}` : ""
|
|
9918
11163
|
] }),
|
|
9919
11164
|
evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
|
|
9920
11165
|
] }),
|
|
@@ -10227,9 +11472,9 @@ function PayCard(props) {
|
|
|
10227
11472
|
const optionStates = react.useMemo(() => {
|
|
10228
11473
|
const map = {};
|
|
10229
11474
|
for (const a of annotated) {
|
|
10230
|
-
const
|
|
11475
|
+
const key2 = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
|
|
10231
11476
|
if (!a.balance || holdings.loading) {
|
|
10232
|
-
map[
|
|
11477
|
+
map[key2] = { disabled: false, reason: "checking" };
|
|
10233
11478
|
continue;
|
|
10234
11479
|
}
|
|
10235
11480
|
let zero = false;
|
|
@@ -10239,23 +11484,23 @@ function PayCard(props) {
|
|
|
10239
11484
|
zero = false;
|
|
10240
11485
|
}
|
|
10241
11486
|
if (zero) {
|
|
10242
|
-
map[
|
|
11487
|
+
map[key2] = { disabled: true, reason: "no-balance", hint: "No balance on this chain" };
|
|
10243
11488
|
} else if (a.affordable === false) {
|
|
10244
|
-
map[
|
|
11489
|
+
map[key2] = { disabled: true, reason: "insufficient", hint: `Need ${a.route.source.payAmount} ${a.route.source.ticker || a.route.source.asset}` };
|
|
10245
11490
|
} else {
|
|
10246
|
-
map[
|
|
11491
|
+
map[key2] = { disabled: false };
|
|
10247
11492
|
}
|
|
10248
11493
|
}
|
|
10249
11494
|
for (const o of unquoted) {
|
|
10250
|
-
const
|
|
10251
|
-
if (map[
|
|
11495
|
+
const key2 = balanceKey(o.chainId, o.address);
|
|
11496
|
+
if (map[key2]) continue;
|
|
10252
11497
|
let zero = false;
|
|
10253
11498
|
try {
|
|
10254
|
-
zero = BigInt(listBalances[
|
|
11499
|
+
zero = BigInt(listBalances[key2]?.raw ?? "x") === 0n;
|
|
10255
11500
|
} catch {
|
|
10256
11501
|
zero = false;
|
|
10257
11502
|
}
|
|
10258
|
-
map[
|
|
11503
|
+
map[key2] = zero ? { disabled: true, reason: "no-balance", hint: "No balance on this chain" } : { disabled: false };
|
|
10259
11504
|
}
|
|
10260
11505
|
return map;
|
|
10261
11506
|
}, [annotated, holdings.loading, unquoted, listBalances]);
|
|
@@ -10269,9 +11514,9 @@ function PayCard(props) {
|
|
|
10269
11514
|
const seen = /* @__PURE__ */ new Set();
|
|
10270
11515
|
const list = [];
|
|
10271
11516
|
const push = (chainId, address, fallback) => {
|
|
10272
|
-
const
|
|
10273
|
-
if (seen.has(
|
|
10274
|
-
seen.add(
|
|
11517
|
+
const key2 = balanceKey(chainId, address);
|
|
11518
|
+
if (seen.has(key2)) return;
|
|
11519
|
+
seen.add(key2);
|
|
10275
11520
|
list.push(registryTokens.find((t) => Number(t.chainId) === chainId && addrEq2(t.address, address)) ?? fallback);
|
|
10276
11521
|
};
|
|
10277
11522
|
for (const r of visibleRoutes) {
|
|
@@ -10345,13 +11590,13 @@ function PayCard(props) {
|
|
|
10345
11590
|
const option = unquoted.find((o) => o.chainId === pick.chainId && o.symbolKey === symbolKey(pick.symbol));
|
|
10346
11591
|
closeSelector();
|
|
10347
11592
|
if (!option || !wallet.account) return;
|
|
10348
|
-
const
|
|
10349
|
-
setPricing(
|
|
11593
|
+
const key2 = balanceKey(option.chainId, option.address);
|
|
11594
|
+
setPricing(key2);
|
|
10350
11595
|
userPicked.current = true;
|
|
10351
11596
|
engine.quotePayOption({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, wallet.account, { chainId: option.chainId, address: option.address }, { chainId: wallet.chainId ?? void 0, fundingAssets: planFundingAssets }).then((route) => flow.addRoute(route)).catch(() => {
|
|
10352
|
-
setFailedOptions((prev) => /* @__PURE__ */ new Set([...prev,
|
|
11597
|
+
setFailedOptions((prev) => /* @__PURE__ */ new Set([...prev, key2]));
|
|
10353
11598
|
setPickError(`${option.ticker || option.symbol} on ${option.chainName} cannot settle this payment right now. Pick another way to pay.`);
|
|
10354
|
-
}).finally(() => setPricing((cur) => cur ===
|
|
11599
|
+
}).finally(() => setPricing((cur) => cur === key2 ? null : cur));
|
|
10355
11600
|
};
|
|
10356
11601
|
const parked = !isLiveMethod(method);
|
|
10357
11602
|
const submitting = flow.status === "submitting";
|
|
@@ -10384,7 +11629,7 @@ function PayCard(props) {
|
|
|
10384
11629
|
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-wallet", "data-connected": "true", children: [
|
|
10385
11630
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }),
|
|
10386
11631
|
" ",
|
|
10387
|
-
|
|
11632
|
+
shortAddress3(wallet.account)
|
|
10388
11633
|
] })
|
|
10389
11634
|
] }) : /* @__PURE__ */ jsxRuntime.jsx("span", {});
|
|
10390
11635
|
const nativeWei = sel ? routeNativeValue(sel) : 0n;
|
|
@@ -10424,7 +11669,7 @@ function PayCard(props) {
|
|
|
10424
11669
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
|
|
10425
11670
|
deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
|
|
10426
11671
|
" \xB7 ",
|
|
10427
|
-
|
|
11672
|
+
shortAddress3(props.recipient)
|
|
10428
11673
|
] }),
|
|
10429
11674
|
evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
|
|
10430
11675
|
] }),
|
|
@@ -10592,7 +11837,7 @@ function StableGenieSwap(props) {
|
|
|
10592
11837
|
] }),
|
|
10593
11838
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
|
|
10594
11839
|
deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
|
|
10595
|
-
recipientState.recipientFamily === "solana" ? ` \xB7 ${
|
|
11840
|
+
recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress3(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress3(props.recipient)}` : ""
|
|
10596
11841
|
] }),
|
|
10597
11842
|
evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
|
|
10598
11843
|
] }),
|
|
@@ -10656,7 +11901,7 @@ function useSolanaSourceFlow(args) {
|
|
|
10656
11901
|
const planArgs = react.useRef(null);
|
|
10657
11902
|
const changedWhileBusy = react.useRef(false);
|
|
10658
11903
|
const addressed = Boolean(owner && payer && recipient2);
|
|
10659
|
-
const
|
|
11904
|
+
const key2 = keyOf(args);
|
|
10660
11905
|
react.useEffect(() => {
|
|
10661
11906
|
const id = ++req.current;
|
|
10662
11907
|
if (!enabled || !fromSymbol || !toChainId || !toSymbol || !(Number(amount) > 0)) {
|
|
@@ -10690,7 +11935,7 @@ function useSolanaSourceFlow(args) {
|
|
|
10690
11935
|
const quoted = await engine.quoteSolanaSource(input);
|
|
10691
11936
|
const built = await engine.buildSolanaSourcePlan(input, quoted);
|
|
10692
11937
|
if (id !== req.current) return;
|
|
10693
|
-
planKey.current =
|
|
11938
|
+
planKey.current = key2;
|
|
10694
11939
|
planArgs.current = { ...latest.current };
|
|
10695
11940
|
setPreview(quoted);
|
|
10696
11941
|
setPlan(built);
|
|
@@ -10706,7 +11951,7 @@ function useSolanaSourceFlow(args) {
|
|
|
10706
11951
|
}
|
|
10707
11952
|
}, 350);
|
|
10708
11953
|
return () => clearTimeout(timer2);
|
|
10709
|
-
}, [engine, enabled,
|
|
11954
|
+
}, [engine, enabled, key2, addressed, nonce]);
|
|
10710
11955
|
react.useEffect(() => {
|
|
10711
11956
|
let alive = true;
|
|
10712
11957
|
setBalanceRaw(void 0);
|
|
@@ -11030,11 +12275,11 @@ function ExchangeCard(props) {
|
|
|
11030
12275
|
const [fiatCurrency, setFiatCurrency] = react.useState(props.fiatCurrency ?? "EUR");
|
|
11031
12276
|
const sellableFrom = react.useCallback((t) => t && product === "rwa" && !isSellableRwa(t) ? null : t, [product]);
|
|
11032
12277
|
const fromToken = react.useMemo(() => from ? sellableFrom(findToken(tokens, from.chainId, from.symbol)) : null, [tokens, from, sellableFrom]);
|
|
11033
|
-
const
|
|
11034
|
-
const toSymbol =
|
|
12278
|
+
const toToken2 = react.useMemo(() => to ? findToken(tokens, to.chainId, to.symbol) : null, [tokens, to]);
|
|
12279
|
+
const toSymbol = toToken2?.symbol ?? to?.symbol ?? "";
|
|
11035
12280
|
const fromTicker = fromToken ? tokenTicker(fromToken) : from?.symbol ?? "";
|
|
11036
|
-
const toTicker =
|
|
11037
|
-
const fromPickerTokens = react.useMemo(() => product === "rwa" ? counterpartTokens(sourceTokens,
|
|
12281
|
+
const toTicker = toToken2 ? tokenTicker(toToken2) : toSymbol;
|
|
12282
|
+
const fromPickerTokens = react.useMemo(() => product === "rwa" ? counterpartTokens(sourceTokens, toToken2) : sourceTokens, [product, sourceTokens, toToken2]);
|
|
11038
12283
|
const toPickerTokens = react.useMemo(() => product === "rwa" ? counterpartTokens(tokens, fromToken) : tokens, [product, tokens, fromToken]);
|
|
11039
12284
|
const rwaSeeded = react.useRef(false);
|
|
11040
12285
|
react.useEffect(() => {
|
|
@@ -11051,19 +12296,19 @@ function ExchangeCard(props) {
|
|
|
11051
12296
|
if (!catalogue?.ready) return void 0;
|
|
11052
12297
|
const states2 = {};
|
|
11053
12298
|
for (const token of catalogue.tokens) {
|
|
11054
|
-
const
|
|
12299
|
+
const key2 = `${Number(token.chainId)}:${String(token.address || "").toLowerCase()}`;
|
|
11055
12300
|
const measured = fromToken ? brokenLaneFor(token, fromToken, catalogue.brokenLanes) : void 0;
|
|
11056
12301
|
if (measured) {
|
|
11057
|
-
states2[
|
|
12302
|
+
states2[key2] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
|
|
11058
12303
|
continue;
|
|
11059
12304
|
}
|
|
11060
12305
|
const verdict = destinationAvailability(token, catalogue, fromToken);
|
|
11061
12306
|
if (verdict === "available") {
|
|
11062
12307
|
const limit = laneLimitFor(token, fromToken, catalogue.limitedLanes);
|
|
11063
|
-
if (limit) states2[
|
|
12308
|
+
if (limit) states2[key2] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, fromToken ? tokenTicker(fromToken) : void 0)) };
|
|
11064
12309
|
continue;
|
|
11065
12310
|
}
|
|
11066
|
-
states2[
|
|
12311
|
+
states2[key2] = {
|
|
11067
12312
|
disabled: true,
|
|
11068
12313
|
reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain \u2014 choose an execution chain.` : "ZeroDelta cannot deliver this asset here.",
|
|
11069
12314
|
hint: verdict === "hub-only" ? "Not here" : "Unavailable"
|
|
@@ -11079,8 +12324,8 @@ function ExchangeCard(props) {
|
|
|
11079
12324
|
const amountValid = /^\d+(\.\d+)?$/.test(normalizedAmount) && Number(normalizedAmount) > 0 && Number(normalizedAmount) <= 1e9;
|
|
11080
12325
|
const rampMode = mode !== "exchange";
|
|
11081
12326
|
const laneLimit = react.useMemo(
|
|
11082
|
-
() => mode === "exchange" && fromToken &&
|
|
11083
|
-
[mode, catalogue, fromToken,
|
|
12327
|
+
() => mode === "exchange" && fromToken && toToken2 ? laneLimitFor(toToken2, fromToken, catalogue?.limitedLanes) : void 0,
|
|
12328
|
+
[mode, catalogue, fromToken, toToken2]
|
|
11084
12329
|
);
|
|
11085
12330
|
const limitSymbol = laneLimit ? laneLimitSymbol(laneLimit, fromTicker) : "";
|
|
11086
12331
|
const overLimit = react.useMemo(() => {
|
|
@@ -11234,11 +12479,11 @@ function ExchangeCard(props) {
|
|
|
11234
12479
|
useFitText(receiveSideRef, receiveShown);
|
|
11235
12480
|
const toDecimals = react.useMemo(() => {
|
|
11236
12481
|
try {
|
|
11237
|
-
return
|
|
12482
|
+
return toToken2 ? assetDecimals(toToken2) : void 0;
|
|
11238
12483
|
} catch {
|
|
11239
12484
|
return void 0;
|
|
11240
12485
|
}
|
|
11241
|
-
}, [
|
|
12486
|
+
}, [toToken2]);
|
|
11242
12487
|
const meta = solActive ? solFlow.preview ? { bridge: solFlow.preview.bridge || "ZeroDelta", feeBps: solFlow.preview.feeBps, duration: solFlow.preview.estimatedDuration } : null : addressed ? flow.selected ? { bridge: flow.selected.quote.bridge || "ZeroDelta", feeBps: Number(flow.selected.quote.feeBps || 0), duration: Number(flow.selected.quote.estimatedDuration || 0) } : null : preview.data ? { bridge: preview.data.bridge || "ZeroDelta", feeBps: preview.data.feeBps, duration: preview.data.estimatedDuration } : null;
|
|
11243
12488
|
const pct = (p) => {
|
|
11244
12489
|
if (!fromBal || !fromToken) return;
|
|
@@ -11450,7 +12695,7 @@ function ExchangeCard(props) {
|
|
|
11450
12695
|
] }),
|
|
11451
12696
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
|
|
11452
12697
|
solDelivery.phase === "tracking" ? "Submitted on Solana \u2014 tracking delivery" : deliveryHeadline(solDelivery, true),
|
|
11453
|
-
solFlow.sent?.recipient ? ` \xB7 ${
|
|
12698
|
+
solFlow.sent?.recipient ? ` \xB7 ${shortAddress3(solFlow.sent.recipient)}` : ""
|
|
11454
12699
|
] }),
|
|
11455
12700
|
/* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: solDelivery })
|
|
11456
12701
|
] }),
|
|
@@ -11471,7 +12716,7 @@ function ExchangeCard(props) {
|
|
|
11471
12716
|
] }),
|
|
11472
12717
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
|
|
11473
12718
|
deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
|
|
11474
|
-
recipientState.recipientFamily === "solana" ? ` \xB7 ${
|
|
12719
|
+
recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress3(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress3(props.recipient)}` : ""
|
|
11475
12720
|
] }),
|
|
11476
12721
|
evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
|
|
11477
12722
|
] }),
|
|
@@ -11482,7 +12727,7 @@ function ExchangeCard(props) {
|
|
|
11482
12727
|
] });
|
|
11483
12728
|
} else {
|
|
11484
12729
|
const payToken = mode === "onramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatButton, { fiat, onCurrency: setFiatCurrency, disabled: submitting }) : /* @__PURE__ */ jsxRuntime.jsx(TokenButton, { label: "You pay", symbol: from?.symbol ?? null, chainId: from?.chainId ?? null, chainName: nameOf(from?.chainId), token: fromToken, disabled: submitting, btnRef: fromTileRef, onClick: () => setView("from") });
|
|
11485
|
-
const receiveToken = mode === "offramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatButton, { fiat, onCurrency: setFiatCurrency, disabled: submitting }) : /* @__PURE__ */ jsxRuntime.jsx(TokenButton, { label: "You receive", symbol: to?.symbol ?? null, chainId: to?.chainId ?? null, chainName: nameOf(to?.chainId), token:
|
|
12730
|
+
const receiveToken = mode === "offramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatButton, { fiat, onCurrency: setFiatCurrency, disabled: submitting }) : /* @__PURE__ */ jsxRuntime.jsx(TokenButton, { label: "You receive", symbol: to?.symbol ?? null, chainId: to?.chainId ?? null, chainName: nameOf(to?.chainId), token: toToken2, disabled: submitting, btnRef: toTileRef, onClick: () => setView("to") });
|
|
11486
12731
|
const cta = solActive ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
11487
12732
|
solanaSteps,
|
|
11488
12733
|
solanaCta,
|
|
@@ -11505,7 +12750,7 @@ function ExchangeCard(props) {
|
|
|
11505
12750
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-ft", children: [
|
|
11506
12751
|
mode === "onramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatTile, { label: "From", currency: fiatCurrency, onCurrency: setFiatCurrency }) : /* @__PURE__ */ jsxRuntime.jsx(TokenTile, { label: "From", pick: from, chainName: nameOf(from?.chainId), token: fromToken, disabled: submitting, btnRef: fromTileRef, onClick: () => setView("from") }),
|
|
11507
12752
|
/* @__PURE__ */ jsxRuntime.jsx(FlipButton, { small: true, onClick: flip, disabled: !flippable }),
|
|
11508
|
-
mode === "offramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatTile, { label: "To", currency: fiatCurrency, onCurrency: setFiatCurrency }) : /* @__PURE__ */ jsxRuntime.jsx(TokenTile, { label: "To", pick: to, chainName: nameOf(to?.chainId), token:
|
|
12753
|
+
mode === "offramp" ? /* @__PURE__ */ jsxRuntime.jsx(FiatTile, { label: "To", currency: fiatCurrency, onCurrency: setFiatCurrency }) : /* @__PURE__ */ jsxRuntime.jsx(TokenTile, { label: "To", pick: to, chainName: nameOf(to?.chainId), token: toToken2, disabled: submitting, btnRef: toTileRef, onClick: () => setView("to") })
|
|
11509
12754
|
] }),
|
|
11510
12755
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-pane", "data-kind": "send", children: [
|
|
11511
12756
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-pane-top", children: [
|
|
@@ -11599,7 +12844,7 @@ function ExchangeCard(props) {
|
|
|
11599
12844
|
side = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-side-body", children: [
|
|
11600
12845
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv", children: [
|
|
11601
12846
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv-line", children: [
|
|
11602
|
-
/* @__PURE__ */ jsxRuntime.jsx(TokenGlyph, { symbol: to?.symbol ?? "", logoUrl:
|
|
12847
|
+
/* @__PURE__ */ jsxRuntime.jsx(TokenGlyph, { symbol: to?.symbol ?? "", logoUrl: toToken2?.logoUrl, chainId: to?.chainId, size: "xs" }),
|
|
11603
12848
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-recv-amt", ref: receiveSideRef, children: /* @__PURE__ */ jsxRuntime.jsx(AmountText, { value: formatCalculatedAmount(receive, toDecimals), exact: receive, suffix: toTicker }) })
|
|
11604
12849
|
] }),
|
|
11605
12850
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv-sub", children: [
|