@glacislabs/stablegenie-zerodelta 2.0.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/LICENSE +21 -0
- package/README.md +157 -0
- package/dist/chunk-DSQ7MRF7.js +3107 -0
- package/dist/chunk-VL5MWEY2.js +1426 -0
- package/dist/core/index.cjs +1522 -0
- package/dist/core/index.d.cts +353 -0
- package/dist/core/index.d.ts +353 -0
- package/dist/core/index.js +1 -0
- package/dist/index.cjs +4491 -0
- package/dist/index.d.cts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/mount-yTJi4VdA.d.ts +204 -0
- package/dist/mount-yqXrDBLc.d.cts +204 -0
- package/dist/mount.cjs +4481 -0
- package/dist/mount.d.cts +3 -0
- package/dist/mount.d.ts +3 -0
- package/dist/mount.js +2 -0
- package/dist/standalone.global.js +451 -0
- package/dist/verify-CaO0OD4Z.d.cts +351 -0
- package/dist/verify-CaO0OD4Z.d.ts +351 -0
- package/package.json +119 -0
|
@@ -0,0 +1,1522 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/core/constants.ts
|
|
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]);
|
|
6
|
+
var SUPPORTED_ASSETS = /* @__PURE__ */ new Set(["USDC", "USDT", "USDE", "XAUT"]);
|
|
7
|
+
var API_CACHE_TTL_MS = 6e4;
|
|
8
|
+
var MAX_QUOTE_CANDIDATES = 8;
|
|
9
|
+
var QUOTE_BUFFER_BPS = 50;
|
|
10
|
+
var LZ_FEE_BUFFER_BPS = 1500n;
|
|
11
|
+
var SUBMIT_ORDER_SELECTOR = "0xbbd71141";
|
|
12
|
+
var ERC20_APPROVE_SELECTOR = "0x095ea7b3";
|
|
13
|
+
var ERC20_TRANSFER_SELECTOR = "0xa9059cbb";
|
|
14
|
+
var ERC20_ALLOWANCE_SELECTOR = "0xdd62ed3e";
|
|
15
|
+
var ERC20_BALANCEOF_SELECTOR = "0x70a08231";
|
|
16
|
+
var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
17
|
+
var PREVIEW_OWNER = "0x1111111111111111111111111111111111111111";
|
|
18
|
+
var CANONICAL_DECIMALS = { USDC: 6, USDT: 6, USDE: 18, XAUT: 6 };
|
|
19
|
+
var CANONICAL_ESCROW = Object.freeze({
|
|
20
|
+
1: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
|
|
21
|
+
// Ethereum — impl 0x49d173C4AbC90B3665D691f1FF2064eb9732A743
|
|
22
|
+
10: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
|
|
23
|
+
// Optimism — impl 0xB47eCBa71039694D28E76C482aC2bE34d5faC22A
|
|
24
|
+
130: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
|
|
25
|
+
// Unichain — impl 0xA9B1bBF52EF242aa4b9a8018bfD48fe64BbDfD03
|
|
26
|
+
146: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
|
|
27
|
+
// Sonic — impl 0x4c66dECff081Cf282af4C7f9CA436CB7b46A700d
|
|
28
|
+
8453: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
|
|
29
|
+
// Base — impl 0x70E37bF2c258015DAB7FE26942185D0362ebEd46
|
|
30
|
+
9745: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
|
|
31
|
+
// Plasma — impl 0x70168A99722f3041ceff211C4E505e8732ee965D
|
|
32
|
+
57073: "0x46A3219c357C2E50129d4839058FCFD421789aE7",
|
|
33
|
+
// Ink — impl 0x8A9e68864f476DA577e948cb61Cedffe7e17b562
|
|
34
|
+
42161: "0x46A3219c357C2E50129d4839058FCFD421789aE7"
|
|
35
|
+
// Arbitrum — impl 0x453B00aeB8c7dDBaff10f2812A0bA7dc88DdbC35
|
|
36
|
+
});
|
|
37
|
+
var MAX_LZ_MSG_VALUE_WEI = 10n ** 18n;
|
|
38
|
+
var MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = {};
|
|
39
|
+
function maxNativeFeeWei(chainId) {
|
|
40
|
+
return MAX_LZ_MSG_VALUE_WEI_BY_CHAIN[Number(chainId)] ?? MAX_LZ_MSG_VALUE_WEI;
|
|
41
|
+
}
|
|
42
|
+
var CANONICAL_INBOUND_BRIDGE = {
|
|
43
|
+
USDC: "cctp",
|
|
44
|
+
USDT: "layerzero",
|
|
45
|
+
USDE: "layerzero",
|
|
46
|
+
XAUT: "layerzero"
|
|
47
|
+
};
|
|
48
|
+
var SAME_CLASS_STABLE = /* @__PURE__ */ new Set(["USDC", "USDT", "USDE"]);
|
|
49
|
+
var MAX_SAME_CLASS_PAY_BPS = 30000n;
|
|
50
|
+
var BUNDLED_NATIVE_SYMBOL = {
|
|
51
|
+
1: "ETH",
|
|
52
|
+
10: "ETH",
|
|
53
|
+
130: "ETH",
|
|
54
|
+
146: "S",
|
|
55
|
+
8453: "ETH",
|
|
56
|
+
57073: "ETH",
|
|
57
|
+
42161: "ETH"
|
|
58
|
+
};
|
|
59
|
+
var BUNDLED_RPC = {
|
|
60
|
+
1: "https://ethereum-rpc.publicnode.com",
|
|
61
|
+
10: "https://optimism-rpc.publicnode.com",
|
|
62
|
+
130: "https://mainnet.unichain.org",
|
|
63
|
+
146: "https://rpc.soniclabs.com",
|
|
64
|
+
8453: "https://mainnet.base.org",
|
|
65
|
+
9745: "https://rpc.plasma.to",
|
|
66
|
+
57073: "https://rpc-gel.inkonchain.com",
|
|
67
|
+
42161: "https://arb1.arbitrum.io/rpc"
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
// src/core/address.ts
|
|
71
|
+
function symbolKey(value) {
|
|
72
|
+
return String(value || "").trim().toUpperCase();
|
|
73
|
+
}
|
|
74
|
+
function isAddress(value) {
|
|
75
|
+
return /^0x[a-fA-F0-9]{40}$/.test(String(value || ""));
|
|
76
|
+
}
|
|
77
|
+
function normalizeAddress(value) {
|
|
78
|
+
if (!isAddress(value)) return null;
|
|
79
|
+
return String(value).toLowerCase();
|
|
80
|
+
}
|
|
81
|
+
function assertAddress(value, label) {
|
|
82
|
+
const normalized = normalizeAddress(value);
|
|
83
|
+
if (!normalized || normalized === ZERO_ADDRESS) throw new Error(`${label} is not a valid EVM address.`);
|
|
84
|
+
return normalized;
|
|
85
|
+
}
|
|
86
|
+
function resolveSwapReceiver(recipient, payer) {
|
|
87
|
+
const payerAddr = assertAddress(payer, "Swap wallet");
|
|
88
|
+
if (recipient === void 0 || recipient === null || recipient === "") return payerAddr;
|
|
89
|
+
const normalized = normalizeAddress(recipient);
|
|
90
|
+
if (!normalized || normalized === ZERO_ADDRESS) throw new Error("Deposit recipient is not a valid EVM address.");
|
|
91
|
+
return normalized;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// src/core/units.ts
|
|
95
|
+
function assetDecimals(token) {
|
|
96
|
+
const sym = symbolKey(token?.symbol);
|
|
97
|
+
const registry = Number(token?.decimals);
|
|
98
|
+
const canonical = CANONICAL_DECIMALS[sym];
|
|
99
|
+
if (canonical !== void 0) {
|
|
100
|
+
if (!Number.isInteger(registry)) {
|
|
101
|
+
throw new Error(`ZeroDelta token registry is missing decimals for ${sym}; refusing to price.`);
|
|
102
|
+
}
|
|
103
|
+
if (registry !== canonical) {
|
|
104
|
+
throw new Error(`ZeroDelta token registry reported ${registry} decimals for ${sym}; expected ${canonical}. Refusing to price.`);
|
|
105
|
+
}
|
|
106
|
+
return canonical;
|
|
107
|
+
}
|
|
108
|
+
if (!Number.isInteger(registry) || registry < 0 || registry > 36) {
|
|
109
|
+
throw new Error(`ZeroDelta token registry has invalid decimals for ${sym || "token"}; refusing to price.`);
|
|
110
|
+
}
|
|
111
|
+
return registry;
|
|
112
|
+
}
|
|
113
|
+
function normalizeDecimalText(value) {
|
|
114
|
+
const text = String(value || "").trim().replace(/\s+/g, "");
|
|
115
|
+
if (!text) return "";
|
|
116
|
+
if (/^\d{1,3}(,\d{3})+(?:\.\d+)?$/.test(text)) return text.replace(/,/g, "");
|
|
117
|
+
if (/^\d+,\d{1,18}$/.test(text) && !text.includes(".")) return text.replace(",", ".");
|
|
118
|
+
if (text.includes(",")) return "";
|
|
119
|
+
return text;
|
|
120
|
+
}
|
|
121
|
+
function parseUnitsDecimal(amount, decimals) {
|
|
122
|
+
const text = normalizeDecimalText(amount);
|
|
123
|
+
if (!/^\d+(\.\d+)?$/.test(text)) throw new Error("Could not detect a valid payment amount.");
|
|
124
|
+
const [whole, frac = ""] = text.split(".");
|
|
125
|
+
if (frac.length > decimals) throw new Error("Payment amount has more decimal places than the asset supports.");
|
|
126
|
+
const padded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
127
|
+
const value = BigInt(whole || "0") * 10n ** BigInt(decimals) + BigInt(padded || "0");
|
|
128
|
+
if (value <= 0n) throw new Error("Payment amount must be greater than zero.");
|
|
129
|
+
return value;
|
|
130
|
+
}
|
|
131
|
+
function scaleDecimals(amount, fromDecimals, toDecimals) {
|
|
132
|
+
if (toDecimals === fromDecimals) return amount;
|
|
133
|
+
if (toDecimals > fromDecimals) return amount * 10n ** BigInt(toDecimals - fromDecimals);
|
|
134
|
+
return amount / 10n ** BigInt(fromDecimals - toDecimals);
|
|
135
|
+
}
|
|
136
|
+
function formatUnits(raw, decimals, maxDecimals = 6) {
|
|
137
|
+
const value = BigInt(raw || "0");
|
|
138
|
+
const base = 10n ** BigInt(decimals);
|
|
139
|
+
const whole = value / base;
|
|
140
|
+
const fracFull = (value % base).toString().padStart(decimals, "0");
|
|
141
|
+
const frac = fracFull.slice(0, Math.min(decimals, maxDecimals)).replace(/0+$/, "");
|
|
142
|
+
return frac ? `${whole}.${frac}` : whole.toString();
|
|
143
|
+
}
|
|
144
|
+
function finalOf(quote) {
|
|
145
|
+
return BigInt(quote?.finalAmount || quote?.toAmount || "0");
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/core/abi.ts
|
|
149
|
+
function strip0x(value) {
|
|
150
|
+
return String(value || "").replace(/^0x/i, "");
|
|
151
|
+
}
|
|
152
|
+
function uintWord(value) {
|
|
153
|
+
const n = BigInt(value || 0);
|
|
154
|
+
if (n < 0n) throw new Error("Cannot encode a negative uint256.");
|
|
155
|
+
const hex = n.toString(16);
|
|
156
|
+
if (hex.length > 64) throw new Error("uint256 value is too large.");
|
|
157
|
+
return hex.padStart(64, "0");
|
|
158
|
+
}
|
|
159
|
+
function addressWord(address) {
|
|
160
|
+
return strip0x(assertAddress(address, "Address")).padStart(64, "0");
|
|
161
|
+
}
|
|
162
|
+
function bytesPayload(value) {
|
|
163
|
+
const hex = strip0x(value || "0x");
|
|
164
|
+
if (hex.length % 2) throw new Error("Order data has an odd-length hex payload; refusing to encode.");
|
|
165
|
+
if (!/^[a-fA-F0-9]*$/.test(hex)) throw new Error("Order data is not valid hex.");
|
|
166
|
+
const byteLength = hex.length / 2;
|
|
167
|
+
const paddedLength = Math.ceil(hex.length / 64) * 64;
|
|
168
|
+
return `${uintWord(byteLength)}${hex.padEnd(paddedLength, "0")}`;
|
|
169
|
+
}
|
|
170
|
+
function encodeApprove(spender, amount) {
|
|
171
|
+
return `0x${ERC20_APPROVE_SELECTOR.slice(2)}${addressWord(spender)}${uintWord(amount)}`;
|
|
172
|
+
}
|
|
173
|
+
function encodeTransfer(to, amount) {
|
|
174
|
+
return `0x${ERC20_TRANSFER_SELECTOR.slice(2)}${addressWord(to)}${uintWord(amount)}`;
|
|
175
|
+
}
|
|
176
|
+
function encodeAllowance(owner, spender) {
|
|
177
|
+
return `${ERC20_ALLOWANCE_SELECTOR}${addressWord(owner)}${addressWord(spender)}`;
|
|
178
|
+
}
|
|
179
|
+
function encodeBalanceOf(account) {
|
|
180
|
+
return `${ERC20_BALANCEOF_SELECTOR}${addressWord(account)}`;
|
|
181
|
+
}
|
|
182
|
+
function encodeSubmitOrder(order) {
|
|
183
|
+
const tupleHead = [
|
|
184
|
+
addressWord(order.owner),
|
|
185
|
+
addressWord(order.bidToken),
|
|
186
|
+
uintWord(order.bidTokenAmount),
|
|
187
|
+
addressWord(order.askToken),
|
|
188
|
+
uintWord(order.askTokenAmount),
|
|
189
|
+
addressWord(order.destinationReceiver),
|
|
190
|
+
uintWord(order.destinationChainId),
|
|
191
|
+
uintWord(order.deadline),
|
|
192
|
+
uintWord(9n * 32n)
|
|
193
|
+
].join("");
|
|
194
|
+
return `0x${SUBMIT_ORDER_SELECTOR.slice(2)}${uintWord(32)}${tupleHead}${bytesPayload(order.data || "0x")}`;
|
|
195
|
+
}
|
|
196
|
+
function toHexQuantity(value) {
|
|
197
|
+
const n = BigInt(value || 0);
|
|
198
|
+
return `0x${n.toString(16)}`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// src/core/escrow.ts
|
|
202
|
+
function checkEscrow(chainId, quoteEscrow, chainsEscrow) {
|
|
203
|
+
const fromQuote = normalizeAddress(quoteEscrow);
|
|
204
|
+
const fromChains = normalizeAddress(chainsEscrow);
|
|
205
|
+
if (!fromChains || fromChains === ZERO_ADDRESS) {
|
|
206
|
+
throw new Error(`No registry escrow is available for ${chainId}; refusing to sign.`);
|
|
207
|
+
}
|
|
208
|
+
if (!fromQuote || fromQuote === ZERO_ADDRESS) {
|
|
209
|
+
throw new Error("ZeroDelta quote did not include an escrow address; refusing to sign.");
|
|
210
|
+
}
|
|
211
|
+
if (fromQuote !== fromChains) {
|
|
212
|
+
throw new Error("Escrow address from ZeroDelta quote does not match the chain registry.");
|
|
213
|
+
}
|
|
214
|
+
const pinned = normalizeAddress(CANONICAL_ESCROW[Number(chainId)]);
|
|
215
|
+
if (pinned && pinned !== fromChains) {
|
|
216
|
+
throw new Error(`Escrow address for ${chainId} does not match the pinned canonical escrow; refusing to sign.`);
|
|
217
|
+
}
|
|
218
|
+
return fromChains;
|
|
219
|
+
}
|
|
220
|
+
function isLayerZeroRoute(quote, option = {}) {
|
|
221
|
+
const bridge = `${quote?.bridge || ""} ${option?.bridge || ""}`.toLowerCase();
|
|
222
|
+
return bridge.includes("layerzero") || bridge.includes("layer zero");
|
|
223
|
+
}
|
|
224
|
+
function sourceAssetKey(quote, option = {}) {
|
|
225
|
+
return symbolKey(option?.symbolKey || option?.symbol || quote?.fromToken);
|
|
226
|
+
}
|
|
227
|
+
function requiresNativeBridgeFee(quote, option = {}) {
|
|
228
|
+
const sourceChainId = Number(option?.chainId ?? quote?.fromChainId);
|
|
229
|
+
const execChainId = Number(quote?.executionChainId);
|
|
230
|
+
if (Number.isFinite(sourceChainId) && Number.isFinite(execChainId) && execChainId > 0 && sourceChainId === execChainId) {
|
|
231
|
+
return false;
|
|
232
|
+
}
|
|
233
|
+
const canonical = CANONICAL_INBOUND_BRIDGE[sourceAssetKey(quote, option)];
|
|
234
|
+
if (canonical) return canonical === "layerzero";
|
|
235
|
+
return isLayerZeroRoute(quote, option);
|
|
236
|
+
}
|
|
237
|
+
function applyLayerZeroBuffer(quote, option = {}) {
|
|
238
|
+
const gas = BigInt(quote?.gasCostSource || "0");
|
|
239
|
+
if (gas <= 0n) return 0n;
|
|
240
|
+
if (!requiresNativeBridgeFee(quote, option)) return 0n;
|
|
241
|
+
return gas * (10000n + LZ_FEE_BUFFER_BPS) / 10000n;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// src/core/options.ts
|
|
245
|
+
function chainNameOf(chainId, chains) {
|
|
246
|
+
const chain = chains.find((item) => Number(item.chainId) === Number(chainId));
|
|
247
|
+
return chain?.displayName || chain?.name || `Chain ${chainId}`;
|
|
248
|
+
}
|
|
249
|
+
function chainById(chains, chainId) {
|
|
250
|
+
return chains.find((chain) => Number(chain.chainId) === Number(chainId)) || null;
|
|
251
|
+
}
|
|
252
|
+
function isDeliverable(symbol, chainId) {
|
|
253
|
+
if (Number(chainId) === 8453 && symbolKey(symbol) === "USDT") return false;
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
function chainSelectable(chain, chainId) {
|
|
257
|
+
if (!SUPPORTED_CHAIN_IDS.has(Number(chainId))) return false;
|
|
258
|
+
if (!chain) return true;
|
|
259
|
+
return chain.isEnabled !== false;
|
|
260
|
+
}
|
|
261
|
+
function tokenEnabled(token) {
|
|
262
|
+
return token?.isEnabled !== false && isAddress(token?.address) && Number.isFinite(Number(token?.chainId));
|
|
263
|
+
}
|
|
264
|
+
function findToken(tokens, chainId, symbol) {
|
|
265
|
+
const key = symbolKey(symbol);
|
|
266
|
+
return tokens.find((token) => tokenEnabled(token) && Number(token.chainId) === Number(chainId) && symbolKey(token.symbol) === key) || null;
|
|
267
|
+
}
|
|
268
|
+
function buildPayOptions({ invoiceAsset, invoiceChainId, tokens, routes, chains, walletChainId }) {
|
|
269
|
+
const invoiceKey = symbolKey(invoiceAsset);
|
|
270
|
+
const tokenBySymbolAndChain = /* @__PURE__ */ new Map();
|
|
271
|
+
for (const token of tokens) {
|
|
272
|
+
if (!tokenEnabled(token)) continue;
|
|
273
|
+
const key = symbolKey(token.symbol);
|
|
274
|
+
if (!tokenBySymbolAndChain.has(key)) tokenBySymbolAndChain.set(key, /* @__PURE__ */ new Map());
|
|
275
|
+
tokenBySymbolAndChain.get(key).set(Number(token.chainId), token);
|
|
276
|
+
}
|
|
277
|
+
const routeBridge = /* @__PURE__ */ new Map();
|
|
278
|
+
for (const route of routes || []) {
|
|
279
|
+
if (route.isEnabled === false || Number(route.toChainId) !== Number(invoiceChainId)) continue;
|
|
280
|
+
routeBridge.set(`${symbolKey(route.tokenName || route.tokenId)}:${Number(route.fromChainId)}`, route.bridge);
|
|
281
|
+
routeBridge.set(`${symbolKey(route.tokenId)}:${Number(route.fromChainId)}`, route.bridge);
|
|
282
|
+
}
|
|
283
|
+
const receiveDeliverable = isDeliverable(invoiceKey, invoiceChainId);
|
|
284
|
+
const options = [];
|
|
285
|
+
for (const [payKey, byChain] of tokenBySymbolAndChain.entries()) {
|
|
286
|
+
if (!byChain.has(Number(invoiceChainId))) continue;
|
|
287
|
+
for (const [chainId, token] of byChain.entries()) {
|
|
288
|
+
const chain = chainById(chains, chainId);
|
|
289
|
+
if (!chainSelectable(chain, chainId)) continue;
|
|
290
|
+
const direct = chainId === Number(invoiceChainId) && payKey === invoiceKey;
|
|
291
|
+
if (!direct && payKey === invoiceKey) continue;
|
|
292
|
+
if (!direct && (!receiveDeliverable || !isDeliverable(payKey, chainId))) continue;
|
|
293
|
+
options.push({
|
|
294
|
+
symbol: token.symbol,
|
|
295
|
+
symbolKey: payKey,
|
|
296
|
+
name: token.name || token.symbol,
|
|
297
|
+
chainId,
|
|
298
|
+
chainName: chainNameOf(chainId, chains),
|
|
299
|
+
address: token.address,
|
|
300
|
+
decimals: assetDecimals(token),
|
|
301
|
+
logoUrl: token.logoUrl,
|
|
302
|
+
bridge: routeBridge.get(`${payKey}:${chainId}`) || token.bridge,
|
|
303
|
+
sameChain: chainId === Number(invoiceChainId),
|
|
304
|
+
direct
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
options.sort((a, b) => {
|
|
309
|
+
const walletChain = Number(walletChainId || 0);
|
|
310
|
+
if (walletChain) {
|
|
311
|
+
if (a.chainId === walletChain && b.chainId !== walletChain) return -1;
|
|
312
|
+
if (b.chainId === walletChain && a.chainId !== walletChain) return 1;
|
|
313
|
+
}
|
|
314
|
+
if (a.direct !== b.direct) return a.direct ? -1 : 1;
|
|
315
|
+
if (a.symbolKey !== b.symbolKey) {
|
|
316
|
+
if (a.symbolKey === invoiceKey) return -1;
|
|
317
|
+
if (b.symbolKey === invoiceKey) return 1;
|
|
318
|
+
return a.symbolKey.localeCompare(b.symbolKey);
|
|
319
|
+
}
|
|
320
|
+
if (a.sameChain !== b.sameChain) return a.sameChain ? -1 : 1;
|
|
321
|
+
return a.chainId - b.chainId;
|
|
322
|
+
});
|
|
323
|
+
return options;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// src/core/native-fee.ts
|
|
327
|
+
function routeNativeValue(route) {
|
|
328
|
+
try {
|
|
329
|
+
const raw = route?.quote?.msgValue;
|
|
330
|
+
if (raw === void 0 || raw === null || raw === "") return 0n;
|
|
331
|
+
const value = BigInt(raw);
|
|
332
|
+
return value > 0n ? value : 0n;
|
|
333
|
+
} catch {
|
|
334
|
+
return 0n;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
function nativeSymbol(chainId, chains = []) {
|
|
338
|
+
const registry = chainById(chains, Number(chainId))?.nativeCurrency;
|
|
339
|
+
const fromRegistry = typeof registry === "string" ? registry.trim() : "";
|
|
340
|
+
return fromRegistry || BUNDLED_NATIVE_SYMBOL[Number(chainId)] || "ETH";
|
|
341
|
+
}
|
|
342
|
+
function formatNative(wei) {
|
|
343
|
+
const text = formatUnits(wei.toString(), 18, 8);
|
|
344
|
+
return text === "0" && wei > 0n ? "<0.00000001" : text;
|
|
345
|
+
}
|
|
346
|
+
function checkNativeFee(route, balance) {
|
|
347
|
+
const required = routeNativeValue(route);
|
|
348
|
+
if (required <= 0n || balance === null || balance === void 0) {
|
|
349
|
+
return { required, balance: balance ?? null, short: false, shortfall: 0n };
|
|
350
|
+
}
|
|
351
|
+
const shortfall = required > balance ? required - balance : 0n;
|
|
352
|
+
return { required, balance, short: shortfall > 0n, shortfall };
|
|
353
|
+
}
|
|
354
|
+
function nativeFeeShortLabel(check, symbol) {
|
|
355
|
+
if (!check.short) return null;
|
|
356
|
+
return `Need ${formatNative(check.required)} ${symbol} for the bridge fee`;
|
|
357
|
+
}
|
|
358
|
+
function nativeFeeShortMessage(check, symbol, chainName) {
|
|
359
|
+
const need = formatNative(check.required);
|
|
360
|
+
const have = formatNative(check.balance ?? 0n);
|
|
361
|
+
const where = chainName ? ` on ${chainName}` : "";
|
|
362
|
+
return `This route bridges via LayerZero, which charges a ${need} ${symbol} network fee paid as part of the transaction. Your wallet holds ${have} ${symbol}${where}. Add ${symbol}${where} and try again \u2014 gas is owed on top of this fee.`;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// src/core/solve.ts
|
|
366
|
+
async function solveExactOut({ option, destination, destinationToken, payer, fetchQuote }) {
|
|
367
|
+
const destDecimals = assetDecimals(destinationToken);
|
|
368
|
+
const targetRaw = parseUnitsDecimal(destination.amount, destDecimals);
|
|
369
|
+
if (option.direct) {
|
|
370
|
+
return {
|
|
371
|
+
directTransfer: true,
|
|
372
|
+
quote: {
|
|
373
|
+
fromChainId: option.chainId,
|
|
374
|
+
toChainId: Number(destination.chainId),
|
|
375
|
+
fromToken: option.symbol,
|
|
376
|
+
toToken: destinationToken.symbol,
|
|
377
|
+
fromAmount: targetRaw.toString(),
|
|
378
|
+
toAmount: targetRaw.toString(),
|
|
379
|
+
finalAmount: targetRaw.toString(),
|
|
380
|
+
bridge: "direct",
|
|
381
|
+
feeBps: 0,
|
|
382
|
+
estimatedDuration: 0,
|
|
383
|
+
gasCostSource: "0",
|
|
384
|
+
gasCostDest: "0",
|
|
385
|
+
orderRequest: null
|
|
386
|
+
},
|
|
387
|
+
youPayRaw: targetRaw.toString(),
|
|
388
|
+
recipientReceivesRaw: targetRaw.toString(),
|
|
389
|
+
targetRaw: targetRaw.toString(),
|
|
390
|
+
overageBps: 0,
|
|
391
|
+
meetsTarget: true,
|
|
392
|
+
iterations: 0
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
const local1to1 = scaleDecimals(targetRaw, destDecimals, option.decimals);
|
|
396
|
+
const samePriceClass = option.symbolKey === symbolKey(destinationToken.symbol) || SAME_CLASS_STABLE.has(option.symbolKey) && SAME_CLASS_STABLE.has(symbolKey(destinationToken.symbol));
|
|
397
|
+
const maxPayRaw = samePriceClass && local1to1 > 0n ? local1to1 * MAX_SAME_CLASS_PAY_BPS / 10000n : 0n;
|
|
398
|
+
const enforcePayCeiling = (raw) => {
|
|
399
|
+
if (maxPayRaw > 0n && BigInt(raw) > maxPayRaw) {
|
|
400
|
+
throw new Error("ZeroDelta priced this payment above the safety ceiling for the amount.");
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
const bufferNum = BigInt(1e4 + QUOTE_BUFFER_BPS);
|
|
404
|
+
let guess = scaleDecimals(targetRaw, destDecimals, option.decimals) * bufferNum / 10000n;
|
|
405
|
+
if (guess <= 0n) guess = 1n;
|
|
406
|
+
let best = null;
|
|
407
|
+
let bestFinal = -1n;
|
|
408
|
+
let bestGuess = guess;
|
|
409
|
+
for (let i = 0; i < 3; i += 1) {
|
|
410
|
+
const guessSent = guess;
|
|
411
|
+
const quote = await fetchQuote({
|
|
412
|
+
fromChainId: option.chainId,
|
|
413
|
+
toChainId: Number(destination.chainId),
|
|
414
|
+
fromToken: option.symbol,
|
|
415
|
+
toToken: destinationToken.symbol,
|
|
416
|
+
fromAmount: guessSent.toString(),
|
|
417
|
+
owner: payer,
|
|
418
|
+
destinationReceiver: destination.address
|
|
419
|
+
});
|
|
420
|
+
if (BigInt(quote?.fromAmount || "0") !== guessSent) {
|
|
421
|
+
throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
422
|
+
}
|
|
423
|
+
const guaranteed = BigInt(quote?.toAmount || "0");
|
|
424
|
+
const final = finalOf(quote);
|
|
425
|
+
if (final > bestFinal) {
|
|
426
|
+
bestFinal = final;
|
|
427
|
+
best = quote;
|
|
428
|
+
bestGuess = guessSent;
|
|
429
|
+
}
|
|
430
|
+
if (final >= targetRaw) {
|
|
431
|
+
const overageBps = targetRaw > 0n ? Number((final - targetRaw) * 10000n / targetRaw) : 0;
|
|
432
|
+
if (overageBps <= QUOTE_BUFFER_BPS + 25 || i === 2) {
|
|
433
|
+
enforcePayCeiling(guessSent.toString());
|
|
434
|
+
return {
|
|
435
|
+
directTransfer: false,
|
|
436
|
+
quote,
|
|
437
|
+
youPayRaw: guessSent.toString(),
|
|
438
|
+
recipientReceivesRaw: guaranteed.toString(),
|
|
439
|
+
targetRaw: targetRaw.toString(),
|
|
440
|
+
overageBps,
|
|
441
|
+
meetsTarget: true,
|
|
442
|
+
iterations: i + 1
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
guess = guess * targetRaw * bufferNum / (final * 10000n);
|
|
446
|
+
} else if (final <= 0n) {
|
|
447
|
+
guess = guess * 12000n / 10000n;
|
|
448
|
+
} else {
|
|
449
|
+
guess = guess * targetRaw * bufferNum / (final * 10000n);
|
|
450
|
+
}
|
|
451
|
+
if (guess <= 0n) guess = 1n;
|
|
452
|
+
if (maxPayRaw > 0n && guess > maxPayRaw) guess = maxPayRaw;
|
|
453
|
+
}
|
|
454
|
+
if (!best) throw new Error("Could not price this payment route.");
|
|
455
|
+
enforcePayCeiling(bestGuess.toString());
|
|
456
|
+
return {
|
|
457
|
+
directTransfer: false,
|
|
458
|
+
quote: best,
|
|
459
|
+
youPayRaw: bestGuess.toString(),
|
|
460
|
+
recipientReceivesRaw: BigInt(best.toAmount || "0").toString(),
|
|
461
|
+
targetRaw: targetRaw.toString(),
|
|
462
|
+
overageBps: targetRaw > 0n ? Number((bestFinal - targetRaw) * 10000n / targetRaw) : 0,
|
|
463
|
+
meetsTarget: bestFinal >= targetRaw,
|
|
464
|
+
iterations: 3
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
async function solveExactIn({ option, destination, destinationToken, payer, fetchQuote, amountInRaw }) {
|
|
468
|
+
const fromRaw = BigInt(amountInRaw || "0");
|
|
469
|
+
if (fromRaw <= 0n) throw new Error("Swap amount must be greater than zero.");
|
|
470
|
+
const quote = await fetchQuote({
|
|
471
|
+
fromChainId: option.chainId,
|
|
472
|
+
toChainId: Number(destination.chainId),
|
|
473
|
+
fromToken: option.symbol,
|
|
474
|
+
toToken: destinationToken.symbol,
|
|
475
|
+
fromAmount: fromRaw.toString(),
|
|
476
|
+
owner: payer,
|
|
477
|
+
destinationReceiver: destination.address
|
|
478
|
+
});
|
|
479
|
+
if (BigInt(quote?.fromAmount || "0") !== fromRaw) {
|
|
480
|
+
throw new Error("ZeroDelta echoed a different input amount than requested.");
|
|
481
|
+
}
|
|
482
|
+
const guaranteed = BigInt(quote?.toAmount || "0");
|
|
483
|
+
if (guaranteed <= 0n) throw new Error("ZeroDelta could not price this swap.");
|
|
484
|
+
return {
|
|
485
|
+
directTransfer: false,
|
|
486
|
+
quote,
|
|
487
|
+
youPayRaw: fromRaw.toString(),
|
|
488
|
+
recipientReceivesRaw: guaranteed.toString(),
|
|
489
|
+
targetRaw: guaranteed.toString(),
|
|
490
|
+
overageBps: 0,
|
|
491
|
+
meetsTarget: true,
|
|
492
|
+
iterations: 1
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// src/core/order.ts
|
|
497
|
+
function normalizeOrderRequest(order, payer, destination) {
|
|
498
|
+
const apiDeadline = Number(order.deadline);
|
|
499
|
+
const deadline = Number.isFinite(apiDeadline) && apiDeadline > 0 ? String(order.deadline) : String(Math.floor(Date.now() / 1e3) + 1800);
|
|
500
|
+
return {
|
|
501
|
+
owner: assertAddress(order.owner || payer, "Order owner"),
|
|
502
|
+
bidToken: assertAddress(order.bidToken, "Bid token"),
|
|
503
|
+
bidTokenAmount: String(order.bidTokenAmount || "0"),
|
|
504
|
+
askToken: assertAddress(order.askToken, "Ask token"),
|
|
505
|
+
askTokenAmount: String(order.askTokenAmount || "0"),
|
|
506
|
+
destinationReceiver: assertAddress(order.destinationReceiver || destination.address, "Destination receiver"),
|
|
507
|
+
destinationChainId: String(order.destinationChainId || destination.chainId),
|
|
508
|
+
deadline,
|
|
509
|
+
data: order.data || "0x"
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
function assertQuoteMatchesSelection({ quote, order, option, destinationToken, destination, payer, result }) {
|
|
513
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
514
|
+
const deadline = Number(order.deadline || 0);
|
|
515
|
+
if (normalizeAddress(order.owner) !== normalizeAddress(payer)) {
|
|
516
|
+
throw new Error("ZeroDelta quote returned an owner that does not match the connected wallet.");
|
|
517
|
+
}
|
|
518
|
+
if (normalizeAddress(order.destinationReceiver) !== normalizeAddress(destination.address)) {
|
|
519
|
+
throw new Error("ZeroDelta quote returned a receiver that does not match the detected destination.");
|
|
520
|
+
}
|
|
521
|
+
if (normalizeAddress(order.bidToken) !== normalizeAddress(option.address)) {
|
|
522
|
+
throw new Error("ZeroDelta quote returned a bid token that does not match the selected route.");
|
|
523
|
+
}
|
|
524
|
+
if (normalizeAddress(order.askToken) !== normalizeAddress(destinationToken.address)) {
|
|
525
|
+
throw new Error("ZeroDelta quote returned an ask token that does not match the destination asset.");
|
|
526
|
+
}
|
|
527
|
+
if (Number(order.destinationChainId) !== Number(destination.chainId) || Number(quote.toChainId) !== Number(destination.chainId)) {
|
|
528
|
+
throw new Error("ZeroDelta quote returned a destination chain that does not match the payment request.");
|
|
529
|
+
}
|
|
530
|
+
if (Number(quote.fromChainId) !== Number(option.chainId)) {
|
|
531
|
+
throw new Error("ZeroDelta quote returned a source chain that does not match the selected route.");
|
|
532
|
+
}
|
|
533
|
+
if (symbolKey(quote.fromToken) !== option.symbolKey || symbolKey(quote.toToken) !== symbolKey(destinationToken.symbol)) {
|
|
534
|
+
throw new Error("ZeroDelta quote returned token symbols that do not match the selected route.");
|
|
535
|
+
}
|
|
536
|
+
if (BigInt(order.bidTokenAmount || "0") !== BigInt(result.youPayRaw || "0")) {
|
|
537
|
+
throw new Error("ZeroDelta quote returned a bid amount that does not match the displayed payment amount.");
|
|
538
|
+
}
|
|
539
|
+
if (BigInt(order.askTokenAmount || "0") !== BigInt(quote.toAmount || "0")) {
|
|
540
|
+
throw new Error("ZeroDelta quote returned an ask amount that does not match the quoted output.");
|
|
541
|
+
}
|
|
542
|
+
if (BigInt(order.askTokenAmount || "0") <= 0n || BigInt(quote.toAmount || "0") <= 0n) {
|
|
543
|
+
throw new Error("ZeroDelta quote returned a non-positive output amount.");
|
|
544
|
+
}
|
|
545
|
+
if (BigInt(order.askTokenAmount || "0") < BigInt(result.targetRaw || "0")) {
|
|
546
|
+
throw new Error("ZeroDelta quote would not cover the requested destination amount.");
|
|
547
|
+
}
|
|
548
|
+
if (BigInt(order.askTokenAmount || "0") < BigInt(result.recipientReceivesRaw || "0")) {
|
|
549
|
+
throw new Error("ZeroDelta order guarantees less than the displayed receive amount.");
|
|
550
|
+
}
|
|
551
|
+
if (!Number.isFinite(deadline) || deadline <= now || deadline > now + 60 * 60) {
|
|
552
|
+
throw new Error("ZeroDelta quote deadline is invalid or too far in the future.");
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// src/core/route.ts
|
|
557
|
+
function routeDeltaLabel(result, quote) {
|
|
558
|
+
if (result.directTransfer) return "~0";
|
|
559
|
+
if (!result.meetsTarget) return "Below requested amount";
|
|
560
|
+
if (result.overageBps > 0) return `+${(result.overageBps / 100).toFixed(2)}% buffer`;
|
|
561
|
+
if (quote.feeBps) return `${quote.feeBps} bps fee`;
|
|
562
|
+
return "~0";
|
|
563
|
+
}
|
|
564
|
+
function routeLabelFor(option, destinationToken, result) {
|
|
565
|
+
if (result.directTransfer) return "Direct transfer: asset and chain already match.";
|
|
566
|
+
const bridge = result.quote.bridge ? ` via ${result.quote.bridge}` : "";
|
|
567
|
+
return `Swap ${option.symbol} to ${destinationToken.symbol} and settle on ZeroDelta${bridge}.`;
|
|
568
|
+
}
|
|
569
|
+
async function buildRoute({ option, destination, destinationToken, chains, payer, fetchQuote, solve = solveExactOut, amountInRaw }) {
|
|
570
|
+
const result = await solve({ option, destination, destinationToken, payer, fetchQuote, amountInRaw });
|
|
571
|
+
const quote = result.quote;
|
|
572
|
+
const destDecimals = assetDecimals(destinationToken);
|
|
573
|
+
const receiveAmount = formatUnits(result.recipientReceivesRaw, destDecimals);
|
|
574
|
+
const sourceAmount = formatUnits(result.youPayRaw, option.decimals);
|
|
575
|
+
if (result.directTransfer) {
|
|
576
|
+
return {
|
|
577
|
+
id: `direct-${option.symbolKey}-${option.chainId}`,
|
|
578
|
+
recommended: false,
|
|
579
|
+
state: "DIRECT",
|
|
580
|
+
source: {
|
|
581
|
+
asset: option.symbol,
|
|
582
|
+
chainId: option.chainId,
|
|
583
|
+
chainName: option.chainName,
|
|
584
|
+
tokenAddress: option.address,
|
|
585
|
+
decimals: option.decimals,
|
|
586
|
+
amount: sourceAmount,
|
|
587
|
+
payAmount: sourceAmount
|
|
588
|
+
},
|
|
589
|
+
receive: {
|
|
590
|
+
asset: destinationToken.symbol,
|
|
591
|
+
chainId: Number(destination.chainId),
|
|
592
|
+
chainName: chainNameOf(Number(destination.chainId), chains),
|
|
593
|
+
tokenAddress: destinationToken.address,
|
|
594
|
+
decimals: destDecimals,
|
|
595
|
+
amount: receiveAmount
|
|
596
|
+
},
|
|
597
|
+
routeLabel: routeLabelFor(option, destinationToken, result),
|
|
598
|
+
deltaLabel: routeDeltaLabel(result, quote),
|
|
599
|
+
transactions: [
|
|
600
|
+
{
|
|
601
|
+
id: "transfer",
|
|
602
|
+
kind: "transfer",
|
|
603
|
+
label: `Transfer ${destinationToken.symbol}`,
|
|
604
|
+
chainId: option.chainId,
|
|
605
|
+
to: option.address,
|
|
606
|
+
data: encodeTransfer(destination.address, result.youPayRaw),
|
|
607
|
+
value: "0x0",
|
|
608
|
+
token: option.address,
|
|
609
|
+
amountRaw: result.youPayRaw
|
|
610
|
+
}
|
|
611
|
+
],
|
|
612
|
+
quote: {
|
|
613
|
+
bridge: quote.bridge,
|
|
614
|
+
feeBps: quote.feeBps,
|
|
615
|
+
estimatedDuration: quote.estimatedDuration,
|
|
616
|
+
iterations: result.iterations
|
|
617
|
+
}
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
if (!quote.orderRequest) throw new Error("ZeroDelta quote did not include an order request.");
|
|
621
|
+
const sourceChain = chainById(chains, option.chainId);
|
|
622
|
+
const escrow = checkEscrow(option.chainId, quote.escrowAddress, sourceChain?.escrowContract);
|
|
623
|
+
const order = normalizeOrderRequest(quote.orderRequest, payer, destination);
|
|
624
|
+
assertQuoteMatchesSelection({ quote, order, option, destinationToken, destination, payer, result });
|
|
625
|
+
const needsNativeFee = requiresNativeBridgeFee(quote, option);
|
|
626
|
+
if (needsNativeFee) {
|
|
627
|
+
let rawFee;
|
|
628
|
+
try {
|
|
629
|
+
rawFee = BigInt(quote.gasCostSource || "0");
|
|
630
|
+
} catch {
|
|
631
|
+
throw new Error("ZeroDelta quote returned an unreadable LayerZero bridge fee; refusing to sign.");
|
|
632
|
+
}
|
|
633
|
+
if (rawFee > maxNativeFeeWei(option.chainId)) {
|
|
634
|
+
throw new Error("LayerZero native fee exceeds the safety cap; refusing to sign.");
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
const valueRaw = applyLayerZeroBuffer(quote, option);
|
|
638
|
+
if (!needsNativeFee) {
|
|
639
|
+
if (valueRaw !== 0n) throw new Error("Non-LayerZero route requested a non-zero native value; refusing to sign.");
|
|
640
|
+
} else if (valueRaw === 0n && Number(quote.executionChainId) > 0) {
|
|
641
|
+
throw new Error("ZeroDelta quote is missing the LayerZero bridge fee for this route; refusing to sign.");
|
|
642
|
+
}
|
|
643
|
+
return {
|
|
644
|
+
id: `zd-${option.symbolKey}-${option.chainId}-${symbolKey(destinationToken.symbol)}-${destination.chainId}`,
|
|
645
|
+
recommended: false,
|
|
646
|
+
state: result.meetsTarget ? "ROUTE" : "SHORT",
|
|
647
|
+
source: {
|
|
648
|
+
asset: option.symbol,
|
|
649
|
+
chainId: option.chainId,
|
|
650
|
+
chainName: option.chainName,
|
|
651
|
+
tokenAddress: option.address,
|
|
652
|
+
decimals: option.decimals,
|
|
653
|
+
amount: sourceAmount,
|
|
654
|
+
payAmount: sourceAmount
|
|
655
|
+
},
|
|
656
|
+
receive: {
|
|
657
|
+
asset: destinationToken.symbol,
|
|
658
|
+
chainId: Number(destination.chainId),
|
|
659
|
+
chainName: chainNameOf(Number(destination.chainId), chains),
|
|
660
|
+
tokenAddress: destinationToken.address,
|
|
661
|
+
decimals: destDecimals,
|
|
662
|
+
amount: receiveAmount
|
|
663
|
+
},
|
|
664
|
+
routeLabel: routeLabelFor(option, destinationToken, result),
|
|
665
|
+
deltaLabel: routeDeltaLabel(result, quote),
|
|
666
|
+
transactions: [
|
|
667
|
+
{
|
|
668
|
+
id: "approve",
|
|
669
|
+
kind: "approve",
|
|
670
|
+
label: `Approve ${option.symbol}`,
|
|
671
|
+
chainId: option.chainId,
|
|
672
|
+
to: option.address,
|
|
673
|
+
data: encodeApprove(escrow, order.bidTokenAmount),
|
|
674
|
+
value: "0x0",
|
|
675
|
+
token: option.address,
|
|
676
|
+
spender: escrow,
|
|
677
|
+
amountRaw: order.bidTokenAmount
|
|
678
|
+
},
|
|
679
|
+
{
|
|
680
|
+
id: "submit-order",
|
|
681
|
+
kind: "submitOrder",
|
|
682
|
+
label: "Submit ZeroDelta order",
|
|
683
|
+
chainId: option.chainId,
|
|
684
|
+
to: escrow,
|
|
685
|
+
data: encodeSubmitOrder(order),
|
|
686
|
+
value: toHexQuantity(valueRaw),
|
|
687
|
+
escrow,
|
|
688
|
+
amountRaw: order.bidTokenAmount
|
|
689
|
+
}
|
|
690
|
+
],
|
|
691
|
+
quote: {
|
|
692
|
+
bridge: quote.bridge,
|
|
693
|
+
feeBps: quote.feeBps,
|
|
694
|
+
estimatedDuration: quote.estimatedDuration,
|
|
695
|
+
gasCostSource: quote.gasCostSource,
|
|
696
|
+
msgValue: valueRaw.toString(),
|
|
697
|
+
deadline: order.deadline,
|
|
698
|
+
iterations: result.iterations
|
|
699
|
+
}
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
// src/core/api.ts
|
|
704
|
+
function apiError(message, props = {}) {
|
|
705
|
+
const err = new Error(message);
|
|
706
|
+
Object.assign(err, props);
|
|
707
|
+
return err;
|
|
708
|
+
}
|
|
709
|
+
function toQuery(params) {
|
|
710
|
+
const entries = Object.entries(params).filter(([, v]) => v !== void 0 && v !== "" && v !== null);
|
|
711
|
+
if (!entries.length) return "";
|
|
712
|
+
return `?${new URLSearchParams(entries.map(([k, v]) => [k, String(v)])).toString()}`;
|
|
713
|
+
}
|
|
714
|
+
var MAX_MESSAGE_LEN = 160;
|
|
715
|
+
function sanitizeMessage(value, fallback) {
|
|
716
|
+
const text = typeof value === "string" ? value.trim() : "";
|
|
717
|
+
if (!text) return fallback;
|
|
718
|
+
const leaksInfra = /(https?:\/\/|\b\w+:\/\/|\b[\w.-]+\.(?:internal|local|amazonaws\.com|vercel\.app)\b|\b\d{1,3}(?:\.\d{1,3}){3}\b|\b[a-z0-9][a-z0-9.-]*\.[a-z]{2,}:\d{2,5}\b|\blocalhost:\d{2,5}\b|[A-Za-z]:\\|\/(?:usr|var|home|opt|etc)\/|\bat\s+\w+\s*\(|\.(?:go|ts|js|py|tsx|jsx):\d+)/i.test(
|
|
719
|
+
text
|
|
720
|
+
);
|
|
721
|
+
if (leaksInfra) return fallback;
|
|
722
|
+
return text.length > MAX_MESSAGE_LEN ? `${text.slice(0, MAX_MESSAGE_LEN - 1)}\u2026` : text;
|
|
723
|
+
}
|
|
724
|
+
function apiMessage(json, fallback) {
|
|
725
|
+
const err = json?.error || json;
|
|
726
|
+
if (err?.fieldErrors?.[0]?.message) return sanitizeMessage(err.fieldErrors[0].message, fallback);
|
|
727
|
+
if (Array.isArray(err?.reasons) && err.reasons.length) {
|
|
728
|
+
const head = sanitizeMessage(err.message, fallback);
|
|
729
|
+
const detail = sanitizeMessage(err.reasons.filter((r) => typeof r === "string").join(", "), "");
|
|
730
|
+
return detail ? `${head}: ${detail}` : head;
|
|
731
|
+
}
|
|
732
|
+
return sanitizeMessage(err?.message, fallback);
|
|
733
|
+
}
|
|
734
|
+
var BLOCK_CATEGORY_LABELS = {
|
|
735
|
+
STOLEN_FUNDS: "flagged as associated with stolen funds",
|
|
736
|
+
SANCTIONS: "on a sanctions list",
|
|
737
|
+
SANCTIONED: "on a sanctions list",
|
|
738
|
+
OFAC: "on a sanctions list",
|
|
739
|
+
TERRORIST_FINANCING: "flagged for terrorist financing",
|
|
740
|
+
FRAUD: "flagged for fraud",
|
|
741
|
+
SCAM: "flagged as a scam address"
|
|
742
|
+
};
|
|
743
|
+
var BLOCK_LABEL_DEFAULT = "flagged by compliance screening";
|
|
744
|
+
function classifyQuoteError(error) {
|
|
745
|
+
if (!error) return null;
|
|
746
|
+
const reasons = Array.isArray(error.reasons) ? error.reasons : [];
|
|
747
|
+
const haystack = `${error.message || ""} ${reasons.join(" ")}`;
|
|
748
|
+
const catMatch = /blocked_category:\s*([A-Za-z_]+)/i.exec(haystack);
|
|
749
|
+
const isBlock = !!catMatch || error.code === "blocked" || error.code === "compliance_block" || /\b(stolen|sanction(?:s|ed|ing)?|block(?:ed|list)|screen(?:ed|ing)?|compliance|ofac|denylist|blacklist)\b/i.test(haystack);
|
|
750
|
+
if (!isBlock) return null;
|
|
751
|
+
const category = (catMatch?.[1] || "").toUpperCase() || "COMPLIANCE";
|
|
752
|
+
const label = BLOCK_CATEGORY_LABELS[category] || BLOCK_LABEL_DEFAULT;
|
|
753
|
+
return {
|
|
754
|
+
blocked: true,
|
|
755
|
+
category,
|
|
756
|
+
reason: reasons.join(", ") || error.message || "",
|
|
757
|
+
message: `This payment was blocked by compliance screening \u2014 the recipient is ${label}. Choose a different recipient or connect a different wallet.`
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
function nowFresh(entry) {
|
|
761
|
+
return !!entry && Date.now() - entry.at < API_CACHE_TTL_MS;
|
|
762
|
+
}
|
|
763
|
+
function isTransientQuoteError(error) {
|
|
764
|
+
return error?.code === "gateway_timeout" || error?.status === 502 || error?.status === 503 || error?.status === 504 || /failed to get swap quote|timeout|temporar/i.test(error?.message || "");
|
|
765
|
+
}
|
|
766
|
+
function wait(ms) {
|
|
767
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
768
|
+
}
|
|
769
|
+
function createApiClient(cfg) {
|
|
770
|
+
const cache = {
|
|
771
|
+
chains: null,
|
|
772
|
+
tokens: null,
|
|
773
|
+
routes: null
|
|
774
|
+
};
|
|
775
|
+
const apiBase = cfg.apiBase.replace(/\/$/, "");
|
|
776
|
+
async function apiRequest(path, init = {}) {
|
|
777
|
+
const apiKey = await cfg.getApiKey();
|
|
778
|
+
const headers = { "Content-Type": "application/json", ...init.headers || {} };
|
|
779
|
+
if (apiKey) headers["x-api-key"] = apiKey;
|
|
780
|
+
const controller = new AbortController();
|
|
781
|
+
const timeoutId = setTimeout(() => controller.abort(), init.timeoutMs || 15e3);
|
|
782
|
+
let response;
|
|
783
|
+
try {
|
|
784
|
+
response = await cfg.fetchImpl(`${apiBase}${path}`, { ...init, headers, signal: init.signal || controller.signal });
|
|
785
|
+
} catch (error) {
|
|
786
|
+
throw apiError(error?.name === "AbortError" ? "ZeroDelta request timed out." : error?.message || "ZeroDelta request failed.", {
|
|
787
|
+
code: error?.name === "AbortError" ? "gateway_timeout" : "network_error"
|
|
788
|
+
});
|
|
789
|
+
} finally {
|
|
790
|
+
clearTimeout(timeoutId);
|
|
791
|
+
}
|
|
792
|
+
const text = await response.text();
|
|
793
|
+
let json = null;
|
|
794
|
+
if (text) {
|
|
795
|
+
try {
|
|
796
|
+
json = JSON.parse(text);
|
|
797
|
+
} catch {
|
|
798
|
+
throw apiError(response.ok ? "ZeroDelta returned an invalid response." : `ZeroDelta upstream error (${response.status}).`, {
|
|
799
|
+
status: response.status,
|
|
800
|
+
code: response.status >= 502 ? "gateway_timeout" : "bad_response"
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
if (!response.ok) {
|
|
805
|
+
throw apiError(apiMessage(json, `ZeroDelta request failed (${response.status}).`), {
|
|
806
|
+
status: response.status,
|
|
807
|
+
code: json?.error?.code || json?.code || (response.status >= 502 ? "gateway_timeout" : "api_error"),
|
|
808
|
+
fieldErrors: json?.error?.fieldErrors || json?.fieldErrors,
|
|
809
|
+
reasons: json?.error?.reasons || json?.reasons
|
|
810
|
+
});
|
|
811
|
+
}
|
|
812
|
+
return json?.data ?? json;
|
|
813
|
+
}
|
|
814
|
+
async function fetchChains() {
|
|
815
|
+
if (nowFresh(cache.chains)) return cache.chains.value;
|
|
816
|
+
const chains = await apiRequest(`/chains${toQuery({ enabledOnly: true, limit: 500 })}`);
|
|
817
|
+
const normalized = (Array.isArray(chains) ? chains : []).map((chain) => ({ ...chain, chainId: Number(chain.chainId) })).map((chain) => {
|
|
818
|
+
const escrow = normalizeAddress(chain.escrowContract);
|
|
819
|
+
return escrow ? { ...chain, escrowContract: escrow } : { ...chain, escrowContract: void 0 };
|
|
820
|
+
});
|
|
821
|
+
cache.chains = { at: Date.now(), value: normalized };
|
|
822
|
+
return normalized;
|
|
823
|
+
}
|
|
824
|
+
async function fetchTokens() {
|
|
825
|
+
if (nowFresh(cache.tokens)) return cache.tokens.value;
|
|
826
|
+
const tokens = await apiRequest(`/tokens${toQuery({ limit: 500 })}`);
|
|
827
|
+
const normalized = (Array.isArray(tokens) ? tokens : []).map((token) => ({ ...token, chainId: Number(token.chainId) }));
|
|
828
|
+
cache.tokens = { at: Date.now(), value: normalized };
|
|
829
|
+
return normalized;
|
|
830
|
+
}
|
|
831
|
+
async function fetchRoutes() {
|
|
832
|
+
if (nowFresh(cache.routes)) return cache.routes.value;
|
|
833
|
+
try {
|
|
834
|
+
const routes = await apiRequest(`/routes${toQuery({ limit: 500 })}`);
|
|
835
|
+
const normalized = Array.isArray(routes) ? routes : [];
|
|
836
|
+
cache.routes = { at: Date.now(), value: normalized };
|
|
837
|
+
return normalized;
|
|
838
|
+
} catch {
|
|
839
|
+
cache.routes = { at: Date.now(), value: [] };
|
|
840
|
+
return [];
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
async function fetchQuote(body, retries = 1) {
|
|
844
|
+
let lastError;
|
|
845
|
+
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
|
846
|
+
try {
|
|
847
|
+
const quote = await apiRequest("/quote", { method: "POST", body: JSON.stringify(body), timeoutMs: 18e3 });
|
|
848
|
+
return quote && quote.executionChainId != null ? { ...quote, executionChainId: Number(quote.executionChainId) } : quote;
|
|
849
|
+
} catch (error) {
|
|
850
|
+
lastError = error;
|
|
851
|
+
if (attempt >= retries || !isTransientQuoteError(error)) throw error;
|
|
852
|
+
await wait(1400);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
throw lastError;
|
|
856
|
+
}
|
|
857
|
+
return { apiRequest, fetchChains, fetchTokens, fetchRoutes, fetchQuote, apiBase };
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// src/core/plan.ts
|
|
861
|
+
function validateDestination(destination) {
|
|
862
|
+
assertAddress(destination.address, "Destination address");
|
|
863
|
+
const chainId = Number(destination.chainId);
|
|
864
|
+
const asset = symbolKey(destination.asset);
|
|
865
|
+
if (!SUPPORTED_CHAIN_IDS.has(chainId)) throw new Error("Unsupported destination chain.");
|
|
866
|
+
if (!SUPPORTED_ASSETS.has(asset)) throw new Error("Unsupported destination asset.");
|
|
867
|
+
const normalizedAmount = normalizeDecimalText(destination.amount);
|
|
868
|
+
if (!/^\d+(\.\d+)?$/.test(normalizedAmount)) throw new Error("Could not detect a valid payment amount.");
|
|
869
|
+
if (Number(normalizedAmount) <= 0 || Number(normalizedAmount) > 1e9) throw new Error("Payment amount is outside the supported range.");
|
|
870
|
+
destination.amount = normalizedAmount;
|
|
871
|
+
}
|
|
872
|
+
function planErrorSummary(errors) {
|
|
873
|
+
const unique = [...new Set(errors.map((error) => error?.message || String(error)).filter(Boolean))].slice(0, 3);
|
|
874
|
+
return unique.length ? unique.join(" | ") : "No ZeroDelta route is currently available for this payment.";
|
|
875
|
+
}
|
|
876
|
+
async function fetchPaymentPlan(api, request, payer, wallet = {}) {
|
|
877
|
+
validateDestination(request);
|
|
878
|
+
assertAddress(payer, "Payer wallet");
|
|
879
|
+
const [chains, tokens, routes] = await Promise.all([api.fetchChains(), api.fetchTokens(), api.fetchRoutes()]);
|
|
880
|
+
const destination = {
|
|
881
|
+
...request,
|
|
882
|
+
chainId: Number(request.chainId),
|
|
883
|
+
asset: symbolKey(request.asset)
|
|
884
|
+
};
|
|
885
|
+
const destinationToken = findToken(tokens, destination.chainId, destination.asset);
|
|
886
|
+
if (!destinationToken) throw new Error(`${destination.asset} is not enabled on ${chainNameOf(destination.chainId, chains)}.`);
|
|
887
|
+
const options = buildPayOptions({
|
|
888
|
+
invoiceAsset: destination.asset,
|
|
889
|
+
invoiceChainId: destination.chainId,
|
|
890
|
+
tokens,
|
|
891
|
+
routes,
|
|
892
|
+
chains,
|
|
893
|
+
walletChainId: wallet?.chainId
|
|
894
|
+
});
|
|
895
|
+
if (!options.length) throw new Error(`No enabled ZeroDelta funding assets can settle ${destination.asset} on ${chainNameOf(destination.chainId, chains)}.`);
|
|
896
|
+
const candidates = options.filter((option) => option.direct);
|
|
897
|
+
const seenChains = /* @__PURE__ */ new Set();
|
|
898
|
+
const perChainBest = [];
|
|
899
|
+
const leftovers = [];
|
|
900
|
+
for (const option of options) {
|
|
901
|
+
if (option.direct) continue;
|
|
902
|
+
if (seenChains.has(option.chainId)) {
|
|
903
|
+
leftovers.push(option);
|
|
904
|
+
} else {
|
|
905
|
+
seenChains.add(option.chainId);
|
|
906
|
+
perChainBest.push(option);
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
for (const option of [...perChainBest, ...leftovers].slice(0, MAX_QUOTE_CANDIDATES)) {
|
|
910
|
+
candidates.push(option);
|
|
911
|
+
}
|
|
912
|
+
const routeErrors = [];
|
|
913
|
+
const routePromises = candidates.map(
|
|
914
|
+
(option) => buildRoute({ option, destination, destinationToken, chains, payer, fetchQuote: api.fetchQuote }).catch((error) => {
|
|
915
|
+
routeErrors.push(error);
|
|
916
|
+
return null;
|
|
917
|
+
})
|
|
918
|
+
);
|
|
919
|
+
const routesBuilt = (await Promise.all(routePromises)).filter(Boolean);
|
|
920
|
+
routesBuilt.sort((a, b) => {
|
|
921
|
+
const walletChain = Number(wallet?.chainId || 0);
|
|
922
|
+
if (a.state !== "SHORT" && b.state === "SHORT") return -1;
|
|
923
|
+
if (b.state !== "SHORT" && a.state === "SHORT") return 1;
|
|
924
|
+
if (walletChain) {
|
|
925
|
+
if (a.source.chainId === walletChain && b.source.chainId !== walletChain) return -1;
|
|
926
|
+
if (b.source.chainId === walletChain && a.source.chainId !== walletChain) return 1;
|
|
927
|
+
}
|
|
928
|
+
if (a.state !== b.state) return a.state === "DIRECT" ? -1 : b.state === "DIRECT" ? 1 : 0;
|
|
929
|
+
return Number(a.quote?.feeBps || 0) - Number(b.quote?.feeBps || 0);
|
|
930
|
+
});
|
|
931
|
+
const recommended = routesBuilt.find((route) => route.state !== "SHORT");
|
|
932
|
+
if (recommended) recommended.recommended = true;
|
|
933
|
+
if (!routesBuilt.length || !recommended) {
|
|
934
|
+
const blocked = routeErrors.map(classifyQuoteError).find(Boolean);
|
|
935
|
+
if (blocked) throw apiError(blocked.message, { blocked: true, blockedCategory: blocked.category, blockedReason: blocked.reason });
|
|
936
|
+
throw new Error(planErrorSummary(routeErrors));
|
|
937
|
+
}
|
|
938
|
+
return {
|
|
939
|
+
mode: "zerodelta",
|
|
940
|
+
requestId: `zd_${Date.now().toString(36)}_${Math.random().toString(16).slice(2, 10)}`,
|
|
941
|
+
expiresAt: new Date(Date.now() + 2 * 60 * 1e3).toISOString(),
|
|
942
|
+
apiBase: api.apiBase,
|
|
943
|
+
routes: routesBuilt,
|
|
944
|
+
destination: {
|
|
945
|
+
asset: destinationToken.symbol,
|
|
946
|
+
chainId: destination.chainId,
|
|
947
|
+
chainName: chainNameOf(destination.chainId, chains),
|
|
948
|
+
tokenAddress: destinationToken.address,
|
|
949
|
+
decimals: assetDecimals(destinationToken),
|
|
950
|
+
amount: destination.amount,
|
|
951
|
+
address: destination.address
|
|
952
|
+
}
|
|
953
|
+
};
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
// src/core/swap.ts
|
|
957
|
+
function validateSwap(swap = {}) {
|
|
958
|
+
const fromChainId = Number(swap.fromChainId);
|
|
959
|
+
const toChainId = Number(swap.toChainId);
|
|
960
|
+
const fromToken = symbolKey(swap.fromToken);
|
|
961
|
+
const toToken = symbolKey(swap.toToken);
|
|
962
|
+
if (!SUPPORTED_CHAIN_IDS.has(fromChainId) || !SUPPORTED_CHAIN_IDS.has(toChainId)) throw new Error("Unsupported swap chain.");
|
|
963
|
+
if (!SUPPORTED_ASSETS.has(fromToken) || !SUPPORTED_ASSETS.has(toToken)) throw new Error("Unsupported swap asset.");
|
|
964
|
+
const amountIn = normalizeDecimalText(swap.amountIn);
|
|
965
|
+
if (!/^\d+(\.\d+)?$/.test(amountIn) || Number(amountIn) <= 0 || Number(amountIn) > 1e9) throw new Error("Enter a valid swap amount.");
|
|
966
|
+
return { fromChainId, toChainId, fromToken, toToken, amountIn };
|
|
967
|
+
}
|
|
968
|
+
async function quoteSwapPreview(api, swap, owner) {
|
|
969
|
+
const v = validateSwap(swap);
|
|
970
|
+
const tokens = await api.fetchTokens();
|
|
971
|
+
const sourceToken = findToken(tokens, v.fromChainId, v.fromToken);
|
|
972
|
+
const destToken = findToken(tokens, v.toChainId, v.toToken);
|
|
973
|
+
if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on that source chain.`);
|
|
974
|
+
if (!destToken) throw new Error(`${v.toToken} is not enabled on that destination chain.`);
|
|
975
|
+
const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
|
|
976
|
+
const account = normalizeAddress(owner) || PREVIEW_OWNER;
|
|
977
|
+
const previewReceiver = normalizeAddress(swap.recipient) || account;
|
|
978
|
+
const quote = await api.fetchQuote({
|
|
979
|
+
fromChainId: v.fromChainId,
|
|
980
|
+
toChainId: v.toChainId,
|
|
981
|
+
fromToken: sourceToken.symbol,
|
|
982
|
+
toToken: destToken.symbol,
|
|
983
|
+
fromAmount: amountInRaw.toString(),
|
|
984
|
+
owner: account,
|
|
985
|
+
destinationReceiver: previewReceiver
|
|
986
|
+
});
|
|
987
|
+
const final = finalOf(quote);
|
|
988
|
+
return {
|
|
989
|
+
receive: formatUnits(final, assetDecimals(destToken)),
|
|
990
|
+
receiveRaw: final.toString(),
|
|
991
|
+
fromAmount: v.amountIn,
|
|
992
|
+
fromToken: sourceToken.symbol,
|
|
993
|
+
toToken: destToken.symbol,
|
|
994
|
+
bridge: quote.bridge || "",
|
|
995
|
+
feeBps: Number(quote.feeBps || 0),
|
|
996
|
+
estimatedDuration: Number(quote.estimatedDuration || 0)
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
async function buildSwapPlan(api, swap, payer, wallet = {}) {
|
|
1000
|
+
const v = validateSwap(swap);
|
|
1001
|
+
const account = assertAddress(payer, "Swap wallet");
|
|
1002
|
+
const [chains, tokens] = await Promise.all([api.fetchChains(), api.fetchTokens()]);
|
|
1003
|
+
const sourceToken = findToken(tokens, v.fromChainId, v.fromToken);
|
|
1004
|
+
const destToken = findToken(tokens, v.toChainId, v.toToken);
|
|
1005
|
+
if (!sourceToken) throw new Error(`${v.fromToken} is not enabled on ${chainNameOf(v.fromChainId, chains)}.`);
|
|
1006
|
+
if (!destToken) throw new Error(`${v.toToken} is not enabled on ${chainNameOf(v.toChainId, chains)}.`);
|
|
1007
|
+
const amountInRaw = parseUnitsDecimal(v.amountIn, assetDecimals(sourceToken));
|
|
1008
|
+
const receiver = resolveSwapReceiver(swap.recipient, account);
|
|
1009
|
+
const option = {
|
|
1010
|
+
symbol: sourceToken.symbol,
|
|
1011
|
+
symbolKey: symbolKey(sourceToken.symbol),
|
|
1012
|
+
name: sourceToken.name || sourceToken.symbol,
|
|
1013
|
+
chainId: v.fromChainId,
|
|
1014
|
+
chainName: chainNameOf(v.fromChainId, chains),
|
|
1015
|
+
address: sourceToken.address,
|
|
1016
|
+
decimals: assetDecimals(sourceToken),
|
|
1017
|
+
// Carry the source token's bridge through: it is the inbound (source -> execution chain) leg,
|
|
1018
|
+
// which is what decides whether the escrow order owes a native LayerZero fee. buildPayOptions
|
|
1019
|
+
// sets this for the Pay flow; omitting it here left the Swap flow with no bridge signal at all.
|
|
1020
|
+
bridge: sourceToken.bridge,
|
|
1021
|
+
direct: false
|
|
1022
|
+
};
|
|
1023
|
+
const destination = { address: receiver, chainId: v.toChainId, asset: destToken.symbol };
|
|
1024
|
+
const route = await buildRoute({ option, destination, destinationToken: destToken, chains, payer: account, fetchQuote: api.fetchQuote, solve: solveExactIn, amountInRaw });
|
|
1025
|
+
if (route.state === "SHORT") throw new Error("ZeroDelta could not price this swap right now.");
|
|
1026
|
+
route.recommended = true;
|
|
1027
|
+
return {
|
|
1028
|
+
mode: "swap",
|
|
1029
|
+
requestId: `zdswap_${Date.now().toString(36)}`,
|
|
1030
|
+
expiresAt: new Date(Date.now() + 2 * 60 * 1e3).toISOString(),
|
|
1031
|
+
apiBase: api.apiBase,
|
|
1032
|
+
routes: [route],
|
|
1033
|
+
destination: {
|
|
1034
|
+
asset: destToken.symbol,
|
|
1035
|
+
chainId: v.toChainId,
|
|
1036
|
+
chainName: chainNameOf(v.toChainId, chains),
|
|
1037
|
+
tokenAddress: destToken.address,
|
|
1038
|
+
decimals: assetDecimals(destToken),
|
|
1039
|
+
amount: route.receive.amount,
|
|
1040
|
+
address: receiver
|
|
1041
|
+
}
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
// src/core/validate-tx.ts
|
|
1046
|
+
var lower = (v) => String(v || "").toLowerCase();
|
|
1047
|
+
function isHexAddress(value) {
|
|
1048
|
+
return /^0x[a-fA-F0-9]{40}$/.test(String(value || ""));
|
|
1049
|
+
}
|
|
1050
|
+
function isHexData(value) {
|
|
1051
|
+
return /^0x(?:[a-fA-F0-9]{2})*$/.test(String(value || "0x"));
|
|
1052
|
+
}
|
|
1053
|
+
function isHexQuantity(value) {
|
|
1054
|
+
return /^0x[0-9a-fA-F]+$/.test(String(value || "0x0"));
|
|
1055
|
+
}
|
|
1056
|
+
function dataWord(data, index) {
|
|
1057
|
+
const word = String(data || "").slice(10 + index * 64, 10 + (index + 1) * 64);
|
|
1058
|
+
return /^[a-fA-F0-9]{64}$/.test(word) ? word : "";
|
|
1059
|
+
}
|
|
1060
|
+
function dataAddress(data, index) {
|
|
1061
|
+
const word = dataWord(data, index);
|
|
1062
|
+
return word ? `0x${word.slice(24)}` : "";
|
|
1063
|
+
}
|
|
1064
|
+
function dataUint(data, index) {
|
|
1065
|
+
const word = dataWord(data, index);
|
|
1066
|
+
return word ? BigInt(`0x${word}`) : null;
|
|
1067
|
+
}
|
|
1068
|
+
function rawEquals(value, expected) {
|
|
1069
|
+
try {
|
|
1070
|
+
return value === BigInt(expected || "0");
|
|
1071
|
+
} catch {
|
|
1072
|
+
return false;
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
function planMsgValueHex(route) {
|
|
1076
|
+
try {
|
|
1077
|
+
const raw = route?.quote?.msgValue;
|
|
1078
|
+
if (raw === void 0 || raw === null || raw === "") return "0x0";
|
|
1079
|
+
return "0x" + BigInt(raw).toString(16);
|
|
1080
|
+
} catch {
|
|
1081
|
+
return null;
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
function validatePlannedTransaction(tx, route, expectedRecipient) {
|
|
1085
|
+
if (!tx || tx.mock) return true;
|
|
1086
|
+
if (!isHexAddress(tx.to) || !isHexData(tx.data || "0x") || !isHexQuantity(tx.value || "0x0")) return false;
|
|
1087
|
+
const data = String(tx.data || "0x").toLowerCase();
|
|
1088
|
+
const selector = data.slice(0, 10);
|
|
1089
|
+
const value = lower(tx.value || "0x0");
|
|
1090
|
+
if (tx.kind === "transfer") {
|
|
1091
|
+
if (value !== "0x0") return false;
|
|
1092
|
+
return selector === "0xa9059cbb" && isHexAddress(tx.token) && lower(tx.to) === lower(tx.token) && lower(dataAddress(data, 0)) === lower(expectedRecipient) && rawEquals(dataUint(data, 1), tx.amountRaw);
|
|
1093
|
+
}
|
|
1094
|
+
if (tx.kind === "approve") {
|
|
1095
|
+
if (value !== "0x0") return false;
|
|
1096
|
+
return selector === "0x095ea7b3" && isHexAddress(tx.token) && isHexAddress(tx.spender) && lower(tx.to) === lower(tx.token) && lower(dataAddress(data, 0)) === lower(tx.spender) && rawEquals(dataUint(data, 1), tx.amountRaw);
|
|
1097
|
+
}
|
|
1098
|
+
if (tx.kind === "submitOrder") {
|
|
1099
|
+
const expected = planMsgValueHex(route);
|
|
1100
|
+
if (expected === null || value !== lower(expected)) return false;
|
|
1101
|
+
return selector === "0xbbd71141" && isHexAddress(tx.escrow) && lower(tx.to) === lower(tx.escrow);
|
|
1102
|
+
}
|
|
1103
|
+
return false;
|
|
1104
|
+
}
|
|
1105
|
+
async function allowanceCovers(tx, account, ethCall) {
|
|
1106
|
+
if (tx?.kind !== "approve" || !tx.token || !tx.spender || !tx.amountRaw || !account) return false;
|
|
1107
|
+
try {
|
|
1108
|
+
const raw = await ethCall(tx.token, encodeAllowance(account, tx.spender));
|
|
1109
|
+
return BigInt(raw || "0x0") >= BigInt(tx.amountRaw || "0");
|
|
1110
|
+
} catch {
|
|
1111
|
+
return false;
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
// src/core/intent-schema.ts
|
|
1116
|
+
var STABLEGENIE_INTENT_VERSION = 1;
|
|
1117
|
+
var STABLEGENIE_INTENT_TTL_MS = 5 * 60 * 1e3;
|
|
1118
|
+
var STABLEGENIE_SUPPORTED_CHAIN_IDS = Object.freeze([1, 10, 130, 146, 8453, 9745, 57073, 42161]);
|
|
1119
|
+
var STABLEGENIE_SUPPORTED_ASSETS = Object.freeze(["USDC", "USDE", "USDT", "XAUT"]);
|
|
1120
|
+
var stableGenieIntentSchema = {
|
|
1121
|
+
type: "object",
|
|
1122
|
+
additionalProperties: false,
|
|
1123
|
+
required: ["version", "product", "lane", "nonce", "createdAt", "expiresAt", "sourcePage", "destination"],
|
|
1124
|
+
properties: {
|
|
1125
|
+
version: { const: STABLEGENIE_INTENT_VERSION },
|
|
1126
|
+
product: { const: "stablegenie" },
|
|
1127
|
+
lane: { enum: ["CRYPTO_TO_CRYPTO"] },
|
|
1128
|
+
status: { enum: ["unsigned", "quoted", "submitted", "settled", "expired"] },
|
|
1129
|
+
nonce: { type: "string", minLength: 16, maxLength: 128 },
|
|
1130
|
+
createdAt: { type: "string", format: "date-time" },
|
|
1131
|
+
expiresAt: { type: "string", format: "date-time" },
|
|
1132
|
+
intentHash: { type: "string", pattern: "^0x[a-fA-F0-9]{64}$" },
|
|
1133
|
+
sourcePage: {
|
|
1134
|
+
type: "object",
|
|
1135
|
+
additionalProperties: false,
|
|
1136
|
+
required: ["origin", "url"],
|
|
1137
|
+
properties: {
|
|
1138
|
+
origin: { type: "string", pattern: "^https?://" },
|
|
1139
|
+
url: { type: "string", pattern: "^https?://" },
|
|
1140
|
+
title: { type: "string", maxLength: 256 }
|
|
1141
|
+
}
|
|
1142
|
+
},
|
|
1143
|
+
destination: {
|
|
1144
|
+
type: "object",
|
|
1145
|
+
additionalProperties: false,
|
|
1146
|
+
required: ["address", "chainId", "asset", "amount"],
|
|
1147
|
+
properties: {
|
|
1148
|
+
address: { type: "string", pattern: "^0x[a-fA-F0-9]{40}$" },
|
|
1149
|
+
chainId: { type: "integer", enum: STABLEGENIE_SUPPORTED_CHAIN_IDS },
|
|
1150
|
+
chainName: { type: "string", maxLength: 64 },
|
|
1151
|
+
asset: { type: "string", enum: STABLEGENIE_SUPPORTED_ASSETS },
|
|
1152
|
+
amount: { type: "string", pattern: "^(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?$" }
|
|
1153
|
+
}
|
|
1154
|
+
},
|
|
1155
|
+
detector: {
|
|
1156
|
+
type: "object",
|
|
1157
|
+
additionalProperties: false,
|
|
1158
|
+
properties: {
|
|
1159
|
+
confidence: { type: "number", minimum: 0, maximum: 1 },
|
|
1160
|
+
evidence: { type: "object" },
|
|
1161
|
+
elementText: { type: "string", maxLength: 500 }
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
};
|
|
1166
|
+
|
|
1167
|
+
// src/core/verify.ts
|
|
1168
|
+
var TX_VERIFY_ATTEMPTS = 5;
|
|
1169
|
+
var TX_VERIFY_INTERVAL_MS = 2500;
|
|
1170
|
+
var TX_VERIFY_FETCH_MS = 5e3;
|
|
1171
|
+
var TX_VERIFY_DEADLINE_MS = 18e3;
|
|
1172
|
+
function registryRpc(chain) {
|
|
1173
|
+
if (!chain) return "";
|
|
1174
|
+
const candidates = [chain.rpcUrl, Array.isArray(chain.rpcUrls) ? chain.rpcUrls[0] : null, chain.publicRpcUrl, chain.rpc, chain.rpcEndpoint];
|
|
1175
|
+
const found = candidates.find((url) => typeof url === "string" && /^https:\/\//i.test(url));
|
|
1176
|
+
return found || "";
|
|
1177
|
+
}
|
|
1178
|
+
function txMatchesPlan(tx, plan) {
|
|
1179
|
+
if (!tx) return false;
|
|
1180
|
+
const wantFrom = normalizeAddress(plan.from);
|
|
1181
|
+
if (!wantFrom || normalizeAddress(tx.from) !== wantFrom) return false;
|
|
1182
|
+
const wantTo = normalizeAddress(plan.to);
|
|
1183
|
+
if (wantTo && normalizeAddress(tx.to) !== wantTo) return false;
|
|
1184
|
+
const wantData = String(plan.data || "0x").toLowerCase();
|
|
1185
|
+
const gotData = String(tx.input || tx.data || "0x").toLowerCase();
|
|
1186
|
+
if (wantData !== "0x" && gotData !== wantData) return false;
|
|
1187
|
+
if (plan.value !== void 0 && plan.value !== null) {
|
|
1188
|
+
try {
|
|
1189
|
+
if (BigInt(tx.value || "0x0") !== BigInt(plan.value || "0x0")) return false;
|
|
1190
|
+
} catch {
|
|
1191
|
+
return false;
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
if (typeof plan.minNonce !== "number") return false;
|
|
1195
|
+
let n;
|
|
1196
|
+
try {
|
|
1197
|
+
n = Number(BigInt(tx.nonce));
|
|
1198
|
+
} catch {
|
|
1199
|
+
return false;
|
|
1200
|
+
}
|
|
1201
|
+
if (n < plan.minNonce) return false;
|
|
1202
|
+
return true;
|
|
1203
|
+
}
|
|
1204
|
+
function createVerifier(api, fetchImpl, rpcOverrides = {}) {
|
|
1205
|
+
async function chainRpcUrl(chainId) {
|
|
1206
|
+
const override = rpcOverrides[Number(chainId)];
|
|
1207
|
+
if (override && /^https?:\/\//i.test(override)) return override;
|
|
1208
|
+
const bundled = BUNDLED_RPC[Number(chainId)];
|
|
1209
|
+
if (bundled) return bundled;
|
|
1210
|
+
const chains = await api.fetchChains().catch(() => []);
|
|
1211
|
+
return registryRpc(chainById(chains, Number(chainId)));
|
|
1212
|
+
}
|
|
1213
|
+
async function rpcCall(rpcUrl, method, params) {
|
|
1214
|
+
const response = await fetchImpl(rpcUrl, {
|
|
1215
|
+
method: "POST",
|
|
1216
|
+
headers: { "Content-Type": "application/json" },
|
|
1217
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
1218
|
+
signal: AbortSignal.timeout(TX_VERIFY_FETCH_MS)
|
|
1219
|
+
});
|
|
1220
|
+
if (!response.ok) throw new Error(`RPC ${response.status}`);
|
|
1221
|
+
const json = await response.json();
|
|
1222
|
+
return json?.result ?? null;
|
|
1223
|
+
}
|
|
1224
|
+
async function payerNonceBaseline(chainId, account) {
|
|
1225
|
+
if (!isAddress(account)) return null;
|
|
1226
|
+
const rpcUrl = await chainRpcUrl(chainId);
|
|
1227
|
+
if (!rpcUrl) return null;
|
|
1228
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
1229
|
+
try {
|
|
1230
|
+
const hex = await rpcCall(rpcUrl, "eth_getTransactionCount", [normalizeAddress(account), "latest"]);
|
|
1231
|
+
if (typeof hex === "string") return Number(BigInt(hex));
|
|
1232
|
+
} catch {
|
|
1233
|
+
}
|
|
1234
|
+
if (attempt < 2) await new Promise((resolve) => setTimeout(resolve, 1500));
|
|
1235
|
+
}
|
|
1236
|
+
return null;
|
|
1237
|
+
}
|
|
1238
|
+
async function verifySubmittedTx({ chainId, hash, from, to, data, value, minNonce }) {
|
|
1239
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(String(hash || ""))) return { status: "mismatch" };
|
|
1240
|
+
if (!normalizeAddress(from) || typeof minNonce !== "number") return { status: "unconfirmed", reason: "no-binding" };
|
|
1241
|
+
const rpcUrl = await chainRpcUrl(chainId);
|
|
1242
|
+
if (!rpcUrl) return { status: "unconfirmed", reason: "no-rpc" };
|
|
1243
|
+
const plan = { from, to, data, value, minNonce };
|
|
1244
|
+
const deadline = Date.now() + TX_VERIFY_DEADLINE_MS;
|
|
1245
|
+
let matched = false;
|
|
1246
|
+
for (let attempt = 0; attempt < TX_VERIFY_ATTEMPTS && Date.now() < deadline; attempt += 1) {
|
|
1247
|
+
if (!matched) {
|
|
1248
|
+
let tx = null;
|
|
1249
|
+
try {
|
|
1250
|
+
tx = await rpcCall(rpcUrl, "eth_getTransactionByHash", [hash]);
|
|
1251
|
+
} catch {
|
|
1252
|
+
tx = null;
|
|
1253
|
+
}
|
|
1254
|
+
if (tx) {
|
|
1255
|
+
if (!txMatchesPlan(tx, plan)) return { status: "mismatch" };
|
|
1256
|
+
matched = true;
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
if (matched) {
|
|
1260
|
+
let receipt = null;
|
|
1261
|
+
try {
|
|
1262
|
+
receipt = await rpcCall(rpcUrl, "eth_getTransactionReceipt", [hash]);
|
|
1263
|
+
} catch {
|
|
1264
|
+
receipt = null;
|
|
1265
|
+
}
|
|
1266
|
+
if (receipt && receipt.status != null) {
|
|
1267
|
+
const code = String(receipt.status).toLowerCase();
|
|
1268
|
+
if (code === "0x0" || code === "0x00" || code === "0") return { status: "reverted" };
|
|
1269
|
+
return { status: "confirmed" };
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
if (attempt < TX_VERIFY_ATTEMPTS - 1 && Date.now() + TX_VERIFY_INTERVAL_MS < deadline) {
|
|
1273
|
+
await new Promise((resolve) => setTimeout(resolve, TX_VERIFY_INTERVAL_MS));
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
return { status: "unconfirmed", reason: matched ? "pending" : "not-found" };
|
|
1277
|
+
}
|
|
1278
|
+
async function balanceRpcUrl(chainId) {
|
|
1279
|
+
const override = rpcOverrides[Number(chainId)];
|
|
1280
|
+
if (override && /^https?:\/\//i.test(override)) return override;
|
|
1281
|
+
const bundled = BUNDLED_RPC[Number(chainId)];
|
|
1282
|
+
if (bundled) return bundled;
|
|
1283
|
+
const chains = await api.fetchChains().catch(() => []);
|
|
1284
|
+
return registryRpc(chainById(chains, Number(chainId)));
|
|
1285
|
+
}
|
|
1286
|
+
async function readBalances(account, targets) {
|
|
1287
|
+
const out = {};
|
|
1288
|
+
if (!isAddress(account) || !Array.isArray(targets) || !targets.length) return out;
|
|
1289
|
+
const owner = normalizeAddress(account);
|
|
1290
|
+
const CONCURRENCY = 6;
|
|
1291
|
+
let cursor = 0;
|
|
1292
|
+
async function worker() {
|
|
1293
|
+
while (cursor < targets.length) {
|
|
1294
|
+
const target = targets[cursor++];
|
|
1295
|
+
if (!target || !isAddress(target.tokenAddress)) continue;
|
|
1296
|
+
const key = `${Number(target.chainId)}:${String(target.tokenAddress).toLowerCase()}`;
|
|
1297
|
+
try {
|
|
1298
|
+
const rpcUrl = await balanceRpcUrl(Number(target.chainId));
|
|
1299
|
+
if (!rpcUrl) continue;
|
|
1300
|
+
const hex = await rpcCall(rpcUrl, "eth_call", [{ to: normalizeAddress(target.tokenAddress), data: encodeBalanceOf(owner) }, "latest"]);
|
|
1301
|
+
if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) continue;
|
|
1302
|
+
const raw = BigInt(hex || "0x0").toString();
|
|
1303
|
+
out[key] = { raw, formatted: formatUnits(raw, Number(target.decimals)) };
|
|
1304
|
+
} catch {
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, targets.length) }, () => worker()));
|
|
1309
|
+
return out;
|
|
1310
|
+
}
|
|
1311
|
+
async function readNativeBalance(chainId, account) {
|
|
1312
|
+
if (!isAddress(account)) return null;
|
|
1313
|
+
try {
|
|
1314
|
+
const rpcUrl = await balanceRpcUrl(Number(chainId));
|
|
1315
|
+
if (!rpcUrl) return null;
|
|
1316
|
+
const hex = await rpcCall(rpcUrl, "eth_getBalance", [normalizeAddress(account), "latest"]);
|
|
1317
|
+
if (typeof hex !== "string" || !/^0x[0-9a-fA-F]*$/.test(hex)) return null;
|
|
1318
|
+
return BigInt(hex || "0x0");
|
|
1319
|
+
} catch {
|
|
1320
|
+
return null;
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
return { payerNonceBaseline, verifySubmittedTx, readBalances, readNativeBalance };
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
// src/core/config.ts
|
|
1327
|
+
function parseAllowedApiBase(value) {
|
|
1328
|
+
try {
|
|
1329
|
+
const url = new URL(String(value || ""));
|
|
1330
|
+
const localDev = url.protocol === "http:" && /^(localhost|127\.0\.0\.1)$/i.test(url.hostname);
|
|
1331
|
+
if (url.protocol !== "https:" && !localDev) return null;
|
|
1332
|
+
url.hash = "";
|
|
1333
|
+
url.search = "";
|
|
1334
|
+
return url.toString().replace(/\/$/, "");
|
|
1335
|
+
} catch {
|
|
1336
|
+
return null;
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
function isSameOriginPath(value) {
|
|
1340
|
+
return value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\");
|
|
1341
|
+
}
|
|
1342
|
+
function resolveApiBase(value) {
|
|
1343
|
+
const raw = value ?? DEFAULT_WIDGET_API_BASE;
|
|
1344
|
+
if (isSameOriginPath(raw)) return raw.replace(/\/+$/, "") || "/";
|
|
1345
|
+
return parseAllowedApiBase(raw) || DEFAULT_WIDGET_API_BASE;
|
|
1346
|
+
}
|
|
1347
|
+
function canAttachApiKey(apiBase, trustedOrigin) {
|
|
1348
|
+
if (isSameOriginPath(apiBase)) return true;
|
|
1349
|
+
if (apiBase.startsWith("/")) return false;
|
|
1350
|
+
if (!trustedOrigin) return false;
|
|
1351
|
+
try {
|
|
1352
|
+
const trusted = parseAllowedApiBase(trustedOrigin);
|
|
1353
|
+
if (!trusted) return false;
|
|
1354
|
+
return new URL(apiBase).origin === new URL(trusted).origin;
|
|
1355
|
+
} catch {
|
|
1356
|
+
return false;
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
function resolveConfig(config = {}) {
|
|
1360
|
+
const apiBase = resolveApiBase(config.apiBase);
|
|
1361
|
+
const fetchImpl = config.fetchImpl ?? globalThis.fetch?.bind(globalThis);
|
|
1362
|
+
if (typeof fetchImpl !== "function") {
|
|
1363
|
+
throw new Error("No fetch implementation available; pass EngineConfig.fetchImpl.");
|
|
1364
|
+
}
|
|
1365
|
+
const getApiKey = async () => {
|
|
1366
|
+
if (!canAttachApiKey(apiBase, config.trustedApiOrigin)) return "";
|
|
1367
|
+
if (config.getApiKey) return String(await config.getApiKey() || "");
|
|
1368
|
+
return String(config.apiKey || "");
|
|
1369
|
+
};
|
|
1370
|
+
return {
|
|
1371
|
+
apiBase,
|
|
1372
|
+
getApiKey,
|
|
1373
|
+
fetchImpl,
|
|
1374
|
+
rpcOverrides: config.rpcOverrides ?? {},
|
|
1375
|
+
onTransaction: config.onTransaction
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
// src/core/index.ts
|
|
1380
|
+
function sanitizeTxEntry(entry) {
|
|
1381
|
+
return {
|
|
1382
|
+
kind: entry.kind === "swap" ? "swap" : "payment",
|
|
1383
|
+
hash: /^0x[0-9a-fA-F]{6,80}$/.test(String(entry.hash || "")) ? String(entry.hash) : "",
|
|
1384
|
+
txKind: entry.txKind === "transfer" || entry.txKind === "approve" || entry.txKind === "submitOrder" ? entry.txKind : void 0,
|
|
1385
|
+
chainId: Number(entry.chainId) || null,
|
|
1386
|
+
chainName: String(entry.chainName || "").slice(0, 40),
|
|
1387
|
+
fromAsset: String(entry.fromAsset || "").slice(0, 10),
|
|
1388
|
+
toAsset: String(entry.toAsset || "").slice(0, 10),
|
|
1389
|
+
payAmount: String(entry.payAmount || "").slice(0, 40),
|
|
1390
|
+
receiveAmount: String(entry.receiveAmount || "").slice(0, 40),
|
|
1391
|
+
account: isAddress(entry.account) ? normalizeAddress(entry.account) : "",
|
|
1392
|
+
recipient: isAddress(entry.recipient) ? normalizeAddress(entry.recipient) : "",
|
|
1393
|
+
settlement: entry.settlement === "direct" ? "direct" : "escrow",
|
|
1394
|
+
status: entry.status && ["confirmed", "unconfirmed", "error"].includes(entry.status) ? entry.status : "submitted",
|
|
1395
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
function createEngine(config = {}) {
|
|
1399
|
+
const resolved = resolveConfig(config);
|
|
1400
|
+
const api = createApiClient(resolved);
|
|
1401
|
+
const verifier = createVerifier(api, resolved.fetchImpl, resolved.rpcOverrides);
|
|
1402
|
+
return {
|
|
1403
|
+
api,
|
|
1404
|
+
verifier,
|
|
1405
|
+
apiBase: api.apiBase,
|
|
1406
|
+
fetchChains: api.fetchChains,
|
|
1407
|
+
fetchTokens: api.fetchTokens,
|
|
1408
|
+
fetchRoutes: api.fetchRoutes,
|
|
1409
|
+
fetchQuote: api.fetchQuote,
|
|
1410
|
+
fetchPaymentPlan: (request, payer, wallet) => fetchPaymentPlan(api, request, payer, wallet),
|
|
1411
|
+
quoteSwapPreview: (swap, owner) => quoteSwapPreview(api, swap, owner),
|
|
1412
|
+
buildSwapPlan: (swap, payer, wallet) => buildSwapPlan(api, swap, payer, wallet),
|
|
1413
|
+
payerNonceBaseline: verifier.payerNonceBaseline,
|
|
1414
|
+
verifySubmittedTx: verifier.verifySubmittedTx,
|
|
1415
|
+
readBalances: verifier.readBalances,
|
|
1416
|
+
readNativeBalance: verifier.readNativeBalance,
|
|
1417
|
+
recordTransaction: (entry) => {
|
|
1418
|
+
const clean = sanitizeTxEntry(entry);
|
|
1419
|
+
try {
|
|
1420
|
+
resolved.onTransaction?.(clean);
|
|
1421
|
+
} catch {
|
|
1422
|
+
}
|
|
1423
|
+
return clean;
|
|
1424
|
+
}
|
|
1425
|
+
};
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
exports.API_CACHE_TTL_MS = API_CACHE_TTL_MS;
|
|
1429
|
+
exports.BUNDLED_NATIVE_SYMBOL = BUNDLED_NATIVE_SYMBOL;
|
|
1430
|
+
exports.BUNDLED_RPC = BUNDLED_RPC;
|
|
1431
|
+
exports.CANONICAL_DECIMALS = CANONICAL_DECIMALS;
|
|
1432
|
+
exports.CANONICAL_ESCROW = CANONICAL_ESCROW;
|
|
1433
|
+
exports.CANONICAL_INBOUND_BRIDGE = CANONICAL_INBOUND_BRIDGE;
|
|
1434
|
+
exports.DEFAULT_WIDGET_API_BASE = DEFAULT_WIDGET_API_BASE;
|
|
1435
|
+
exports.ERC20_ALLOWANCE_SELECTOR = ERC20_ALLOWANCE_SELECTOR;
|
|
1436
|
+
exports.ERC20_APPROVE_SELECTOR = ERC20_APPROVE_SELECTOR;
|
|
1437
|
+
exports.ERC20_BALANCEOF_SELECTOR = ERC20_BALANCEOF_SELECTOR;
|
|
1438
|
+
exports.ERC20_TRANSFER_SELECTOR = ERC20_TRANSFER_SELECTOR;
|
|
1439
|
+
exports.LZ_FEE_BUFFER_BPS = LZ_FEE_BUFFER_BPS;
|
|
1440
|
+
exports.MAX_LZ_MSG_VALUE_WEI = MAX_LZ_MSG_VALUE_WEI;
|
|
1441
|
+
exports.MAX_LZ_MSG_VALUE_WEI_BY_CHAIN = MAX_LZ_MSG_VALUE_WEI_BY_CHAIN;
|
|
1442
|
+
exports.MAX_QUOTE_CANDIDATES = MAX_QUOTE_CANDIDATES;
|
|
1443
|
+
exports.MAX_SAME_CLASS_PAY_BPS = MAX_SAME_CLASS_PAY_BPS;
|
|
1444
|
+
exports.PREVIEW_OWNER = PREVIEW_OWNER;
|
|
1445
|
+
exports.QUOTE_BUFFER_BPS = QUOTE_BUFFER_BPS;
|
|
1446
|
+
exports.SAME_CLASS_STABLE = SAME_CLASS_STABLE;
|
|
1447
|
+
exports.STABLEGENIE_INTENT_TTL_MS = STABLEGENIE_INTENT_TTL_MS;
|
|
1448
|
+
exports.STABLEGENIE_INTENT_VERSION = STABLEGENIE_INTENT_VERSION;
|
|
1449
|
+
exports.STABLEGENIE_SUPPORTED_ASSETS = STABLEGENIE_SUPPORTED_ASSETS;
|
|
1450
|
+
exports.STABLEGENIE_SUPPORTED_CHAIN_IDS = STABLEGENIE_SUPPORTED_CHAIN_IDS;
|
|
1451
|
+
exports.SUBMIT_ORDER_SELECTOR = SUBMIT_ORDER_SELECTOR;
|
|
1452
|
+
exports.SUPPORTED_ASSETS = SUPPORTED_ASSETS;
|
|
1453
|
+
exports.SUPPORTED_CHAIN_IDS = SUPPORTED_CHAIN_IDS;
|
|
1454
|
+
exports.ZERO_ADDRESS = ZERO_ADDRESS;
|
|
1455
|
+
exports.addressWord = addressWord;
|
|
1456
|
+
exports.allowanceCovers = allowanceCovers;
|
|
1457
|
+
exports.apiError = apiError;
|
|
1458
|
+
exports.applyLayerZeroBuffer = applyLayerZeroBuffer;
|
|
1459
|
+
exports.assertAddress = assertAddress;
|
|
1460
|
+
exports.assertQuoteMatchesSelection = assertQuoteMatchesSelection;
|
|
1461
|
+
exports.assetDecimals = assetDecimals;
|
|
1462
|
+
exports.buildPayOptions = buildPayOptions;
|
|
1463
|
+
exports.buildRoute = buildRoute;
|
|
1464
|
+
exports.buildSwapPlan = buildSwapPlan;
|
|
1465
|
+
exports.bytesPayload = bytesPayload;
|
|
1466
|
+
exports.canAttachApiKey = canAttachApiKey;
|
|
1467
|
+
exports.chainById = chainById;
|
|
1468
|
+
exports.chainNameOf = chainNameOf;
|
|
1469
|
+
exports.chainSelectable = chainSelectable;
|
|
1470
|
+
exports.checkEscrow = checkEscrow;
|
|
1471
|
+
exports.checkNativeFee = checkNativeFee;
|
|
1472
|
+
exports.classifyQuoteError = classifyQuoteError;
|
|
1473
|
+
exports.createApiClient = createApiClient;
|
|
1474
|
+
exports.createEngine = createEngine;
|
|
1475
|
+
exports.createVerifier = createVerifier;
|
|
1476
|
+
exports.encodeAllowance = encodeAllowance;
|
|
1477
|
+
exports.encodeApprove = encodeApprove;
|
|
1478
|
+
exports.encodeBalanceOf = encodeBalanceOf;
|
|
1479
|
+
exports.encodeSubmitOrder = encodeSubmitOrder;
|
|
1480
|
+
exports.encodeTransfer = encodeTransfer;
|
|
1481
|
+
exports.fetchPaymentPlan = fetchPaymentPlan;
|
|
1482
|
+
exports.finalOf = finalOf;
|
|
1483
|
+
exports.findToken = findToken;
|
|
1484
|
+
exports.formatNative = formatNative;
|
|
1485
|
+
exports.formatUnits = formatUnits;
|
|
1486
|
+
exports.isAddress = isAddress;
|
|
1487
|
+
exports.isDeliverable = isDeliverable;
|
|
1488
|
+
exports.isHexAddress = isHexAddress;
|
|
1489
|
+
exports.isHexData = isHexData;
|
|
1490
|
+
exports.isHexQuantity = isHexQuantity;
|
|
1491
|
+
exports.isLayerZeroRoute = isLayerZeroRoute;
|
|
1492
|
+
exports.maxNativeFeeWei = maxNativeFeeWei;
|
|
1493
|
+
exports.nativeFeeShortLabel = nativeFeeShortLabel;
|
|
1494
|
+
exports.nativeFeeShortMessage = nativeFeeShortMessage;
|
|
1495
|
+
exports.nativeSymbol = nativeSymbol;
|
|
1496
|
+
exports.normalizeAddress = normalizeAddress;
|
|
1497
|
+
exports.normalizeDecimalText = normalizeDecimalText;
|
|
1498
|
+
exports.normalizeOrderRequest = normalizeOrderRequest;
|
|
1499
|
+
exports.parseAllowedApiBase = parseAllowedApiBase;
|
|
1500
|
+
exports.parseUnitsDecimal = parseUnitsDecimal;
|
|
1501
|
+
exports.planErrorSummary = planErrorSummary;
|
|
1502
|
+
exports.planMsgValueHex = planMsgValueHex;
|
|
1503
|
+
exports.quoteSwapPreview = quoteSwapPreview;
|
|
1504
|
+
exports.registryRpc = registryRpc;
|
|
1505
|
+
exports.requiresNativeBridgeFee = requiresNativeBridgeFee;
|
|
1506
|
+
exports.resolveApiBase = resolveApiBase;
|
|
1507
|
+
exports.resolveConfig = resolveConfig;
|
|
1508
|
+
exports.resolveSwapReceiver = resolveSwapReceiver;
|
|
1509
|
+
exports.routeNativeValue = routeNativeValue;
|
|
1510
|
+
exports.scaleDecimals = scaleDecimals;
|
|
1511
|
+
exports.solveExactIn = solveExactIn;
|
|
1512
|
+
exports.solveExactOut = solveExactOut;
|
|
1513
|
+
exports.stableGenieIntentSchema = stableGenieIntentSchema;
|
|
1514
|
+
exports.strip0x = strip0x;
|
|
1515
|
+
exports.symbolKey = symbolKey;
|
|
1516
|
+
exports.toHexQuantity = toHexQuantity;
|
|
1517
|
+
exports.tokenEnabled = tokenEnabled;
|
|
1518
|
+
exports.txMatchesPlan = txMatchesPlan;
|
|
1519
|
+
exports.uintWord = uintWord;
|
|
1520
|
+
exports.validateDestination = validateDestination;
|
|
1521
|
+
exports.validatePlannedTransaction = validatePlannedTransaction;
|
|
1522
|
+
exports.validateSwap = validateSwap;
|