@glacislabs/stablegenie-zerodelta 3.0.1 → 3.0.2

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/dist/index.cjs CHANGED
@@ -872,6 +872,16 @@ function createApiClient(cfg) {
872
872
  }
873
873
 
874
874
  // src/core/plan.ts
875
+ function optionBalanceKey(option) {
876
+ return `${Number(option.chainId)}:${String(option.address || "").toLowerCase()}`;
877
+ }
878
+ function hasPositiveBalance(option, balances) {
879
+ try {
880
+ return BigInt(balances[optionBalanceKey(option)]?.raw ?? "0") > 0n;
881
+ } catch {
882
+ return false;
883
+ }
884
+ }
875
885
  function validateDestination(destination) {
876
886
  assertAddress(destination.address, "Destination address");
877
887
  const chainId = Number(destination.chainId);
@@ -887,7 +897,7 @@ function planErrorSummary(errors) {
887
897
  const unique = [...new Set(errors.map((error) => error?.message || String(error)).filter(Boolean))].slice(0, 3);
888
898
  return unique.length ? unique.join(" | ") : "No ZeroDelta route is currently available for this payment.";
889
899
  }
890
- async function fetchPaymentPlan(api, request, payer, wallet = {}) {
900
+ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances) {
891
901
  validateDestination(request);
892
902
  assertAddress(payer, "Payer wallet");
893
903
  const [chains, tokens, routes] = await Promise.all([api.fetchChains(), api.fetchTokens(), api.fetchRoutes()]);
@@ -898,6 +908,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}) {
898
908
  };
899
909
  const destinationToken = findToken(tokens, destination.chainId, destination.asset);
900
910
  if (!destinationToken) throw new Error(`${destination.asset} is not enabled on ${chainNameOf(destination.chainId, chains)}.`);
911
+ const allowedFunding = wallet.fundingAssets?.length ? new Set(wallet.fundingAssets.map(symbolKey)) : null;
901
912
  const options = buildPayOptions({
902
913
  invoiceAsset: destination.asset,
903
914
  invoiceChainId: destination.chainId,
@@ -905,14 +916,25 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}) {
905
916
  routes,
906
917
  chains,
907
918
  walletChainId: wallet?.chainId
908
- });
919
+ }).filter((option) => option.direct || !allowedFunding || allowedFunding.has(option.symbolKey));
909
920
  if (!options.length) throw new Error(`No enabled ZeroDelta funding assets can settle ${destination.asset} on ${chainNameOf(destination.chainId, chains)}.`);
921
+ const balanceTargets = [];
922
+ const seenTargets = /* @__PURE__ */ new Set();
923
+ for (const option of options) {
924
+ const key = optionBalanceKey(option);
925
+ if (seenTargets.has(key)) continue;
926
+ seenTargets.add(key);
927
+ balanceTargets.push({ chainId: option.chainId, tokenAddress: option.address, decimals: option.decimals });
928
+ }
929
+ const walletBalances = readBalances ? await readBalances(payer, balanceTargets).catch(() => ({})) : {};
910
930
  const candidates = options.filter((option) => option.direct);
931
+ const heldOptions = options.filter((option) => !option.direct && hasPositiveBalance(option, walletBalances));
932
+ const heldKeys = new Set(heldOptions.map(optionBalanceKey));
911
933
  const seenChains = /* @__PURE__ */ new Set();
912
934
  const perChainBest = [];
913
935
  const leftovers = [];
914
936
  for (const option of options) {
915
- if (option.direct) continue;
937
+ if (option.direct || heldKeys.has(optionBalanceKey(option))) continue;
916
938
  if (seenChains.has(option.chainId)) {
917
939
  leftovers.push(option);
918
940
  } else {
@@ -920,7 +942,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}) {
920
942
  perChainBest.push(option);
921
943
  }
922
944
  }
