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