@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/README.md +1 -1
- package/dist/{chunk-DH7QYQG4.js → chunk-NSH3PT2J.js} +247 -51
- package/dist/{chunk-VL5MWEY2.js → chunk-OOURZ5DL.js} +283 -80
- package/dist/core/index.cjs +288 -79
- package/dist/core/index.d.cts +68 -13
- package/dist/core/index.d.ts +68 -13
- package/dist/core/index.js +1 -1
- package/dist/index.cjs +528 -129
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/{mount-yqXrDBLc.d.cts → mount-DNvmtX0y.d.cts} +1 -1
- package/dist/{mount-yTJi4VdA.d.ts → mount-jxrT-DMe.d.ts} +1 -1
- package/dist/mount.cjs +528 -129
- package/dist/mount.d.cts +2 -2
- package/dist/mount.d.ts +2 -2
- package/dist/mount.js +2 -2
- package/dist/standalone.global.js +8 -8
- package/dist/{verify-CaO0OD4Z.d.cts → verify-7lk90Ado.d.cts} +20 -4
- package/dist/{verify-CaO0OD4Z.d.ts → verify-7lk90Ado.d.ts} +20 -4
- package/package.json +2 -1
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
// src/core/constants.ts
|
|
2
2
|
var DEFAULT_WIDGET_API_BASE = "/api/widget/v1";
|
|
3
|
-
var SUPPORTED_CHAIN_IDS = /* @__PURE__ */ new Set([1, 10, 42161, 8453, 57073, 130, 9745, 146]);
|
|
3
|
+
var SUPPORTED_CHAIN_IDS = /* @__PURE__ */ new Set([1, 10, 42161, 8453, 57073, 130, 9745, 146, 98866]);
|
|
4
4
|
var SUPPORTED_ASSETS = /* @__PURE__ */ new Set(["USDC", "USDT", "USDE", "XAUT"]);
|
|
5
5
|
var API_CACHE_TTL_MS = 6e4;
|
|
6
6
|
var MAX_QUOTE_CANDIDATES = 8;
|
|
7
7
|
var QUOTE_BUFFER_BPS = 50;
|
|
8
8
|
var LZ_FEE_BUFFER_BPS = 1500n;
|
|
9
|
-
var SUBMIT_ORDER_SELECTOR = "
|
|
9
|
+
var SUBMIT_ORDER_SELECTOR = "0xaf439ecd";
|
|
10
|
+
var NO_PARTNER_ID = `0x${"0".repeat(64)}`;
|
|
10
11
|
var ERC20_APPROVE_SELECTOR = "0x095ea7b3";
|
|
11
12
|
var ERC20_TRANSFER_SELECTOR = "0xa9059cbb";
|
|
12
13
|
var ERC20_ALLOWANCE_SELECTOR = "0xdd62ed3e";
|
|
@@ -15,22 +16,24 @@ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
|
15
16
|
var PREVIEW_OWNER = "0x1111111111111111111111111111111111111111";
|
|
16
17
|
var CANONICAL_DECIMALS = { USDC: 6, USDT: 6, USDE: 18, XAUT: 6 };
|
|
17
18
|
var CANONICAL_ESCROW = Object.freeze({
|
|
18
|
-
1: "
|
|
19
|
-
// Ethereum
|
|
20
|
-
10: "
|
|
21
|
-
// Optimism
|
|
22
|
-
130: "
|
|
23
|
-
// Unichain
|
|
24
|
-
146: "
|
|
25
|
-
// Sonic
|
|
26
|
-
8453: "
|
|
27
|
-
// Base
|
|
28
|
-
9745: "
|
|
29
|
-
// Plasma
|
|
30
|
-
57073: "
|
|
31
|
-
// Ink
|
|
32
|
-
42161: "
|
|
33
|
-
// Arbitrum
|
|
19
|
+
1: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
|
|
20
|
+
// Ethereum
|
|
21
|
+
10: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
|
|
22
|
+
// Optimism
|
|
23
|
+
130: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
|
|
24
|
+
// Unichain
|
|
25
|
+
146: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
|
|
26
|
+
// Sonic
|
|
27
|
+
8453: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
|
|
28
|
+
// Base
|
|
29
|
+
9745: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
|
|
30
|
+
// Plasma
|
|
31
|
+
57073: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
|
|
32
|
+
// Ink
|
|
33
|
+
42161: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40",
|
|
34
|
+
// Arbitrum
|
|
35
|
+
98866: "0x5e25c8ABc19b88d6A7Ab0D805C77A34987a68b40"
|
|
36
|
+
// Plume
|
|
34
37
|
});
|
|
35
38
|
var MAX_LZ_MSG_VALUE_WEI = 10n ** 18n;
|
|
36
39
|
var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {};
|
|
@@ -52,7 +55,8 @@ var BUNDLED_NATIVE_SYMBOL = {
|
|
|
52
55
|
146: "S",
|
|
53
56
|
8453: "ETH",
|
|
54
57
|
57073: "ETH",
|
|
55
|
-
42161: "ETH"
|
|
58
|
+
42161: "ETH",
|
|
59
|
+
98866: "PLUME"
|
|
56
60
|
};
|
|
57
61
|
var BUNDLED_RPC = {
|
|
58
62
|
1: "https://ethereum-rpc.publicnode.com",
|
|
@@ -62,7 +66,8 @@ var BUNDLED_RPC = {
|
|
|
62
66
|
8453: "https://mainnet.base.org",
|
|
63
67
|
9745: "https://rpc.plasma.to",
|
|
64
68
|
57073: "https://rpc-gel.inkonchain.com",
|
|
65
|
-
42161: "https://arb1.arbitrum.io/rpc"
|
|
69
|
+
42161: "https://arb1.arbitrum.io/rpc",
|
|
70
|
+
98866: "https://rpc.plume.org"
|
|
66
71
|
};
|
|
67
72
|
|
|
68
73
|
// src/core/address.ts
|
|
@@ -154,13 +159,25 @@ function uintWord(value) {
|
|
|
154
159
|
if (hex.length > 64) throw new Error("uint256 value is too large.");
|
|
155
160
|
return hex.padStart(64, "0");
|
|
156
161
|
}
|
|
162
|
+
var MAX_UINT64 = (1n << 64n) - 1n;
|
|
163
|
+
function uint64Word(value) {
|
|
164
|
+
const n = BigInt(value || 0);
|
|
165
|
+
if (n < 0n) throw new Error("Cannot encode a negative uint64.");
|
|
166
|
+
if (n > MAX_UINT64) throw new Error("uint64 value is too large.");
|
|
167
|
+
return n.toString(16).padStart(64, "0");
|
|
168
|
+
}
|
|
169
|
+
function bytes32Word(value) {
|
|
170
|
+
const hex = strip0x(value);
|
|
171
|
+
if (!/^[a-fA-F0-9]{64}$/.test(hex)) throw new Error("bytes32 value must be exactly 32 bytes of hex.");
|
|
172
|
+
return hex.toLowerCase();
|
|
173
|
+
}
|
|
157
174
|
function addressWord(address) {
|
|
158
175
|
return strip0x(assertAddress(address, "Address")).padStart(64, "0");
|
|
159
176
|
}
|
|
160
177
|
function bytesPayload(value) {
|
|
161
178
|
const hex = strip0x(value || "0x");
|
|
162
|
-
if (hex.length % 2) throw new Error("
|
|
163
|
-
if (!/^[a-fA-F0-9]*$/.test(hex)) throw new Error("
|
|
179
|
+
if (hex.length % 2) throw new Error("Bytes payload has an odd-length hex value; refusing to encode.");
|
|
180
|
+
if (!/^[a-fA-F0-9]*$/.test(hex)) throw new Error("Bytes payload is not valid hex.");
|
|
164
181
|
const byteLength = hex.length / 2;
|
|
165
182
|
const paddedLength = Math.ceil(hex.length / 64) * 64;
|
|
166
183
|
return `${uintWord(byteLength)}${hex.padEnd(paddedLength, "0")}`;
|
|
@@ -177,19 +194,96 @@ function encodeAllowance(owner, spender) {
|
|
|
177
194
|
function encodeBalanceOf(account) {
|
|
178
195
|
return `${ERC20_BALANCEOF_SELECTOR}${addressWord(account)}`;
|
|
179
196
|
}
|
|
180
|
-
|
|
181
|
-
|
|
197
|
+
var ORDER_HEAD_WORDS = 9n;
|
|
198
|
+
var ORDER_HEAD_BYTES = ORDER_HEAD_WORDS * 32n;
|
|
199
|
+
function encodeOrderTuple(order) {
|
|
200
|
+
const askToken = bytesPayload(order.askToken);
|
|
201
|
+
const receiver = bytesPayload(order.destinationReceiver);
|
|
202
|
+
const receiverOffset = ORDER_HEAD_BYTES + BigInt(askToken.length / 2);
|
|
203
|
+
const head = [
|
|
182
204
|
addressWord(order.owner),
|
|
183
205
|
addressWord(order.bidToken),
|
|
184
206
|
uintWord(order.bidTokenAmount),
|
|
185
|
-
|
|
207
|
+
uintWord(ORDER_HEAD_BYTES),
|
|
186
208
|
uintWord(order.askTokenAmount),
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
209
|
+
uintWord(receiverOffset),
|
|
210
|
+
uint64Word(order.destinationChainId),
|
|
211
|
+
uint64Word(order.executionChainId),
|
|
212
|
+
uint64Word(order.deadline)
|
|
191
213
|
].join("");
|
|
192
|
-
return
|
|
214
|
+
return `${head}${askToken}${receiver}`;
|
|
215
|
+
}
|
|
216
|
+
function encodeSubmitOrder(orders, partnerId = NO_PARTNER_ID) {
|
|
217
|
+
if (!orders.length) throw new Error("Cannot encode an empty order request array.");
|
|
218
|
+
const tuples = orders.map(encodeOrderTuple);
|
|
219
|
+
let offset = 32n * BigInt(tuples.length);
|
|
220
|
+
const offsets = tuples.map((tuple) => {
|
|
221
|
+
const word = uintWord(offset);
|
|
222
|
+
offset += BigInt(tuple.length / 2);
|
|
223
|
+
return word;
|
|
224
|
+
}).join("");
|
|
225
|
+
return `0x${SUBMIT_ORDER_SELECTOR.slice(2)}${uintWord(64)}${bytes32Word(partnerId)}${uintWord(tuples.length)}${offsets}${tuples.join("")}`;
|
|
226
|
+
}
|
|
227
|
+
var EVM_BYTES_PAYLOAD_BYTES = 64;
|
|
228
|
+
var EVM_ORDER_TUPLE_BYTES = Number(ORDER_HEAD_BYTES) + 2 * EVM_BYTES_PAYLOAD_BYTES;
|
|
229
|
+
var MAX_DECODED_ORDERS = 16;
|
|
230
|
+
function decodeSubmitOrderCalldata(data) {
|
|
231
|
+
const hex = strip0x(String(data || "")).toLowerCase();
|
|
232
|
+
if (hex.length < 8 || hex.length % 2 !== 0 || !/^[a-f0-9]*$/.test(hex)) return null;
|
|
233
|
+
if (`0x${hex.slice(0, 8)}` !== SUBMIT_ORDER_SELECTOR) return null;
|
|
234
|
+
const body = hex.slice(8);
|
|
235
|
+
const totalBytes = body.length / 2;
|
|
236
|
+
const word = (byteOffset) => {
|
|
237
|
+
if (!Number.isSafeInteger(byteOffset) || byteOffset < 0 || byteOffset + 32 > totalBytes) return null;
|
|
238
|
+
return BigInt(`0x${body.slice(byteOffset * 2, byteOffset * 2 + 64)}`);
|
|
239
|
+
};
|
|
240
|
+
const addressAt = (byteOffset) => {
|
|
241
|
+
const w = word(byteOffset);
|
|
242
|
+
if (w === null || w >= 1n << 160n) return null;
|
|
243
|
+
return `0x${w.toString(16).padStart(40, "0")}`;
|
|
244
|
+
};
|
|
245
|
+
const uint64At = (byteOffset) => {
|
|
246
|
+
const w = word(byteOffset);
|
|
247
|
+
return w === null || w > MAX_UINT64 ? null : w;
|
|
248
|
+
};
|
|
249
|
+
const evmBytesAt = (byteOffset) => {
|
|
250
|
+
const len = word(byteOffset);
|
|
251
|
+
if (len !== 20n) return null;
|
|
252
|
+
const content = body.slice((byteOffset + 32) * 2, (byteOffset + 64) * 2);
|
|
253
|
+
if (content.length !== 64 || !content.endsWith("0".repeat(24))) return null;
|
|
254
|
+
return `0x${content.slice(0, 40)}`;
|
|
255
|
+
};
|
|
256
|
+
if (word(0) !== 64n) return null;
|
|
257
|
+
if (word(32) === null) return null;
|
|
258
|
+
const partnerId = `0x${body.slice(64, 128)}`;
|
|
259
|
+
const count = word(64);
|
|
260
|
+
if (count === null || count < 1n || count > BigInt(MAX_DECODED_ORDERS)) return null;
|
|
261
|
+
const n = Number(count);
|
|
262
|
+
const arrayBase = 96;
|
|
263
|
+
if (totalBytes !== arrayBase + 32 * n + EVM_ORDER_TUPLE_BYTES * n) return null;
|
|
264
|
+
const orders = [];
|
|
265
|
+
for (let i = 0; i < n; i += 1) {
|
|
266
|
+
const rel = word(arrayBase + i * 32);
|
|
267
|
+
if (rel === null || rel !== BigInt(32 * n + EVM_ORDER_TUPLE_BYTES * i)) return null;
|
|
268
|
+
const base = arrayBase + Number(rel);
|
|
269
|
+
const owner = addressAt(base);
|
|
270
|
+
const bidToken = addressAt(base + 32);
|
|
271
|
+
const bidTokenAmount = word(base + 64);
|
|
272
|
+
const askOffset = word(base + 96);
|
|
273
|
+
const askTokenAmount = word(base + 128);
|
|
274
|
+
const receiverOffset = word(base + 160);
|
|
275
|
+
const destinationChainId = uint64At(base + 192);
|
|
276
|
+
const executionChainId = uint64At(base + 224);
|
|
277
|
+
const deadline = uint64At(base + 256);
|
|
278
|
+
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)) {
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
const askToken = evmBytesAt(base + Number(askOffset));
|
|
282
|
+
const destinationReceiver = evmBytesAt(base + Number(receiverOffset));
|
|
283
|
+
if (askToken === null || destinationReceiver === null) return null;
|
|
284
|
+
orders.push({ owner, bidToken, bidTokenAmount, askToken, askTokenAmount, destinationReceiver, destinationChainId, executionChainId, deadline });
|
|
285
|
+
}
|
|
286
|
+
return { partnerId, orders };
|
|
193
287
|
}
|
|
194
288
|
function toHexQuantity(value) {
|
|
195
289
|
const n = BigInt(value || 0);
|
|
@@ -380,7 +474,7 @@ async function solveExactOut({ option, destination, destinationToken, payer, fet
|
|
|
380
474
|
estimatedDuration: 0,
|
|
381
475
|
gasCostSource: "0",
|
|
382
476
|
gasCostDest: "0",
|
|
383
|
-
|
|
477
|
+
orderRequests: null
|
|
384
478
|
},
|
|
385
479
|
youPayRaw: targetRaw.toString(),
|
|
386
480
|
recipientReceivesRaw: targetRaw.toString(),
|
|
@@ -492,9 +586,13 @@ async function solveExactIn({ option, destination, destinationToken, payer, fetc
|
|
|
492
586
|
}
|
|
493
587
|
|
|
494
588
|
// src/core/order.ts
|
|
495
|
-
|
|
589
|
+
var DEFAULT_DEADLINE_SECONDS = 1800;
|
|
590
|
+
var MAX_DEADLINE_SECONDS = 60 * 60;
|
|
591
|
+
function normalizeOrderRequest(order, payer, destination, fallbackExecutionChainId, deadlineOverride) {
|
|
496
592
|
const apiDeadline = Number(order.deadline);
|
|
497
|
-
const deadline = Number.isFinite(apiDeadline) && apiDeadline > 0 ? String(order.deadline) : String(Math.floor(Date.now() / 1e3) +
|
|
593
|
+
const deadline = deadlineOverride ?? (Number.isFinite(apiDeadline) && apiDeadline > 0 ? String(order.deadline) : String(Math.floor(Date.now() / 1e3) + DEFAULT_DEADLINE_SECONDS));
|
|
594
|
+
const executionChainId = String(order.executionChainId || fallbackExecutionChainId || "0");
|
|
595
|
+
if (!/^\d+$/.test(executionChainId) || BigInt(executionChainId) <= 0n) throw new Error("ZeroDelta quote did not include an execution chain.");
|
|
498
596
|
return {
|
|
499
597
|
owner: assertAddress(order.owner || payer, "Order owner"),
|
|
500
598
|
bidToken: assertAddress(order.bidToken, "Bid token"),
|
|
@@ -503,26 +601,40 @@ function normalizeOrderRequest(order, payer, destination) {
|
|
|
503
601
|
askTokenAmount: String(order.askTokenAmount || "0"),
|
|
504
602
|
destinationReceiver: assertAddress(order.destinationReceiver || destination.address, "Destination receiver"),
|
|
505
603
|
destinationChainId: String(order.destinationChainId || destination.chainId),
|
|
506
|
-
|
|
507
|
-
|
|
604
|
+
executionChainId,
|
|
605
|
+
deadline
|
|
508
606
|
};
|
|
509
607
|
}
|
|
510
|
-
function
|
|
608
|
+
function normalizeOrderRequests(requests, payer, destination, fallbackExecutionChainId) {
|
|
609
|
+
if (!requests.length) throw new Error("ZeroDelta quote did not include any order requests.");
|
|
610
|
+
return requests.map(
|
|
611
|
+
(request, index) => index === 0 ? normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId) : normalizeOrderRequest(request, payer, destination, fallbackExecutionChainId, String(request.deadline || "0"))
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
function assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result }) {
|
|
615
|
+
const list = orders?.length ? orders : [order];
|
|
616
|
+
const sourceOrder = list[0];
|
|
617
|
+
const finalOrder = list[list.length - 1];
|
|
511
618
|
const now = Math.floor(Date.now() / 1e3);
|
|
512
|
-
const deadline = Number(
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
619
|
+
const deadline = Number(sourceOrder.deadline || 0);
|
|
620
|
+
for (const current of list) {
|
|
621
|
+
if (normalizeAddress(current.owner) !== normalizeAddress(payer)) {
|
|
622
|
+
throw new Error("ZeroDelta quote returned an owner that does not match the connected wallet.");
|
|
623
|
+
}
|
|
624
|
+
if (normalizeAddress(current.destinationReceiver) !== normalizeAddress(destination.address)) {
|
|
625
|
+
throw new Error("ZeroDelta quote returned a receiver that does not match the detected destination.");
|
|
626
|
+
}
|
|
627
|
+
if (!/^\d+$/.test(current.executionChainId || "") || BigInt(current.executionChainId) <= 0n) {
|
|
628
|
+
throw new Error("ZeroDelta quote returned an order without an execution chain.");
|
|
629
|
+
}
|
|
518
630
|
}
|
|
519
|
-
if (normalizeAddress(
|
|
631
|
+
if (normalizeAddress(sourceOrder.bidToken) !== normalizeAddress(option.address)) {
|
|
520
632
|
throw new Error("ZeroDelta quote returned a bid token that does not match the selected route.");
|
|
521
633
|
}
|
|
522
|
-
if (normalizeAddress(
|
|
634
|
+
if (normalizeAddress(finalOrder.askToken) !== normalizeAddress(destinationToken.address)) {
|
|
523
635
|
throw new Error("ZeroDelta quote returned an ask token that does not match the destination asset.");
|
|
524
636
|
}
|
|
525
|
-
if (Number(
|
|
637
|
+
if (Number(finalOrder.destinationChainId) !== Number(destination.chainId) || Number(quote.toChainId) !== Number(destination.chainId)) {
|
|
526
638
|
throw new Error("ZeroDelta quote returned a destination chain that does not match the payment request.");
|
|
527
639
|
}
|
|
528
640
|
if (Number(quote.fromChainId) !== Number(option.chainId)) {
|
|
@@ -531,24 +643,38 @@ function assertQuoteMatchesSelection({ quote, order, option, destinationToken, d
|
|
|
531
643
|
if (symbolKey(quote.fromToken) !== option.symbolKey || symbolKey(quote.toToken) !== symbolKey(destinationToken.symbol)) {
|
|
532
644
|
throw new Error("ZeroDelta quote returned token symbols that do not match the selected route.");
|
|
533
645
|
}
|
|
534
|
-
if (BigInt(
|
|
646
|
+
if (BigInt(sourceOrder.bidTokenAmount || "0") !== BigInt(result.youPayRaw || "0")) {
|
|
535
647
|
throw new Error("ZeroDelta quote returned a bid amount that does not match the displayed payment amount.");
|
|
536
648
|
}
|
|
537
|
-
if (BigInt(
|
|
649
|
+
if (BigInt(finalOrder.askTokenAmount || "0") !== BigInt(quote.toAmount || "0")) {
|
|
538
650
|
throw new Error("ZeroDelta quote returned an ask amount that does not match the quoted output.");
|
|
539
651
|
}
|
|
540
|
-
if (BigInt(
|
|
652
|
+
if (BigInt(finalOrder.askTokenAmount || "0") <= 0n || BigInt(quote.toAmount || "0") <= 0n) {
|
|
541
653
|
throw new Error("ZeroDelta quote returned a non-positive output amount.");
|
|
542
654
|
}
|
|
543
|
-
if (BigInt(
|
|
655
|
+
if (BigInt(finalOrder.askTokenAmount || "0") < BigInt(result.targetRaw || "0")) {
|
|
544
656
|
throw new Error("ZeroDelta quote would not cover the requested destination amount.");
|
|
545
657
|
}
|
|
546
|
-
if (BigInt(
|
|
658
|
+
if (BigInt(finalOrder.askTokenAmount || "0") < BigInt(result.recipientReceivesRaw || "0")) {
|
|
547
659
|
throw new Error("ZeroDelta order guarantees less than the displayed receive amount.");
|
|
548
660
|
}
|
|
549
|
-
if (!Number.isFinite(deadline) || deadline <= now || deadline > now +
|
|
661
|
+
if (!Number.isFinite(deadline) || deadline <= now || deadline > now + MAX_DEADLINE_SECONDS) {
|
|
550
662
|
throw new Error("ZeroDelta quote deadline is invalid or too far in the future.");
|
|
551
663
|
}
|
|
664
|
+
for (let index = 1; index < list.length; index += 1) {
|
|
665
|
+
const previous = list[index - 1];
|
|
666
|
+
const current = list[index];
|
|
667
|
+
if (normalizeAddress(previous.askToken) !== normalizeAddress(current.bidToken)) {
|
|
668
|
+
throw new Error("ZeroDelta chained quote returned disconnected order tokens.");
|
|
669
|
+
}
|
|
670
|
+
if (Number(previous.destinationChainId) !== Number(current.executionChainId)) {
|
|
671
|
+
throw new Error("ZeroDelta chained quote returned disconnected execution chains.");
|
|
672
|
+
}
|
|
673
|
+
const followupDeadline = Number(current.deadline || 0);
|
|
674
|
+
if (followupDeadline !== 0 && (!Number.isFinite(followupDeadline) || followupDeadline <= now || followupDeadline > now + MAX_DEADLINE_SECONDS)) {
|
|
675
|
+
throw new Error("ZeroDelta chained quote returned an invalid follow-up deadline.");
|
|
676
|
+
}
|
|
677
|
+
}
|
|
552
678
|
}
|
|
553
679
|
|
|
554
680
|
// src/core/route.ts
|
|
@@ -615,11 +741,13 @@ async function buildRoute({ option, destination, destinationToken, chains, payer
|
|
|
615
741
|
}
|
|
616
742
|
};
|
|
617
743
|
}
|
|
618
|
-
|
|
744
|
+
const requestList = quote.orderRequests?.length ? quote.orderRequests : quote.orderRequest ? [quote.orderRequest] : [];
|
|
745
|
+
if (!requestList.length) throw new Error("ZeroDelta quote did not include an order request.");
|
|
619
746
|
const sourceChain = chainById(chains, option.chainId);
|
|
620
747
|
const escrow = checkEscrow(option.chainId, quote.escrowAddress, sourceChain?.escrowContract);
|
|
621
|
-
const
|
|
622
|
-
|
|
748
|
+
const orders = normalizeOrderRequests(requestList, payer, destination, quote.executionChainId);
|
|
749
|
+
const order = orders[0];
|
|
750
|
+
assertQuoteMatchesSelection({ quote, order, orders, option, destinationToken, destination, payer, result });
|
|
623
751
|
const needsNativeFee = requiresNativeBridgeFee(quote, option);
|
|
624
752
|
if (needsNativeFee) {
|
|
625
753
|
let rawFee;
|
|
@@ -680,7 +808,7 @@ async function buildRoute({ option, destination, destinationToken, chains, payer
|
|
|
680
808
|
label: "Submit ZeroDelta order",
|
|
681
809
|
chainId: option.chainId,
|
|
682
810
|
to: escrow,
|
|
683
|
-
data: encodeSubmitOrder(
|
|
811
|
+
data: encodeSubmitOrder(orders),
|
|
684
812
|
value: toHexQuantity(valueRaw),
|
|
685
813
|
escrow,
|
|
686
814
|
amountRaw: order.bidTokenAmount
|
|
@@ -856,6 +984,16 @@ function createApiClient(cfg) {
|
|
|
856
984
|
}
|
|
857
985
|
|
|
858
986
|
// src/core/plan.ts
|
|
987
|
+
function optionBalanceKey(option) {
|
|
988
|
+
return `${Number(option.chainId)}:${String(option.address || "").toLowerCase()}`;
|
|
989
|
+
}
|
|
990
|
+
function hasPositiveBalance(option, balances) {
|
|
991
|
+
try {
|
|
992
|
+
return BigInt(balances[optionBalanceKey(option)]?.raw ?? "0") > 0n;
|
|
993
|
+
} catch {
|
|
994
|
+
return false;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
859
997
|
function validateDestination(destination) {
|
|
860
998
|
assertAddress(destination.address, "Destination address");
|
|
861
999
|
const chainId = Number(destination.chainId);
|
|
@@ -871,7 +1009,7 @@ function planErrorSummary(errors) {
|
|
|
871
1009
|
const unique = [...new Set(errors.map((error) => error?.message || String(error)).filter(Boolean))].slice(0, 3);
|
|
872
1010
|
return unique.length ? unique.join(" | ") : "No ZeroDelta route is currently available for this payment.";
|
|
873
1011
|
}
|
|
874
|
-
async function fetchPaymentPlan(api, request, payer, wallet = {}) {
|
|
1012
|
+
async function fetchPaymentPlan(api, request, payer, wallet = {}, readBalances) {
|
|
875
1013
|
validateDestination(request);
|
|
876
1014
|
assertAddress(payer, "Payer wallet");
|
|
877
1015
|
const [chains, tokens, routes] = await Promise.all([api.fetchChains(), api.fetchTokens(), api.fetchRoutes()]);
|
|
@@ -882,6 +1020,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}) {
|
|
|
882
1020
|
};
|
|
883
1021
|
const destinationToken = findToken(tokens, destination.chainId, destination.asset);
|
|
884
1022
|
if (!destinationToken) throw new Error(`${destination.asset} is not enabled on ${chainNameOf(destination.chainId, chains)}.`);
|
|
1023
|
+
const allowedFunding = wallet.fundingAssets?.length ? new Set(wallet.fundingAssets.map(symbolKey)) : null;
|
|
885
1024
|
const options = buildPayOptions({
|
|
886
1025
|
invoiceAsset: destination.asset,
|
|
887
1026
|
invoiceChainId: destination.chainId,
|
|
@@ -889,14 +1028,25 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}) {
|
|
|
889
1028
|
routes,
|
|
890
1029
|
chains,
|
|
891
1030
|
walletChainId: wallet?.chainId
|
|
892
|
-
});
|
|
1031
|
+
}).filter((option) => option.direct || !allowedFunding || allowedFunding.has(option.symbolKey));
|
|
893
1032
|
if (!options.length) throw new Error(`No enabled ZeroDelta funding assets can settle ${destination.asset} on ${chainNameOf(destination.chainId, chains)}.`);
|
|
1033
|
+
const balanceTargets = [];
|
|
1034
|
+
const seenTargets = /* @__PURE__ */ new Set();
|
|
1035
|
+
for (const option of options) {
|
|
1036
|
+
const key = optionBalanceKey(option);
|
|
1037
|
+
if (seenTargets.has(key)) continue;
|
|
1038
|
+
seenTargets.add(key);
|
|
1039
|
+
balanceTargets.push({ chainId: option.chainId, tokenAddress: option.address, decimals: option.decimals });
|
|
1040
|
+
}
|
|
1041
|
+
const walletBalances = readBalances ? await readBalances(payer, balanceTargets).catch(() => ({})) : {};
|
|
894
1042
|
const candidates = options.filter((option) => option.direct);
|
|
1043
|
+
const heldOptions = options.filter((option) => !option.direct && hasPositiveBalance(option, walletBalances));
|
|
1044
|
+
const heldKeys = new Set(heldOptions.map(optionBalanceKey));
|
|
895
1045
|
const seenChains = /* @__PURE__ */ new Set();
|
|
896
1046
|
const perChainBest = [];
|
|
897
1047
|
const leftovers = [];
|
|
898
1048
|
for (const option of options) {
|
|
899
|
-
if (option.direct) continue;
|
|
1049
|
+
if (option.direct || heldKeys.has(optionBalanceKey(option))) continue;
|
|
900
1050
|
if (seenChains.has(option.chainId)) {
|
|
901
1051
|
leftovers.push(option);
|
|
902
1052
|
} else {
|
|
@@ -904,7 +1054,7 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}) {
|
|
|
904
1054
|
perChainBest.push(option);
|
|
905
1055
|
}
|
|
906
1056
|
}
|
|
907
|
-
for (const option of [...perChainBest, ...leftovers].slice(0, MAX_QUOTE_CANDIDATES)) {
|
|
1057
|
+
for (const option of [...heldOptions, ...perChainBest, ...leftovers].slice(0, MAX_QUOTE_CANDIDATES)) {
|
|
908
1058
|
candidates.push(option);
|
|
909
1059
|
}
|
|
910
1060
|
const routeErrors = [];
|
|
@@ -939,6 +1089,8 @@ async function fetchPaymentPlan(api, request, payer, wallet = {}) {
|
|
|
939
1089
|
expiresAt: new Date(Date.now() + 2 * 60 * 1e3).toISOString(),
|
|
940
1090
|
apiBase: api.apiBase,
|
|
941
1091
|
routes: routesBuilt,
|
|
1092
|
+
fundingBalances: walletBalances,
|
|
1093
|
+
fundingAccount: payer.toLowerCase(),
|
|
942
1094
|
destination: {
|
|
943
1095
|
asset: destinationToken.symbol,
|
|
944
1096
|
chainId: destination.chainId,
|
|
@@ -1096,7 +1248,12 @@ function validatePlannedTransaction(tx, route, expectedRecipient) {
|
|
|
1096
1248
|
if (tx.kind === "submitOrder") {
|
|
1097
1249
|
const expected = planMsgValueHex(route);
|
|
1098
1250
|
if (expected === null || value !== lower(expected)) return false;
|
|
1099
|
-
|
|
1251
|
+
if (selector !== SUBMIT_ORDER_SELECTOR || !isHexAddress(tx.escrow) || lower(tx.to) !== lower(tx.escrow)) return false;
|
|
1252
|
+
const decoded = decodeSubmitOrderCalldata(data);
|
|
1253
|
+
if (!decoded) return false;
|
|
1254
|
+
const first = decoded.orders[0];
|
|
1255
|
+
const last = decoded.orders[decoded.orders.length - 1];
|
|
1256
|
+
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);
|
|
1100
1257
|
}
|
|
1101
1258
|
return false;
|
|
1102
1259
|
}
|
|
@@ -1113,7 +1270,7 @@ async function allowanceCovers(tx, account, ethCall) {
|
|
|
1113
1270
|
// src/core/intent-schema.ts
|
|
1114
1271
|
var STABLEGENIE_INTENT_VERSION = 1;
|
|
1115
1272
|
var STABLEGENIE_INTENT_TTL_MS = 5 * 60 * 1e3;
|
|
1116
|
-
var STABLEGENIE_SUPPORTED_CHAIN_IDS = Object.freeze([1, 10, 130, 146, 8453, 9745, 57073, 42161]);
|
|
1273
|
+
var STABLEGENIE_SUPPORTED_CHAIN_IDS = Object.freeze([1, 10, 130, 146, 8453, 9745, 57073, 42161, 98866]);
|
|
1117
1274
|
var STABLEGENIE_SUPPORTED_ASSETS = Object.freeze(["USDC", "USDE", "USDT", "XAUT"]);
|
|
1118
1275
|
var stableGenieIntentSchema = {
|
|
1119
1276
|
type: "object",
|
|
@@ -1219,6 +1376,23 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
1219
1376
|
const json = await response.json();
|
|
1220
1377
|
return json?.result ?? null;
|
|
1221
1378
|
}
|
|
1379
|
+
async function rpcBatchCall(rpcUrl, calls) {
|
|
1380
|
+
const response = await fetchImpl(rpcUrl, {
|
|
1381
|
+
method: "POST",
|
|
1382
|
+
headers: { "Content-Type": "application/json" },
|
|
1383
|
+
body: JSON.stringify(calls.map((call, index) => ({ jsonrpc: "2.0", id: index + 1, ...call }))),
|
|
1384
|
+
signal: AbortSignal.timeout(TX_VERIFY_FETCH_MS)
|
|
1385
|
+
});
|
|
1386
|
+
if (!response.ok) throw new Error(`RPC ${response.status}`);
|
|
1387
|
+
const json = await response.json();
|
|
1388
|
+
if (!Array.isArray(json)) throw new Error("RPC batch unsupported");
|
|
1389
|
+
const results = /* @__PURE__ */ new Map();
|
|
1390
|
+
for (const item of json) {
|
|
1391
|
+
const id = Number(item?.id);
|
|
1392
|
+
if (Number.isInteger(id) && Object.hasOwn(item || {}, "result")) results.set(id, item.result);
|
|
1393
|
+
}
|
|
1394
|
+
return results;
|
|
1395
|
+
}
|
|
1222
1396
|
async function payerNonceBaseline(chainId, account) {
|
|
1223
1397
|
if (!isAddress(account)) return null;
|
|
1224
1398
|
const rpcUrl = await chainRpcUrl(chainId);
|
|
@@ -1285,25 +1459,54 @@ function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
|
1285
1459
|
const out = {};
|
|
1286
1460
|
if (!isAddress(account) || !Array.isArray(targets) || !targets.length) return out;
|
|
1287
1461
|
const owner = normalizeAddress(account);
|
|
1288
|
-
const
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1462
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1463
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1464
|
+
for (const target of targets) {
|
|
1465
|
+
if (!target || !isAddress(target.tokenAddress)) continue;
|
|
1466
|
+
const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
|
|
1467
|
+
if (seen.has(key)) continue;
|
|
1468
|
+
seen.add(key);
|
|
1469
|
+
const chainId = Number(target.chainId);
|
|
1470
|
+
const group = groups.get(chainId) || [];
|
|
1471
|
+
group.push(target);
|
|
1472
|
+
groups.set(chainId, group);
|
|
1473
|
+
}
|
|
1474
|
+
function record(target, hex) {
|
|
1475
|
+
if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return false;
|
|
1476
|
+
const raw = BigInt(hex || "0x0").toString();
|
|
1477
|
+
const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
|
|
1478
|
+
out[key] = { raw, formatted: formatUnits(raw, Number(target.decimals)) };
|
|
1479
|
+
return true;
|
|
1480
|
+
}
|
|
1481
|
+
async function readOne(rpcUrl, target) {
|
|
1482
|
+
try {
|
|
1483
|
+
const hex = await rpcCall(rpcUrl, "eth_call", [{ to: normalizeAddress(target.tokenAddress), data: encodeBalanceOf(owner) }, "latest"]);
|
|
1484
|
+
record(target, hex);
|
|
1485
|
+
} catch {
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
async function readGroup(chainId, group) {
|
|
1489
|
+
const rpcUrl = await balanceRpcUrl(chainId).catch(() => "");
|
|
1490
|
+
if (!rpcUrl) return;
|
|
1491
|
+
if (group.length === 1) return readOne(rpcUrl, group[0]);
|
|
1492
|
+
try {
|
|
1493
|
+
const results = await rpcBatchCall(
|
|
1494
|
+
rpcUrl,
|
|
1495
|
+
group.map((target) => ({
|
|
1496
|
+
method: "eth_call",
|
|
1497
|
+
params: [{ to: normalizeAddress(target.tokenAddress), data: encodeBalanceOf(owner) }, "latest"]
|
|
1498
|
+
}))
|
|
1499
|
+
);
|
|
1500
|
+
const missing = [];
|
|
1501
|
+
group.forEach((target, index) => {
|
|
1502
|
+
if (!record(target, results.get(index + 1))) missing.push(target);
|
|
1503
|
+
});
|
|
1504
|
+
await Promise.all(missing.map((target) => readOne(rpcUrl, target)));
|
|
1505
|
+
} catch {
|
|
1506
|
+
await Promise.all(group.map((target) => readOne(rpcUrl, target)));
|
|
1304
1507
|
}
|
|
1305
1508
|
}
|
|
1306
|
-
await Promise.all(
|
|
1509
|
+
await Promise.all([...groups.entries()].map(([chainId, group]) => readGroup(chainId, group)));
|
|
1307
1510
|
return out;
|
|
1308
1511
|
}
|
|
1309
1512
|
async function readNativeBalance(chainId, account) {
|
|
@@ -1405,7 +1608,7 @@ function createEngine(config = {}) {
|
|
|
1405
1608
|
fetchTokens: api.fetchTokens,
|
|
1406
1609
|
fetchRoutes: api.fetchRoutes,
|
|
1407
1610
|
fetchQuote: api.fetchQuote,
|
|
1408
|
-
fetchPaymentPlan: (request, payer, wallet) => fetchPaymentPlan(api, request, payer, wallet),
|
|
1611
|
+
fetchPaymentPlan: (request, payer, wallet) => fetchPaymentPlan(api, request, payer, wallet, verifier.readBalances),
|
|
1409
1612
|
quoteSwapPreview: (swap, owner) => quoteSwapPreview(api, swap, owner),
|
|
1410
1613
|
buildSwapPlan: (swap, payer, wallet) => buildSwapPlan(api, swap, payer, wallet),
|
|
1411
1614
|
payerNonceBaseline: verifier.payerNonceBaseline,
|
|
@@ -1423,4 +1626,4 @@ function createEngine(config = {}) {
|
|
|
1423
1626
|
};
|
|
1424
1627
|
}
|
|
1425
1628
|
|
|
1426
|
-
export { API_CACHE_TTL_MS, BUNDLED_NATIVE_SYMBOL, BUNDLED_RPC, CANONICAL_DECIMALS, CANONICAL_ESCROW, CANONICAL_INBOUND_BRIDGE, DEFAULT_WIDGET_API_BASE, ERC20_ALLOWANCE_SELECTOR, ERC20_APPROVE_SELECTOR, ERC20_BALANCEOF_SELECTOR, ERC20_TRANSFER_SELECTOR, LZ_FEE_BUFFER_BPS, MAX_LZ_MSG_VALUE_WEI, MAX_LZ_MSG_VALUE_WEI_BY_CHAIN, MAX_QUOTE_CANDIDATES, MAX_SAME_CLASS_PAY_BPS, PREVIEW_OWNER, QUOTE_BUFFER_BPS, SAME_CLASS_STABLE, STABLEGENIE_INTENT_TTL_MS, STABLEGENIE_INTENT_VERSION, STABLEGENIE_SUPPORTED_ASSETS, STABLEGENIE_SUPPORTED_CHAIN_IDS, SUBMIT_ORDER_SELECTOR, SUPPORTED_ASSETS, SUPPORTED_CHAIN_IDS, ZERO_ADDRESS, addressWord, allowanceCovers, apiError, applyLayerZeroBuffer, assertAddress, assertQuoteMatchesSelection, assetDecimals, buildPayOptions, buildRoute, buildSwapPlan, bytesPayload, canAttachApiKey, chainById, chainNameOf, chainSelectable, checkEscrow, checkNativeFee, classifyQuoteError, createApiClient, createEngine, createVerifier, encodeAllowance, encodeApprove, encodeBalanceOf, encodeSubmitOrder, encodeTransfer, fetchPaymentPlan, finalOf, findToken, formatNative, formatUnits, isAddress, isDeliverable, isHexAddress, isHexData, isHexQuantity, isLayerZeroRoute, maxNativeFeeWei, nativeFeeShortLabel, nativeFeeShortMessage, nativeSymbol, normalizeAddress, normalizeDecimalText, normalizeOrderRequest, parseAllowedApiBase, parseUnitsDecimal, planErrorSummary, planMsgValueHex, quoteSwapPreview, registryRpc, requiresNativeBridgeFee, resolveApiBase, resolveConfig, resolveSwapReceiver, routeNativeValue, scaleDecimals, solveExactIn, solveExactOut, stableGenieIntentSchema, strip0x, symbolKey, toHexQuantity, tokenEnabled, txMatchesPlan, uintWord, validateDestination, validatePlannedTransaction, validateSwap };
|
|
1629
|
+
export { API_CACHE_TTL_MS, BUNDLED_NATIVE_SYMBOL, BUNDLED_RPC, CANONICAL_DECIMALS, CANONICAL_ESCROW, CANONICAL_INBOUND_BRIDGE, DEFAULT_WIDGET_API_BASE, ERC20_ALLOWANCE_SELECTOR, ERC20_APPROVE_SELECTOR, ERC20_BALANCEOF_SELECTOR, ERC20_TRANSFER_SELECTOR, LZ_FEE_BUFFER_BPS, MAX_LZ_MSG_VALUE_WEI, MAX_LZ_MSG_VALUE_WEI_BY_CHAIN, MAX_QUOTE_CANDIDATES, MAX_SAME_CLASS_PAY_BPS, MAX_UINT64, NO_PARTNER_ID, PREVIEW_OWNER, QUOTE_BUFFER_BPS, SAME_CLASS_STABLE, STABLEGENIE_INTENT_TTL_MS, STABLEGENIE_INTENT_VERSION, STABLEGENIE_SUPPORTED_ASSETS, STABLEGENIE_SUPPORTED_CHAIN_IDS, SUBMIT_ORDER_SELECTOR, SUPPORTED_ASSETS, SUPPORTED_CHAIN_IDS, ZERO_ADDRESS, addressWord, allowanceCovers, apiError, applyLayerZeroBuffer, assertAddress, assertQuoteMatchesSelection, assetDecimals, buildPayOptions, buildRoute, buildSwapPlan, bytes32Word, bytesPayload, canAttachApiKey, chainById, chainNameOf, chainSelectable, checkEscrow, checkNativeFee, classifyQuoteError, createApiClient, createEngine, createVerifier, decodeSubmitOrderCalldata, encodeAllowance, encodeApprove, encodeBalanceOf, encodeSubmitOrder, encodeTransfer, fetchPaymentPlan, finalOf, findToken, formatNative, formatUnits, isAddress, isDeliverable, isHexAddress, isHexData, isHexQuantity, isLayerZeroRoute, maxNativeFeeWei, nativeFeeShortLabel, nativeFeeShortMessage, nativeSymbol, normalizeAddress, normalizeDecimalText, normalizeOrderRequest, normalizeOrderRequests, parseAllowedApiBase, parseUnitsDecimal, planErrorSummary, planMsgValueHex, quoteSwapPreview, registryRpc, requiresNativeBridgeFee, resolveApiBase, resolveConfig, resolveSwapReceiver, routeNativeValue, scaleDecimals, solveExactIn, solveExactOut, stableGenieIntentSchema, strip0x, symbolKey, toHexQuantity, tokenEnabled, txMatchesPlan, uint64Word, uintWord, validateDestination, validatePlannedTransaction, validateSwap };
|