923
- for (const option of [...perChainBest, ...leftovers].slice(0, MAX_QUOTE_CANDIDATES)) {
945
+ for (const option of [...heldOptions, ...perChainBest, ...leftovers].slice(0, MAX_QUOTE_CANDIDATES)) {
924
946
  candidates.push(option);
925
947
  }
926
948
  const routeErrors = [];
@@ -955,6 +977,8 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}) {
955
977
  expiresAt: new Date(Date.now() + 2 * 60 * 1e3).toISOString(),
956
978
  apiBase: api.apiBase,
957
979
  routes: routesBuilt,
980
+ fundingBalances: walletBalances,
981
+ fundingAccount: payer.toLowerCase(),
958
982
  destination: {
959
983
  asset: destinationToken.symbol,
960
984
  chainId: destination.chainId,
@@ -1183,6 +1207,23 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
1183
1207
  const json = await response.json();
1184
1208
  return json?.result ?? null;
1185
1209
  }
1210
+ async function rpcBatchCall(rpcUrl, calls) {
1211
+ const response = await fetchImpl(rpcUrl, {
1212
+ method: "POST",
1213
+ headers: { "Content-Type": "application/json" },
1214
+ body: JSON.stringify(calls.map((call, index) => ({ jsonrpc: "2.0", id: index + 1, ...call }))),
1215
+ signal: AbortSignal.timeout(TX_VERIFY_FETCH_MS)
1216
+ });
1217
+ if (!response.ok) throw new Error(`RPC ${response.status}`);
1218
+ const json = await response.json();
1219
+ if (!Array.isArray(json)) throw new Error("RPC batch unsupported");
1220
+ const results = /* @__PURE__ */ new Map();
1221
+ for (const item of json) {
1222
+ const id = Number(item?.id);
1223
+ if (Number.isInteger(id) && Object.hasOwn(item || {}, "result")) results.set(id, item.result);
1224
+ }
1225
+ return results;
1226
+ }
1186
1227
  async function payerNonceBaseline(chainId, account) {
1187
1228
  if (!isAddress(account)) return null;
1188
1229
  const rpcUrl = await chainRpcUrl(chainId);
@@ -1249,25 +1290,54 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
1249
1290
  const out = {};
1250
1291
  if (!isAddress(account) || !Array.isArray(targets) || !targets.length) return out;
1251
1292
  const owner = normalizeAddress(account);
1252
- const CONCURRENCY = 6;
1253
- let cursor = 0;
1254
- async function worker() {
1255
- while (cursor < targets.length) {
1256
- const target = targets[cursor++];
1257
- if (!target || !isAddress(target.tokenAddress)) continue;
1258
- const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
1259
- try {
1260
- const rpcUrl = await balanceRpcUrl(Number(target.chainId));
1261
- if (!rpcUrl) continue;
1262
- const hex = await rpcCall(rpcUrl, "eth_call", [{ to: normalizeAddress(target.tokenAddress), data: encodeBalanceOf(owner) }, "latest"]);
1263
- if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) continue;
1264
- const raw = BigInt(hex || "0x0").toString();
1265
- out[key] = { raw, formatted: formatUnits(raw, Number(target.decimals)) };
1266
- } catch {
1267
- }
1293
+ const groups = /* @__PURE__ */ new Map();
1294
+ const seen = /* @__PURE__ */ new Set();
1295
+ for (const target of targets) {
1296
+ if (!target || !isAddress(target.tokenAddress)) continue;
1297
+ const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
1298
+ if (seen.has(key)) continue;
1299
+ seen.add(key);
1300
+ const chainId = Number(target.chainId);
1301
+ const group = groups.get(chainId) || [];
1302
+ group.push(target);
1303
+ groups.set(chainId, group);
1304
+ }
1305
+ function record(target, hex) {
1306
+ if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
1307
+ const raw = BigInt(hex || "0x0").toString();
1308
+ const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
1309
+ out[key] = { raw, formatted: formatUnits(raw, Number(target.decimals)) };
1310
+ return true;
1311
+ }
1312
+ async function readOne(rpcUrl, target) {
1313
+ try {
1314
+ const hex = await rpcCall(rpcUrl, "eth_call", [{ to: normalizeAddress(target.tokenAddress), data: encodeBalanceOf(owner) }, "latest"]);
1315
+ record(target, hex);
1316
+ } catch {
1317
+ }
1318
+ }
1319
+ async function readGroup(chainId, group) {
1320
+ const rpcUrl = await balanceRpcUrl(chainId).catch(() => "");
1321
+ if (!rpcUrl) return;
1322
+ if (group.length === 1) return readOne(rpcUrl, group[0]);
1323
+ try {
1324
+ const results = await rpcBatchCall(
1325
+ rpcUrl,
1326
+ group.map((target) => ({
1327
+ method: "eth_call",
1328
+ params: [{ to: normalizeAddress(target.tokenAddress), data: encodeBalanceOf(owner) }, "latest"]
1329
+ }))
1330
+ );
1331
+ const missing = [];
1332
+ group.forEach((target, index) => {
1333
+ if (!record(target, results.get(index + 1))) missing.push(target);
1334
+ });
1335
+ await Promise.all(missing.map((target) => readOne(rpcUrl, target)));
1336
+ } catch {
1337
+ await Promise.all(group.map((target) => readOne(rpcUrl, target)));
1268
1338
  }
1269
1339
  }
1270
- await Promise.all(Array.from({ length: Math.min(CONCURRENCY, targets.length) }, () => worker()));
1340
+ await Promise.all([...groups.entries()].map(([chainId, group]) => readGroup(chainId, group)));
1271
1341
  return out;
1272
1342
  }
1273
1343
  async function readNativeBalance(chainId, account) {
@@ -1369,7 +1439,7 @@ function createEngine(config = {}) {
1369
1439
  fetchTokens: api.fetchTokens,
1370
1440
  fetchRoutes: api.fetchRoutes,
1371
1441
  fetchQuote: api.fetchQuote,
1372
- fetchPaymentPlan: (request, payer, wallet) => fetchPaymentPlan(api, request, payer, wallet),
1442
+ fetchPaymentPlan: (request, payer, wallet) => fetchPaymentPlan(api, request, payer, wallet, verifier.readBalances),
1373
1443
  quoteSwapPreview: (swap, owner) => quoteSwapPreview(api, swap, owner),
1374
1444
  buildSwapPlan: (swap, payer, wallet) => buildSwapPlan(api, swap, payer, wallet),
1375
1445
  payerNonceBaseline: verifier.payerNonceBaseline,
@@ -1878,7 +1948,7 @@ function useFlow(args) {
1878
1948
  function balanceKey(chainId, tokenAddress) {
1879
1949
  return `${Number(chainId)}:${String(tokenAddress || "").toLowerCase()}`;
1880
1950
  }
1881
- function useHoldings(engine, account, routes) {
1951
+ function useHoldings(engine, account, routes, initialBalances) {
1882
1952
  const [balances, setBalances] = react.useState({});
1883
1953
  const [loading, setLoading] = react.useState(false);
1884
1954
  const reqId = react.useRef(0);
@@ -1903,19 +1973,32 @@ function useHoldings(engine, account, routes) {
1903
1973
  return;
1904
1974
  }
1905
1975
  const id = ++reqId.current;
1976
+ const seeded = {};
1977
+ const missing = [];
1978
+ for (const target of targets) {
1979
+ const key = balanceKey(target.chainId, target.tokenAddress);
1980
+ const balance = initialBalances?.[key];
1981
+ if (balance) seeded[key] = balance;
1982
+ else missing.push(target);
1983
+ }
1984
+ setBalances(seeded);
1985
+ if (!missing.length) {
1986
+ setLoading(false);
1987
+ return;
1988
+ }
1906
1989
  setLoading(true);
1907
1990
  (async () => {
1908
1991
  try {
1909
- const res = await engine.readBalances(account, targets);
1992
+ const res = await engine.readBalances(account, missing);
1910
1993
  if (id !== reqId.current) return;
1911
- setBalances(res);
1994
+ setBalances({ ...seeded, ...res });
1912
1995
  } catch {
1913
- if (id === reqId.current) setBalances({});
1996
+ if (id === reqId.current) setBalances(seeded);
1914
1997
  } finally {
1915
1998
  if (id === reqId.current) setLoading(false);
1916
1999
  }
1917
2000
  })();
1918
- }, [engine, account, targetsKey]);
2001
+ }, [engine, account, targetsKey, initialBalances]);
1919
2002
  return { balances, loading };
1920
2003
  }
1921
2004
 
@@ -3054,7 +3137,21 @@ var addrEq = (a, b) => String(a || "").toLowerCase() === String(b || "").toLower
3054
3137
  var chainName = (id) => id != null ? CHAIN_LABELS[id] || `Chain ${id}` : "";
3055
3138
  var STABLES = /* @__PURE__ */ new Set(["USDC", "USDT", "USDE"]);
3056
3139
  function BankGlyph() {
3057
- return /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M3 10h18M5 10v8M10 10v8M14 10v8M19 10v8M3 19h18M12 3 3 8h18Z" }) });
3140
+ return /* @__PURE__ */ jsxRuntime.jsx(
3141
+ "svg",
3142
+ {
3143
+ width: "18",
3144
+ height: "18",
3145
+ viewBox: "0 0 24 24",
3146
+ fill: "none",
3147
+ stroke: "currentColor",
3148
+ strokeWidth: "2",
3149
+ strokeLinecap: "round",
3150
+ strokeLinejoin: "round",
3151
+ "aria-hidden": "true",
3152
+ children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M3 10h18M5 10v8M10 10v8M14 10v8M19 10v8M3 19h18M12 3 3 8h18Z" })
3153
+ }
3154
+ );
3058
3155
  }
3059
3156
  function MerchantBankPayout(props) {
3060
3157
  const bankName = props.account?.bankName?.trim() || "Bank account";
@@ -3081,25 +3178,81 @@ function MerchantBankPayout(props) {
3081
3178
  ] }) }) });
