@glacislabs/stablegenie-zerodelta 3.0.1 → 3.1.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/dist/index.cjs CHANGED
@@ -16,13 +16,14 @@ function useMergedConfig(local) {
16
16
 
17
17
  // src/core/constants.ts
18
18
  var DEFAULT_WIDGET_API_BASE = "/api/widget/v1";
19
- var SUPPORTED_CHAIN_IDS = /* @__PURE__ */ new Set([1, 10, 42161, 8453, 57073, 130, 9745, 146]);
19
+ var SUPPORTED_CHAIN_IDS = /* @__PURE__ */ new Set([1, 10, 42161, 8453, 57073, 130, 9745, 146, 98866]);
20
20
  var SUPPORTED_ASSETS = /* @__PURE__ */ new Set(["USDC", "USDT", "USDE", "XAUT"]);
21
21
  var API_CACHE_TTL_MS = 6e4;
22
22
  var MAX_QUOTE_CANDIDATES = 8;
23
23
  var QUOTE_BUFFER_BPS = 50;
24
24
  var LZ_FEE_BUFFER_BPS = 1500n;
25
- var SUBMIT_ORDER_SELECTOR = "0xbbd71141";
25
+ var SUBMIT_ORDER_SELECTOR = "0xaf439ecd";
26
+ var NO_PARTNER_ID = `0x${"0".repeat(64)}`;
26
27
  var ERC20_APPROVE_SELECTOR = "0x095ea7b3";
27
28
  var ERC20_TRANSFER_SELECTOR = "0xa9059cbb";
28
29
  var ERC20_ALLOWANCE_SELECTOR = "0xdd62ed3e";
@@ -31,22 +32,24 @@ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
31
32
  var PREVIEW_OWNER = "0x1111111111111111111111111111111111111111";
32
33
  var CANONICAL_DECIMALS = { USDC: 6, USDT: 6, USDE: 18, XAUT: 6 };
33
34
  var CANONICAL_ESCROW = Object.freeze({
34
- 1: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
35
- // Ethereum — impl 0x49d173C4AbC90B3665D691f1FF2064eb9732A743
36
- 10: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
37
- // Optimism — impl 0xB47eCBa71039694D28E76C482aC2bE34d5faC22A
38
- 130: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
39
- // Unichain — impl 0xA9B1bBF52EF242aa4b9a8018bfD48fe64BbDfD03
40
- 146: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
41
- // Sonic — impl 0x4c66dECff081Cf282af4C7f9CA436CB7b46A700d
42
- 8453: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
43
- // Base — impl 0x70E37bF2c258015DAB7FE26942185D0362ebEd46
44
- 9745: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
45
- // Plasma — impl 0x70168A99722f3041ceff211C4E505e8732ee965D
46
- 57073: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
47
- // Ink — impl 0x8A9e68864f476DA577e948cb61Cedffe7e17b562
48
- 42161: "0x46A3219c357C2E50129d4839058FCFD421789aE7"
49
- // Arbitrum — impl 0x453B00aeB8c7dDBaff10f2812A0bA7dc88DdbC35
35
+ 1: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
36
+ // Ethereum
37
+ 10: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
38
+ // Optimism
39
+ 130: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
40
+ // Unichain
41
+ 146: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
42
+ // Sonic
43
+ 8453: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
44
+ // Base
45
+ 9745: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
46
+ // Plasma
47
+ 57073: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
48
+ // Ink
49
+ 42161: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
50
+ // Arbitrum
51
+ 98866: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40"
52
+ // Plume
50
53
  });
51
54
  var MAX_LZ_MSG_VALUE_WEI = 10n ** 18n;
52
55
  var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {};
@@ -68,7 +71,8 @@ var BUNDLED_NATIVE_SYMBOL = {
68
71
  146: "S",
69
72
  8453: "ETH",
70
73
  57073: "ETH",
71
- 42161: "ETH"
74
+ 42161: "ETH",
75
+ 98866: "PLUME"
72
76
  };
73
77
  var BUNDLED_RPC = {
74
78
  1: "https://ethereum-rpc.publicnode.com",
@@ -78,7 +82,8 @@ var BUNDLED_RPC = {
78
82
  8453: "https://mainnet.base.org",
79
83
  9745: "https://rpc.plasma.to",
80
84
  57073: "https://rpc-gel.inkonchain.com",
81
- 42161: "https://arb1.arbitrum.io/rpc"
85
+ 42161: "https://arb1.arbitrum.io/rpc",
86
+ 98866: "https://rpc.plume.org"
82
87
  };
83
88
 
84
89
  // src/core/address.ts
@@ -170,13 +175,25 @@ function uintWord(value) {
170
175
  if (hex.length > 64) throw new Error("uint256 value is too large.");
171
176
  return hex.padStart(64, "0");
172
177
  }
178
+ var MAX_UINT64 = (1n << 64n) - 1n;
179
+ function uint64Word(value) {
180
+ const n = BigInt(value || 0);
181
+ if (n < 0n) throw new Error("Cannot encode a negative uint64.");
182
+ if (n > MAX_UINT64) throw new Error("uint64 value is too large.");
183
+ return n.toString(16).padStart(64, "0");
184
+ }
185
+ function bytes32Word(value) {
186
+ const hex = strip0x(value);
187
+ if (!/^[a-fA-F0-9]{64}$/.test(hex)) throw new Error("bytes32 value must be exactly 32 bytes of hex.");
188
+ return hex.toLowerCase();
189
+ }
173
190
  function addressWord(address) {
174
191
  return strip0x(assertAddress(address, "Address")).padStart(64, "0");
175
192
  }
176
193
  function bytesPayload(value) {
177
- const hex = strip0x(value);
178
- if (hex.length % 2) throw new Error("Order data has an odd-length hex payload; refusing to encode.");
179
- if (!/^[a-fA-F0-9]*$/.test(hex)) throw new Error("Order data is not valid hex.");
194
+ const hex = strip0x(value || "0x");
195
+ if (hex.length % 2) throw new Error("Bytes payload has an odd-length hex value; refusing to encode.");
196
+ if (!/^[a-fA-F0-9]*$/.test(hex)) throw new Error("Bytes payload is not valid hex.");
180
197
  const byteLength = hex.length / 2;
181
198
  const paddedLength = Math.ceil(hex.length / 64) * 64;
182
199
  return `${uintWord(byteLength)}${hex.padEnd(paddedLength, "0")}`;
@@ -193,19 +210,96 @@ function encodeAllowance(owner, spender) {
193
210
  function encodeBalanceOf(account) {
194
211
  return `${ERC20_BALANCEOF_SELECTOR}${addressWord(account)}`;
195
212
  }
196
- function encodeSubmitOrder(order) {
197
- const tupleHead = [
213
+ var ORDER_HEAD_WORDS = 9n;
214
+ var ORDER_HEAD_BYTES = ORDER_HEAD_WORDS * 32n;
215
+ function encodeOrderTuple(order) {
216
+ const askToken = bytesPayload(order.askToken);
217
+ const receiver = bytesPayload(order.destinationReceiver);
218
+ const receiverOffset = ORDER_HEAD_BYTES + BigInt(askToken.length / 2);
219
+ const head = [
198
220
  addressWord(order.owner),
199
221
  addressWord(order.bidToken),
200
222
  uintWord(order.bidTokenAmount),
201
- addressWord(order.askToken),
223
+ uintWord(ORDER_HEAD_BYTES),
202
224
  uintWord(order.askTokenAmount),
203
- addressWord(order.destinationReceiver),
204
- uintWord(order.destinationChainId),
205
- uintWord(order.deadline),
206
- uintWord(9n * 32n)
225
+ uintWord(receiverOffset),
226
+ uint64Word(order.destinationChainId),
227
+ uint64Word(order.executionChainId),
228
+ uint64Word(order.deadline)
207
229
  ].join("");
208
- return `0x${SUBMIT_ORDER_SELECTOR.slice(2)}${uintWord(32)}${tupleHead}${bytesPayload(order.data)}`;
230
+ return `${head}${askToken}${receiver}`;
231
+ }
232
+ function encodeSubmitOrder(orders, partnerId = NO_PARTNER_ID) {
233
+ if (!orders.length) throw new Error("Cannot encode an empty order request array.");
234
+ const tuples = orders.map(encodeOrderTuple);
235
+ let offset = 32n * BigInt(tuples.length);
236
+ const offsets = tuples.map((tuple) => {
237
+ const word = uintWord(offset);
238
+ offset += BigInt(tuple.length / 2);
239
+ return word;
240
+ }).join("");
241
+ return `0x${SUBMIT_ORDER_SELECTOR.slice(2)}${uintWord(64)}${bytes32Word(partnerId)}${uintWord(tuples.length)}${offsets}${tuples.join("")}`;
242
+ }
243
+ var EVM_BYTES_PAYLOAD_BYTES = 64;
244
+ var EVM_ORDER_TUPLE_BYTES = Number(ORDER_HEAD_BYTES) + 2 * EVM_BYTES_PAYLOAD_BYTES;
245
+ var MAX_DECODED_ORDERS = 16;
246
+ function decodeSubmitOrderCalldata(data) {
247
+ const hex = strip0x(String(data || "")).toLowerCase();
248
+ if (hex.length < 8 || hex.length % 2 !== 0 || !/^[a-f0-9]*$/.test(hex)) return null;
249
+ if (`0x${hex.slice(0, 8)}` !== SUBMIT_ORDER_SELECTOR) return null;
250
+ const body = hex.slice(8);
251
+ const totalBytes = body.length / 2;
252
+ const word = (byteOffset) => {
253
+ if (!Number.isSafeInteger(byteOffset) || byteOffset < 0 || byteOffset + 32 > totalBytes) return null;
254
+ return BigInt(`0x${body.slice(byteOffset * 2, byteOffset * 2 + 64)}`);
255
+ };
256
+ const addressAt = (byteOffset) => {
257
+ const w = word(byteOffset);
258
+ if (w === null || w >= 1n << 160n) return null;
259
+ return `0x${w.toString(16).padStart(40, "0")}`;
260
+ };
261
+ const uint64At = (byteOffset) => {
262
+ const w = word(byteOffset);
263
+ return w === null || w > MAX_UINT64 ? null : w;
264
+ };
265
+ const evmBytesAt = (byteOffset) => {
266
+ const len = word(byteOffset);
267
+ if (len !== 20n) return null;
268
+ const content = body.slice((byteOffset + 32) * 2, (byteOffset + 64) * 2);
269
+ if (content.length !== 64 || !content.endsWith("0".repeat(24))) return null;
270
+ return `0x${content.slice(0, 40)}`;
271
+ };
272
+ if (word(0) !== 64n) return null;
273
+ if (word(32) === null) return null;
274
+ const partnerId = `0x${body.slice(64, 128)}`;
275
+ const count = word(64);
276
+ if (count === null || count < 1n || count > BigInt(MAX_DECODED_ORDERS)) return null;
277
+ const n = Number(count);
278
+ const arrayBase = 96;
279
+ if (totalBytes !== arrayBase + 32 * n + EVM_ORDER_TUPLE_BYTES * n) return null;
280
+ const orders = [];
281
+ for (let i = 0; i < n; i += 1) {
282
+ const rel = word(arrayBase + i * 32);
283
+ if (rel === null || rel !== BigInt(32 * n + EVM_ORDER_TUPLE_BYTES * i)) return null;
284
+ const base = arrayBase + Number(rel);
285
+ const owner = addressAt(base);
286
+ const bidToken = addressAt(base + 32);
287
+ const bidTokenAmount = word(base + 64);
288
+ const askOffset = word(base + 96);
289
+ const askTokenAmount = word(base + 128);
290
+ const receiverOffset = word(base + 160);
291
+ const destinationChainId = uint64At(base + 192);
292
+ const executionChainId = uint64At(base + 224);
293
+ const deadline = uint64At(base + 256);
294
+ if (owner === null || bidToken === null || bidTokenAmount === null || askTokenAmount === null || destinationChainId === null || executionChainId === null || deadline === null || askOffset !== ORDER_HEAD_BYTES || receiverOffset !== ORDER_HEAD_BYTES + BigInt(EVM_BYTES_PAYLOAD_BYTES)) {
295
+ return null;
296
+ }
297
+ const askToken = evmBytesAt(base + Number(askOffset));
298
+ const destinationReceiver = evmBytesAt(base + Number(receiverOffset));
299
+ if (askToken === null || destinationReceiver === null) return null;
300
+ orders.push({ owner, bidToken, bidTokenAmount, askToken, askTokenAmount, destinationReceiver, destinationChainId, executionChainId, deadline });
301
+ }
302
+ return { partnerId, orders };
209
303
  }
210
304
  function toHexQuantity(value) {
211
305
  const n = BigInt(value || 0);
@@ -396,7 +490,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
396
490
  estimatedDuration: 0,
397
491
  gasCostSource: "0",
398
492
  gasCostDest: "0",
399
- orderRequest: null
493
+ orderRequests: null
400
494
  },
401
495
  youPayRaw: targetRaw.toString(),
402
496
  recipientReceivesRaw: targetRaw.toString(),
@@ -508,9 +602,13 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
508
602
  }
509
603
 
510
604
  // src/core/order.ts
511
- function normalizeOrderRequest(order, payer, destination) {
605
+ var DEFAULT_DEADLINE_SECONDS = 1800;
606
+ var MAX_DEADLINE_SECONDS = 60 * 60;
607
+ function normalizeOrderRequest(order, payer, destination, fallbackExecutionChainId, deadlineOverride) {
512
608
  const apiDeadline = Number(order.deadline);
513
- const deadline = Number.isFinite(apiDeadline) && apiDeadline > 0 ? String(order.deadline) : String(Math.floor(Date.now() / 1e3) + 1800);
609
+ const deadline = deadlineOverride ?? (Number.isFinite(apiDeadline) && apiDeadline > 0 ? String(order.deadline) : String(Math.floor(Date.now() / 1e3) + DEFAULT_DEADLINE_SECONDS));
610
+ const executionChainId = String(order.executionChainId || fallbackExecutionChainId || "0");
611
+ if (!/^\d+$/.test(executionChainId) || BigInt(executionChainId) <= 0n) throw new Error("ZeroDelta quote did not include an execution chain.");
514
612
  return {
515
613
  owner: assertAddress(order.owner || payer, "Order owner"),
516
614
  bidToken: assertAddress(order.bidToken, "Bid token"),
@@ -519,26 +617,40 @@ function normalizeOrderRequest(order, payer, destination) {
519
617
  askTokenAmount: String(order.askTokenAmount || "0"),
520
618
  destinationReceiver: assertAddress(order.destinationReceiver || destination.address, "Destination receiver"),
521
619
  destinationChainId: String(order.destinationChainId || destination.chainId),
522
- deadline,
523
- data: order.data || "0x"
620
+ executionChainId,
621
+ deadline
524
622
  };
525
623
  }
526
- function assertQuoteMatchesSelection({ quote, order, option, destinationToken, destination, payer, result }) {
624
+ function normalizeOrderRequests(requests, payer, destination, fallbackExecutionChainId) {
625
+ if (!requests.length) throw new Error("ZeroDelta quote did not include any order requests.");
626
+ return requests.map(
627
+ (request, index) => index === 0 ? normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId) : normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, String(request.deadline || "0"))
628
+ );
629
+ }
630
+ function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result }) {
631
+ const list = orders?.length ? orders : [order];
632
+ const sourceOrder = list[0];
633
+ const finalOrder = list[list.length - 1];
527
634
  const now = Math.floor(Date.now() / 1e3);
528
- const deadline = Number(order.deadline || 0);
529
- if (normalizeAddress(order.owner) !== normalizeAddress(payer)) {
530
- throw new Error("ZeroDelta quote returned an owner that does not match the connected wallet.");
531
- }
532
- if (normalizeAddress(order.destinationReceiver) !== normalizeAddress(destination.address)) {
533
- throw new Error("ZeroDelta quote returned a receiver that does not match the detected destination.");
635
+ const deadline = Number(sourceOrder.deadline || 0);
636
+ for (const current of list) {
637
+ if (normalizeAddress(current.owner) !== normalizeAddress(payer)) {
638
+ throw new Error("ZeroDelta quote returned an owner that does not match the connected wallet.");
639
+ }
640
+ if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(destination.address)) {
641
+ throw new Error("ZeroDelta quote returned a receiver that does not match the detected destination.");
642
+ }
643
+ if (!/^\d+$/.test(current.executionChainId || "") || BigInt(current.executionChainId) <= 0n) {
644
+ throw new Error("ZeroDelta quote returned an order without an execution chain.");
645
+ }
534
646
  }
535
- if (normalizeAddress(order.bidToken) !== normalizeAddress(option.address)) {
647
+ if (normalizeAddress(sourceOrder.bidToken) !== normalizeAddress(option.address)) {
536
648
  throw new Error("ZeroDelta quote returned a bid token that does not match the selected route.");
537
649
  }
538
- if (normalizeAddress(order.askToken) !== normalizeAddress(destinationToken.address)) {
650
+ if (normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
539
651
  throw new Error("ZeroDelta quote returned an ask token that does not match the destination asset.");
540
652
  }
541
- if (Number(order.destinationChainId) !== Number(destination.chainId) || Number(quote.toChainId) !== Number(destination.chainId)) {
653
+ if (Number(finalOrder.destinationChainId) !== Number(destination.chainId) || Number(quote.toChainId) !== Number(destination.chainId)) {
542
654
  throw new Error("ZeroDelta quote returned a destination chain that does not match the payment request.");
543
655
  }
544
656
  if (Number(quote.fromChainId) !== Number(option.chainId)) {
@@ -547,24 +659,38 @@ function assertQuoteMatchesSelection({ quote, order, option, destinationToken, d
547
659
  if (symbolKey(quote.fromToken) !== option.symbolKey || symbolKey(quote.toToken) !== symbolKey(destinationToken.symbol)) {
548
660
  throw new Error("ZeroDelta quote returned token symbols that do not match the selected route.");
549
661
  }
550
- if (BigInt(order.bidTokenAmount || "0") !== BigInt(result.youPayRaw || "0")) {
662
+ if (BigInt(sourceOrder.bidTokenAmount || "0") !== BigInt(result.youPayRaw || "0")) {
551
663
  throw new Error("ZeroDelta quote returned a bid amount that does not match the displayed payment amount.");
552
664
  }
553
- if (BigInt(order.askTokenAmount || "0") !== BigInt(quote.toAmount || "0")) {
665
+ if (BigInt(finalOrder.askTokenAmount || "0") !== BigInt(quote.toAmount || "0")) {
554
666
  throw new Error("ZeroDelta quote returned an ask amount that does not match the quoted output.");
555
667
  }
556
- if (BigInt(order.askTokenAmount || "0") <= 0n || BigInt(quote.toAmount || "0") <= 0n) {
668
+ if (BigInt(finalOrder.askTokenAmount || "0") <= 0n || BigInt(quote.toAmount || "0") <= 0n) {
557
669
  throw new Error("ZeroDelta quote returned a non-positive output amount.");
558
670
  }
559
- if (BigInt(order.askTokenAmount || "0") < BigInt(result.targetRaw || "0")) {
671
+ if (BigInt(finalOrder.askTokenAmount || "0") < BigInt(result.targetRaw || "0")) {
560
672
  throw new Error("ZeroDelta quote would not cover the requested destination amount.");
561
673
  }
562
- if (BigInt(order.askTokenAmount || "0") < BigInt(result.recipientReceivesRaw || "0")) {
674
+ if (BigInt(finalOrder.askTokenAmount || "0") < BigInt(result.recipientReceivesRaw || "0")) {
563
675
  throw new Error("ZeroDelta order guarantees less than the displayed receive amount.");
564
676
  }
565
- if (!Number.isFinite(deadline) || deadline <= now || deadline > now + 60 * 60) {
677
+ if (!Number.isFinite(deadline) || deadline <= now || deadline > now + MAX_DEADLINE_SECONDS) {
566
678
  throw new Error("ZeroDelta quote deadline is invalid or too far in the future.");
567
679
  }
680
+ for (let index = 1; index < list.length; index += 1) {
681
+ const previous = list[index - 1];
682
+ const current = list[index];
683
+ if (normalizeAddress(previous.askToken) !== normalizeAddress(current.bidToken)) {
684
+ throw new Error("ZeroDelta chained quote returned disconnected order tokens.");
685
+ }
686
+ if (Number(previous.destinationChainId) !== Number(current.executionChainId)) {
687
+ throw new Error("ZeroDelta chained quote returned disconnected execution chains.");
688
+ }
689
+ const followupDeadline = Number(current.deadline || 0);
690
+ if (followupDeadline !== 0 && (!Number.isFinite(followupDeadline) || followupDeadline <= now || followupDeadline > now + MAX_DEADLINE_SECONDS)) {
691
+ throw new Error("ZeroDelta chained quote returned an invalid follow-up deadline.");
692
+ }
693
+ }
568
694
  }
569
695
 
570
696
  // src/core/route.ts
@@ -631,11 +757,13 @@ async function buildRoute({ option, destination, destinationToken, chains, payer
631
757
  }
632
758
  };
633
759
  }
634
- if (!quote.orderRequest) throw new Error("ZeroDelta quote did not include an order request.");
760
+ const requestList = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
761
+ if (!requestList.length) throw new Error("ZeroDelta quote did not include an order request.");
635
762
  const sourceChain = chainById(chains, option.chainId);
636
763
  const escrow = checkEscrow(option.chainId, quote.escrowAddress, sourceChain?.escrowContract);
637
- const order = normalizeOrderRequest(quote.orderRequest, payer, destination);
638
- assertQuoteMatchesSelection({ quote, order, option, destinationToken, destination, payer, result });
764
+ const orders = normalizeOrderRequests(requestList, payer, destination, quote.executionChainId);
765
+ const order = orders[0];
766
+ assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result });
639
767
  const needsNativeFee = requiresNativeBridgeFee(quote, option);
640
768
  if (needsNativeFee) {
641
769
  let rawFee;
@@ -696,7 +824,7 @@ async function buildRoute({ option, destination, destinationToken, chains, payer
696
824
  label: "Submit ZeroDelta order",
697
825
  chainId: option.chainId,
698
826
  to: escrow,
699
- data: encodeSubmitOrder(order),
827
+ data: encodeSubmitOrder(orders),
700
828
  value: toHexQuantity(valueRaw),
701
829
  escrow,
702
830
  amountRaw: order.bidTokenAmount
@@ -872,6 +1000,16 @@ function createApiClient(cfg) {
872
1000
  }
873
1001
 
874
1002
  // src/core/plan.ts
1003
+ function optionBalanceKey(option) {
1004
+ return `${Number(option.chainId)}:${String(option.address || "").toLowerCase()}`;
1005
+ }
1006
+ function hasPositiveBalance(option, balances) {
1007
+ try {
1008
+ return BigInt(balances[optionBalanceKey(option)]?.raw ?? "0") > 0n;
1009
+ } catch {
1010
+ return false;
1011
+ }
1012
+ }
875
1013
  function validateDestination(destination) {
876
1014
  assertAddress(destination.address, "Destination address");
877
1015
  const chainId = Number(destination.chainId);
@@ -887,7 +1025,7 @@ function planErrorSummary(errors) {
887
1025
  const unique = [...new Set(errors.map((error) => error?.message || String(error)).filter(Boolean))].slice(0, 3);
888
1026
  return unique.length ? unique.join(" | ") : "No ZeroDelta route is currently available for this payment.";
889
1027
  }
890
- async function fetchPaymentPlan(api, request, payer, wallet = {}) {
1028
+ async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances) {
891
1029
  validateDestination(request);
892
1030
  assertAddress(payer, "Payer wallet");
893
1031
  const [chains, tokens, routes] = await Promise.all([api.fetchChains(), api.fetchTokens(), api.fetchRoutes()]);
@@ -898,6 +1036,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}) {
898
1036
  };
899
1037
  const destinationToken = findToken(tokens, destination.chainId, destination.asset);
900
1038
  if (!destinationToken) throw new Error(`${destination.asset} is not enabled on ${chainNameOf(destination.chainId, chains)}.`);
1039
+ const allowedFunding = wallet.fundingAssets?.length ? new Set(wallet.fundingAssets.map(symbolKey)) : null;
901
1040
  const options = buildPayOptions({
902
1041
  invoiceAsset: destination.asset,
903
1042
  invoiceChainId: destination.chainId,
@@ -905,14 +1044,25 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}) {
905
1044
  routes,
906
1045
  chains,
907
1046
  walletChainId: wallet?.chainId
908
- });
1047
+ }).filter((option) => option.direct || !allowedFunding || allowedFunding.has(option.symbolKey));
909
1048
  if (!options.length) throw new Error(`No enabled ZeroDelta funding assets can settle ${destination.asset} on ${chainNameOf(destination.chainId, chains)}.`);
1049
+ const balanceTargets = [];
1050
+ const seenTargets = /* @__PURE__ */ new Set();
1051
+ for (const option of options) {
1052
+ const key = optionBalanceKey(option);
1053
+ if (seenTargets.has(key)) continue;
1054
+ seenTargets.add(key);
1055
+ balanceTargets.push({ chainId: option.chainId, tokenAddress: option.address, decimals: option.decimals });
1056
+ }
1057
+ const walletBalances = readBalances ? await readBalances(payer, balanceTargets).catch(() => ({})) : {};
910
1058
  const candidates = options.filter((option) => option.direct);
1059
+ const heldOptions = options.filter((option) => !option.direct && hasPositiveBalance(option, walletBalances));
1060
+ const heldKeys = new Set(heldOptions.map(optionBalanceKey));
911
1061
  const seenChains = /* @__PURE__ */ new Set();
912
1062
  const perChainBest = [];
913
1063
  const leftovers = [];
914
1064
  for (const option of options) {
915
- if (option.direct) continue;
1065
+ if (option.direct || heldKeys.has(optionBalanceKey(option))) continue;
916
1066
  if (seenChains.has(option.chainId)) {
917
1067
  leftovers.push(option);
918
1068
  } else {
@@ -920,7 +1070,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}) {
920
1070
  perChainBest.push(option);
921
1071
  }
922
1072
  }
923
- for (const option of [...perChainBest, ...leftovers].slice(0, MAX_QUOTE_CANDIDATES)) {
1073
+ for (const option of [...heldOptions, ...perChainBest, ...leftovers].slice(0, MAX_QUOTE_CANDIDATES)) {
924
1074
  candidates.push(option);
925
1075
  }
926
1076
  const routeErrors = [];
@@ -955,6 +1105,8 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}) {
955
1105
  expiresAt: new Date(Date.now() + 2 * 60 * 1e3).toISOString(),
956
1106
  apiBase: api.apiBase,
957
1107
  routes: routesBuilt,
1108
+ fundingBalances: walletBalances,
1109
+ fundingAccount: payer.toLowerCase(),
958
1110
  destination: {
959
1111
  asset: destinationToken.symbol,
960
1112
  chainId: destination.chainId,
@@ -1112,7 +1264,12 @@ function validatePlannedTransaction(tx, route, expectedRecipient) {
1112
1264
  if (tx.kind === "submitOrder") {
1113
1265
  const expected = planMsgValueHex(route);
1114
1266
  if (expected === null || value !== lower(expected)) return false;
1115
- return selector === "0xbbd71141" && isHexAddress(tx.escrow) && lower(tx.to) === lower(tx.escrow);
1267
+ if (selector !== SUBMIT_ORDER_SELECTOR || !isHexAddress(tx.escrow) || lower(tx.to) !== lower(tx.escrow)) return false;
1268
+ const decoded = decodeSubmitOrderCalldata(data);
1269
+ if (!decoded) return false;
1270
+ const first = decoded.orders[0];
1271
+ const last = decoded.orders[decoded.orders.length - 1];
1272
+ return decoded.partnerId === NO_PARTNER_ID && lower(first.bidToken) === lower(route.source.tokenAddress) && rawEquals(first.bidTokenAmount, tx.amountRaw) && lower(last.askToken) === lower(route.receive.tokenAddress) && Number(last.destinationChainId) === Number(route.receive.chainId) && lower(last.destinationReceiver) === lower(expectedRecipient);
1116
1273
  }
1117
1274
  return false;
1118
1275
  }
@@ -1183,6 +1340,23 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
1183
1340
  const json = await response.json();
1184
1341
  return json?.result ?? null;
1185
1342
  }
1343
+ async function rpcBatchCall(rpcUrl, calls) {
1344
+ const response = await fetchImpl(rpcUrl, {
1345
+ method: "POST",
1346
+ headers: { "Content-Type": "application/json" },
1347
+ body: JSON.stringify(calls.map((call, index) => ({ jsonrpc: "2.0", id: index + 1, ...call }))),
1348
+ signal: AbortSignal.timeout(TX_VERIFY_FETCH_MS)
1349
+ });
1350
+ if (!response.ok) throw new Error(`RPC ${response.status}`);
1351
+ const json = await response.json();
1352
+ if (!Array.isArray(json)) throw new Error("RPC batch unsupported");
1353
+ const results = /* @__PURE__ */ new Map();
1354
+ for (const item of json) {
1355
+ const id = Number(item?.id);
1356
+ if (Number.isInteger(id) && Object.hasOwn(item || {}, "result")) results.set(id, item.result);
1357
+ }
1358
+ return results;
1359
+ }
1186
1360
  async function payerNonceBaseline(chainId, account) {
1187
1361
  if (!isAddress(account)) return null;
1188
1362
  const rpcUrl = await chainRpcUrl(chainId);
@@ -1249,25 +1423,54 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
1249
1423
  const out = {};
1250
1424
  if (!isAddress(account) || !Array.isArray(targets) || !targets.length) return out;
1251
1425
  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
- }
1426
+ const groups = /* @__PURE__ */ new Map();
1427
+ const seen = /* @__PURE__ */ new Set();
1428
+ for (const target of targets) {
1429
+ if (!target || !isAddress(target.tokenAddress)) continue;
1430
+ const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
1431
+ if (seen.has(key)) continue;
1432
+ seen.add(key);
1433
+ const chainId = Number(target.chainId);
1434
+ const group = groups.get(chainId) || [];
1435
+ group.push(target);
1436
+ groups.set(chainId, group);
1437
+ }
1438
+ function record(target, hex) {
1439
+ if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
1440
+ const raw = BigInt(hex || "0x0").toString();
1441
+ const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
1442
+ out[key] = { raw, formatted: formatUnits(raw, Number(target.decimals)) };
1443
+ return true;
1444
+ }
1445
+ async function readOne(rpcUrl, target) {
1446
+ try {
1447
+ const hex = await rpcCall(rpcUrl, "eth_call", [{ to: normalizeAddress(target.tokenAddress), data: encodeBalanceOf(owner) }, "latest"]);
1448
+ record(target, hex);
1449
+ } catch {
1268
1450
  }
1269
1451
  }
1270
- await Promise.all(Array.from({ length: Math.min(CONCURRENCY, targets.length) }, () => worker()));
1452
+ async function readGroup(chainId, group) {
1453
+ const rpcUrl = await balanceRpcUrl(chainId).catch(() => "");
1454
+ if (!rpcUrl) return;
1455
+ if (group.length === 1) return readOne(rpcUrl, group[0]);
1456
+ try {
1457
+ const results = await rpcBatchCall(
1458
+ rpcUrl,
1459
+ group.map((target) => ({
1460
+ method: "eth_call",
1461
+ params: [{ to: normalizeAddress(target.tokenAddress), data: encodeBalanceOf(owner) }, "latest"]
1462
+ }))
1463
+ );
1464
+ const missing = [];
1465
+ group.forEach((target, index) => {
1466
+ if (!record(target, results.get(index + 1))) missing.push(target);
1467
+ });
1468
+ await Promise.all(missing.map((target) => readOne(rpcUrl, target)));
1469
+ } catch {
1470
+ await Promise.all(group.map((target) => readOne(rpcUrl, target)));
1471
+ }
1472
+ }
1473
+ await Promise.all([...groups.entries()].map(([chainId, group]) => readGroup(chainId, group)));
1271
1474
  return out;
1272
1475
  }
1273
1476
  async function readNativeBalance(chainId, account) {
@@ -1369,7 +1572,7 @@ function createEngine(config = {}) {
1369
1572
  fetchTokens: api.fetchTokens,
1370
1573
  fetchRoutes: api.fetchRoutes,
1371
1574
  fetchQuote: api.fetchQuote,
1372
- fetchPaymentPlan: (request, payer, wallet) => fetchPaymentPlan(api, request, payer, wallet),
1575
+ fetchPaymentPlan: (request, payer, wallet) => fetchPaymentPlan(api, request, payer, wallet, verifier.readBalances),
1373
1576
  quoteSwapPreview: (swap, owner) => quoteSwapPreview(api, swap, owner),
1374
1577
  buildSwapPlan: (swap, payer, wallet) => buildSwapPlan(api, swap, payer, wallet),
1375
1578
  payerNonceBaseline: verifier.payerNonceBaseline,
@@ -1878,7 +2081,7 @@ function useFlow(args) {
1878
2081
  function balanceKey(chainId, tokenAddress) {
1879
2082
  return `${Number(chainId)}:${String(tokenAddress || "").toLowerCase()}`;
1880
2083
  }
1881
- function useHoldings(engine, account, routes) {
2084
+ function useHoldings(engine, account, routes, initialBalances) {
1882
2085
  const [balances, setBalances] = react.useState({});
1883
2086
  const [loading, setLoading] = react.useState(false);
1884
2087
  const reqId = react.useRef(0);
@@ -1903,19 +2106,32 @@ function useHoldings(engine, account, routes) {
1903
2106
  return;
1904
2107
  }
1905
2108
  const id = ++reqId.current;
2109
+ const seeded = {};
2110
+ const missing = [];
2111
+ for (const target of targets) {
2112
+ const key = balanceKey(target.chainId, target.tokenAddress);
2113
+ const balance = initialBalances?.[key];
2114
+ if (balance) seeded[key] = balance;
2115
+ else missing.push(target);
2116
+ }
2117
+ setBalances(seeded);
2118
+ if (!missing.length) {
2119
+ setLoading(false);
2120
+ return;
2121
+ }
1906
2122
  setLoading(true);
1907
2123
  (async () => {
1908
2124
  try {
1909
- const res = await engine.readBalances(account, targets);
2125
+ const res = await engine.readBalances(account, missing);
1910
2126
  if (id !== reqId.current) return;
1911
- setBalances(res);
2127
+ setBalances({ ...seeded, ...res });
1912
2128
  } catch {
1913
- if (id === reqId.current) setBalances({});
2129
+ if (id === reqId.current) setBalances(seeded);
1914
2130
  } finally {
1915
2131
  if (id === reqId.current) setLoading(false);
1916
2132
  }
1917
2133
  })();
1918
- }, [engine, account, targetsKey]);
2134
+ }, [engine, account, targetsKey, initialBalances]);
1919
2135
  return { balances, loading };
1920
2136
  }
1921
2137
 
@@ -2459,9 +2675,10 @@ var CHAIN_LABELS = {
2459
2675
  8453: "Base",
2460
2676
  9745: "Plasma",
2461
2677
  57073: "Ink",
2462
- 42161: "Arbitrum"
2678
+ 42161: "Arbitrum",
2679
+ 98866: "Plume"
2463
2680
  };
2464
- var SUPPORTED_CHAINS = [1, 10, 42161, 8453, 57073, 130, 9745, 146];
2681
+ var SUPPORTED_CHAINS = [1, 10, 42161, 8453, 57073, 130, 9745, 146, 98866];
2465
2682
  var SUPPORTED_ASSETS2 = ["USDC", "USDT", "USDE", "XAUT"];
2466
2683
  function Button(props) {
2467
2684
  const soft = !!props.softDisabled && !props.disabled;
@@ -2660,7 +2877,8 @@ var CHAIN_SHORT = {
2660
2877
  8453: "BASE",
2661
2878
  9745: "PLS",
2662
2879
  57073: "INK",
2663
- 42161: "ARB"
2880
+ 42161: "ARB",
2881
+ 98866: "PLM"
2664
2882
  };
2665
2883
  function isHttpsUrl(u) {
2666
2884
  return typeof u === "string" && /^https:\/\//i.test(u);
@@ -3054,7 +3272,21 @@ var addrEq = (a, b) => String(a || "").toLowerCase() === String(b || "").toLower
3054
3272
  var chainName = (id) => id != null ? CHAIN_LABELS[id] || `Chain ${id}` : "";
3055
3273
  var STABLES = /* @__PURE__ */ new Set(["USDC", "USDT", "USDE"]);
3056
3274
  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" }) });
3275
+ return /* @__PURE__ */ jsxRuntime.jsx(
3276
+ "svg",
3277
+ {
3278
+ width: "18",
3279
+ height: "18",
3280
+ viewBox: "0 0 24 24",
3281
+ fill: "none",
3282
+ stroke: "currentColor",
3283
+ strokeWidth: "2",
3284
+ strokeLinecap: "round",
3285
+ strokeLinejoin: "round",
3286
+ "aria-hidden": "true",
3287
+ children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M3 10h18M5 10v8M10 10v8M14 10v8M19 10v8M3 19h18M12 3 3 8h18Z" })
3288
+ }
3289
+ );
3058
3290
  }
3059
3291
  function MerchantBankPayout(props) {
3060
3292
  const bankName = props.account?.bankName?.trim() || "Bank account";
@@ -3081,25 +3313,81 @@ function MerchantBankPayout(props) {
3081
3313
  ] }) }) });
3082
3314
  }
3083
3315
  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" }) });
3316
+ return /* @__PURE__ */ jsxRuntime.jsx(
3317
+ "svg",
3318
+ {
3319
+ width: "20",
3320
+ height: "20",
3321
+ viewBox: "0 0 24 24",
3322
+ fill: "none",
3323
+ stroke: "currentColor",
3324
+ strokeWidth: "3",
3325
+ strokeLinecap: "round",
3326
+ strokeLinejoin: "round",
3327
+ "aria-hidden": "true",
3328
+ children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M20 6 9 17l-5-5" })
3329
+ }
3330
+ );
3085
3331
  }
3086
3332
  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
- ] });
3333
+ return /* @__PURE__ */ jsxRuntime.jsxs(
3334
+ "svg",
3335
+ {
3336
+ width: "14",
3337
+ height: "14",
3338
+ viewBox: "0 0 24 24",
3339
+ fill: "none",
3340
+ stroke: "currentColor",
3341
+ strokeWidth: "2.4",
3342
+ strokeLinecap: "round",
3343
+ strokeLinejoin: "round",
3344
+ "aria-hidden": "true",
3345
+ children: [
3346
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M5 12h14" }),
3347
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "m13 6 6 6-6 6" })
3348
+ ]
3349
+ }
3350
+ );
3091
3351
  }
