@glacislabs/stablegenie-zerodelta 4.18.2 → 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-OIJN6SHV.js → chunk-NLXQVXZ5.js} +1511 -180
- package/dist/{chunk-LMK5C6VA.js → chunk-NS444RZM.js} +118 -81
- package/dist/core/index.cjs +1545 -179
- 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 +1584 -349
- 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 +1584 -349
- 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
|
@@ -581,6 +581,58 @@ 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);
|
|
@@ -679,7 +732,15 @@ var STEP_LABEL = {
|
|
|
679
732
|
arrived: "Arrived",
|
|
680
733
|
filled: "Filled",
|
|
681
734
|
outbound_bridging: "Bridging",
|
|
682
|
-
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"
|
|
683
744
|
};
|
|
684
745
|
var label = (name) => STEP_LABEL[name] ?? name.replace(/_/g, " ");
|
|
685
746
|
function deliveryHeadline(delivery, sourceConfirmed, direct2 = false) {
|
|
@@ -688,12 +749,14 @@ function deliveryHeadline(delivery, sourceConfirmed, direct2 = false) {
|
|
|
688
749
|
case "delivered":
|
|
689
750
|
return "Delivered";
|
|
690
751
|
case "failed":
|
|
752
|
+
if (delivery.status === "cancelled" && delivery.refunded) return "Cancelled \u2014 refunded to the owner";
|
|
691
753
|
return delivery.status === "cancelled" ? "Cancelled \u2014 not delivered" : `Not delivered (${delivery.status.replace(/_/g, " ")}) \u2014 open the transaction for details`;
|
|
692
754
|
case "attention":
|
|
693
755
|
return delivery.status === "cancel_pending" ? "Being cancelled \u2014 not delivered" : "Waiting to be claimed \u2014 open the transaction";
|
|
694
756
|
case "in-progress": {
|
|
695
757
|
if (delivery.status === "continuing") return "On its way \u2014 final leg next";
|
|
696
758
|
const next = delivery.steps.find((s) => !s.done);
|
|
759
|
+
if (next?.name === "route") return "On its way";
|
|
697
760
|
return next ? `On its way \u2014 ${label(next.name).toLowerCase()} next` : "On its way";
|
|
698
761
|
}
|
|
699
762
|
case "unavailable":
|
|
@@ -918,7 +981,7 @@ var CHAIN_DISPLAY_NAMES = Object.freeze({
|
|
|
918
981
|
8453: "Base",
|
|
919
982
|
9745: "Plasma",
|
|
920
983
|
34443: "Mode",
|
|
921
|
-
42161: "Arbitrum
|
|
984
|
+
42161: "Arbitrum",
|
|
922
985
|
// "Avalanche", as the dApp prints it since zd-dapp#582 (from ZD Heavy's /chains). The widget's
|
|
923
986
|
// registry read lists no row for a payout-only chain, so this table is what names it here.
|
|
924
987
|
43114: "Avalanche",
|
|
@@ -994,8 +1057,8 @@ var SOLANA_DESTINATION_ASSETS = Object.freeze({
|
|
|
994
1057
|
AymATz4TCL9sWNEEV9Kvyz45CHVhDZ6kUgjTJPzLpU9P: pin("XAUT", 6, "layerzero", TOKEN_PROGRAM)
|
|
995
1058
|
});
|
|
996
1059
|
function solanaDestinationAsset(mint) {
|
|
997
|
-
const
|
|
998
|
-
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;
|
|
999
1062
|
}
|
|
1000
1063
|
function solanaBridgeOf(token) {
|
|
1001
1064
|
const pinned = solanaDestinationAsset(token.address);
|
|
@@ -1369,9 +1432,9 @@ function hexBytes(hex) {
|
|
|
1369
1432
|
if (h2.length % 2 || !/^[a-fA-F0-9]*$/.test(h2)) throw new Error("Invalid hex bytes.");
|
|
1370
1433
|
return Uint8Array.from(h2.match(/../g) || [], (v) => Number.parseInt(v, 16));
|
|
1371
1434
|
}
|
|
1372
|
-
function solanaKeyBytes(
|
|
1373
|
-
if (!isSolanaAddress(
|
|
1374
|
-
return base58Decode(
|
|
1435
|
+
function solanaKeyBytes(key2) {
|
|
1436
|
+
if (!isSolanaAddress(key2) || key2 !== key2.trim()) throw new Error("Invalid Solana public key.");
|
|
1437
|
+
return base58Decode(key2);
|
|
1375
1438
|
}
|
|
1376
1439
|
var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
1377
1440
|
function base64Decode(text) {
|
|
@@ -1717,16 +1780,16 @@ function tokenTicker(token) {
|
|
|
1717
1780
|
}
|
|
1718
1781
|
function tickerOn(tokens, chainId, symbol) {
|
|
1719
1782
|
if (!symbol || !chainId || !tokens?.length) return symbol;
|
|
1720
|
-
const
|
|
1721
|
-
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);
|
|
1722
1785
|
return deployment ? tokenTicker(deployment) : symbol;
|
|
1723
1786
|
}
|
|
1724
1787
|
|
|
1725
1788
|
// src/core/availability.ts
|
|
1726
1789
|
function assetClassOf(symbol) {
|
|
1727
|
-
const
|
|
1728
|
-
if (TRADEABLE_RWA_ASSETS.has(
|
|
1729
|
-
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";
|
|
1730
1793
|
return null;
|
|
1731
1794
|
}
|
|
1732
1795
|
var NEST_VAULT_SHARES = /* @__PURE__ */ new Set(["NALPHA", "NTBILL", "NBASIS", "NCREDIT", "NOPAL", "NWISDOM", "NACRDX", "NLCRD", "NAXI", "NCLOA", "NFALCON"]);
|
|
@@ -1835,8 +1898,8 @@ function buildCatalogue(input) {
|
|
|
1835
1898
|
if (product === "rwa") return true;
|
|
1836
1899
|
if (execution.has(chainId) || token.isChainedDestination === true) return true;
|
|
1837
1900
|
if (!isExecutableBridge(token)) return false;
|
|
1838
|
-
const
|
|
1839
|
-
return source2.has(
|
|
1901
|
+
const key2 = tokenKey(token.chainId, token.address);
|
|
1902
|
+
return source2.has(key2) || destination.has(key2);
|
|
1840
1903
|
});
|
|
1841
1904
|
const ready = chains.length > 0 && routes.length > 0 && projectedCatalogue.length > 0;
|
|
1842
1905
|
const catalogue = ready ? projectedCatalogue : allowed;
|
|
@@ -1880,8 +1943,8 @@ function tokenEnabled(token) {
|
|
|
1880
1943
|
return token?.isEnabled !== false && isChainAddress(token?.chainId, token?.address) && Number.isFinite(Number(token?.chainId));
|
|
1881
1944
|
}
|
|
1882
1945
|
function findToken(tokens, chainId, symbol) {
|
|
1883
|
-
const
|
|
1884
|
-
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;
|
|
1885
1948
|
}
|
|
1886
1949
|
function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains, walletChainId, catalogue }) {
|
|
1887
1950
|
const invoiceKey = symbolKey(invoiceAsset);
|
|
@@ -1915,10 +1978,10 @@ function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains,
|
|
|
1915
1978
|
const chainId = Number(token.chainId);
|
|
1916
1979
|
const chain2 = chainById(chains, chainId);
|
|
1917
1980
|
if (!chainSelectable(chain2, chainId)) continue;
|
|
1918
|
-
const
|
|
1919
|
-
if (seen.has(
|
|
1981
|
+
const key2 = tokenKey(chainId, token.address);
|
|
1982
|
+
if (seen.has(key2)) continue;
|
|
1920
1983
|
if (refusal(token)) continue;
|
|
1921
|
-
seen.add(
|
|
1984
|
+
seen.add(key2);
|
|
1922
1985
|
const payKey = symbolKey(token.symbol);
|
|
1923
1986
|
const direct2 = chainId === invoiceChain && payKey === invoiceKey;
|
|
1924
1987
|
options.push({
|
|
@@ -2104,7 +2167,7 @@ function normalizePreview(request, quote, to, amount) {
|
|
|
2104
2167
|
async function quoteSolanaSource(api, input) {
|
|
2105
2168
|
const { from, to, amount } = selections(input, await api.fetchTokens());
|
|
2106
2169
|
const request = makeRequest(input, from, to, amount);
|
|
2107
|
-
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 });
|
|
2108
2171
|
const preview = normalizePreview(request, quote, to, input.amountIn);
|
|
2109
2172
|
quoteRequests.set(preview, { api, request: clone(request) });
|
|
2110
2173
|
return preview;
|
|
@@ -2118,7 +2181,7 @@ async function previewSolanaSource(api, input) {
|
|
|
2118
2181
|
raw(amount, "input amount", true);
|
|
2119
2182
|
const body = { inputChain: SOLANA_CHAIN_ID, outputChain: input.toChainId, inputToken: from.symbol, outputToken: to.symbol, inputAmount: amount };
|
|
2120
2183
|
const request = body;
|
|
2121
|
-
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 });
|
|
2122
2185
|
const option = quote?.options?.[0];
|
|
2123
2186
|
if (!option) throw new Error("Native quote returned no options.");
|
|
2124
2187
|
const receive = raw(option.finalAmount, "quoted output", true);
|
|
@@ -2475,8 +2538,8 @@ function historyKey(value) {
|
|
|
2475
2538
|
var str = (v) => typeof v === "string" ? v : typeof v === "number" ? String(v) : "";
|
|
2476
2539
|
function tokenAt(tokens, chainId, address) {
|
|
2477
2540
|
if (!address) return void 0;
|
|
2478
|
-
const
|
|
2479
|
-
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);
|
|
2480
2543
|
}
|
|
2481
2544
|
function amountOf(raw2, token, rowDecimals, rowAmount) {
|
|
2482
2545
|
const decimals = token ? Number(token.decimals) : Number(rowDecimals);
|
|
@@ -2562,13 +2625,13 @@ function mergeHistory(local, remote, limit = WALLET_HISTORY_LIMIT) {
|
|
|
2562
2625
|
const out = [];
|
|
2563
2626
|
const seen = /* @__PURE__ */ new Set();
|
|
2564
2627
|
for (const entry of local) {
|
|
2565
|
-
const
|
|
2566
|
-
if (seen.has(
|
|
2567
|
-
seen.add(
|
|
2568
|
-
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);
|
|
2569
2632
|
out.push(known ? { ...entry, delivery: known.delivery, legs: entry.legs ?? known.legs } : entry);
|
|
2570
2633
|
}
|
|
2571
|
-
for (const [
|
|
2634
|
+
for (const [key2, entry] of byHash) if (!seen.has(key2)) out.push(entry);
|
|
2572
2635
|
return out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, limit);
|
|
2573
2636
|
}
|
|
2574
2637
|
|
|
@@ -2679,12 +2742,12 @@ function suppressedLanes(health) {
|
|
|
2679
2742
|
const out = /* @__PURE__ */ new Map();
|
|
2680
2743
|
for (const lane of health.lanes) {
|
|
2681
2744
|
if (!lane || typeof lane !== "object" || !isSuppressed(lane)) continue;
|
|
2682
|
-
const
|
|
2683
|
-
if (!
|
|
2745
|
+
const key2 = healthLaneKey(lane.laneKey);
|
|
2746
|
+
if (!key2) continue;
|
|
2684
2747
|
const availability = laneAvailabilityState(lane) ? lane.availability : void 0;
|
|
2685
2748
|
const code = typeof availability?.code === "string" && availability.code ? availability.code : lane.code;
|
|
2686
2749
|
const message = typeof availability?.message === "string" && availability.message ? availability.message : lane.message;
|
|
2687
|
-
out.set(
|
|
2750
|
+
out.set(key2, {
|
|
2688
2751
|
route: typeof lane.route === "string" ? lane.route : "",
|
|
2689
2752
|
code: typeof code === "string" ? code : "",
|
|
2690
2753
|
message: typeof message === "string" ? message : "",
|
|
@@ -2699,15 +2762,15 @@ function limitedLanes(health) {
|
|
|
2699
2762
|
const out = /* @__PURE__ */ new Map();
|
|
2700
2763
|
for (const lane of health.lanes) {
|
|
2701
2764
|
if (!lane || typeof lane !== "object" || laneAvailabilityState(lane) !== "limited") continue;
|
|
2702
|
-
const
|
|
2765
|
+
const key2 = healthLaneKey(lane.laneKey);
|
|
2703
2766
|
const limit = lane.availability?.limit;
|
|
2704
|
-
if (!
|
|
2767
|
+
if (!key2 || !limit || typeof limit !== "object") continue;
|
|
2705
2768
|
const side = limit.side === "bid" || limit.side === "ask" ? limit.side : null;
|
|
2706
2769
|
const maxAmount = typeof limit.maxAmount === "string" ? limit.maxAmount.trim() : "";
|
|
2707
2770
|
const decimals = limit.decimals;
|
|
2708
2771
|
if (!side || !BASE_UNITS.test(maxAmount) || typeof decimals !== "number" || !Number.isInteger(decimals) || decimals < 0 || decimals > 36) continue;
|
|
2709
2772
|
const code = lane.availability?.code;
|
|
2710
|
-
out.set(
|
|
2773
|
+
out.set(key2, {
|
|
2711
2774
|
side,
|
|
2712
2775
|
token: typeof limit.token === "string" ? limit.token : "",
|
|
2713
2776
|
fromChainId: Number(limit.fromChainId) || 0,
|
|
@@ -2770,10 +2833,10 @@ function resolveVaultIcon(apiBase, iconPath) {
|
|
|
2770
2833
|
function vaultIconsBySymbol(apiBase, vaults) {
|
|
2771
2834
|
const out = /* @__PURE__ */ new Map();
|
|
2772
2835
|
for (const vault of vaults) {
|
|
2773
|
-
const
|
|
2774
|
-
if (!
|
|
2836
|
+
const key2 = symbolKey(vault?.symbol);
|
|
2837
|
+
if (!key2 || out.has(key2)) continue;
|
|
2775
2838
|
const url = resolveVaultIcon(apiBase, vault?.iconMiniUrl) ?? resolveVaultIcon(apiBase, vault?.iconUrl);
|
|
2776
|
-
if (url) out.set(
|
|
2839
|
+
if (url) out.set(key2, url);
|
|
2777
2840
|
}
|
|
2778
2841
|
return out;
|
|
2779
2842
|
}
|
|
@@ -2870,7 +2933,7 @@ var CATEGORY_PHRASES = {
|
|
|
2870
2933
|
UNKNOWN: "an unrecognized risk"
|
|
2871
2934
|
};
|
|
2872
2935
|
function categoryLabel(code) {
|
|
2873
|
-
const
|
|
2936
|
+
const key2 = code.trim().toUpperCase();
|
|
2874
2937
|
const LABELS = {
|
|
2875
2938
|
SANCTIONS: "Sanctions",
|
|
2876
2939
|
TERRORISM_FINANCING: "Terrorist financing",
|
|
@@ -2885,7 +2948,7 @@ function categoryLabel(code) {
|
|
|
2885
2948
|
UNCLASSIFIED: "Unclassified risk",
|
|
2886
2949
|
UNKNOWN: "Unclassified risk"
|
|
2887
2950
|
};
|
|
2888
|
-
return LABELS[
|
|
2951
|
+
return LABELS[key2] ?? key2.toLowerCase().replace(/_/g, " ");
|
|
2889
2952
|
}
|
|
2890
2953
|
function cleanJurisdiction(code) {
|
|
2891
2954
|
return code.replace(/^(OFAC|TIER\d+|SANCTIONED)_/i, "").trim();
|
|
@@ -2998,9 +3061,9 @@ function distinctScreenedWallets(compliance) {
|
|
|
2998
3061
|
for (const raw2 of compliance?.screenedWallets ?? []) {
|
|
2999
3062
|
const address = raw2?.trim();
|
|
3000
3063
|
if (!address) continue;
|
|
3001
|
-
const
|
|
3002
|
-
if (seen.has(
|
|
3003
|
-
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);
|
|
3004
3067
|
wallets.push(address);
|
|
3005
3068
|
}
|
|
3006
3069
|
return wallets;
|
|
@@ -3127,9 +3190,9 @@ var TUNED_OUTCOMES = {
|
|
|
3127
3190
|
UNCLASSIFIED: "flagged"
|
|
3128
3191
|
};
|
|
3129
3192
|
function screeningOutcomeOf(category) {
|
|
3130
|
-
const
|
|
3131
|
-
if (FLOOR_CATEGORIES.includes(
|
|
3132
|
-
return TUNED_OUTCOMES[
|
|
3193
|
+
const key2 = category.trim().toUpperCase();
|
|
3194
|
+
if (FLOOR_CATEGORIES.includes(key2)) return "always-blocked";
|
|
3195
|
+
return TUNED_OUTCOMES[key2] ?? null;
|
|
3133
3196
|
}
|
|
3134
3197
|
var labelsFor = (outcome) => [...FLOOR_CATEGORIES, ...TUNABLE_CATEGORIES].filter((c) => screeningOutcomeOf(c) === outcome).map(categoryLabel);
|
|
3135
3198
|
var SCREENING_BUCKETS = [
|
|
@@ -3138,6 +3201,91 @@ var SCREENING_BUCKETS = [
|
|
|
3138
3201
|
{ outcome: "flagged", title: "Flagged", detail: "A warning is shown.", categories: labelsFor("flagged") }
|
|
3139
3202
|
];
|
|
3140
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
|
+
|
|
3141
3289
|
// src/core/solve.ts
|
|
3142
3290
|
async function solveExactOut({ option, destination, destinationToken, payer, fetchQuote }) {
|
|
3143
3291
|
const destDecimals = assetDecimals(destinationToken);
|
|
@@ -3184,7 +3332,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
3184
3332
|
let bestGuess = guess;
|
|
3185
3333
|
for (let i = 0; i < 3; i += 1) {
|
|
3186
3334
|
const guessSent = guess;
|
|
3187
|
-
const quote = await fetchQuote({
|
|
3335
|
+
const quote = selectQuoteOption(await fetchQuote({
|
|
3188
3336
|
fromChainId: option.chainId,
|
|
3189
3337
|
toChainId: Number(destination.chainId),
|
|
3190
3338
|
fromToken: option.symbol,
|
|
@@ -3192,11 +3340,11 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
3192
3340
|
fromAmount: guessSent.toString(),
|
|
3193
3341
|
owner: payer,
|
|
3194
3342
|
destinationReceiver: destination.address
|
|
3195
|
-
});
|
|
3343
|
+
}));
|
|
3196
3344
|
if (BigInt(quote?.fromAmount || "0") !== guessSent) {
|
|
3197
3345
|
throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
3198
3346
|
}
|
|
3199
|
-
const guaranteed = isSolanaChainId(destination.chainId)
|
|
3347
|
+
const guaranteed = deliveredAmount(quote, isSolanaChainId(destination.chainId));
|
|
3200
3348
|
const final = finalOf(quote);
|
|
3201
3349
|
if (final > bestFinal) {
|
|
3202
3350
|
bestFinal = final;
|
|
@@ -3233,7 +3381,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
3233
3381
|
directTransfer: false,
|
|
3234
3382
|
quote: best,
|
|
3235
3383
|
youPayRaw: bestGuess.toString(),
|
|
3236
|
-
recipientReceivesRaw: (isSolanaChainId(destination.chainId)
|
|
3384
|
+
recipientReceivesRaw: deliveredAmount(best, isSolanaChainId(destination.chainId)).toString(),
|
|
3237
3385
|
targetRaw: targetRaw.toString(),
|
|
3238
3386
|
overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
|
|
3239
3387
|
meetsTarget: bestFinal >= targetRaw,
|
|
@@ -3243,7 +3391,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
3243
3391
|
async function solveExactIn({ option, destination, destinationToken, payer, fetchQuote, amountInRaw }) {
|
|
3244
3392
|
const fromRaw = BigInt(amountInRaw || "0");
|
|
3245
3393
|
if (fromRaw <= 0n) throw new Error("Swap amount must be greater than zero.");
|
|
3246
|
-
const quote = await fetchQuote({
|
|
3394
|
+
const quote = selectQuoteOption(await fetchQuote({
|
|
3247
3395
|
fromChainId: option.chainId,
|
|
3248
3396
|
toChainId: Number(destination.chainId),
|
|
3249
3397
|
fromToken: option.symbol,
|
|
@@ -3251,11 +3399,11 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
|
|
|
3251
3399
|
fromAmount: fromRaw.toString(),
|
|
3252
3400
|
owner: payer,
|
|
3253
3401
|
destinationReceiver: destination.address
|
|
3254
|
-
});
|
|
3402
|
+
}));
|
|
3255
3403
|
if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
|
|
3256
3404
|
throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
3257
3405
|
}
|
|
3258
|
-
const guaranteed = isSolanaChainId(destination.chainId)
|
|
3406
|
+
const guaranteed = deliveredAmount(quote, isSolanaChainId(destination.chainId));
|
|
3259
3407
|
if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
|
|
3260
3408
|
return {
|
|
3261
3409
|
directTransfer: false,
|
|
@@ -3268,6 +3416,24 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
|
|
|
3268
3416
|
iterations: 1
|
|
3269
3417
|
};
|
|
3270
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
|
+
}
|
|
3271
3437
|
|
|
3272
3438
|
// src/core/order.ts
|
|
3273
3439
|
var DEFAULT_DEADLINE_SECONDS = 1800;
|
|
@@ -3387,6 +3553,954 @@ function assertQuoteMatchesSelection({ quote, order, orders, option, destination
|
|
|
3387
3553
|
}
|
|
3388
3554
|
}
|
|
3389
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
|
+
|
|
3390
4504
|
// src/core/route.ts
|
|
3391
4505
|
function routeDeltaLabel(result, quote) {
|
|
3392
4506
|
if (result.directTransfer) return "~0";
|
|
@@ -3407,9 +4521,9 @@ function routeLabelFor(option, destinationToken, result) {
|
|
|
3407
4521
|
const bridge = result.quote.bridge ? ` via ${result.quote.bridge}` : "";
|
|
3408
4522
|
return `Swap ${optionTicker(option)} to ${tokenTicker(destinationToken)} and settle on ZeroDelta${bridge}.`;
|
|
3409
4523
|
}
|
|
3410
|
-
function
|
|
3411
|
-
const
|
|
3412
|
-
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;
|
|
3413
4527
|
if (!wanted || !tokens?.length) return void 0;
|
|
3414
4528
|
return tokens.find((t) => Number(t.chainId) === Number(chainId) && chainAddressKey(chainId, t.address) === wanted);
|
|
3415
4529
|
}
|
|
@@ -3431,7 +4545,7 @@ function buildLegs(orders, ctx) {
|
|
|
3431
4545
|
const order = orders[index];
|
|
3432
4546
|
const isLast = index === orders.length - 1;
|
|
3433
4547
|
const toChainId = Number(order.destinationChainId);
|
|
3434
|
-
const askToken = isLast ? ctx.destinationToken :
|
|
4548
|
+
const askToken = isLast ? ctx.destinationToken : tokenAt3(ctx.tokens, toChainId, order.askToken);
|
|
3435
4549
|
const toAsset = isLast ? ctx.destinationToken.symbol : askToken?.symbol ?? "";
|
|
3436
4550
|
const toTicker = askToken ? tokenTicker(askToken) : "";
|
|
3437
4551
|
const toDecimals = askToken ? assetDecimals(askToken) : void 0;
|
|
@@ -3458,19 +4572,42 @@ function buildLegs(orders, ctx) {
|
|
|
3458
4572
|
}
|
|
3459
4573
|
return legs;
|
|
3460
4574
|
}
|
|
3461
|
-
async function buildRoute({
|
|
3462
|
-
option,
|
|
3463
|
-
|
|
3464
|
-
destinationToken,
|
|
3465
|
-
chains,
|
|
3466
|
-
tokens,
|
|
3467
|
-
payer,
|
|
3468
|
-
fetchQuote,
|
|
3469
|
-
solve = solveExactOut,
|
|
3470
|
-
amountInRaw,
|
|
3471
|
-
compliance
|
|
3472
|
-
}) {
|
|
4575
|
+
async function buildRoute(args) {
|
|
4576
|
+
const { option, destination, destinationToken, payer, fetchQuote, amountInRaw } = args;
|
|
4577
|
+
const solve = args.solve ?? solveExactOut;
|
|
3473
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) {
|
|
3474
4611
|
const quote = result.quote;
|
|
3475
4612
|
const destDecimals = assetDecimals(destinationToken);
|
|
3476
4613
|
const receiveAmount = formatUnits(result.recipientReceivesRaw, destDecimals);
|
|
@@ -3545,6 +4682,9 @@ async function buildRoute({
|
|
|
3545
4682
|
}
|
|
3546
4683
|
};
|
|
3547
4684
|
}
|
|
4685
|
+
if (quote.protocol === "zdheavy") {
|
|
4686
|
+
return buildZdHeavyRoute({ option, destination, destinationToken, chains, tokens: tokens ?? [], routes: routes ?? [], payer, result });
|
|
4687
|
+
}
|
|
3548
4688
|
const requestList = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
|
|
3549
4689
|
if (!requestList.length) throw new Error("ZeroDelta quote did not include an order request.");
|
|
3550
4690
|
const sourceChain = chainById(chains, option.chainId);
|
|
@@ -3646,12 +4786,134 @@ async function buildRoute({
|
|
|
3646
4786
|
};
|
|
3647
4787
|
}
|
|
3648
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
|
+
|
|
3649
4911
|
// src/core/channel.ts
|
|
3650
4912
|
var CHANNEL_HEADER = "x-zd-channel";
|
|
3651
4913
|
var CHANNEL_VERSION_HEADER = "x-zd-channel-version";
|
|
3652
4914
|
var CHANNEL_ORIGIN_HEADER = "x-zd-channel-origin";
|
|
3653
4915
|
var WIDGET_CHANNEL = "widget";
|
|
3654
|
-
var WIDGET_VERSION = "4.
|
|
4916
|
+
var WIDGET_VERSION = "4.19.0" ;
|
|
3655
4917
|
var MAX_CHANNEL_VERSION_LEN = 32;
|
|
3656
4918
|
function sanitizeVersion(raw2) {
|
|
3657
4919
|
const v = String(raw2).trim();
|
|
@@ -3743,7 +5005,7 @@ function classifyQuoteError(error) {
|
|
|
3743
5005
|
function amountFieldError(error) {
|
|
3744
5006
|
const fieldErrors = error?.fieldErrors;
|
|
3745
5007
|
if (!Array.isArray(fieldErrors)) return null;
|
|
3746
|
-
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");
|
|
3747
5009
|
const message = entry ? sanitizeMessage(entry.message, "") : "";
|
|
3748
5010
|
return message || null;
|
|
3749
5011
|
}
|
|
@@ -3759,7 +5021,7 @@ function wait(ms) {
|
|
|
3759
5021
|
}
|
|
3760
5022
|
var PAGE_LIMIT = 500;
|
|
3761
5023
|
var MAX_PAGES = 10;
|
|
3762
|
-
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() });
|
|
3763
5025
|
var SHARED_REGISTRY = /* @__PURE__ */ new WeakMap();
|
|
3764
5026
|
function registryCacheFor(scope) {
|
|
3765
5027
|
if (!scope) return newRegistryCache();
|
|
@@ -3916,6 +5178,20 @@ function createApiClient(cfg) {
|
|
|
3916
5178
|
return value;
|
|
3917
5179
|
});
|
|
3918
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
|
+
}
|
|
3919
5195
|
const priceCache = /* @__PURE__ */ new Map();
|
|
3920
5196
|
async function fetchPrices(symbols) {
|
|
3921
5197
|
const wanted = [...new Set(symbols.map((s) => String(s || "").toUpperCase()).filter((s) => /^[A-Z0-9]{1,16}$/.test(s)))];
|
|
@@ -3946,11 +5222,12 @@ function createApiClient(cfg) {
|
|
|
3946
5222
|
return out;
|
|
3947
5223
|
}
|
|
3948
5224
|
async function fetchQuote(body, retries = 1) {
|
|
5225
|
+
const request = nativeQuoteRequest(body);
|
|
3949
5226
|
let lastError;
|
|
3950
5227
|
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
|
3951
5228
|
try {
|
|
3952
|
-
const quote = await apiRequest("/quote", { method: "POST", body: JSON.stringify(
|
|
3953
|
-
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);
|
|
3954
5231
|
} catch (error) {
|
|
3955
5232
|
lastError = error;
|
|
3956
5233
|
if (attempt >= retries || !isTransientQuoteError(error)) throw error;
|
|
@@ -3964,10 +5241,10 @@ function createApiClient(cfg) {
|
|
|
3964
5241
|
if (!addr) throw apiError("An address is required to screen a wallet.", { code: "bad_request" });
|
|
3965
5242
|
const solana = isSolanaChainId(chainId) || isSolanaAddress(addr);
|
|
3966
5243
|
if (solana && !isSolanaAddress(addr)) throw apiError("Not a valid Solana address.", { code: "bad_request" });
|
|
3967
|
-
const
|
|
3968
|
-
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);
|
|
3969
5246
|
if (hit && Date.now() - hit.at < SCREEN_CACHE_TTL_MS) return hit.value;
|
|
3970
|
-
const inflight = screenInflight.get(
|
|
5247
|
+
const inflight = screenInflight.get(key2);
|
|
3971
5248
|
if (inflight) return inflight;
|
|
3972
5249
|
const request = apiRequest("/screen/wallet", {
|
|
3973
5250
|
method: "POST",
|
|
@@ -3978,12 +5255,12 @@ function createApiClient(cfg) {
|
|
|
3978
5255
|
throw apiError("Compliance screening returned an unusable result.", { code: "bad_response" });
|
|
3979
5256
|
}
|
|
3980
5257
|
const value = { ...screen, address: screen.address || addr };
|
|
3981
|
-
screenCache.set(
|
|
5258
|
+
screenCache.set(key2, { at: Date.now(), value });
|
|
3982
5259
|
return value;
|
|
3983
5260
|
}).finally(() => {
|
|
3984
|
-
screenInflight.delete(
|
|
5261
|
+
screenInflight.delete(key2);
|
|
3985
5262
|
});
|
|
3986
|
-
screenInflight.set(
|
|
5263
|
+
screenInflight.set(key2, request);
|
|
3987
5264
|
return request;
|
|
3988
5265
|
}
|
|
3989
5266
|
async function reportSubmission(report) {
|
|
@@ -4006,7 +5283,7 @@ function createApiClient(cfg) {
|
|
|
4006
5283
|
return false;
|
|
4007
5284
|
}
|
|
4008
5285
|
}
|
|
4009
|
-
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 };
|
|
4010
5287
|
}
|
|
4011
5288
|
|
|
4012
5289
|
// src/core/plan.ts
|
|
@@ -4069,9 +5346,9 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
|
|
|
4069
5346
|
const balanceTargets = [];
|
|
4070
5347
|
const seenTargets = /* @__PURE__ */ new Set();
|
|
4071
5348
|
for (const option of options) {
|
|
4072
|
-
const
|
|
4073
|
-
if (seenTargets.has(
|
|
4074
|
-
seenTargets.add(
|
|
5349
|
+
const key2 = optionBalanceKey(option);
|
|
5350
|
+
if (seenTargets.has(key2)) continue;
|
|
5351
|
+
seenTargets.add(key2);
|
|
4075
5352
|
balanceTargets.push({ chainId: option.chainId, tokenAddress: option.address, decimals: option.decimals });
|
|
4076
5353
|
}
|
|
4077
5354
|
const walletBalances = readBalances ? await readBalances(payer, balanceTargets).catch(() => ({})) : {};
|
|
@@ -4083,9 +5360,9 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
|
|
|
4083
5360
|
for (const raw2 of [payer, destination.address]) {
|
|
4084
5361
|
const addr = String(raw2 || "").trim();
|
|
4085
5362
|
if (!addr) continue;
|
|
4086
|
-
const
|
|
4087
|
-
if (seenParty.has(
|
|
4088
|
-
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);
|
|
4089
5366
|
parties.push(addr);
|
|
4090
5367
|
}
|
|
4091
5368
|
try {
|
|
@@ -4132,6 +5409,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances)
|
|
|
4132
5409
|
destinationToken,
|
|
4133
5410
|
chains,
|
|
4134
5411
|
tokens,
|
|
5412
|
+
routes,
|
|
4135
5413
|
payer,
|
|
4136
5414
|
fetchQuote: api.fetchQuote,
|
|
4137
5415
|
compliance: option.direct ? directCompliance ?? void 0 : void 0
|
|
@@ -4192,7 +5470,7 @@ async function quotePayOption(api, request, payer, picked, wallet = {}) {
|
|
|
4192
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))
|
|
4193
5471
|
);
|
|
4194
5472
|
if (!option) throw new Error("That funding option is not available for this payment right now.");
|
|
4195
|
-
return buildRoute({ option, destination, destinationToken, chains, tokens, payer, fetchQuote: api.fetchQuote });
|
|
5473
|
+
return buildRoute({ option, destination, destinationToken, chains, tokens, routes, payer, fetchQuote: api.fetchQuote });
|
|
4196
5474
|
}
|
|
4197
5475
|
|
|
4198
5476
|
// src/core/swap.ts
|
|
@@ -4200,13 +5478,13 @@ function validateSwap(swap = {}) {
|
|
|
4200
5478
|
const fromChainId = Number(swap.fromChainId);
|
|
4201
5479
|
const toChainId = Number(swap.toChainId);
|
|
4202
5480
|
const fromToken = symbolKey(swap.fromToken);
|
|
4203
|
-
const
|
|
5481
|
+
const toToken2 = symbolKey(swap.toToken);
|
|
4204
5482
|
if (!SUPPORTED_CHAIN_IDS.has(fromChainId)) throw new Error("Unsupported swap chain.");
|
|
4205
5483
|
if (!Number.isSafeInteger(toChainId) || toChainId <= 0) throw new Error("Unsupported swap chain.");
|
|
4206
|
-
if (!SUPPORTED_ASSETS.has(fromToken) || !SUPPORTED_ASSETS.has(
|
|
5484
|
+
if (!SUPPORTED_ASSETS.has(fromToken) || !SUPPORTED_ASSETS.has(toToken2)) throw new Error("Unsupported swap asset.");
|
|
4207
5485
|
const amountIn = normalizeDecimalText(swap.amountIn);
|
|
4208
5486
|
if (!/^\d+(\.\d+)?$/.test(amountIn) || Number(amountIn) <= 0 || Number(amountIn) > 1e9) throw new Error("Enter a valid swap amount.");
|
|
4209
|
-
return { fromChainId, toChainId, fromToken, toToken, amountIn };
|
|
5487
|
+
return { fromChainId, toChainId, fromToken, toToken: toToken2, amountIn };
|
|
4210
5488
|
}
|
|
4211
5489
|
function viaOf(quote, tokens) {
|
|
4212
5490
|
const orders = Array.isArray(quote.orderRequests) ? quote.orderRequests : [];
|
|
@@ -4256,7 +5534,7 @@ async function quoteSwapPreview(api, swap, owner) {
|
|
|
4256
5534
|
async function buildSwapPlan(api, swap, payer, wallet = {}) {
|
|
4257
5535
|
const v = validateSwap(swap);
|
|
4258
5536
|
const account = assertAddress(payer, "Swap wallet");
|
|
4259
|
-
const [chains, tokens] = await Promise.all([api.fetchChains(), api.fetchTokens()]);
|
|
5537
|
+
const [chains, tokens, routes] = await Promise.all([api.fetchChains(), api.fetchTokens(), api.fetchRoutes()]);
|
|
4260
5538
|
const sourceToken = findToken(tokens, v.fromChainId, v.fromToken);
|
|
4261
5539
|
const destToken = findToken(tokens, v.toChainId, v.toToken);
|
|
4262
5540
|
if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
|
|
@@ -4279,7 +5557,7 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
|
|
|
4279
5557
|
direct: false
|
|
4280
5558
|
};
|
|
4281
5559
|
const destination = { address: receiver, chainId: v.toChainId, asset: destToken.symbol };
|
|
4282
|
-
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 });
|
|
4283
5561
|
if (route.state === "SHORT") throw new Error("ZeroDelta could not price this swap right now.");
|
|
4284
5562
|
route.recommended = true;
|
|
4285
5563
|
return {
|
|
@@ -4300,88 +5578,6 @@ async function buildSwapPlan(api, swap, payer, wallet = {}) {
|
|
|
4300
5578
|
};
|
|
4301
5579
|
}
|
|
4302
5580
|
|
|
4303
|
-
// src/core/validate-tx.ts
|
|
4304
|
-
var lower = (v) => String(v || "").toLowerCase();
|
|
4305
|
-
function isHexAddress(value) {
|
|
4306
|
-
return /^0x[a-fA-F0-9]{40}$/.test(String(value || ""));
|
|
4307
|
-
}
|
|
4308
|
-
function isHexData(value) {
|
|
4309
|
-
return /^0x(?:[a-fA-F0-9]{2})*$/.test(String(value));
|
|
4310
|
-
}
|
|
4311
|
-
function isHexQuantity(value) {
|
|
4312
|
-
return /^0x[0-9a-fA-F]+$/.test(String(value));
|
|
4313
|
-
}
|
|
4314
|
-
function dataWord(data, index) {
|
|
4315
|
-
const word2 = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
|
|
4316
|
-
return /^[a-fA-F0-9]{64}$/.test(word2) ? word2 : "";
|
|
4317
|
-
}
|
|
4318
|
-
function dataAddress(data, index) {
|
|
4319
|
-
const word2 = dataWord(data, index);
|
|
4320
|
-
return word2 ? `0x${word2.slice(24)}` : "";
|
|
4321
|
-
}
|
|
4322
|
-
function dataUint(data, index) {
|
|
4323
|
-
const word2 = dataWord(data, index);
|
|
4324
|
-
return word2 ? BigInt(`0x${word2}`) : null;
|
|
4325
|
-
}
|
|
4326
|
-
function rawEquals(value, expected) {
|
|
4327
|
-
try {
|
|
4328
|
-
return value === BigInt(expected || "0");
|
|
4329
|
-
} catch {
|
|
4330
|
-
return false;
|
|
4331
|
-
}
|
|
4332
|
-
}
|
|
4333
|
-
function planMsgValueHex(route) {
|
|
4334
|
-
try {
|
|
4335
|
-
const raw2 = route?.quote?.msgValue;
|
|
4336
|
-
if (raw2 === void 0 || raw2 === null || raw2 === "") return "0x0";
|
|
4337
|
-
return "0x" + BigInt(raw2).toString(16);
|
|
4338
|
-
} catch {
|
|
4339
|
-
return null;
|
|
4340
|
-
}
|
|
4341
|
-
}
|
|
4342
|
-
function validatePlannedTransaction(tx, route, expectedRecipient) {
|
|
4343
|
-
if (!tx || tx.mock) return true;
|
|
4344
|
-
if (!isHexAddress(tx.to) || !isHexData(tx.data || "0x") || !isHexQuantity(tx.value || "0x0")) return false;
|
|
4345
|
-
const data = String(tx.data || "0x").toLowerCase();
|
|
4346
|
-
const selector = data.slice(0, 10);
|
|
4347
|
-
const value = lower(tx.value || "0x0");
|
|
4348
|
-
if (tx.kind === "transfer") {
|
|
4349
|
-
if (value !== "0x0") return false;
|
|
4350
|
-
return selector === "0xa9059cbb" && isHexAddress(tx.token) && lower(tx.to) === lower(tx.token) && lower(dataAddress(data, 0)) === lower(expectedRecipient) && rawEquals(dataUint(data, 1), tx.amountRaw);
|
|
4351
|
-
}
|
|
4352
|
-
if (tx.kind === "approve") {
|
|
4353
|
-
if (value !== "0x0") return false;
|
|
4354
|
-
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);
|
|
4355
|
-
}
|
|
4356
|
-
if (tx.kind === "submitOrder") {
|
|
4357
|
-
const expected = planMsgValueHex(route);
|
|
4358
|
-
if (expected === null || value !== lower(expected)) return false;
|
|
4359
|
-
if (selector !== SUBMIT_ORDER_SELECTOR || !isHexAddress(tx.escrow) || lower(tx.to) !== lower(tx.escrow)) return false;
|
|
4360
|
-
const decoded = decodeSubmitOrderCalldata(data);
|
|
4361
|
-
if (!decoded) return false;
|
|
4362
|
-
const first = decoded.orders[0];
|
|
4363
|
-
const last = decoded.orders[decoded.orders.length - 1];
|
|
4364
|
-
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));
|
|
4365
|
-
}
|
|
4366
|
-
return false;
|
|
4367
|
-
}
|
|
4368
|
-
function solanaDeliveryMatches(encoded, recipient2, mint) {
|
|
4369
|
-
try {
|
|
4370
|
-
return lower(encoded) === expectedSolanaDelivery(recipient2, mint || "");
|
|
4371
|
-
} catch {
|
|
4372
|
-
return false;
|
|
4373
|
-
}
|
|
4374
|
-
}
|
|
4375
|
-
async function allowanceCovers(tx, account, ethCall2) {
|
|
4376
|
-
if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
|
|
4377
|
-
try {
|
|
4378
|
-
const raw2 = await ethCall2(tx.token, encodeAllowance(account, tx.spender));
|
|
4379
|
-
return BigInt(raw2 || "0x0") >= BigInt(tx.amountRaw || "0");
|
|
4380
|
-
} catch {
|
|
4381
|
-
return false;
|
|
4382
|
-
}
|
|
4383
|
-
}
|
|
4384
|
-
|
|
4385
5581
|
// src/core/verify.ts
|
|
4386
5582
|
var TX_VERIFY_ATTEMPTS = 5;
|
|
4387
5583
|
var TX_VERIFY_INTERVAL_MS = 2500;
|
|
@@ -4526,9 +5722,9 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
4526
5722
|
const seen = /* @__PURE__ */ new Set();
|
|
4527
5723
|
for (const target of targets) {
|
|
4528
5724
|
if (!target || !isAddress(target.tokenAddress)) continue;
|
|
4529
|
-
const
|
|
4530
|
-
if (seen.has(
|
|
4531
|
-
seen.add(
|
|
5725
|
+
const key2 = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
|
|
5726
|
+
if (seen.has(key2)) continue;
|
|
5727
|
+
seen.add(key2);
|
|
4532
5728
|
const chainId = Number(target.chainId);
|
|
4533
5729
|
const group = groups.get(chainId) || [];
|
|
4534
5730
|
group.push(target);
|
|
@@ -4537,8 +5733,8 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
4537
5733
|
function record(target, hex) {
|
|
4538
5734
|
if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
|
|
4539
5735
|
const raw2 = BigInt(hex || "0x0").toString();
|
|
4540
|
-
const
|
|
4541
|
-
out[
|
|
5736
|
+
const key2 = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
|
|
5737
|
+
out[key2] = { raw: raw2, formatted: formatUnits(raw2, Number(target.decimals)) };
|
|
4542
5738
|
return true;
|
|
4543
5739
|
}
|
|
4544
5740
|
async function readOne(rpcUrl, target) {
|
|
@@ -4584,7 +5780,18 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
4584
5780
|
return null;
|
|
4585
5781
|
}
|
|
4586
5782
|
}
|
|
4587
|
-
|
|
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 };
|
|
4588
5795
|
}
|
|
4589
5796
|
|
|
4590
5797
|
// src/core/config.ts
|
|
@@ -4705,6 +5912,7 @@ function createEngine(config = {}) {
|
|
|
4705
5912
|
fetchRouteHealth: api.fetchRouteHealth,
|
|
4706
5913
|
fetchQuote: api.fetchQuote,
|
|
4707
5914
|
fetchPrices: (symbols) => api.fetchPrices ? api.fetchPrices(symbols) : Promise.resolve({}),
|
|
5915
|
+
fetchPromotions: () => api.fetchPromotions ? api.fetchPromotions() : Promise.resolve([]),
|
|
4708
5916
|
fetchCatalogue: async (allowedAssets, product, options) => {
|
|
4709
5917
|
const [chains, registryTokens, routes, health, vaults] = await Promise.all([
|
|
4710
5918
|
api.fetchChains().catch(() => []),
|
|
@@ -5148,7 +6356,13 @@ function useFlow(args) {
|
|
|
5148
6356
|
statusRef.current = status;
|
|
5149
6357
|
const { idle: idle2, returnedAt: returnedAt2 } = useUserPresence();
|
|
5150
6358
|
const routes = plan?.routes ?? [];
|
|
5151
|
-
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]);
|
|
5152
6366
|
const reload = react.useCallback(() => setNonce((n) => n + 1), []);
|
|
5153
6367
|
const addRoute = react.useCallback((route) => {
|
|
5154
6368
|
setPlan((p) => p ? { ...p, routes: [...p.routes.filter((r) => r.id !== route.id), route] } : p);
|
|
@@ -5203,11 +6417,11 @@ function useFlow(args) {
|
|
|
5203
6417
|
if (!wallet.account || !src?.tokenAddress || src.decimals == null) return;
|
|
5204
6418
|
(async () => {
|
|
5205
6419
|
try {
|
|
5206
|
-
const
|
|
6420
|
+
const key2 = `${Number(src.chainId)}:${String(src.tokenAddress).toLowerCase()}`;
|
|
5207
6421
|
const balances = await engine.readBalances(wallet.account, [
|
|
5208
6422
|
{ chainId: Number(src.chainId), tokenAddress: src.tokenAddress, decimals: Number(src.decimals) }
|
|
5209
6423
|
]);
|
|
5210
|
-
const entry = balances[
|
|
6424
|
+
const entry = balances[key2];
|
|
5211
6425
|
if (!entry) return;
|
|
5212
6426
|
const need = parseUnitsDecimal(src.payAmount || src.amount, src.decimals);
|
|
5213
6427
|
if (alive) setInsufficient(BigInt(entry.raw) < need);
|
|
@@ -5271,6 +6485,8 @@ function useFlow(args) {
|
|
|
5271
6485
|
throw new Error(nativeFeeShortMessage(check2, nativeSymbol(Number(sourceChainId), chains), route.source.chainName));
|
|
5272
6486
|
}
|
|
5273
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);
|
|
5274
6490
|
const minNonce = await engine.payerNonceBaseline(Number(sourceChainId), account);
|
|
5275
6491
|
const txs = route.transactions;
|
|
5276
6492
|
let settleHash = "";
|
|
@@ -5286,7 +6502,7 @@ function useFlow(args) {
|
|
|
5286
6502
|
patch(tx.id, "done");
|
|
5287
6503
|
continue;
|
|
5288
6504
|
}
|
|
5289
|
-
if (!validatePlannedTransaction(tx, route, recipient2)) {
|
|
6505
|
+
if (!validatePlannedTransaction(tx, route, recipient2, heavyExpected ? { ...heavyExpected, nowSec: Math.floor(Date.now() / 1e3) } : void 0)) {
|
|
5290
6506
|
throw new Error(`Refusing to sign a ${tx.kind} that does not match the reviewed plan.`);
|
|
5291
6507
|
}
|
|
5292
6508
|
patch(tx.id, "active");
|
|
@@ -5357,6 +6573,98 @@ function useFlow(args) {
|
|
|
5357
6573
|
busyRef.current = false;
|
|
5358
6574
|
}
|
|
5359
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]);
|
|
5360
6668
|
const quoteReady = status === "ready" && !!plan;
|
|
5361
6669
|
const quotePaused = quoteReady && idle2;
|
|
5362
6670
|
const quoteStale = quoteReady && (idle2 || planAt < returnedAt2);
|
|
@@ -5378,7 +6686,10 @@ function useFlow(args) {
|
|
|
5378
6686
|
quoteStale,
|
|
5379
6687
|
submit,
|
|
5380
6688
|
reload,
|
|
5381
|
-
addRoute
|
|
6689
|
+
addRoute,
|
|
6690
|
+
compare,
|
|
6691
|
+
selectOption,
|
|
6692
|
+
promotions
|
|
5382
6693
|
};
|
|
5383
6694
|
}
|
|
5384
6695
|
var RETRY_DELAYS_MS = [800, 2400, 6e3];
|
|
@@ -5446,9 +6757,9 @@ function useHoldings(engine, account, routes, initialBalances) {
|
|
|
5446
6757
|
const seeded = {};
|
|
5447
6758
|
const missing = [];
|
|
5448
6759
|
for (const target of targets) {
|
|
5449
|
-
const
|
|
5450
|
-
const balance = initialBalances?.[
|
|
5451
|
-
if (balance) seeded[
|
|
6760
|
+
const key2 = balanceKey(target.chainId, target.tokenAddress);
|
|
6761
|
+
const balance = initialBalances?.[key2];
|
|
6762
|
+
if (balance) seeded[key2] = balance;
|
|
5452
6763
|
else missing.push(target);
|
|
5453
6764
|
}
|
|
5454
6765
|
setBalances(seeded);
|
|
@@ -6972,7 +8283,7 @@ function priceOf(prices, symbol) {
|
|
|
6972
8283
|
const p = prices?.[String(symbol).toUpperCase()];
|
|
6973
8284
|
return typeof p === "number" && Number.isFinite(p) ? p : void 0;
|
|
6974
8285
|
}
|
|
6975
|
-
function buildGroup(
|
|
8286
|
+
function buildGroup(key2, members, prices) {
|
|
6976
8287
|
const tokens = members.map((m) => m.token);
|
|
6977
8288
|
let amount = null;
|
|
6978
8289
|
let usd2 = null;
|
|
@@ -6984,7 +8295,7 @@ function buildGroup(key, members, prices) {
|
|
|
6984
8295
|
}
|
|
6985
8296
|
const first = members[0].token;
|
|
6986
8297
|
return {
|
|
6987
|
-
key,
|
|
8298
|
+
key: key2,
|
|
6988
8299
|
symbol: dominantSymbol(tokens),
|
|
6989
8300
|
name: String(first.name || first.symbol),
|
|
6990
8301
|
logoUrl: first.logoUrl,
|
|
@@ -7005,15 +8316,15 @@ function groupDeployments(deployments, prices) {
|
|
|
7005
8316
|
const order = [];
|
|
7006
8317
|
const members = /* @__PURE__ */ new Map();
|
|
7007
8318
|
for (const d of [...deployments].sort(byDeployment)) {
|
|
7008
|
-
const
|
|
7009
|
-
const list = members.get(
|
|
8319
|
+
const key2 = String(d.token.symbol).toUpperCase();
|
|
8320
|
+
const list = members.get(key2);
|
|
7010
8321
|
if (list) list.push(d);
|
|
7011
8322
|
else {
|
|
7012
|
-
members.set(
|
|
7013
|
-
order.push(
|
|
8323
|
+
members.set(key2, [d]);
|
|
8324
|
+
order.push(key2);
|
|
7014
8325
|
}
|
|
7015
8326
|
}
|
|
7016
|
-
return order.map((
|
|
8327
|
+
return order.map((key2) => buildGroup(key2, members.get(key2), prices)).sort(byPickability);
|
|
7017
8328
|
}
|
|
7018
8329
|
var CHAIN_ALIASES = {
|
|
7019
8330
|
56: ["bsc", "binance"],
|
|
@@ -7021,10 +8332,10 @@ var CHAIN_ALIASES = {
|
|
|
7021
8332
|
43114: ["avax"]
|
|
7022
8333
|
};
|
|
7023
8334
|
function labelForms(label2) {
|
|
7024
|
-
const
|
|
7025
|
-
if (!
|
|
7026
|
-
const compact =
|
|
7027
|
-
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];
|
|
7028
8339
|
}
|
|
7029
8340
|
function buildChainSearchTerms(chains) {
|
|
7030
8341
|
const byId = /* @__PURE__ */ new Map();
|
|
@@ -7287,14 +8598,14 @@ function TokenSelect(props) {
|
|
|
7287
8598
|
const groups = react.useMemo(() => {
|
|
7288
8599
|
const deployments = [];
|
|
7289
8600
|
for (const token of props.tokens) {
|
|
7290
|
-
const
|
|
7291
|
-
const n = Number(props.balances?.[
|
|
7292
|
-
const st = props.optionStates?.[
|
|
8601
|
+
const key2 = rowKey(token);
|
|
8602
|
+
const n = Number(props.balances?.[key2]?.formatted);
|
|
8603
|
+
const st = props.optionStates?.[key2];
|
|
7293
8604
|
if (st?.disabled && !WALLET_STATE_REASONS.has(String(st.reason))) continue;
|
|
7294
8605
|
deployments.push({
|
|
7295
8606
|
token,
|
|
7296
|
-
key,
|
|
7297
|
-
balance: showBalances && props.balances?.[
|
|
8607
|
+
key: key2,
|
|
8608
|
+
balance: showBalances && props.balances?.[key2] && Number.isFinite(n) ? n : null,
|
|
7298
8609
|
disabled: !!st?.disabled,
|
|
7299
8610
|
// The line under a greyed row says why. Callers send either a sentence in `reason` (the
|
|
7300
8611
|
// exchange's "cannot be delivered on this chain") or a machine code there with the words in
|
|
@@ -7666,7 +8977,7 @@ function WidgetShell(props) {
|
|
|
7666
8977
|
}
|
|
7667
8978
|
);
|
|
7668
8979
|
}
|
|
7669
|
-
function
|
|
8980
|
+
function shortAddress3(a) {
|
|
7670
8981
|
if (!a) return "";
|
|
7671
8982
|
return `${a.slice(0, 6)}\u2026${a.slice(-4)}`;
|
|
7672
8983
|
}
|
|
@@ -7935,13 +9246,13 @@ function useTxHistory(account) {
|
|
|
7935
9246
|
react.useEffect(() => {
|
|
7936
9247
|
setEntries(readTxHistory(account));
|
|
7937
9248
|
if (typeof window === "undefined" || !account) return;
|
|
7938
|
-
const
|
|
9249
|
+
const key2 = txHistoryKey(account);
|
|
7939
9250
|
const onLocal = (e) => {
|
|
7940
9251
|
const detail = e.detail;
|
|
7941
9252
|
if (!detail?.account || detail.account === account.toLowerCase()) setEntries(readTxHistory(account));
|
|
7942
9253
|
};
|
|
7943
9254
|
const onStorage = (e) => {
|
|
7944
|
-
if (e.key ===
|
|
9255
|
+
if (e.key === key2) setEntries(readTxHistory(account));
|
|
7945
9256
|
};
|
|
7946
9257
|
window.addEventListener(TX_HISTORY_EVENT, onLocal);
|
|
7947
9258
|
window.addEventListener("storage", onStorage);
|
|
@@ -7957,10 +9268,10 @@ var hidden2 = () => typeof document !== "undefined" && document.visibilityState
|
|
|
7957
9268
|
var travelling = (entries) => !!entries?.some((e) => e.delivery === "in-progress" || e.delivery === "attention");
|
|
7958
9269
|
function useWalletHistory(engine, wallets) {
|
|
7959
9270
|
const [entries, setEntries] = react.useState(null);
|
|
7960
|
-
const
|
|
9271
|
+
const key2 = wallets.filter((w) => !!w).join("|");
|
|
7961
9272
|
react.useEffect(() => {
|
|
7962
9273
|
setEntries(null);
|
|
7963
|
-
if (!engine || !
|
|
9274
|
+
if (!engine || !key2) return;
|
|
7964
9275
|
let alive = true;
|
|
7965
9276
|
let timer2;
|
|
7966
9277
|
let started2 = Date.now();
|
|
@@ -7968,7 +9279,7 @@ function useWalletHistory(engine, wallets) {
|
|
|
7968
9279
|
if (timer2) clearTimeout(timer2);
|
|
7969
9280
|
timer2 = void 0;
|
|
7970
9281
|
if (!hidden2()) {
|
|
7971
|
-
const next = await engine.fetchWalletHistory(
|
|
9282
|
+
const next = await engine.fetchWalletHistory(key2.split("|"));
|
|
7972
9283
|
if (!alive) return;
|
|
7973
9284
|
if (next) setEntries(next);
|
|
7974
9285
|
if (!travelling(next)) return;
|
|
@@ -7987,7 +9298,7 @@ function useWalletHistory(engine, wallets) {
|
|
|
7987
9298
|
if (timer2) clearTimeout(timer2);
|
|
7988
9299
|
if (typeof window !== "undefined") window.removeEventListener(TX_HISTORY_EVENT, onRecorded);
|
|
7989
9300
|
};
|
|
7990
|
-
}, [engine,
|
|
9301
|
+
}, [engine, key2]);
|
|
7991
9302
|
return entries;
|
|
7992
9303
|
}
|
|
7993
9304
|
function BackGlyph() {
|
|
@@ -8124,15 +9435,15 @@ function TxPair(props) {
|
|
|
8124
9435
|
] });
|
|
8125
9436
|
}
|
|
8126
9437
|
function logoFor(art, symbol, chainId) {
|
|
8127
|
-
const
|
|
8128
|
-
if (!
|
|
9438
|
+
const key2 = symbolKey(symbol);
|
|
9439
|
+
if (!key2) return void 0;
|
|
8129
9440
|
const tokens = art.tokens;
|
|
8130
9441
|
if (tokens?.length) {
|
|
8131
|
-
const sameChain = chainId == null ? void 0 : tokens.find((t) => Number(t.chainId) === chainId && symbolKey(t.symbol) ===
|
|
8132
|
-
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;
|
|
8133
9444
|
if (found) return found;
|
|
8134
9445
|
}
|
|
8135
|
-
return art.vaultIcons?.get(
|
|
9446
|
+
return art.vaultIcons?.get(key2);
|
|
8136
9447
|
}
|
|
8137
9448
|
function TxHistoryList(props) {
|
|
8138
9449
|
if (!props.entries.length) {
|
|
@@ -8209,7 +9520,7 @@ function TxDetail(props) {
|
|
|
8209
9520
|
] }),
|
|
8210
9521
|
e.recipient ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta-row", children: [
|
|
8211
9522
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Recipient" }),
|
|
8212
|
-
/* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", children:
|
|
9523
|
+
/* @__PURE__ */ jsxRuntime.jsx("b", { className: "sg-mono", children: shortAddress3(e.recipient) })
|
|
8213
9524
|
] }) : null,
|
|
8214
9525
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-meta-row", children: [
|
|
8215
9526
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-meta-label", children: "Settlement" }),
|
|
@@ -8246,7 +9557,7 @@ function TxHistoryPanel(props) {
|
|
|
8246
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, {}) }),
|
|
8247
9558
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-sel-title", children: [
|
|
8248
9559
|
selected ? "Transaction" : "Transaction history",
|
|
8249
|
-
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
|
|
8250
9561
|
] })
|
|
8251
9562
|
] }),
|
|
8252
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 })
|
|
@@ -8428,8 +9739,8 @@ function onSolanaAccountChange(info, cb) {
|
|
|
8428
9739
|
}
|
|
8429
9740
|
}) ?? (() => {
|
|
8430
9741
|
});
|
|
8431
|
-
const changed = (
|
|
8432
|
-
const address = validAddress(
|
|
9742
|
+
const changed = (key2) => {
|
|
9743
|
+
const address = validAddress(key2);
|
|
8433
9744
|
connected.set(provider, address ? [{ address }] : []);
|
|
8434
9745
|
cb(address);
|
|
8435
9746
|
};
|
|
@@ -8601,82 +9912,6 @@ function useRecipient(destinationChainId, hostRecipient, opts = {}) {
|
|
|
8601
9912
|
const recipientFor = (account) => required ? recipient2 || "" : hostRecipient || custom.evm || account;
|
|
8602
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 };
|
|
8603
9914
|
}
|
|
8604
|
-
|
|
8605
|
-
// src/core/checksum.ts
|
|
8606
|
-
var RC = [
|
|
8607
|
-
0x0000000000000001n,
|
|
8608
|
-
0x0000000000008082n,
|
|
8609
|
-
0x800000000000808an,
|
|
8610
|
-
0x8000000080008000n,
|
|
8611
|
-
0x000000000000808bn,
|
|
8612
|
-
0x0000000080000001n,
|
|
8613
|
-
0x8000000080008081n,
|
|
8614
|
-
0x8000000000008009n,
|
|
8615
|
-
0x000000000000008an,
|
|
8616
|
-
0x0000000000000088n,
|
|
8617
|
-
0x0000000080008009n,
|
|
8618
|
-
0x000000008000000an,
|
|
8619
|
-
0x000000008000808bn,
|
|
8620
|
-
0x800000000000008bn,
|
|
8621
|
-
0x8000000000008089n,
|
|
8622
|
-
0x8000000000008003n,
|
|
8623
|
-
0x8000000000008002n,
|
|
8624
|
-
0x8000000000000080n,
|
|
8625
|
-
0x000000000000800an,
|
|
8626
|
-
0x800000008000000an,
|
|
8627
|
-
0x8000000080008081n,
|
|
8628
|
-
0x8000000000008080n,
|
|
8629
|
-
0x0000000080000001n,
|
|
8630
|
-
0x8000000080008008n
|
|
8631
|
-
];
|
|
8632
|
-
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];
|
|
8633
|
-
var MASK = (1n << 64n) - 1n;
|
|
8634
|
-
var rotl = (x, n) => n === 0 ? x : (x << BigInt(n) | x >> BigInt(64 - n)) & MASK;
|
|
8635
|
-
function keccakF(s) {
|
|
8636
|
-
for (let round = 0; round < 24; round++) {
|
|
8637
|
-
const c = [0, 1, 2, 3, 4].map((x) => s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]);
|
|
8638
|
-
for (let x = 0; x < 5; x++) {
|
|
8639
|
-
const d = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1);
|
|
8640
|
-
for (let y = 0; y < 25; y += 5) s[y + x] = s[y + x] ^ d;
|
|
8641
|
-
}
|
|
8642
|
-
const b = new Array(25);
|
|
8643
|
-
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]);
|
|
8644
|
-
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];
|
|
8645
|
-
s[0] = s[0] ^ RC[round];
|
|
8646
|
-
}
|
|
8647
|
-
}
|
|
8648
|
-
function keccak256Hex(bytes) {
|
|
8649
|
-
const rate = 136;
|
|
8650
|
-
const padded = new Uint8Array(Math.ceil((bytes.length + 1) / rate) * rate);
|
|
8651
|
-
padded.set(bytes);
|
|
8652
|
-
padded[bytes.length] = padded[bytes.length] ^ 1;
|
|
8653
|
-
padded[padded.length - 1] = padded[padded.length - 1] ^ 128;
|
|
8654
|
-
const s = new Array(25).fill(0n);
|
|
8655
|
-
for (let off = 0; off < padded.length; off += rate) {
|
|
8656
|
-
for (let i = 0; i < rate / 8; i++) {
|
|
8657
|
-
let lane = 0n;
|
|
8658
|
-
for (let j = 7; j >= 0; j--) lane = lane << 8n | BigInt(padded[off + i * 8 + j]);
|
|
8659
|
-
s[i] = s[i] ^ lane;
|
|
8660
|
-
}
|
|
8661
|
-
keccakF(s);
|
|
8662
|
-
}
|
|
8663
|
-
let out = "";
|
|
8664
|
-
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");
|
|
8665
|
-
return out;
|
|
8666
|
-
}
|
|
8667
|
-
function toChecksumAddress(address) {
|
|
8668
|
-
const lower2 = address.slice(2).toLowerCase();
|
|
8669
|
-
const hash2 = keccak256Hex(new TextEncoder().encode(lower2));
|
|
8670
|
-
let out = "0x";
|
|
8671
|
-
for (let i = 0; i < 40; i++) out += Number.parseInt(hash2[i], 16) >= 8 ? lower2[i].toUpperCase() : lower2[i];
|
|
8672
|
-
return out;
|
|
8673
|
-
}
|
|
8674
|
-
function hasValidChecksum(address) {
|
|
8675
|
-
if (!/^0x[0-9a-fA-F]{40}$/.test(address)) return false;
|
|
8676
|
-
const body = address.slice(2);
|
|
8677
|
-
if (body === body.toLowerCase() || body === body.toUpperCase()) return true;
|
|
8678
|
-
return toChecksumAddress(address) === address;
|
|
8679
|
-
}
|
|
8680
9915
|
function ArrowLeft() {
|
|
8681
9916
|
return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
|
|
8682
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" }),
|
|
@@ -9357,7 +10592,7 @@ function IdentityLine(props) {
|
|
|
9357
10592
|
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-link-id", children: [
|
|
9358
10593
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-icon", children: /* @__PURE__ */ jsxRuntime.jsx(WalletGlyph, {}) }),
|
|
9359
10594
|
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-link-id-text", children: [
|
|
9360
|
-
/* @__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" }),
|
|
9361
10596
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-link-id-secondary", children: props.email ? props.email : props.account ? "Connected wallet" : "Connect your wallet to continue" })
|
|
9362
10597
|
] }),
|
|
9363
10598
|
props.account ? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }) : null
|
|
@@ -9504,9 +10739,9 @@ function PaymentIsland(props) {
|
|
|
9504
10739
|
const optionStates = react.useMemo(() => {
|
|
9505
10740
|
const map = {};
|
|
9506
10741
|
for (const a of annotated) {
|
|
9507
|
-
const
|
|
10742
|
+
const key2 = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
|
|
9508
10743
|
if (!a.balance || holdings.loading) {
|
|
9509
|
-
map[
|
|
10744
|
+
map[key2] = { disabled: false, reason: "checking" };
|
|
9510
10745
|
continue;
|
|
9511
10746
|
}
|
|
9512
10747
|
let zero = false;
|
|
@@ -9515,9 +10750,9 @@ function PaymentIsland(props) {
|
|
|
9515
10750
|
} catch {
|
|
9516
10751
|
zero = false;
|
|
9517
10752
|
}
|
|
9518
|
-
if (zero) map[
|
|
9519
|
-
else if (a.affordable === false) map[
|
|
9520
|
-
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 };
|
|
9521
10756
|
}
|
|
9522
10757
|
return map;
|
|
9523
10758
|
}, [annotated, holdings.loading]);
|
|
@@ -9557,19 +10792,19 @@ function PaymentIsland(props) {
|
|
|
9557
10792
|
if (!catalogue?.ready) return void 0;
|
|
9558
10793
|
const states2 = {};
|
|
9559
10794
|
for (const token of catalogue.tokens) {
|
|
9560
|
-
const
|
|
10795
|
+
const key2 = balanceKey(Number(token.chainId), token.address);
|
|
9561
10796
|
const measured = exFromToken ? brokenLaneFor(token, exFromToken, catalogue.brokenLanes) : void 0;
|
|
9562
10797
|
if (measured) {
|
|
9563
|
-
states2[
|
|
10798
|
+
states2[key2] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
|
|
9564
10799
|
continue;
|
|
9565
10800
|
}
|
|
9566
10801
|
const verdict = destinationAvailability(token, catalogue, exFromToken);
|
|
9567
10802
|
if (verdict === "available") {
|
|
9568
10803
|
const limit = laneLimitFor(token, exFromToken, catalogue.limitedLanes);
|
|
9569
|
-
if (limit) states2[
|
|
10804
|
+
if (limit) states2[key2] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, exFromToken ? tokenTicker(exFromToken) : void 0)) };
|
|
9570
10805
|
continue;
|
|
9571
10806
|
}
|
|
9572
|
-
states2[
|
|
10807
|
+
states2[key2] = {
|
|
9573
10808
|
disabled: true,
|
|
9574
10809
|
reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain.` : "ZeroDelta cannot deliver this asset here.",
|
|
9575
10810
|
hint: verdict === "hub-only" ? "Not here" : "Unavailable"
|
|
@@ -9582,9 +10817,9 @@ function PaymentIsland(props) {
|
|
|
9582
10817
|
const seen = /* @__PURE__ */ new Set();
|
|
9583
10818
|
const list = [];
|
|
9584
10819
|
for (const r of visibleRoutes) {
|
|
9585
|
-
const
|
|
9586
|
-
if (seen.has(
|
|
9587
|
-
seen.add(
|
|
10820
|
+
const key2 = balanceKey(r.source.chainId, r.source.tokenAddress);
|
|
10821
|
+
if (seen.has(key2)) continue;
|
|
10822
|
+
seen.add(key2);
|
|
9588
10823
|
const reg = registryTokens.find((t) => Number(t.chainId) === r.source.chainId && addrEq(t.address, r.source.tokenAddress));
|
|
9589
10824
|
list.push(
|
|
9590
10825
|
reg ?? {
|
|
@@ -9924,7 +11159,7 @@ function PaymentIsland(props) {
|
|
|
9924
11159
|
] }),
|
|
9925
11160
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-receipt-sub", children: [
|
|
9926
11161
|
deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
|
|
9927
|
-
(flow.lastTxEntry?.recipient || recipient2) && (isPay || recipientState.recipientFamily === "solana") ? ` \xB7 ${
|
|
11162
|
+
(flow.lastTxEntry?.recipient || recipient2) && (isPay || recipientState.recipientFamily === "solana") ? ` \xB7 ${shortAddress3(flow.lastTxEntry?.recipient || recipient2)}` : ""
|
|
9928
11163
|
] }),
|
|
9929
11164
|
evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
|
|
9930
11165
|
] }),
|
|
@@ -10237,9 +11472,9 @@ function PayCard(props) {
|
|
|
10237
11472
|
const optionStates = react.useMemo(() => {
|
|
10238
11473
|
const map = {};
|
|
10239
11474
|
for (const a of annotated) {
|
|
10240
|
-
const
|
|
11475
|
+
const key2 = balanceKey(a.route.source.chainId, a.route.source.tokenAddress);
|
|
10241
11476
|
if (!a.balance || holdings.loading) {
|
|
10242
|
-
map[
|
|
11477
|
+
map[key2] = { disabled: false, reason: "checking" };
|
|
10243
11478
|
continue;
|
|
10244
11479
|
}
|
|
10245
11480
|
let zero = false;
|
|
@@ -10249,23 +11484,23 @@ function PayCard(props) {
|
|
|
10249
11484
|
zero = false;
|
|
10250
11485
|
}
|
|
10251
11486
|
if (zero) {
|
|
10252
|
-
map[
|
|
11487
|
+
map[key2] = { disabled: true, reason: "no-balance", hint: "No balance on this chain" };
|
|
10253
11488
|
} else if (a.affordable === false) {
|
|
10254
|
-
map[
|
|
11489
|
+
map[key2] = { disabled: true, reason: "insufficient", hint: `Need ${a.route.source.payAmount} ${a.route.source.ticker || a.route.source.asset}` };
|
|
10255
11490
|
} else {
|
|
10256
|
-
map[
|
|
11491
|
+
map[key2] = { disabled: false };
|
|
10257
11492
|
}
|
|
10258
11493
|
}
|
|
10259
11494
|
for (const o of unquoted) {
|
|
10260
|
-
const
|
|
10261
|
-
if (map[
|
|
11495
|
+
const key2 = balanceKey(o.chainId, o.address);
|
|
11496
|
+
if (map[key2]) continue;
|
|
10262
11497
|
let zero = false;
|
|
10263
11498
|
try {
|
|
10264
|
-
zero = BigInt(listBalances[
|
|
11499
|
+
zero = BigInt(listBalances[key2]?.raw ?? "x") === 0n;
|
|
10265
11500
|
} catch {
|
|
10266
11501
|
zero = false;
|
|
10267
11502
|
}
|
|
10268
|
-
map[
|
|
11503
|
+
map[key2] = zero ? { disabled: true, reason: "no-balance", hint: "No balance on this chain" } : { disabled: false };
|
|
10269
11504
|
}
|
|
10270
11505
|
return map;
|
|
10271
11506
|
}, [annotated, holdings.loading, unquoted, listBalances]);
|
|
@@ -10279,9 +11514,9 @@ function PayCard(props) {
|
|
|
10279
11514
|
const seen = /* @__PURE__ */ new Set();
|
|
10280
11515
|
const list = [];
|
|
10281
11516
|
const push = (chainId, address, fallback) => {
|
|
10282
|
-
const
|
|
10283
|
-
if (seen.has(
|
|
10284
|
-
seen.add(
|
|
11517
|
+
const key2 = balanceKey(chainId, address);
|
|
11518
|
+
if (seen.has(key2)) return;
|
|
11519
|
+
seen.add(key2);
|
|
10285
11520
|
list.push(registryTokens.find((t) => Number(t.chainId) === chainId && addrEq2(t.address, address)) ?? fallback);
|
|
10286
11521
|
};
|
|
10287
11522
|
for (const r of visibleRoutes) {
|
|
@@ -10355,13 +11590,13 @@ function PayCard(props) {
|
|
|
10355
11590
|
const option = unquoted.find((o) => o.chainId === pick.chainId && o.symbolKey === symbolKey(pick.symbol));
|
|
10356
11591
|
closeSelector();
|
|
10357
11592
|
if (!option || !wallet.account) return;
|
|
10358
|
-
const
|
|
10359
|
-
setPricing(
|
|
11593
|
+
const key2 = balanceKey(option.chainId, option.address);
|
|
11594
|
+
setPricing(key2);
|
|
10360
11595
|
userPicked.current = true;
|
|
10361
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(() => {
|
|
10362
|
-
setFailedOptions((prev) => /* @__PURE__ */ new Set([...prev,
|
|
11597
|
+
setFailedOptions((prev) => /* @__PURE__ */ new Set([...prev, key2]));
|
|
10363
11598
|
setPickError(`${option.ticker || option.symbol} on ${option.chainName} cannot settle this payment right now. Pick another way to pay.`);
|
|
10364
|
-
}).finally(() => setPricing((cur) => cur ===
|
|
11599
|
+
}).finally(() => setPricing((cur) => cur === key2 ? null : cur));
|
|
10365
11600
|
};
|
|
10366
11601
|
const parked = !isLiveMethod(method);
|
|
10367
11602
|
const submitting = flow.status === "submitting";
|
|
@@ -10394,7 +11629,7 @@ function PayCard(props) {
|
|
|
10394
11629
|
/* @__PURE__ */ jsxRuntime.jsxs("span", { className: "sg-wallet", "data-connected": "true", children: [
|
|
10395
11630
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-wallet-dot", "aria-hidden": "true" }),
|
|
10396
11631
|
" ",
|
|
10397
|
-
|
|
11632
|
+
shortAddress3(wallet.account)
|
|
10398
11633
|
] })
|
|
10399
11634
|
] }) : /* @__PURE__ */ jsxRuntime.jsx("span", {});
|
|
10400
11635
|
const nativeWei = sel ? routeNativeValue(sel) : 0n;
|
|
@@ -10434,7 +11669,7 @@ function PayCard(props) {
|
|
|
10434
11669
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
|
|
10435
11670
|
deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
|
|
10436
11671
|
" \xB7 ",
|
|
10437
|
-
|
|
11672
|
+
shortAddress3(props.recipient)
|
|
10438
11673
|
] }),
|
|
10439
11674
|
evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
|
|
10440
11675
|
] }),
|
|
@@ -10602,7 +11837,7 @@ function StableGenieSwap(props) {
|
|
|
10602
11837
|
] }),
|
|
10603
11838
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
|
|
10604
11839
|
deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
|
|
10605
|
-
recipientState.recipientFamily === "solana" ? ` \xB7 ${
|
|
11840
|
+
recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress3(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress3(props.recipient)}` : ""
|
|
10606
11841
|
] }),
|
|
10607
11842
|
evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
|
|
10608
11843
|
] }),
|
|
@@ -10666,7 +11901,7 @@ function useSolanaSourceFlow(args) {
|
|
|
10666
11901
|
const planArgs = react.useRef(null);
|
|
10667
11902
|
const changedWhileBusy = react.useRef(false);
|
|
10668
11903
|
const addressed = Boolean(owner && payer && recipient2);
|
|
10669
|
-
const
|
|
11904
|
+
const key2 = keyOf(args);
|
|
10670
11905
|
react.useEffect(() => {
|
|
10671
11906
|
const id = ++req.current;
|
|
10672
11907
|
if (!enabled || !fromSymbol || !toChainId || !toSymbol || !(Number(amount) > 0)) {
|
|
@@ -10700,7 +11935,7 @@ function useSolanaSourceFlow(args) {
|
|
|
10700
11935
|
const quoted = await engine.quoteSolanaSource(input);
|
|
10701
11936
|
const built = await engine.buildSolanaSourcePlan(input, quoted);
|
|
10702
11937
|
if (id !== req.current) return;
|
|
10703
|
-
planKey.current =
|
|
11938
|
+
planKey.current = key2;
|
|
10704
11939
|
planArgs.current = { ...latest.current };
|
|
10705
11940
|
setPreview(quoted);
|
|
10706
11941
|
setPlan(built);
|
|
@@ -10716,7 +11951,7 @@ function useSolanaSourceFlow(args) {
|
|
|
10716
11951
|
}
|
|
10717
11952
|
}, 350);
|
|
10718
11953
|
return () => clearTimeout(timer2);
|
|
10719
|
-
}, [engine, enabled,
|
|
11954
|
+
}, [engine, enabled, key2, addressed, nonce]);
|
|
10720
11955
|
react.useEffect(() => {
|
|
10721
11956
|
let alive = true;
|
|
10722
11957
|
setBalanceRaw(void 0);
|
|
@@ -11040,11 +12275,11 @@ function ExchangeCard(props) {
|
|
|
11040
12275
|
const [fiatCurrency, setFiatCurrency] = react.useState(props.fiatCurrency ?? "EUR");
|
|
11041
12276
|
const sellableFrom = react.useCallback((t) => t && product === "rwa" && !isSellableRwa(t) ? null : t, [product]);
|
|
11042
12277
|
const fromToken = react.useMemo(() => from ? sellableFrom(findToken(tokens, from.chainId, from.symbol)) : null, [tokens, from, sellableFrom]);
|
|
11043
|
-
const
|
|
11044
|
-
const toSymbol =
|
|
12278
|
+
const toToken2 = react.useMemo(() => to ? findToken(tokens, to.chainId, to.symbol) : null, [tokens, to]);
|
|
12279
|
+
const toSymbol = toToken2?.symbol ?? to?.symbol ?? "";
|
|
11045
12280
|
const fromTicker = fromToken ? tokenTicker(fromToken) : from?.symbol ?? "";
|
|
11046
|
-
const toTicker =
|
|
11047
|
-
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]);
|
|
11048
12283
|
const toPickerTokens = react.useMemo(() => product === "rwa" ? counterpartTokens(tokens, fromToken) : tokens, [product, tokens, fromToken]);
|
|
11049
12284
|
const rwaSeeded = react.useRef(false);
|
|
11050
12285
|
react.useEffect(() => {
|
|
@@ -11061,19 +12296,19 @@ function ExchangeCard(props) {
|
|
|
11061
12296
|
if (!catalogue?.ready) return void 0;
|
|
11062
12297
|
const states2 = {};
|
|
11063
12298
|
for (const token of catalogue.tokens) {
|
|
11064
|
-
const
|
|
12299
|
+
const key2 = `${Number(token.chainId)}:${String(token.address || "").toLowerCase()}`;
|
|
11065
12300
|
const measured = fromToken ? brokenLaneFor(token, fromToken, catalogue.brokenLanes) : void 0;
|
|
11066
12301
|
if (measured) {
|
|
11067
|
-
states2[
|
|
12302
|
+
states2[key2] = { disabled: true, reason: brokenLaneReason(measured), hint: "Unavailable" };
|
|
11068
12303
|
continue;
|
|
11069
12304
|
}
|
|
11070
12305
|
const verdict = destinationAvailability(token, catalogue, fromToken);
|
|
11071
12306
|
if (verdict === "available") {
|
|
11072
12307
|
const limit = laneLimitFor(token, fromToken, catalogue.limitedLanes);
|
|
11073
|
-
if (limit) states2[
|
|
12308
|
+
if (limit) states2[key2] = { disabled: false, hint: laneLimitHint(limit, laneLimitSymbol(limit, fromToken ? tokenTicker(fromToken) : void 0)) };
|
|
11074
12309
|
continue;
|
|
11075
12310
|
}
|
|
11076
|
-
states2[
|
|
12311
|
+
states2[key2] = {
|
|
11077
12312
|
disabled: true,
|
|
11078
12313
|
reason: verdict === "hub-only" ? `${tokenTicker(token)} cannot be delivered on this chain \u2014 choose an execution chain.` : "ZeroDelta cannot deliver this asset here.",
|
|
11079
12314
|
hint: verdict === "hub-only" ? "Not here" : "Unavailable"
|
|
@@ -11089,8 +12324,8 @@ function ExchangeCard(props) {
|
|
|
11089
12324
|
const amountValid = /^\d+(\.\d+)?$/.test(normalizedAmount) && Number(normalizedAmount) > 0 && Number(normalizedAmount) <= 1e9;
|
|
11090
12325
|
const rampMode = mode !== "exchange";
|
|
11091
12326
|
const laneLimit = react.useMemo(
|
|
11092
|
-
() => mode === "exchange" && fromToken &&
|
|
11093
|
-
[mode, catalogue, fromToken,
|
|
12327
|
+
() => mode === "exchange" && fromToken && toToken2 ? laneLimitFor(toToken2, fromToken, catalogue?.limitedLanes) : void 0,
|
|
12328
|
+
[mode, catalogue, fromToken, toToken2]
|
|
11094
12329
|
);
|
|
11095
12330
|
const limitSymbol = laneLimit ? laneLimitSymbol(laneLimit, fromTicker) : "";
|
|
11096
12331
|
const overLimit = react.useMemo(() => {
|
|
@@ -11244,11 +12479,11 @@ function ExchangeCard(props) {
|
|
|
11244
12479
|
useFitText(receiveSideRef, receiveShown);
|
|
11245
12480
|
const toDecimals = react.useMemo(() => {
|
|
11246
12481
|
try {
|
|
11247
|
-
return
|
|
12482
|
+
return toToken2 ? assetDecimals(toToken2) : void 0;
|
|
11248
12483
|
} catch {
|
|
11249
12484
|
return void 0;
|
|
11250
12485
|
}
|
|
11251
|
-
}, [
|
|
12486
|
+
}, [toToken2]);
|
|
11252
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;
|
|
11253
12488
|
const pct = (p) => {
|
|
11254
12489
|
if (!fromBal || !fromToken) return;
|
|
@@ -11460,7 +12695,7 @@ function ExchangeCard(props) {
|
|
|
11460
12695
|
] }),
|
|
11461
12696
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
|
|
11462
12697
|
solDelivery.phase === "tracking" ? "Submitted on Solana \u2014 tracking delivery" : deliveryHeadline(solDelivery, true),
|
|
11463
|
-
solFlow.sent?.recipient ? ` \xB7 ${
|
|
12698
|
+
solFlow.sent?.recipient ? ` \xB7 ${shortAddress3(solFlow.sent.recipient)}` : ""
|
|
11464
12699
|
] }),
|
|
11465
12700
|
/* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: solDelivery })
|
|
11466
12701
|
] }),
|
|
@@ -11481,7 +12716,7 @@ function ExchangeCard(props) {
|
|
|
11481
12716
|
] }),
|
|
11482
12717
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-success-sub", role: "status", "aria-live": "polite", children: [
|
|
11483
12718
|
deliveryHeadline(evmDelivery, evmConfirmed, evmDirect),
|
|
11484
|
-
recipientState.recipientFamily === "solana" ? ` \xB7 ${
|
|
12719
|
+
recipientState.recipientFamily === "solana" ? ` \xB7 ${shortAddress3(flow.lastTxEntry?.recipient || recipient2)}` : props.recipient ? ` \xB7 ${shortAddress3(props.recipient)}` : ""
|
|
11485
12720
|
] }),
|
|
11486
12721
|
evmDirect ? null : /* @__PURE__ */ jsxRuntime.jsx(DeliverySteps, { delivery: evmDelivery })
|
|
11487
12722
|
] }),
|
|
@@ -11492,7 +12727,7 @@ function ExchangeCard(props) {
|
|
|
11492
12727
|
] });
|
|
11493
12728
|
} else {
|
|
11494
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") });
|
|
11495
|
-
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") });
|
|
11496
12731
|
const cta = solActive ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
|
|
11497
12732
|
solanaSteps,
|
|
11498
12733
|
solanaCta,
|
|
@@ -11515,7 +12750,7 @@ function ExchangeCard(props) {
|
|
|
11515
12750
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-ft", children: [
|
|
11516
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") }),
|
|
11517
12752
|
/* @__PURE__ */ jsxRuntime.jsx(FlipButton, { small: true, onClick: flip, disabled: !flippable }),
|
|
11518
|
-
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") })
|
|
11519
12754
|
] }),
|
|
11520
12755
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-pane", "data-kind": "send", children: [
|
|
11521
12756
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-pane-top", children: [
|
|
@@ -11609,7 +12844,7 @@ function ExchangeCard(props) {
|
|
|
11609
12844
|
side = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-side-body", children: [
|
|
11610
12845
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv", children: [
|
|
11611
12846
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv-line", children: [
|
|
11612
|
-
/* @__PURE__ */ jsxRuntime.jsx(TokenGlyph, { symbol: to?.symbol ?? "", logoUrl:
|
|
12847
|
+
/* @__PURE__ */ jsxRuntime.jsx(TokenGlyph, { symbol: to?.symbol ?? "", logoUrl: toToken2?.logoUrl, chainId: to?.chainId, size: "xs" }),
|
|
11613
12848
|
/* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-recv-amt", ref: receiveSideRef, children: /* @__PURE__ */ jsxRuntime.jsx(AmountText, { value: formatCalculatedAmount(receive, toDecimals), exact: receive, suffix: toTicker }) })
|
|
11614
12849
|
] }),
|
|
11615
12850
|
/* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-recv-sub", children: [
|