3082
3179
  }
3083
3180
  function CheckGlyph2() {
3084
- return /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "3", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M20 6 9 17l-5-5" }) });
3181
+ return /* @__PURE__ */ jsxRuntime.jsx(
3182
+ "svg",
3183
+ {
3184
+ width: "20",
3185
+ height: "20",
3186
+ viewBox: "0 0 24 24",
3187
+ fill: "none",
3188
+ stroke: "currentColor",
3189
+ strokeWidth: "3",
3190
+ strokeLinecap: "round",
3191
+ strokeLinejoin: "round",
3192
+ "aria-hidden": "true",
3193
+ children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M20 6 9 17l-5-5" })
3194
+ }
3195
+ );
3085
3196
  }
3086
3197
  function ArrowGlyph() {
3087
- return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.4", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [
3088
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M5 12h14" }),
3089
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "m13 6 6 6-6 6" })
3090
- ] });
3198
+ return /* @__PURE__ */ jsxRuntime.jsxs(
3199
+ "svg",
3200
+ {
3201
+ width: "14",
3202
+ height: "14",
3203
+ viewBox: "0 0 24 24",
3204
+ fill: "none",
3205
+ stroke: "currentColor",
3206
+ strokeWidth: "2.4",
3207
+ strokeLinecap: "round",
3208
+ strokeLinejoin: "round",
3209
+ "aria-hidden": "true",
3210
+ children: [
3211
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M5 12h14" }),
3212
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "m13 6 6 6-6 6" })
3213
+ ]
3214
+ }
3215
+ );
3091
3216
  }