3092
3352
  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
- ] });
3353
+ return /* @__PURE__ */ jsxRuntime.jsxs(
3354
+ "svg",
3355
+ {
3356
+ width: "20",
3357
+ height: "20",
3358
+ viewBox: "0 0 24 24",
3359
+ fill: "none",
3360
+ stroke: "currentColor",
3361
+ strokeWidth: "2.2",
3362
+ strokeLinecap: "round",
3363
+ strokeLinejoin: "round",
3364
+ "aria-hidden": "true",
3365
+ children: [
3366
+ /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "12", cy: "12", r: "9" }),
3367
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M12 7v5l3 2" })
3368
+ ]
3369
+ }
3370
+ );
3097
3371
  }
3098
3372
  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
- ] });
3373
+ return /* @__PURE__ */ jsxRuntime.jsxs(
3374
+ "svg",
3375
+ {
3376
+ width: "16",
3377
+ height: "16",
3378
+ viewBox: "0 0 24 24",
3379
+ fill: "none",
3380
+ stroke: "currentColor",
3381
+ strokeWidth: "2",
3382
+ strokeLinecap: "round",
3383
+ strokeLinejoin: "round",
3384
+ "aria-hidden": "true",
3385
+ children: [
3386
+ /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "3", y: "6", width: "18", height: "13", rx: "2" }),
3387
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M16 12h.01M3 9h18" })
3388
+ ]
3389
+ }
3390
+ );
3103
3391
  }
3104
3392
  function LinkMenu(props) {
3105
3393
  const [open, setOpen] = react.useState(false);
@@ -3210,7 +3498,13 @@ function IdentityLine(props) {
3210
3498
  function PaymentIsland(props) {
3211
3499
  injectStyles();
3212
3500
  const config = useMergedConfig(props);
3213
- const engine = useEngine({ apiBase: config.apiBase, apiKey: config.apiKey, trustedApiOrigin: config.trustedApiOrigin, rpcOverrides: config.rpcOverrides, onTransaction: config.onTransaction });
3501
+ const engine = useEngine({
3502
+ apiBase: config.apiBase,
3503
+ apiKey: config.apiKey,
3504
+ trustedApiOrigin: config.trustedApiOrigin,
3505
+ rpcOverrides: config.rpcOverrides,
3506
+ onTransaction: config.onTransaction
3507
+ });
3214
3508
  const wallet = useWallet(config.provider);
3215
3509
  const kind = props.kind;
3216
3510
  const isPay = kind === "pay";
@@ -3239,7 +3533,8 @@ function PaymentIsland(props) {
3239
3533
  const normEx = normalizeDecimalText(exAmount);
3240
3534
  const exAmountValid = /^\d+(\.\d+)?$/.test(normEx) && Number(normEx) > 0 && Number(normEx) <= 1e9;
3241
3535
  const exQuotable = !rampMode && exAmountValid && Boolean(exFromChainId && exFromAsset && exToChainId && exToAsset);
3242
- const payParamsKey = `pay|${props.recipient}|${props.toChainId}|${props.toAsset}|${props.amount}`;
3536
+ const payFundingAssets = props.fundingAssets?.length ? props.fundingAssets : ["USDC", "USDT", "USDE"];
3537
+ const payParamsKey = `pay|${props.recipient}|${props.toChainId}|${props.toAsset}|${props.amount}|${payFundingAssets.join(",")}`;
3243
3538
  const exParamsKey = `${kind}|${mode}|${exFromChainId}|${exFromAsset}|${exToChainId}|${exToAsset}|${normEx}|${props.recipient ?? ""}`;
3244
3539
  const flow = useFlow({
3245
3540
  engine,
@@ -3249,7 +3544,20 @@ function PaymentIsland(props) {
3249
3544
  // quote (and fire onQuote) for a payment whose CTA it never shows.
3250
3545
  enabled: isPay ? Boolean(props.recipient && props.amount) && !bankSettlement : exQuotable,
3251
3546
  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),
3547
+ loadPlan: isPay ? (e, payer, chainId) => e.fetchPaymentPlan({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, payer, {
3548
+ chainId,
3549
+ fundingAssets: payFundingAssets
3550
+ }) : (e, payer) => e.buildSwapPlan(
3551
+ {
3552
+ fromChainId: exFromChainId,
3553
+ toChainId: exToChainId,
3554
+ fromToken: exFromAsset,
3555
+ toToken: exToAsset,
3556
+ amountIn: normEx,
3557
+ recipient: props.recipient
3558
+ },
3559
+ payer
3560
+ ),
3253
3561
  recipientFor: (account) => isPay ? props.recipient : props.recipient || account,
3254
3562
  onQuote: config.onQuote,
3255
3563
  onSuccess: config.onSuccess,
@@ -3257,15 +3565,14 @@ function PaymentIsland(props) {
3257
3565
  });
3258
3566
  const [method, setMethod] = react.useState("stablecoin");
3259
3567
  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
- );
3568
+ const fundingSet = react.useMemo(() => props.fundingAssets?.length ? new Set(props.fundingAssets.map((a) => a.toUpperCase())) : null, [props.fundingAssets]);
3264
3569
  const visibleRoutes = react.useMemo(() => {
3265
3570
  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;
3571
+ return isPay && method === "stablecoin" ? base.filter((r) => STABLES.has(symbolKey(r.source.asset))) : base;
3267
3572
  }, [flow.routes, fundingSet, isPay, method]);
3268
- const holdings = useHoldings(engine, wallet.account, flow.routes);
3573
+ const paymentPlan = flow.plan;
3574
+ const prefetchedBalances = paymentPlan && paymentPlan.fundingAccount === wallet.account?.toLowerCase() ? paymentPlan.fundingBalances : void 0;
3575
+ const holdings = useHoldings(engine, wallet.account, flow.routes, prefetchedBalances);
3269
3576
  const annotated = react.useMemo(
3270
3577
  () => visibleRoutes.map((r) => {
3271
3578
  const balance = holdings.balances[balanceKey(r.source.chainId, r.source.tokenAddress)];
@@ -3360,7 +3667,15 @@ function PaymentIsland(props) {
3360
3667
  if (seen.has(key)) continue;
3361
3668
  seen.add(key);
3362
3669
  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 });
3670
+ list.push(
3671
+ reg ?? {
3672
+ symbol: r.source.asset,
3673
+ name: r.source.asset,
3674
+ chainId: r.source.chainId,
3675
+ address: r.source.tokenAddress ?? "",
3676
+ decimals: r.source.decimals ?? 18
3677
+ }
3678
+ );
3364
3679
  }
3365
3680
  return list;
3366
3681
  }, [visibleRoutes, registryTokens]);
@@ -3570,7 +3885,18 @@ function PaymentIsland(props) {
3570
3885
  if (hist && wallet.account) {
3571
3886
  body = /* @__PURE__ */ jsxRuntime.jsx(TxHistoryPanel, { account: wallet.account, tokens: registryTokens, initialEntry: hist.entry ?? null, onBack: closeHistory });
3572
3887
  } 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 });
3888
+ body = /* @__PURE__ */ jsxRuntime.jsx(
3889
+ TokenSelect,
3890
+ {
3891
+ title: "Pay with",
3892
+ chains: fundingChains,
3893
+ tokens: fundingTokens,
3894
+ balances: holdings.balances,
3895
+ optionStates,
3896
+ onBack: () => closeSelector(),
3897
+ onPick: pickFunding
3898
+ }
3899
+ );
3574
3900
  } else if (!isPay && (view === "from" || view === "to")) {
3575
3901
  const isFrom = view === "from";
3576
3902
  const openerRef = isFrom ? exFromTileRef : exToTileRef;
@@ -3770,22 +4096,66 @@ function PaymentIsland(props) {
3770
4096
  const islandVars = themeToVars(resolved);
3771
4097
  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
4098
  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 }) }) })