3092
3217
  function ClockGlyph() {
3093
- return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [
3094
- /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "12", cy: "12", r: "9" }),
3095
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M12 7v5l3 2" })
3096
- ] });
3218
+ return /* @__PURE__ */ jsxRuntime.jsxs(
3219
+ "svg",
3220
+ {
3221
+ width: "20",
3222
+ height: "20",
3223
+ viewBox: "0 0 24 24",
3224
+ fill: "none",
3225
+ stroke: "currentColor",
3226
+ strokeWidth: "2.2",
3227
+ strokeLinecap: "round",
3228
+ strokeLinejoin: "round",
3229
+ "aria-hidden": "true",
3230
+ children: [
3231
+ /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "12", cy: "12", r: "9" }),
3232
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M12 7v5l3 2" })
3233
+ ]
3234
+ }
3235
+ );
3097
3236
  }
3098
3237
  function WalletGlyph() {
3099
- return /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [
3100
- /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "3", y: "6", width: "18", height: "13", rx: "2" }),
3101
- /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M16 12h.01M3 9h18" })
3102
- ] });
3238
+ return /* @__PURE__ */ jsxRuntime.jsxs(
3239
+ "svg",
3240
+ {
3241
+ width: "16",
3242
+ height: "16",
3243
+ viewBox: "0 0 24 24",
3244
+ fill: "none",
3245
+ stroke: "currentColor",
3246
+ strokeWidth: "2",
3247
+ strokeLinecap: "round",
3248
+ strokeLinejoin: "round",
3249
+ "aria-hidden": "true",
3250
+ children: [
3251
+ /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "3", y: "6", width: "18", height: "13", rx: "2" }),
3252
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M16 12h.01M3 9h18" })
3253
+ ]
3254
+ }
3255
+ );
3103
3256
  }