4099
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-island-reveal", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-island-reveal-inner", children: /* @__PURE__ */ jsxRuntime.jsx(
4100
+ "div",
4101
+ {
4102
+ className: "sg-island-body",
4103
+ id: panelId,
4104
+ ref: regionRef,
4105
+ role: "region",
4106
+ "aria-label": isPay ? "ZeroDelta Link checkout" : `ZeroDelta Link ${verb.present.toLowerCase()}`,
4107
+ tabIndex: -1,
4108
+ children: expanded ? /* @__PURE__ */ jsxRuntime.jsxs(
4109
+ WidgetShell,
4110
+ {
4111
+ variant: "express",
4112
+ title: "ZeroDelta Link",
4113
+ theme: config.theme,
4114
+ heightPx: props.heightPx,
4115
+ brandSlot,
4116
+ walletSlot,
4117
+ children: [
4118
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sg-sr-only", role: "status", "aria-live": "polite", children: liveMsg }),
4119
+ body
4120
+ ]
4121
+ }
4122
+ ) : null
4123
+ }
4124
+ ) }) })
3777
4125
  ] }) });
3778
4126
  }
3779
4127
  var STABLES2 = /* @__PURE__ */ new Set(["USDC", "USDT", "USDE"]);
4128
+ var DEFAULT_FUNDING_ASSETS = ["USDC", "USDT", "USDE"];
3780
4129
  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" }) });
4130
+ return /* @__PURE__ */ jsxRuntime.jsx(
4131
+ "svg",
4132
+ {
4133
+ width: "20",
4134
+ height: "20",
4135
+ viewBox: "0 0 24 24",
4136
+ fill: "none",
4137
+ stroke: "currentColor",
4138
+ strokeWidth: "3",
4139
+ strokeLinecap: "round",
4140
+ strokeLinejoin: "round",
4141
+ "aria-hidden": "true",
4142
+ children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M20 6 9 17l-5-5" })
4143
+ }
4144
+ );
3782
4145
  }
3783
4146
  var addrEq2 = (a, b) => String(a || "").toLowerCase() === String(b || "").toLowerCase();
3784
4147
  function StableGeniePay(props) {
3785
4148
  const config = useMergedConfig(props);
3786
- const engine = useEngine({ apiBase: config.apiBase, apiKey: config.apiKey, trustedApiOrigin: config.trustedApiOrigin, rpcOverrides: config.rpcOverrides, onTransaction: config.onTransaction });
4149
+ const engine = useEngine({
4150
+ apiBase: config.apiBase,
4151
+ apiKey: config.apiKey,
4152
+ trustedApiOrigin: config.trustedApiOrigin,
4153
+ rpcOverrides: config.rpcOverrides,
4154
+ onTransaction: config.onTransaction
4155
+ });
3787
4156
  const wallet = useWallet(config.provider);
3788
- const paramsKey = `${props.recipient}|${props.toChainId}|${props.toAsset}|${props.amount}`;
4157
+ const planFundingAssets = props.fundingAssets?.length ? props.fundingAssets : DEFAULT_FUNDING_ASSETS;
4158
+ const paramsKey = `${props.recipient}|${props.toChainId}|${props.toAsset}|${props.amount}|${planFundingAssets.join(",")}`;
3789
4159
  const flow = useFlow({
3790
4160
  engine,
3791
4161
  wallet,
@@ -3794,22 +4164,24 @@ function StableGeniePay(props) {
3794
4164
  // network work here, or every quote / balance read fires twice and onQuote/onError double-fire.
3795
4165
  enabled: Boolean(props.recipient && props.amount) && props.variant !== "pill",
3796
4166
  paramsKey,
3797
- loadPlan: (e, payer, chainId) => e.fetchPaymentPlan({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, payer, { chainId }),
4167
+ loadPlan: (e, payer, chainId) => e.fetchPaymentPlan({ address: props.recipient, chainId: props.toChainId, asset: props.toAsset, amount: props.amount }, payer, {
4168
+ chainId,
4169
+ fundingAssets: planFundingAssets
4170
+ }),
3798
4171
  recipientFor: () => props.recipient,
3799
4172
  onQuote: config.onQuote,
3800
4173
  onSuccess: config.onSuccess,
3801
4174
  onError: config.onError
3802
4175
  });
3803
4176
  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
- );
4177
+ const fundingSet = react.useMemo(() => props.fundingAssets?.length ? new Set(props.fundingAssets.map((a) => a.toUpperCase())) : null, [props.fundingAssets]);
3808
4178
  const visibleRoutes = react.useMemo(() => {
3809
4179
  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;
4180
+ return method === "stablecoin" ? base.filter((r) => STABLES2.has(symbolKey(r.source.asset))) : base;
3811
4181
  }, [flow.routes, method, fundingSet]);
3812
- const holdings = useHoldings(engine, wallet.account, flow.routes);
4182
+ const paymentPlan = flow.plan;
4183
+ const prefetchedBalances = paymentPlan && paymentPlan.fundingAccount === wallet.account?.toLowerCase() ? paymentPlan.fundingBalances : void 0;
4184
+ const holdings = useHoldings(engine, wallet.account, flow.routes, prefetchedBalances);
3813
4185
  const annotated = react.useMemo(
3814
4186
  () => visibleRoutes.map((r) => {
3815
4187
  const balance = holdings.balances[balanceKey(r.source.chainId, r.source.tokenAddress)];
@@ -3883,7 +4255,15 @@ function StableGeniePay(props) {
3883
4255
  if (seen.has(key)) continue;
3884
4256
  seen.add(key);
3885
4257
  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 });
4258
+ list.push(
4259
+ reg ?? {
4260
+ symbol: r.source.asset,
4261
+ name: r.source.asset,
4262
+ chainId: r.source.chainId,
4263
+ address: r.source.tokenAddress ?? "",
4264
+ decimals: r.source.decimals ?? 18
4265
+ }
4266
+ );
3887
4267
  }
3888
4268
  return list;
3889
4269
  }, [visibleRoutes, registryTokens]);
@@ -3965,7 +4345,18 @@ function StableGeniePay(props) {
3965
4345
  ] })