3104
3257
  function LinkMenu(props) {
3105
3258
  const [open, setOpen] = react.useState(false);
@@ -3210,7 +3363,13 @@ function IdentityLine(props) {
3210
3363
  function PaymentIsland(props) {
3211
3364
  injectStyles();
3212
3365
  const config = useMergedConfig(props);
3213
- const engine = useEngine({ apiBase: config.apiBase, apiKey: config.apiKey, trustedApiOrigin: config.trustedApiOrigin, rpcOverrides: config.rpcOverrides, onTransaction: config.onTransaction });
3366
+ const engine = useEngine({
3367
+ apiBase: config.apiBase,
3368
+ apiKey: config.apiKey,
3369
+ trustedApiOrigin: config.trustedApiOrigin,
3370
+ rpcOverrides: config.rpcOverrides,
3371
+ onTransaction: config.onTransaction
3372
+ });
3214
3373
  const wallet = useWallet(config.provider);
3215
3374
  const kind = props.kind;
3216
3375
  const isPay = kind === "pay";
@@ -3239,7 +3398,8 @@ function PaymentIsland(props) {
3239
3398
  const normEx = normalizeDecimalText(exAmount);
3240
3399
  const exAmountValid = /^\d+(\.\d+)?$/.test(normEx) && Number(normEx) > 0 && Number(normEx) <= 1e9;
3241
3400
  const exQuotable = !rampMode && exAmountValid && Boolean(exFromChainId && exFromAsset && exToChainId && exToAsset);
3242
- const payParamsKey = `pay|${props.recipient}|${props.toChainId}|${props.toAsset}|${props.amount}`;
3401
+ const payFundingAssets = props.fundingAssets?.length ? props.fundingAssets : ["USDC", "USDT", "USDE"];
3402
+ const payParamsKey = `pay|${props.recipient}|${props.toChainId}|${props.toAsset}|${props.amount}|${payFundingAssets.join(",")}`;
3243
3403
  const exParamsKey = `${kind}|${mode}|${exFromChainId}|${exFromAsset}|${exToChainId}|${exToAsset}|${normEx}|${props.recipient ?? ""}`;
3244
3404
  const flow = useFlow({
3245
3405
  engine,
@@ -3249,7 +3409,20 @@ function PaymentIsland(props) {
3249
3409
  // quote (and fire onQuote) for a payment whose CTA it never shows.
3250
3410
  enabled: isPay ? Boolean(props.recipient && props.amount) && !bankSettlement : exQuotable,
3251
3411
  paramsKey: isPay ? payParamsKey : exParamsKey,
3252
- loadPlan: isPay ? (e, payer, chainId) => e.fetchPaymentPlan({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, payer, { chainId }) : (e, payer) => e.buildSwapPlan({ fromChainId: exFromChainId, toChainId: exToChainId, fromToken: exFromAsset, toToken: exToAsset, amountIn: normEx, recipient: props.recipient }, payer),
3412
+ loadPlan: isPay ? (e, payer, chainId) => e.fetchPaymentPlan({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, payer, {
3413
+ chainId,
3414
+ fundingAssets: payFundingAssets
3415
+ }) : (e, payer) => e.buildSwapPlan(
3416
+ {
3417
+ fromChainId: exFromChainId,
3418
+ toChainId: exToChainId,
3419
+ fromToken: exFromAsset,
3420
+ toToken: exToAsset,
3421
+ amountIn: normEx,
3422
+ recipient: props.recipient
3423
+ },
3424
+ payer
3425
+ ),
3253
3426
  recipientFor: (account) => isPay ? props.recipient : props.recipient || account,
3254
3427
  onQuote: config.onQuote,
3255
3428
  onSuccess: config.onSuccess,
@@ -3257,15 +3430,14 @@ function PaymentIsland(props) {
3257
3430
  });
3258
3431
  const [method, setMethod] = react.useState("stablecoin");
3259
3432
  const parked = isPay && !isLiveMethod(method);
3260
- const fundingSet = react.useMemo(
3261
- () => props.fundingAssets?.length ? new Set(props.fundingAssets.map((a) => a.toUpperCase())) : null,
3262
- [props.fundingAssets]
3263
- );
3433
+ const fundingSet = react.useMemo(() => props.fundingAssets?.length ? new Set(props.fundingAssets.map((a) => a.toUpperCase())) : null, [props.fundingAssets]);
3264
3434
  const visibleRoutes = react.useMemo(() => {
3265
3435
  const base = fundingSet ? flow.routes.filter((r) => fundingSet.has(r.source.asset.toUpperCase()) || r.state === "DIRECT") : flow.routes;
3266
- return isPay && method === "stablecoin" ? base.filter((r) => STABLES.has(r.source.asset)) : base;
3436
+ return isPay && method === "stablecoin" ? base.filter((r) => STABLES.has(symbolKey(r.source.asset))) : base;
3267
3437
  }, [flow.routes, fundingSet, isPay, method]);
3268
- const holdings = useHoldings(engine, wallet.account, flow.routes);
3438
+ const paymentPlan = flow.plan;
3439
+ const prefetchedBalances = paymentPlan && paymentPlan.fundingAccount === wallet.account?.toLowerCase() ? paymentPlan.fundingBalances : void 0;
3440
+ const holdings = useHoldings(engine, wallet.account, flow.routes, prefetchedBalances);
3269
3441
  const annotated = react.useMemo(
3270
3442
  () => visibleRoutes.map((r) => {
3271
3443
  const balance = holdings.balances[balanceKey(r.source.chainId, r.source.tokenAddress)];
@@ -3360,7 +3532,15 @@ function PaymentIsland(props) {
3360
3532
  if (seen.has(key)) continue;
3361
3533
  seen.add(key);
3362
3534
  const reg = registryTokens.find((t) => Number(t.chainId) === r.source.chainId && addrEq(t.address, r.source.tokenAddress));
3363
- list.push(reg ?? { symbol: r.source.asset, name: r.source.asset, chainId: r.source.chainId, address: r.source.tokenAddress ?? "", decimals: r.source.decimals ?? 18 });
3535
+ list.push(
3536
+ reg ?? {
3537
+ symbol: r.source.asset,
3538
+ name: r.source.asset,
3539
+ chainId: r.source.chainId,
3540
+ address: r.source.tokenAddress ?? "",
3541
+ decimals: r.source.decimals ?? 18
3542
+ }
3543
+ );
3364
3544
  }
3365
3545
  return list;
3366
3546
  }, [visibleRoutes, registryTokens]);
@@ -3570,7 +3750,18 @@ function PaymentIsland(props) {
3570
3750
  if (hist && wallet.account) {
3571
3751
  body = /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, tokens: registryTokens, initialEntry: hist.entry ?? null, onBack: closeHistory });
3572
3752
  } else if (isPay && view === "select" && wallet.account) {
3573
- body = /* @__PURE__ */ jsxRuntime.jsx(TokenSelect, { title: "Pay with", chains: fundingChains, tokens: fundingTokens, balances: holdings.balances, optionStates, onBack: () => closeSelector(), onPick: pickFunding });
3753
+ body = /* @__PURE__ */ jsxRuntime.jsx(
3754
+ TokenSelect,
3755
+ {
3756
+ title: "Pay with",
3757
+ chains: fundingChains,
3758
+ tokens: fundingTokens,
3759
+ balances: holdings.balances,
3760
+ optionStates,
3761
+ onBack: () => closeSelector(),
3762
+ onPick: pickFunding
3763
+ }
3764
+ );
3574
3765
  } else if (!isPay && (view === "from" || view === "to")) {
3575
3766
  const isFrom = view === "from";
3576
3767
  const openerRef = isFrom ? exFromTileRef : exToTileRef;
@@ -3770,22 +3961,66 @@ function PaymentIsland(props) {
3770
3961
  const islandVars = themeToVars(resolved);
3771
3962
  return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-island-wrap", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-island", "data-sg-mode": resolved.mode, "data-expanded": expanded, "data-status": flow.status, style: islandVars, children: [
3772
3963
  pillFace,
3773
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-island-reveal", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-island-reveal-inner", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-island-body", id: panelId, ref: regionRef, role: "region", "aria-label": isPay ? "ZeroDelta Link checkout" : `ZeroDelta Link ${verb.present.toLowerCase()}`, tabIndex: -1, children: expanded ? /* @__PURE__ */ jsxRuntime.jsxs(WidgetShell, { variant: "express", title: "ZeroDelta Link", theme: config.theme, heightPx: props.heightPx, brandSlot, walletSlot, children: [
3774
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sr-only", role: "status", "aria-live": "polite", children: liveMsg }),
3775
- body
3776
- ] }) : null }) }) })
3964
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-island-reveal", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-island-reveal-inner", children: /* @__PURE__ */ jsxRuntime.jsx(
3965
+ "div",
3966
+ {
3967
+ className: "sg-island-body",
3968
+ id: panelId,
3969
+ ref: regionRef,
3970
+ role: "region",
3971
+ "aria-label": isPay ? "ZeroDelta Link checkout" : `ZeroDelta Link ${verb.present.toLowerCase()}`,
3972
+ tabIndex: -1,
3973
+ children: expanded ? /* @__PURE__ */ jsxRuntime.jsxs(
3974
+ WidgetShell,
3975
+ {
3976
+ variant: "express",
3977
+ title: "ZeroDelta Link",
3978
+ theme: config.theme,
3979
+ heightPx: props.heightPx,
3980
+ brandSlot,
3981
+ walletSlot,
3982
+ children: [
3983
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sr-only", role: "status", "aria-live": "polite", children: liveMsg }),
3984
+ body
3985
+ ]
3986
+ }
3987
+ ) : null
3988
+ }
3989
+ ) }) })
3777
3990
  ] }) });