3966
4346
  ] }) : void 0;
3967
4347
  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: [
4348
+ 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(
4349
+ TokenSelect,
4350
+ {
4351
+ title: "Pay with",
4352
+ chains: fundingChains,
4353
+ tokens: fundingTokens,
4354
+ balances: holdings.balances,
4355
+ optionStates,
4356
+ onBack: closeSelector,
4357
+ onPick: pickFunding
4358
+ }
4359
+ ) : /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: !wallet.account ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "sg-cta-wrap", children: [
3969
4360
  /* @__PURE__ */ jsxRuntime.jsx(Button, { onClick: wallet.connect, busy: wallet.connecting, children: "Connect wallet" }),
3970
4361
  wallet.error ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { tone: "error", children: wallet.error }) : null
3971
4362
  ] }) : flow.status === "success" || flow.status === "pending" ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
@@ -4023,7 +4414,15 @@ function StableGeniePay(props) {
4023
4414
  flow.status === "ready" && !visibleRoutes.length ? /* @__PURE__ */ jsxRuntime.jsx(StatusPanel, { children: "No funding route matches the accepted assets for this payment." }) : null
4024
4415
  ] }),
4025
4416
  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 }) })
4417
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "sg-cta-wrap", children: /* @__PURE__ */ jsxRuntime.jsx(
4418
+ Button,
4419
+ {
4420
+ onClick: parked || !selectedVisible ? void 0 : flow.submit,
4421
+ busy: submitting,
4422
+ disabled: parked || !selectedVisible || flow.insufficient || !!flow.nativeShortfall || flow.status === "loading",
4423
+ children: payLabel
4424
+ }
4425
+ ) })
4027
4426
  ] }) }) });
4028
4427
  }
4029
4428
  var chainOptions = SUPPORTED_CHAINS.map((c) => ({ value: c, label: CHAIN_LABELS[c] || `Chain ${c}` }));