3778
3991
  }
3779
3992
  var STABLES2 = /* @__PURE__ */ new Set(["USDC", "USDT", "USDE"]);
3993
+ var DEFAULT_FUNDING_ASSETS = ["USDC", "USDT", "USDE"];
3780
3994
  function CheckGlyph3() {
3781
- return /* @__PURE__ */ jsxRuntime.jsx("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "3", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M20 6 9 17l-5-5" }) });
3995
+ return /* @__PURE__ */ jsxRuntime.jsx(
3996
+ "svg",
3997
+ {
3998
+ width: "20",
3999
+ height: "20",
4000
+ viewBox: "0 0 24 24",
4001
+ fill: "none",
4002
+ stroke: "currentColor",
4003
+ strokeWidth: "3",
4004
+ strokeLinecap: "round",
4005
+ strokeLinejoin: "round",
4006
+ "aria-hidden": "true",
4007
+ children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M20 6 9 17l-5-5" })
4008
+ }
4009
+ );
3782
4010
  }
3783
4011
  var addrEq2 = (a, b) => String(a || "").toLowerCase() === String(b || "").toLowerCase();
3784
4012
  function StableGeniePay(props) {
3785
4013
  const config = useMergedConfig(props);
3786
- const engine = useEngine({ apiBase: config.apiBase, apiKey: config.apiKey, trustedApiOrigin: config.trustedApiOrigin, rpcOverrides: config.rpcOverrides, onTransaction: config.onTransaction });
4014
+ const engine = useEngine({
4015
+ apiBase: config.apiBase,
4016
+ apiKey: config.apiKey,
4017
+ trustedApiOrigin: config.trustedApiOrigin,
4018
+ rpcOverrides: config.rpcOverrides,
4019
+ onTransaction: config.onTransaction
4020
+ });
3787
4021
  const wallet = useWallet(config.provider);
3788
- const paramsKey = `${props.recipient}|${props.toChainId}|${props.toAsset}|${props.amount}`;
4022
+ const planFundingAssets = props.fundingAssets?.length ? props.fundingAssets : DEFAULT_FUNDING_ASSETS;
4023
+ const paramsKey = `${props.recipient}|${props.toChainId}|${props.toAsset}|${props.amount}|${planFundingAssets.join(",")}`;
3789
4024
  const flow = useFlow({
3790
4025
  engine,
3791
4026
  wallet,
@@ -3794,22 +4029,24 @@ function StableGeniePay(props) {
3794
4029
  // network work here, or every quote / balance read fires twice and onQuote/onError double-fire.
3795
4030
  enabled: Boolean(props.recipient && props.amount) && props.variant !== "pill",
3796
4031
  paramsKey,
3797
- loadPlan: (e, payer, chainId) => e.fetchPaymentPlan({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, payer, { chainId }),
4032
+ loadPlan: (e, payer, chainId) => e.fetchPaymentPlan({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, payer, {
4033
+ chainId,
4034
+ fundingAssets: planFundingAssets
4035
+ }),
3798
4036
  recipientFor: () => props.recipient,
3799
4037
  onQuote: config.onQuote,
3800
4038
  onSuccess: config.onSuccess,
3801
4039
  onError: config.onError
3802
4040
  });
3803
4041
  const [method, setMethod] = react.useState("stablecoin");
3804
- const fundingSet = react.useMemo(
3805
- () => props.fundingAssets?.length ? new Set(props.fundingAssets.map((a) => a.toUpperCase())) : null,
3806
- [props.fundingAssets]
3807
- );
4042
+ const fundingSet = react.useMemo(() => props.fundingAssets?.length ? new Set(props.fundingAssets.map((a) => a.toUpperCase())) : null, [props.fundingAssets]);
3808
4043
  const visibleRoutes = react.useMemo(() => {
3809
4044
  const base = fundingSet ? flow.routes.filter((r) => fundingSet.has(r.source.asset.toUpperCase()) || r.state === "DIRECT") : flow.routes;
3810
- return method === "stablecoin" ? base.filter((r) => STABLES2.has(r.source.asset)) : base;
4045
+ return method === "stablecoin" ? base.filter((r) => STABLES2.has(symbolKey(r.source.asset))) : base;
3811
4046
  }, [flow.routes, method, fundingSet]);
3812
- const holdings = useHoldings(engine, wallet.account, flow.routes);
4047
+ const paymentPlan = flow.plan;
4048
+ const prefetchedBalances = paymentPlan && paymentPlan.fundingAccount === wallet.account?.toLowerCase() ? paymentPlan.fundingBalances : void 0;
4049
+ const holdings = useHoldings(engine, wallet.account, flow.routes, prefetchedBalances);
3813
4050
  const annotated = react.useMemo(
3814
4051
  () => visibleRoutes.map((r) => {
3815
4052
  const balance = holdings.balances[balanceKey(r.source.chainId, r.source.tokenAddress)];
@@ -3883,7 +4120,15 @@ function StableGeniePay(props) {
3883
4120
  if (seen.has(key)) continue;
3884
4121
  seen.add(key);
3885
4122
  const reg = registryTokens.find((t) => Number(t.chainId) === r.source.chainId && addrEq2(t.address, r.source.tokenAddress));
3886
- list.push(reg ?? { symbol: r.source.asset, name: r.source.asset, chainId: r.source.chainId, address: r.source.tokenAddress ?? "", decimals: r.source.decimals ?? 18 });
4123
+ list.push(
4124
+ reg ?? {
4125
+ symbol: r.source.asset,
4126
+ name: r.source.asset,
4127
+ chainId: r.source.chainId,
4128
+ address: r.source.tokenAddress ?? "",
4129
+ decimals: r.source.decimals ?? 18
4130
+ }
4131
+ );
3887
4132
  }
3888
4133
  return list;
3889
4134
  }, [visibleRoutes, registryTokens]);
@@ -3965,7 +4210,18 @@ function StableGeniePay(props) {
3965
4210
  ] })
3966
4211
  ] }) : void 0;
3967
4212
  if (props.variant === "pill") return /* @__PURE__ */ jsxRuntime.jsx(PaymentIsland, { kind: "pay", ...props });
3968
- return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Complete payment", theme: config.theme, heightPx: props.heightPx, walletSlot, children: hist && wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, tokens: registryTokens, initialEntry: hist.entry ?? null, onBack: closeHistory }) : view === "select" && wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(TokenSelect, { title: "Pay with", chains: fundingChains, tokens: fundingTokens, balances: holdings.balances, optionStates, onBack: closeSelector, onPick: pickFunding }) : /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: !wallet.account ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
4213
+ return /* @__PURE__ */ jsxRuntime.jsx(WidgetShell, { title: config.title || "Complete payment", theme: config.theme, heightPx: props.heightPx, walletSlot, children: hist && wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, tokens: registryTokens, initialEntry: hist.entry ?? null, onBack: closeHistory }) : view === "select" && wallet.account ? /* @__PURE__ */ jsxRuntime.jsx(
4214
+ TokenSelect,
4215
+ {
4216
+ title: "Pay with",
4217
+ chains: fundingChains,
4218
+ tokens: fundingTokens,
4219
+ balances: holdings.balances,
4220
+ optionStates,
4221
+ onBack: closeSelector,
4222
+ onPick: pickFunding
4223
+ }
4224
+ ) : /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: !wallet.account ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
3969
4225
  /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }),
3970
4226
  wallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
3971
4227
  ] }) : flow.status === "success" || flow.status === "pending" ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
@@ -4023,7 +4279,15 @@ function StableGeniePay(props) {
4023
4279
  flow.status === "ready" && !visibleRoutes.length ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { children: "No funding route matches the accepted assets for this payment." }) : null
4024
4280
  ] }),
4025
4281
  submitting ? /* @__PURE__ */ jsxRuntime.jsx(StepList, { steps: flow.steps }) : null,
4026
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cta-wrap", children: /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: parked || !selectedVisible ? void 0 : flow.submit, busy: submitting, disabled: parked || !selectedVisible || flow.insufficient || !!flow.nativeShortfall || flow.status === "loading", children: payLabel }) })
4282
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cta-wrap", children: /* @__PURE__ */ jsxRuntime.jsx(
4283
+ Button,
4284
+ {
4285
+ onClick: parked || !selectedVisible ? void 0 : flow.submit,
4286
+ busy: submitting,
4287
+ disabled: parked || !selectedVisible || flow.insufficient || !!flow.nativeShortfall || flow.status === "loading",
4288
+ children: payLabel
4289
+ }
4290
+ ) })
4027
4291
  ] }) }) });
4028
4292
  }
4029
4293
  var chainOptions = SUPPORTED_CHAINS.map((c) => ({ value: c, label: CHAIN_LABELS[c] || `Chain ${c}` }));
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- export { B as BankPayoutAccount, E as Eip1193Provider, a as ExchangeMode, L as LinkIdentity, M as MountConfig, P as PaymentIsland, b as PaymentIslandKind, c as PaymentIslandProps, S as SettlementMethod, d as StableGenieConfig, e as StableGenieExchange, f as StableGenieExchangeProps, g as StableGeniePay, h as StableGeniePayProps, i as StableGenieProvider, j as StableGenieSwap, k as StableGenieSwapProps, l as StableGenieTheme, m as SuccessInfo, n as SupportedAsset, o as darkTheme, p as lightTheme, q as mount, r as resolveTheme } from './mount-yqXrDBLc.cjs';
1
+ export { B as BankPayoutAccount, E as Eip1193Provider, a as ExchangeMode, L as LinkIdentity, M as MountConfig, P as PaymentIsland, b as PaymentIslandKind, c as PaymentIslandProps, S as SettlementMethod, d as StableGenieConfig, e as StableGenieExchange, f as StableGenieExchangeProps, g as StableGeniePay, h as StableGeniePayProps, i as StableGenieProvider, j as StableGenieSwap, k as StableGenieSwapProps, l as StableGenieTheme, m as SuccessInfo, n as SupportedAsset, o as darkTheme, p as lightTheme, q as mount, r as resolveTheme } from './mount-BC5gY1X6.cjs';
2
2
  export { Engine, createEngine } from './core/index.cjs';
3
- export { E as EngineConfig, P as Plan, R as RouteResult, S as SanitizedTxEntry, T as TxHistoryEntry, V as VerifyResult } from './verify-CaO0OD4Z.cjs';
3
+ export { E as EngineConfig, P as Plan, R as RouteResult, S as SanitizedTxEntry, T as TxHistoryEntry, V as VerifyResult } from './verify-DFTuQ2g3.cjs';
4
4
  import 'react';
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { B as BankPayoutAccount, E as Eip1193Provider, a as ExchangeMode, L as LinkIdentity, M as MountConfig, P as PaymentIsland, b as PaymentIslandKind, c as PaymentIslandProps, S as SettlementMethod, d as StableGenieConfig, e as StableGenieExchange, f as StableGenieExchangeProps, g as StableGeniePay, h as StableGeniePayProps, i as StableGenieProvider, j as StableGenieSwap, k as StableGenieSwapProps, l as StableGenieTheme, m as SuccessInfo, n as SupportedAsset, o as darkTheme, p as lightTheme, q as mount, r as resolveTheme } from './mount-yTJi4VdA.js';
1
+ export { B as BankPayoutAccount, E as Eip1193Provider, a as ExchangeMode, L as LinkIdentity, M as MountConfig, P as PaymentIsland, b as PaymentIslandKind, c as PaymentIslandProps, S as SettlementMethod, d as StableGenieConfig, e as StableGenieExchange, f as StableGenieExchangeProps, g as StableGeniePay, h as StableGeniePayProps, i as StableGenieProvider, j as StableGenieSwap, k as StableGenieSwapProps, l as StableGenieTheme, m as SuccessInfo, n as SupportedAsset, o as darkTheme, p as lightTheme, q as mount, r as resolveTheme } from './mount-8nchcNbL.js';
2
2
  export { Engine, createEngine } from './core/index.js';
3
- export { E as EngineConfig, P as Plan, R as RouteResult, S as SanitizedTxEntry, T as TxHistoryEntry, V as VerifyResult } from './verify-CaO0OD4Z.js';
3
+ export { E as EngineConfig, P as Plan, R as RouteResult, S as SanitizedTxEntry, T as TxHistoryEntry, V as VerifyResult } from './verify-DFTuQ2g3.js';
4
4
  import 'react';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { PaymentIsland, StableGenieExchange, StableGeniePay, StableGenieProvider, StableGenieSwap, darkTheme, lightTheme, mount, resolveTheme } from './chunk-DH7QYQG4.js';
2
- export { createEngine } from './chunk-VL5MWEY2.js';
1
+ export { PaymentIsland, StableGenieExchange, StableGeniePay, StableGenieProvider, StableGenieSwap, darkTheme, lightTheme, mount, resolveTheme } from './chunk-TR2XMP7X.js';
2
+ export { createEngine } from './chunk-AZPTL3KD.js';
@@ -1,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { P as Plan, V as VerifyResult, R as RouteResult, S as SanitizedTxEntry } from './verify-CaO0OD4Z.js';
3
+ import { P as Plan, V as VerifyResult, R as RouteResult, S as SanitizedTxEntry } from './verify-DFTuQ2g3.js';
4
4
 
5
5
  interface Eip1193Provider {
6
6
  request(args: {
@@ -1,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { P as Plan, V as VerifyResult, R as RouteResult, S as SanitizedTxEntry } from './verify-CaO0OD4Z.cjs';
3
+ import { P as Plan, V as VerifyResult, R as RouteResult, S as SanitizedTxEntry } from './verify-DFTuQ2g3.cjs';
4
4
 
5
5
  interface Eip1193Provider {
6
6
  request(args: {