@anywalletkit/protocol-swap2-across 0.0.0-stage → 0.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/LICENSE +202 -0
- package/README.md +177 -2
- package/dist/activity.cjs +142 -0
- package/dist/activity.cjs.map +1 -0
- package/dist/activity.d.cts +16 -0
- package/dist/activity.d.ts +16 -0
- package/dist/activity.js +10 -0
- package/dist/activity.js.map +1 -0
- package/dist/api.cjs +441 -0
- package/dist/api.cjs.map +1 -0
- package/dist/api.d.cts +207 -0
- package/dist/api.d.ts +207 -0
- package/dist/api.js +35 -0
- package/dist/api.js.map +1 -0
- package/dist/build.cjs +776 -0
- package/dist/build.cjs.map +1 -0
- package/dist/build.d.cts +93 -0
- package/dist/build.d.ts +93 -0
- package/dist/build.js +14 -0
- package/dist/build.js.map +1 -0
- package/dist/chunk-32YJEBZX.js +125 -0
- package/dist/chunk-32YJEBZX.js.map +1 -0
- package/dist/chunk-3UBRQ3ZE.js +255 -0
- package/dist/chunk-3UBRQ3ZE.js.map +1 -0
- package/dist/chunk-5BDZXOOP.js +21 -0
- package/dist/chunk-5BDZXOOP.js.map +1 -0
- package/dist/chunk-6Z4GXNLE.js +102 -0
- package/dist/chunk-6Z4GXNLE.js.map +1 -0
- package/dist/chunk-AWQT5S4V.js +101 -0
- package/dist/chunk-AWQT5S4V.js.map +1 -0
- package/dist/chunk-E5WFOPN2.js +16 -0
- package/dist/chunk-E5WFOPN2.js.map +1 -0
- package/dist/chunk-GX67FRPG.js +194 -0
- package/dist/chunk-GX67FRPG.js.map +1 -0
- package/dist/chunk-KATEONJQ.js +396 -0
- package/dist/chunk-KATEONJQ.js.map +1 -0
- package/dist/chunk-P32AW6XS.js +27 -0
- package/dist/chunk-P32AW6XS.js.map +1 -0
- package/dist/chunk-PPPZIG7S.js +265 -0
- package/dist/chunk-PPPZIG7S.js.map +1 -0
- package/dist/chunk-SJOFLM27.js +138 -0
- package/dist/chunk-SJOFLM27.js.map +1 -0
- package/dist/chunk-YGNP7KPL.js +311 -0
- package/dist/chunk-YGNP7KPL.js.map +1 -0
- package/dist/config.cjs +214 -0
- package/dist/config.cjs.map +1 -0
- package/dist/config.d.cts +119 -0
- package/dist/config.d.ts +119 -0
- package/dist/config.js +47 -0
- package/dist/config.js.map +1 -0
- package/dist/deposit.cjs +252 -0
- package/dist/deposit.cjs.map +1 -0
- package/dist/deposit.d.cts +95 -0
- package/dist/deposit.d.ts +95 -0
- package/dist/deposit.js +19 -0
- package/dist/deposit.js.map +1 -0
- package/dist/index.cjs +1789 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +34 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.js +242 -0
- package/dist/index.js.map +1 -0
- package/dist/pricing.cjs +132 -0
- package/dist/pricing.cjs.map +1 -0
- package/dist/pricing.d.cts +123 -0
- package/dist/pricing.d.ts +123 -0
- package/dist/pricing.js +42 -0
- package/dist/pricing.js.map +1 -0
- package/dist/protocol.cjs +1596 -0
- package/dist/protocol.cjs.map +1 -0
- package/dist/protocol.d.cts +20 -0
- package/dist/protocol.d.ts +20 -0
- package/dist/protocol.js +17 -0
- package/dist/protocol.js.map +1 -0
- package/dist/provider.cjs +1581 -0
- package/dist/provider.cjs.map +1 -0
- package/dist/provider.d.cts +45 -0
- package/dist/provider.d.ts +45 -0
- package/dist/provider.js +18 -0
- package/dist/provider.js.map +1 -0
- package/dist/remote.cjs +1659 -0
- package/dist/remote.cjs.map +1 -0
- package/dist/remote.d.cts +55 -0
- package/dist/remote.d.ts +55 -0
- package/dist/remote.js +17 -0
- package/dist/remote.js.map +1 -0
- package/dist/status.cjs +443 -0
- package/dist/status.cjs.map +1 -0
- package/dist/status.d.cts +109 -0
- package/dist/status.d.ts +109 -0
- package/dist/status.js +26 -0
- package/dist/status.js.map +1 -0
- package/dist/verify.cjs +690 -0
- package/dist/verify.cjs.map +1 -0
- package/dist/verify.d.cts +245 -0
- package/dist/verify.d.ts +245 -0
- package/dist/verify.js +69 -0
- package/dist/verify.js.map +1 -0
- package/module.json +32 -0
- package/package.json +124 -3
|
@@ -0,0 +1,1581 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/provider.ts
|
|
21
|
+
var provider_exports = {};
|
|
22
|
+
__export(provider_exports, {
|
|
23
|
+
acrossProvider: () => acrossProvider,
|
|
24
|
+
acrossServesRoute: () => acrossServesRoute
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(provider_exports);
|
|
27
|
+
var import_errors4 = require("@anywalletkit/protocol-swap2-core/errors");
|
|
28
|
+
var import_swap2_assets = require("@anywalletkit/swap2-assets");
|
|
29
|
+
|
|
30
|
+
// src/activity.ts
|
|
31
|
+
var import_activity = require("@anywalletkit/protocol-swap2-core/activity");
|
|
32
|
+
|
|
33
|
+
// src/config.ts
|
|
34
|
+
var USDC = (address, symbol = "USDC") => Object.freeze({ asset: "USDC", address, symbol, decimals: 6 });
|
|
35
|
+
var USDT = (address, symbol = "USDT") => Object.freeze({ asset: "USDT", address, symbol, decimals: 6 });
|
|
36
|
+
var WETH = (address) => Object.freeze({ asset: "ETH", address, symbol: "WETH", decimals: 18 });
|
|
37
|
+
var WBTC = (address) => Object.freeze({ asset: "WBTC", address, symbol: "WBTC", decimals: 8 });
|
|
38
|
+
var OP_WETH = "0x4200000000000000000000000000000000000006";
|
|
39
|
+
function chain(chainId, key, name, spokePool, wrappedNative, nativeIsEth, tokens) {
|
|
40
|
+
return Object.freeze({ caip2: `eip155:${chainId}`, chainId, key, name, spokePool, wrappedNative, nativeIsEth, tokens: Object.freeze(tokens) });
|
|
41
|
+
}
|
|
42
|
+
var ACROSS_CHAINS = Object.freeze(Object.assign(/* @__PURE__ */ Object.create(null), Object.fromEntries([
|
|
43
|
+
chain(1, "ethereum", "Ethereum", "0x5c7bcd6e7de5423a257d81b442095a1a6ced35c5", "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", true, [
|
|
44
|
+
USDC("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"),
|
|
45
|
+
USDT("0xdac17f958d2ee523a2206206994597c13d831ec7"),
|
|
46
|
+
WETH("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"),
|
|
47
|
+
WBTC("0x2260fac5e5542a773aa44fbcfedf7c193bc2c599")
|
|
48
|
+
]),
|
|
49
|
+
chain(10, "optimism", "Optimism", "0x6f26bf09b1c792e3228e5467807a900a503c0281", OP_WETH, true, [
|
|
50
|
+
USDC("0x0b2c639c533813f4aa9d7837caf62653d097ff85"),
|
|
51
|
+
USDT("0x94b008aa00579c1307b0ef2c499ad98a8ce58e58"),
|
|
52
|
+
WETH(OP_WETH)
|
|
53
|
+
]),
|
|
54
|
+
chain(130, "unichain", "Unichain", "0x09aea4b2242abc8bb4bb78d537a67a245a7bec64", OP_WETH, true, [
|
|
55
|
+
USDC("0x078d782b760474a361dda0af3839290b0ef57ad6"),
|
|
56
|
+
USDT("0x9151434b16b9763660705744891fa906f660ecc5", "USDT0"),
|
|
57
|
+
WETH(OP_WETH)
|
|
58
|
+
]),
|
|
59
|
+
chain(137, "polygon", "Polygon", "0x9295ee1d8c5b022be115a2ad3c30c72e34e7f096", "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270", false, [
|
|
60
|
+
USDC("0x3c499c542cef5e3811e1192ce70d8cc03d5c3359"),
|
|
61
|
+
USDT("0xc2132d05d31c914a87c6611c10748aeb04b58e8f"),
|
|
62
|
+
WBTC("0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6")
|
|
63
|
+
]),
|
|
64
|
+
chain(143, "monad", "Monad", "0xd2ecb3afe598b746f8123cae365a598da831a449", "0x3bd359c1119da7da1d913d1c4d2b7c461115433a", false, [
|
|
65
|
+
USDC("0x754704bc059f8c67012fed69bc8a327a5aafb603"),
|
|
66
|
+
USDT("0xe7cd86e13ac4309349f30b3435a9d337750fc82d", "USDT0")
|
|
67
|
+
]),
|
|
68
|
+
chain(324, "zksync", "zkSync Era", "0xe0b015e54d54fc84a6cb9b666099c46ade9335ff", "0x5aea5775959fbc2557cc8789bc1bf90a239d9a91", true, [
|
|
69
|
+
USDT("0x493257fd37edb34451f62edf8d2a0c418852ba4c"),
|
|
70
|
+
WETH("0x5aea5775959fbc2557cc8789bc1bf90a239d9a91"),
|
|
71
|
+
WBTC("0xbbeb516fb02a01611cbbe0453fe3c580d7281011")
|
|
72
|
+
]),
|
|
73
|
+
chain(480, "worldchain", "World Chain", "0x09aea4b2242abc8bb4bb78d537a67a245a7bec64", OP_WETH, true, [
|
|
74
|
+
USDC("0x79a02482a880bce3f13e09da970dc34db4cd24d1"),
|
|
75
|
+
WETH(OP_WETH),
|
|
76
|
+
WBTC("0x03c7054bcb39f7b2e5b2c7acb37583e32d70cfa3")
|
|
77
|
+
]),
|
|
78
|
+
chain(999, "hyperevm", "HyperEVM", "0x35e63ea3eb0fb7a3bc543c71fb66412e1f6b0e04", "0x5555555555555555555555555555555555555555", false, [
|
|
79
|
+
USDC("0xb88339cb7199b77e23db6e890353e22632ba630f"),
|
|
80
|
+
USDT("0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb", "USDT0")
|
|
81
|
+
]),
|
|
82
|
+
chain(4326, "megaeth", "MegaETH", "0x3db06da8f0a24a525f314eec954fc5c6a973d40e", OP_WETH, true, [
|
|
83
|
+
USDT("0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb", "USDT0"),
|
|
84
|
+
WETH(OP_WETH)
|
|
85
|
+
]),
|
|
86
|
+
chain(4663, "robinhood", "Robinhood Chain", "0xd29c85f15df544ba632c9e25829fd29d767d7978", "0x0bd7d308f8e1639fab988df18a8011f41eacad73", true, [
|
|
87
|
+
WETH("0x0bd7d308f8e1639fab988df18a8011f41eacad73")
|
|
88
|
+
]),
|
|
89
|
+
// Arc's gas coin is USDC; 0x3600… is its 6-decimal ERC-20 interface, which is what Across moves. The SpokePool
|
|
90
|
+
// reports no wrapped native token, so no deposit or fill on Arc involves the native coin.
|
|
91
|
+
chain(5042, "arc", "Arc", "0x9b4a302a548c7e313c2b74c461db7b84d3074a84", null, false, [
|
|
92
|
+
USDC("0x3600000000000000000000000000000000000000")
|
|
93
|
+
]),
|
|
94
|
+
chain(8453, "base", "Base", "0x09aea4b2242abc8bb4bb78d537a67a245a7bec64", OP_WETH, true, [
|
|
95
|
+
USDC("0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"),
|
|
96
|
+
USDT("0xfde4c96c8593536e31f229ea8f37b2ada2699bb2"),
|
|
97
|
+
WETH(OP_WETH)
|
|
98
|
+
]),
|
|
99
|
+
chain(9745, "plasma", "Plasma", "0x50039faefebef707cfd94d6d462fe6d10b39207a", "0x6100e367285b01f48d07953803a2d8dca5d19873", false, [
|
|
100
|
+
USDT("0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb", "USDT0")
|
|
101
|
+
]),
|
|
102
|
+
chain(42161, "arbitrum", "Arbitrum", "0xe35e9842fceaca96570b734083f4a58e8f7c5f2a", "0x82af49447d8a07e3bd95bd0d56f35241523fbab1", true, [
|
|
103
|
+
USDC("0xaf88d065e77c8cc2239327c5edb3a432268e5831"),
|
|
104
|
+
USDT("0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9", "USDT0"),
|
|
105
|
+
WETH("0x82af49447d8a07e3bd95bd0d56f35241523fbab1"),
|
|
106
|
+
WBTC("0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f")
|
|
107
|
+
]),
|
|
108
|
+
chain(43114, "avalanche", "Avalanche", "0xfe9d541c92e4e90437c7152a00244886de37a658", "0xb31f66aa3c1e785363f0875a1b74e27b85fd66c7", false, [
|
|
109
|
+
USDC("0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e"),
|
|
110
|
+
USDT("0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7")
|
|
111
|
+
]),
|
|
112
|
+
chain(57073, "ink", "Ink", "0xef684c38f94f48775959ecf2012d7e864ffb9dd4", OP_WETH, true, [
|
|
113
|
+
USDC("0x2d270e6886d130d724215a266106e6832161eaed"),
|
|
114
|
+
USDT("0x0200c29006150606b650577bbe7b6248f58470c1", "USDT0"),
|
|
115
|
+
WETH(OP_WETH)
|
|
116
|
+
]),
|
|
117
|
+
chain(59144, "linea", "Linea", "0x7e63a5f1a8f0b4d0934b2f2327daed3f6bb2ee75", "0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f", true, [
|
|
118
|
+
USDC("0x176211869ca2b568f2a7d4ee941e073a821ee1ff"),
|
|
119
|
+
USDT("0xa219439258ca9da29e9cc4ce5596924745e12b93"),
|
|
120
|
+
WETH("0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f"),
|
|
121
|
+
WBTC("0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4")
|
|
122
|
+
])
|
|
123
|
+
].map((x) => [x.caip2, x]))));
|
|
124
|
+
function acrossChain(caip2) {
|
|
125
|
+
return typeof caip2 === "string" && Object.prototype.hasOwnProperty.call(ACROSS_CHAINS, caip2) ? ACROSS_CHAINS[caip2] : void 0;
|
|
126
|
+
}
|
|
127
|
+
function acrossToken(chain2, address) {
|
|
128
|
+
if (typeof address !== "string") return void 0;
|
|
129
|
+
const a = address.toLowerCase();
|
|
130
|
+
return chain2.tokens.find((t) => t.address === a);
|
|
131
|
+
}
|
|
132
|
+
var ACROSS_DEPOSIT = "0xad5425c6";
|
|
133
|
+
var ACROSS_DEPOSIT_V3 = "0x7b939232";
|
|
134
|
+
var ACROSS_REFUSED_SELECTORS = Object.freeze({
|
|
135
|
+
"0x8b15788e": "unsafeDeposit",
|
|
136
|
+
"0xea86bd46": "depositNow",
|
|
137
|
+
"0x7aef642c": "depositV3Now",
|
|
138
|
+
"0xbabb6aac": "speedUpDeposit",
|
|
139
|
+
"0x577f51f8": "speedUpV3Deposit",
|
|
140
|
+
"0xac9650d8": "multicall"
|
|
141
|
+
});
|
|
142
|
+
var ACROSS_SPEED_UP_TYPE = "UpdateDepositDetails";
|
|
143
|
+
var ACROSS_SPEED_UP_DOMAIN = "ACROSS-V2";
|
|
144
|
+
var ACROSS_FUNDS_DEPOSITED = "0x32ed1a409ef04c7b0227189c3a103dc5ac10e775a15b785dcc510201f7c25ad3";
|
|
145
|
+
var ACROSS_FILL_STATUSES = "0xc35c83fc";
|
|
146
|
+
var ACROSS_V5_MESSAGE_PREFIX = "0x89ae4bc75915265a3f10e926c3894a29534f1d6362ee8959cb0e5be00f3527fd";
|
|
147
|
+
var ACROSS_DEPOSIT_QUOTE_TIME_BUFFER_S = 3600;
|
|
148
|
+
var ACROSS_FILL_DEADLINE_BUFFER_S = 21600;
|
|
149
|
+
var ACROSS_MAX_EXCLUSIVITY_PERIOD_S = 31536e3;
|
|
150
|
+
var ACROSS_NATIVE = "0x0000000000000000000000000000000000000000";
|
|
151
|
+
var ACROSS_API = "https://api.across.to";
|
|
152
|
+
var ZERO = /^0x0{40}$/;
|
|
153
|
+
var isNativeRef = (token) => ZERO.test(token);
|
|
154
|
+
function acrossRouteOf(sourceChain, sourceToken, destChain, destToken) {
|
|
155
|
+
const src = acrossChain(sourceChain);
|
|
156
|
+
const dst = acrossChain(destChain);
|
|
157
|
+
if (!src) return { code: "chain-unsupported", detail: `source chain ${String(sourceChain)} is not a pinned Across chain` };
|
|
158
|
+
if (!dst) return { code: "chain-unsupported", detail: `destination chain ${String(destChain)} is not a pinned Across chain` };
|
|
159
|
+
if (src === dst) return { code: "chain-unsupported", detail: "source and destination are the same chain" };
|
|
160
|
+
if (typeof sourceToken !== "string" || typeof destToken !== "string") return { code: "token-unsupported", detail: "the tokens are not addresses" };
|
|
161
|
+
let input;
|
|
162
|
+
let asset;
|
|
163
|
+
if (isNativeRef(sourceToken)) {
|
|
164
|
+
if (!src.nativeIsEth || !src.wrappedNative) return { code: "native-unsupported", detail: `${src.name}'s native coin is not bridged by Across` };
|
|
165
|
+
input = { chain: src, token: src.wrappedNative, native: true, decimals: 18 };
|
|
166
|
+
asset = "ETH";
|
|
167
|
+
} else {
|
|
168
|
+
const t = acrossToken(src, sourceToken);
|
|
169
|
+
if (!t) return { code: "token-unsupported", detail: `${sourceToken.toLowerCase()} is not a token pinned on ${src.name}` };
|
|
170
|
+
input = { chain: src, token: t.address, native: false, decimals: t.decimals };
|
|
171
|
+
asset = t.asset;
|
|
172
|
+
}
|
|
173
|
+
let output;
|
|
174
|
+
if (isNativeRef(destToken)) {
|
|
175
|
+
if (!dst.nativeIsEth || !dst.wrappedNative) return { code: "native-unsupported", detail: `${dst.name}'s native coin is not bridged by Across` };
|
|
176
|
+
if (asset !== "ETH") return { code: "pair-unsupported", detail: `${asset} on ${src.name} is not bridged to ${dst.name}'s native coin` };
|
|
177
|
+
output = { chain: dst, token: dst.wrappedNative, native: true, decimals: 18 };
|
|
178
|
+
} else {
|
|
179
|
+
const t = acrossToken(dst, destToken);
|
|
180
|
+
if (!t) return { code: "token-unsupported", detail: `${destToken.toLowerCase()} is not a token pinned on ${dst.name}` };
|
|
181
|
+
if (dst.wrappedNative !== null && t.address === dst.wrappedNative) {
|
|
182
|
+
return { code: "wrapped-native-destination", detail: `a fill of ${t.symbol} on ${dst.name} pays an EOA the native coin, not ${t.symbol} \u2014 ask for the native coin` };
|
|
183
|
+
}
|
|
184
|
+
if (t.asset !== asset) return { code: "pair-unsupported", detail: `${asset} is only bridged to ${asset}, not to ${t.symbol}` };
|
|
185
|
+
output = { chain: dst, token: t.address, native: false, decimals: t.decimals };
|
|
186
|
+
}
|
|
187
|
+
if (input.decimals !== output.decimals) return { code: "pair-unsupported", detail: "the two sides have different decimals" };
|
|
188
|
+
return { asset, input, output };
|
|
189
|
+
}
|
|
190
|
+
var across = {
|
|
191
|
+
supportsChain(chain2) {
|
|
192
|
+
return acrossChain(chain2) !== void 0;
|
|
193
|
+
},
|
|
194
|
+
/** Two different pinned EVM chains. */
|
|
195
|
+
supports(from, to) {
|
|
196
|
+
return from !== to && acrossChain(from) !== void 0 && acrossChain(to) !== void 0;
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
// src/activity.ts
|
|
201
|
+
var ACROSS_MODULE = "@anywalletkit/protocol-swap2-across";
|
|
202
|
+
function describeAcrossActivity(tx, ctx) {
|
|
203
|
+
const chain2 = acrossChain(tx.chain);
|
|
204
|
+
if (!chain2) return null;
|
|
205
|
+
if (!(0, import_activity.matchesCall)(tx, [chain2.spokePool], [ACROSS_DEPOSIT, ACROSS_DEPOSIT_V3])) return null;
|
|
206
|
+
return (0, import_activity.describeSwapLike)(tx, ctx, { protocol: ACROSS_MODULE, subtitle: `Across \xB7 ${(0, import_activity.chainLabel)(tx.chain)}`, kind: "bridge", outVerb: "Bridged" });
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// src/api.ts
|
|
210
|
+
var import_errors2 = require("@anywalletkit/protocol-swap2-core/errors");
|
|
211
|
+
var import_util = require("@anywalletkit/protocol-swap2-core/util");
|
|
212
|
+
|
|
213
|
+
// src/refusal.ts
|
|
214
|
+
var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
|
|
215
|
+
var AcrossRefusal = class extends Error {
|
|
216
|
+
code;
|
|
217
|
+
constructor(code, detail, reason) {
|
|
218
|
+
super(`across: ${detail} [${code}]`);
|
|
219
|
+
this.name = "AcrossRefusal";
|
|
220
|
+
this.code = code;
|
|
221
|
+
if (reason !== void 0) (0, import_errors.withReason)(this, reason);
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
// src/api.ts
|
|
226
|
+
var ACROSS_API_V1 = `${ACROSS_API}/v1`;
|
|
227
|
+
var ACROSS_SUGGESTED_FEES_URL = "https://app.across.to/api/suggested-fees";
|
|
228
|
+
var ACROSS_V5_PRICING_MAX_FEE_BPS = 5e3;
|
|
229
|
+
var MAX_ANSWER_CHARS = 512 * 1024;
|
|
230
|
+
function acrossV5QuoteRequest(request) {
|
|
231
|
+
const src = acrossChain(request.sourceChain);
|
|
232
|
+
const dst = acrossChain(request.destChain);
|
|
233
|
+
if (!src || !dst) throw new Error("across: the request's chains are not pinned");
|
|
234
|
+
return {
|
|
235
|
+
origin: { token: { chainId: src.chainId, address: request.sourceToken.toLowerCase() }, depositor: request.depositor.toLowerCase(), amount: request.amount.toString(10) },
|
|
236
|
+
destination: { token: { chainId: dst.chainId, address: request.destToken.toLowerCase() }, recipient: request.recipient.toLowerCase() },
|
|
237
|
+
amountType: "exact_input",
|
|
238
|
+
capabilities: { operations: [{ kind: "approve_token", ecosystem: "evm" }, { kind: "send_transaction", ecosystem: "evm" }] },
|
|
239
|
+
authorizationPolicy: { allowedTypes: ["approval"], approvalAmount: "exact" },
|
|
240
|
+
maxFee: { bps: ACROSS_V5_PRICING_MAX_FEE_BPS }
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
var ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
244
|
+
var ZERO2 = /^0x0{40}$/;
|
|
245
|
+
var UINT = /^(?:0|[1-9]\d{0,77})$/;
|
|
246
|
+
var DECIMAL = /^(?:0|[1-9]\d{0,15})(?:\.\d{1,30})?$/;
|
|
247
|
+
var plain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
248
|
+
var own = (o, key) => Object.prototype.hasOwnProperty.call(o, key) ? o[key] : void 0;
|
|
249
|
+
var uint = (v) => typeof v === "string" && UINT.test(v) ? BigInt(v) : null;
|
|
250
|
+
var sameAddress = (a, b) => typeof a === "string" && ADDRESS.test(a) && a.toLowerCase() === b.toLowerCase();
|
|
251
|
+
function scaled(text2, scale) {
|
|
252
|
+
if (!DECIMAL.test(text2)) return null;
|
|
253
|
+
const [whole, frac = ""] = text2.split(".");
|
|
254
|
+
return BigInt(whole + frac.slice(0, scale).padEnd(scale, "0"));
|
|
255
|
+
}
|
|
256
|
+
var USD_SCALE = 18;
|
|
257
|
+
var PRICE_SCALE = 12;
|
|
258
|
+
function acrossUsdToUnits(amountUsd, priceUsd, decimals) {
|
|
259
|
+
if (typeof amountUsd !== "string" || typeof priceUsd !== "number" || !Number.isFinite(priceUsd) || priceUsd <= 0 || priceUsd >= 1e12) return null;
|
|
260
|
+
if (!Number.isInteger(decimals) || decimals < 0 || decimals > 36) return null;
|
|
261
|
+
const usd = scaled(amountUsd, USD_SCALE);
|
|
262
|
+
const price = scaled(priceUsd.toFixed(PRICE_SCALE), PRICE_SCALE);
|
|
263
|
+
if (usd === null || price === null || price === 0n) return null;
|
|
264
|
+
return usd * 10n ** BigInt(decimals) * 10n ** BigInt(PRICE_SCALE) / (price * 10n ** BigInt(USD_SCALE));
|
|
265
|
+
}
|
|
266
|
+
function readAcrossV5Quote(request, route, body) {
|
|
267
|
+
const malformed = (what) => {
|
|
268
|
+
throw new AcrossRefusal("api-answer", `the V5 quote ${what}`, "upstream_unavailable");
|
|
269
|
+
};
|
|
270
|
+
const other = (what) => {
|
|
271
|
+
throw new AcrossRefusal("api-answer", `the V5 quote ${what}`, "policy_refused");
|
|
272
|
+
};
|
|
273
|
+
if (!plain(body)) return malformed("is not a JSON object");
|
|
274
|
+
const amountType = own(body, "amountType");
|
|
275
|
+
if (amountType !== void 0 && amountType !== "exact_input") other(`is ${String(amountType).slice(0, 20)}, not exact input`);
|
|
276
|
+
const src = route.input.chain;
|
|
277
|
+
const dst = route.output.chain;
|
|
278
|
+
const origin = own(body, "origin");
|
|
279
|
+
const destination = own(body, "destination");
|
|
280
|
+
if (!plain(origin) || !plain(destination)) return malformed("has no origin or destination");
|
|
281
|
+
const oToken = own(origin, "token");
|
|
282
|
+
const dToken = own(destination, "token");
|
|
283
|
+
if (!plain(oToken) || !plain(dToken)) return malformed("names no tokens");
|
|
284
|
+
if (own(oToken, "chainId") !== src.chainId || !sameAddress(own(oToken, "address"), request.sourceToken)) other("is for another input token or chain");
|
|
285
|
+
if (own(dToken, "chainId") !== dst.chainId || !sameAddress(own(dToken, "address"), request.destToken)) other("is for another output token or chain");
|
|
286
|
+
const amountIn = uint(own(origin, "amount"));
|
|
287
|
+
if (amountIn === null) return malformed("states no input amount");
|
|
288
|
+
if (amountIn !== request.amount) other(`sends ${amountIn}, the request ${request.amount}`);
|
|
289
|
+
const destinationAmount = uint(own(destination, "amount"));
|
|
290
|
+
if (destinationAmount === null) return malformed("states no output estimate");
|
|
291
|
+
if (destinationAmount > request.amount) other("expects more to arrive than goes in");
|
|
292
|
+
const fee = own(body, "fee");
|
|
293
|
+
if (!plain(fee)) return malformed("has no fee");
|
|
294
|
+
const total = own(fee, "totalFee");
|
|
295
|
+
if (!plain(total)) return malformed("has no total fee");
|
|
296
|
+
const totalFee = uint(own(total, "amount"));
|
|
297
|
+
if (totalFee === null) return malformed("states a total fee that is not a base-unit integer");
|
|
298
|
+
const feeToken = own(total, "token");
|
|
299
|
+
if (!plain(feeToken) || own(feeToken, "chainId") !== dst.chainId || !sameAddress(own(feeToken, "address"), request.destToken) || own(feeToken, "decimals") !== route.output.decimals) {
|
|
300
|
+
malformed("states its fee in another token");
|
|
301
|
+
}
|
|
302
|
+
if (totalFee !== request.amount - destinationAmount) malformed(`fee ${totalFee} is not its input minus its estimate (${request.amount - destinationAmount})`);
|
|
303
|
+
const appFee = own(fee, "appFee");
|
|
304
|
+
if (appFee !== void 0 && appFee !== null) {
|
|
305
|
+
const app = plain(appFee) ? uint(own(appFee, "amount")) : null;
|
|
306
|
+
if (app === null) return malformed("states an app fee that does not read");
|
|
307
|
+
if (app > 0n) other("carries an app fee this module never asks for");
|
|
308
|
+
}
|
|
309
|
+
const fill = own(body, "expectedFillTimeMs");
|
|
310
|
+
if (typeof fill !== "number" || !Number.isFinite(fill) || fill < 0) return malformed("states no fill time");
|
|
311
|
+
const priceUsd = own(dToken, "priceUsd");
|
|
312
|
+
const legs = own(body, "gasEstimates");
|
|
313
|
+
if (!Array.isArray(legs) || legs.length > 16) return malformed("has no gas estimates");
|
|
314
|
+
let originGas = 0n;
|
|
315
|
+
let destinationGas = 0n;
|
|
316
|
+
for (const leg of legs) {
|
|
317
|
+
if (!plain(leg)) return malformed("has a gas estimate that is not an object");
|
|
318
|
+
if (own(leg, "effect") !== "included_in_transfer_fee") continue;
|
|
319
|
+
const side = own(leg, "leg");
|
|
320
|
+
if (side !== "origin" && side !== "destination") continue;
|
|
321
|
+
const units = legUnits(leg, route, priceUsd);
|
|
322
|
+
if (side === "origin") originGas += units ?? 0n;
|
|
323
|
+
else destinationGas = units === null || destinationGas === null ? null : destinationGas + units;
|
|
324
|
+
}
|
|
325
|
+
if (originGas > totalFee) originGas = totalFee;
|
|
326
|
+
const usdText = own(origin, "amountUsd");
|
|
327
|
+
const amountUsd = typeof usdText === "string" && DECIMAL.test(usdText) ? Number(usdText) : void 0;
|
|
328
|
+
return { totalFee, destinationAmount, originGas, destinationGas, expectedFillTimeMs: fill, ...amountUsd !== void 0 && Number.isFinite(amountUsd) ? { amountUsd } : {} };
|
|
329
|
+
}
|
|
330
|
+
function legUnits(leg, route, priceUsd) {
|
|
331
|
+
const token = own(leg, "token");
|
|
332
|
+
const amount = uint(own(leg, "amount"));
|
|
333
|
+
if (route.asset === "ETH" && plain(token) && amount !== null && ZERO2.test(String(own(token, "address"))) && own(token, "decimals") === 18) {
|
|
334
|
+
const chainId = own(token, "chainId");
|
|
335
|
+
const side = chainId === route.input.chain.chainId ? route.input.chain : chainId === route.output.chain.chainId ? route.output.chain : void 0;
|
|
336
|
+
if (side?.nativeIsEth) return amount;
|
|
337
|
+
}
|
|
338
|
+
return acrossUsdToUnits(own(leg, "amountUsd"), priceUsd, route.input.decimals);
|
|
339
|
+
}
|
|
340
|
+
function acrossSuggestedFeesQuery(request, route) {
|
|
341
|
+
const q = [
|
|
342
|
+
["inputToken", route.input.token],
|
|
343
|
+
["outputToken", route.output.token],
|
|
344
|
+
["originChainId", String(route.input.chain.chainId)],
|
|
345
|
+
["destinationChainId", String(route.output.chain.chainId)],
|
|
346
|
+
["amount", request.amount.toString(10)],
|
|
347
|
+
["recipient", request.recipient.toLowerCase()]
|
|
348
|
+
];
|
|
349
|
+
return q.map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
|
|
350
|
+
}
|
|
351
|
+
var ACROSS_SUGGESTED_FEES_MAX_AGE_S = 600;
|
|
352
|
+
var ACROSS_SUGGESTED_FEES_MAX_AHEAD_S = 0;
|
|
353
|
+
function readAcrossSuggestedFees(request, route, status, body, nowS) {
|
|
354
|
+
const unavailable = (detail) => ({ kind: "unavailable", detail });
|
|
355
|
+
const refused = (detail, reason) => ({ kind: "refused", detail, reason });
|
|
356
|
+
if (status !== 200) {
|
|
357
|
+
const code = plain(body) ? own(body, "code") : void 0;
|
|
358
|
+
const label = typeof code === "string" ? ` ${code.slice(0, 40)}` : "";
|
|
359
|
+
if (status === 400) {
|
|
360
|
+
if (code === "AMOUNT_TOO_LOW") return refused("Across's relayer fee quote says the amount is too low relative to fees", "amount_too_small");
|
|
361
|
+
if (code === "AMOUNT_TOO_HIGH") return refused("Across's relayer fee quote says the amount is higher than relayer liquidity", "amount_too_large");
|
|
362
|
+
if (code === "ROUTE_NOT_ENABLED") return refused("Across's relayer fee quote says this route is not enabled for relayers", "unsupported_pair");
|
|
363
|
+
const param = plain(body) ? own(body, "param") : void 0;
|
|
364
|
+
const message = plain(body) ? own(body, "message") : void 0;
|
|
365
|
+
if (code === "INVALID_PARAM" && /token|chain/i.test(`${typeof param === "string" ? param : ""} ${typeof message === "string" ? message : ""}`)) {
|
|
366
|
+
return refused(`Across's relayer fee quote does not serve this token or chain (INVALID_PARAM${typeof param === "string" ? ` ${param.slice(0, 40)}` : ""})`, "unsupported_pair");
|
|
367
|
+
}
|
|
368
|
+
return refused(`Across's relayer fee quote refused the deposit (HTTP 400${label})`, "upstream_unavailable");
|
|
369
|
+
}
|
|
370
|
+
return unavailable(`it answered HTTP ${status}${label}`);
|
|
371
|
+
}
|
|
372
|
+
if (!plain(body)) return unavailable("its answer is not a JSON object");
|
|
373
|
+
const inputToken = own(body, "inputToken");
|
|
374
|
+
const outputToken = own(body, "outputToken");
|
|
375
|
+
if (!plain(inputToken) || !plain(outputToken)) return unavailable("its answer names no tokens");
|
|
376
|
+
if (!sameAddress(own(inputToken, "address"), route.input.token) || own(inputToken, "chainId") !== route.input.chain.chainId || !sameAddress(own(outputToken, "address"), route.output.token) || own(outputToken, "chainId") !== route.output.chain.chainId) {
|
|
377
|
+
return unavailable("its answer is for another route");
|
|
378
|
+
}
|
|
379
|
+
const spoke = own(body, "spokePoolAddress");
|
|
380
|
+
const destSpoke = own(body, "destinationSpokePoolAddress");
|
|
381
|
+
const spokeMoved = spoke !== void 0 && !sameAddress(spoke, route.input.chain.spokePool);
|
|
382
|
+
if (spokeMoved || destSpoke !== void 0 && !sameAddress(destSpoke, route.output.chain.spokePool)) {
|
|
383
|
+
return refused(`Across quotes this route on another SpokePool than the one pinned for ${spokeMoved ? route.input.chain.name : route.output.chain.name} \u2014 the pins need a review`, "vault_mismatch");
|
|
384
|
+
}
|
|
385
|
+
const totalRelay = own(body, "totalRelayFee");
|
|
386
|
+
const total = plain(totalRelay) ? uint(own(totalRelay, "total")) : null;
|
|
387
|
+
const outputAmount = uint(own(body, "outputAmount"));
|
|
388
|
+
if (total === null || outputAmount === null) return unavailable("its answer states no relayer fee");
|
|
389
|
+
if (outputAmount + total !== request.amount) return unavailable("its fee is not the amount minus its output");
|
|
390
|
+
if (own(body, "isAmountTooLow") === true || total >= request.amount) return refused("Across's relayer fee quote says the amount is too low relative to fees", "amount_too_small");
|
|
391
|
+
const limits = own(body, "limits");
|
|
392
|
+
if (plain(limits)) {
|
|
393
|
+
const min = uint(own(limits, "minDeposit"));
|
|
394
|
+
const max = uint(own(limits, "maxDeposit"));
|
|
395
|
+
if (min !== null && request.amount < min) return refused(`Across's relayers take at least ${min} base units on this route`, "amount_too_small");
|
|
396
|
+
if (max !== null && request.amount > max) return refused(`Across's relayers take at most ${max} base units on this route`, "amount_too_large");
|
|
397
|
+
}
|
|
398
|
+
const ts = own(body, "timestamp");
|
|
399
|
+
const timestamp = typeof ts === "string" && /^[1-9]\d{8,9}$/.test(ts) ? Number(ts) : NaN;
|
|
400
|
+
if (!Number.isInteger(timestamp)) return unavailable("its answer states no quote time");
|
|
401
|
+
if (timestamp - nowS > ACROSS_SUGGESTED_FEES_MAX_AHEAD_S) return unavailable(`its quote time is ${timestamp - nowS} s ahead of this clock`);
|
|
402
|
+
if (nowS - timestamp > ACROSS_SUGGESTED_FEES_MAX_AGE_S) return unavailable(`its quote time is ${nowS - timestamp} s old`);
|
|
403
|
+
const eta = own(body, "estimatedFillTimeSec");
|
|
404
|
+
return { kind: "fees", totalRelayFee: total, timestamp, estimatedFillTimeSec: typeof eta === "number" && Number.isFinite(eta) && eta >= 0 ? eta : 2 };
|
|
405
|
+
}
|
|
406
|
+
var text = (v, max) => typeof v === "string" && v.length > 0 ? v.slice(0, max) : void 0;
|
|
407
|
+
var FEE_CAP = /\bmax[ _-]?fee\b|\bmaximum (?:total |transfer )?fee\b|\bfee (?:cap|limit)\b|\bfees? (?:is |are )?(?:above|exceeds?|over|greater than|more than)\b/;
|
|
408
|
+
function reasonOfCode(code, message, param, side, status) {
|
|
409
|
+
switch (code) {
|
|
410
|
+
case "unauthenticated":
|
|
411
|
+
case "auth.missing_credentials":
|
|
412
|
+
case "auth.invalid_credentials":
|
|
413
|
+
// A feature the key is not entitled to (a permission Across grants per integration).
|
|
414
|
+
case "permission.not_entitled":
|
|
415
|
+
return { reason: "key_rejected", httpStatus: status };
|
|
416
|
+
case "policy.amount_out_of_range": {
|
|
417
|
+
if (side === "min") return { reason: "amount_too_small" };
|
|
418
|
+
if (side === "max") return { reason: "amount_too_large" };
|
|
419
|
+
const m = (message ?? "").toLowerCase();
|
|
420
|
+
if (/\b(?:raise|increase) the amount\b/.test(m)) return { reason: "amount_too_small" };
|
|
421
|
+
if (/\b(?:lower|reduce|decrease) the amount\b/.test(m)) return { reason: "amount_too_large" };
|
|
422
|
+
if (FEE_CAP.test(m)) return { reason: "price_check_failed" };
|
|
423
|
+
if (/\b(?:too low|too small|below|minimum|min)\b/.test(m)) return { reason: "amount_too_small" };
|
|
424
|
+
if (/\b(?:too high|too large|above|maximum|max|liquidity)\b/.test(m)) return { reason: "amount_too_large" };
|
|
425
|
+
return { reason: "price_check_failed" };
|
|
426
|
+
}
|
|
427
|
+
// The API no longer takes what this module sends (a field it does not know, or one it now requires): an API of
|
|
428
|
+
// another shape than the one this module was built against.
|
|
429
|
+
case "request.unsupported_param":
|
|
430
|
+
case "request.missing_field":
|
|
431
|
+
return { reason: "upstream_unavailable", httpStatus: status };
|
|
432
|
+
// Only pinned tokens and chains are sent: one V5 calls invalid ("unknown token … is not a known token") is one it
|
|
433
|
+
// does not serve. Any other value it no longer takes is, like the codes above, an API of another shape.
|
|
434
|
+
case "request.invalid_field":
|
|
435
|
+
return /token|chain/i.test(`${param ?? ""} ${message ?? ""}`) ? { reason: "unsupported_pair" } : { reason: "upstream_unavailable", httpStatus: status };
|
|
436
|
+
case "system.unavailable":
|
|
437
|
+
case "conflict.submission_state_unknown":
|
|
438
|
+
return { reason: "upstream_unavailable", httpStatus: status };
|
|
439
|
+
default:
|
|
440
|
+
return void 0;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
function parseAcrossV5Error(status, body, retryAfter, nowMs = Date.now()) {
|
|
444
|
+
const o = plain(body) ? body : void 0;
|
|
445
|
+
const nested = o !== void 0 && plain(o["error"]) ? o["error"] : void 0;
|
|
446
|
+
const code = text(nested?.["code"], 80) ?? text(o?.["code"], 80);
|
|
447
|
+
const type = text(nested?.["type"], 80);
|
|
448
|
+
const message = text(nested?.["message"], 240) ?? text(o?.["message"], 240);
|
|
449
|
+
const param = text(nested?.["param"], 80);
|
|
450
|
+
const requestId = text(nested?.["requestId"], 120);
|
|
451
|
+
const details = nested !== void 0 && plain(nested["details"]) ? nested["details"] : o !== void 0 && plain(o["details"]) ? o["details"] : void 0;
|
|
452
|
+
const limits = details !== void 0 && plain(details["amountLimits"]) ? details["amountLimits"] : void 0;
|
|
453
|
+
const rawSide = limits?.["side"];
|
|
454
|
+
const side = rawSide === "min" || rawSide === "max" ? rawSide : void 0;
|
|
455
|
+
const rawBound = limits?.["amount"];
|
|
456
|
+
const bound = typeof rawBound === "string" && UINT.test(rawBound) ? rawBound : void 0;
|
|
457
|
+
const byStatus = (0, import_errors2.httpRefusal)(status, retryAfter, nowMs);
|
|
458
|
+
let info;
|
|
459
|
+
if (byStatus?.reason === "rate_limited") info = byStatus;
|
|
460
|
+
else info = (code !== void 0 ? reasonOfCode(code, message, param, side, status) : void 0) ?? byStatus ?? (o !== void 0 && status >= 400 && status < 500 && status !== 404 ? { reason: "no_route" } : void 0);
|
|
461
|
+
return {
|
|
462
|
+
status,
|
|
463
|
+
...code !== void 0 ? { code } : {},
|
|
464
|
+
...type !== void 0 ? { type } : {},
|
|
465
|
+
...message !== void 0 ? { message } : {},
|
|
466
|
+
...param !== void 0 ? { param } : {},
|
|
467
|
+
...requestId !== void 0 ? { requestId } : {},
|
|
468
|
+
...side !== void 0 ? { amountLimit: { side, ...bound !== void 0 ? { amount: bound } : {} } } : {},
|
|
469
|
+
...info !== void 0 ? { info } : {},
|
|
470
|
+
retrySameRequest: status === 409 && code === "conflict.submission_state_unknown"
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
function acrossApiUrl(url, what) {
|
|
474
|
+
const u = String(url).trim().replace(/\/+$/, "");
|
|
475
|
+
if (/^https:\/\/[^\s/?#@]+(?:\/[^\s?#]*)?$/i.test(u)) return u;
|
|
476
|
+
if (/^http:\/\/(?:localhost|127\.0\.0\.1)(?::[0-9]{1,5})?(?:\/[^\s?#]*)?$/i.test(u)) return u;
|
|
477
|
+
throw new Error(`across: ${what} must be an https:// URL (http only for localhost)`);
|
|
478
|
+
}
|
|
479
|
+
var acrossOriginOf = (url) => (/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(url)?.[0] ?? "").toLowerCase();
|
|
480
|
+
async function acrossHttp(url, init, opts) {
|
|
481
|
+
const expected = acrossOriginOf(url);
|
|
482
|
+
let status;
|
|
483
|
+
let raw;
|
|
484
|
+
let retryAfter = null;
|
|
485
|
+
try {
|
|
486
|
+
const timeout = (0, import_util.timeoutSignal)(opts.timeoutMs);
|
|
487
|
+
const res = await (opts.fetchImpl ?? fetch)(url, { ...init, redirect: "error", signal: opts.signal ? (0, import_util.anySignal)([opts.signal, timeout]) : timeout });
|
|
488
|
+
if (res.redirected === true || typeof res.url === "string" && res.url !== "" && acrossOriginOf(res.url) !== expected) {
|
|
489
|
+
throw new AcrossRefusal("api-answer", `${opts.what} answered through a redirect or from another origin \u2014 refused (a key must not follow one)`, "policy_refused");
|
|
490
|
+
}
|
|
491
|
+
status = res.status;
|
|
492
|
+
retryAfter = res.headers?.get?.("retry-after") ?? null;
|
|
493
|
+
raw = await res.text();
|
|
494
|
+
} catch (err) {
|
|
495
|
+
if (err instanceof AcrossRefusal) throw err;
|
|
496
|
+
const name = err instanceof Error ? err.name.slice(0, 40) : "error";
|
|
497
|
+
throw new AcrossRefusal("api-answer", `${opts.what} did not answer (${name})`, opts.signal?.aborted ? void 0 : "upstream_unavailable");
|
|
498
|
+
}
|
|
499
|
+
if (raw.length > MAX_ANSWER_CHARS) throw new AcrossRefusal("api-answer", `${opts.what} answered more than any quote`, "upstream_unavailable");
|
|
500
|
+
let body;
|
|
501
|
+
try {
|
|
502
|
+
body = JSON.parse(raw);
|
|
503
|
+
} catch {
|
|
504
|
+
body = void 0;
|
|
505
|
+
}
|
|
506
|
+
return { status, body, retryAfter };
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// src/deposit.ts
|
|
510
|
+
var import_viem = require("viem");
|
|
511
|
+
var SPOKE_POOL_ABI = (0, import_viem.parseAbi)([
|
|
512
|
+
"function deposit(bytes32 depositor, bytes32 recipient, bytes32 inputToken, bytes32 outputToken, uint256 inputAmount, uint256 outputAmount, uint256 destinationChainId, bytes32 exclusiveRelayer, uint32 quoteTimestamp, uint32 fillDeadline, uint32 exclusivityParameter, bytes message) payable"
|
|
513
|
+
]);
|
|
514
|
+
var ADDRESS2 = /^0x[0-9a-fA-F]{40}$/;
|
|
515
|
+
var HEX = /^0x(?:[0-9a-fA-F]{2})*$/;
|
|
516
|
+
var U256_MAX = (1n << 256n) - 1n;
|
|
517
|
+
var U32_MAX = 4294967295;
|
|
518
|
+
var HEAD_WORDS = 12;
|
|
519
|
+
var MESSAGE_OFFSET = HEAD_WORDS * 32;
|
|
520
|
+
var ACROSS_MAX_MESSAGE_BYTES = 65536;
|
|
521
|
+
function acrossBytes32(address) {
|
|
522
|
+
if (typeof address !== "string" || !ADDRESS2.test(address)) throw new AcrossRefusal("request-invalid", `${String(address)} is not an EVM address`);
|
|
523
|
+
return `0x${"0".repeat(24)}${address.slice(2).toLowerCase()}`;
|
|
524
|
+
}
|
|
525
|
+
function acrossAddressOf(word) {
|
|
526
|
+
const w = word.startsWith("0x") ? word.slice(2) : word;
|
|
527
|
+
if (!/^[0-9a-fA-F]{64}$/.test(w) || !/^0{24}/.test(w)) return null;
|
|
528
|
+
return `0x${w.slice(24).toLowerCase()}`;
|
|
529
|
+
}
|
|
530
|
+
function checkArgs(a) {
|
|
531
|
+
const bad = (what) => {
|
|
532
|
+
throw new AcrossRefusal("request-invalid", `the deposit's ${what}`);
|
|
533
|
+
};
|
|
534
|
+
if (a === null || typeof a !== "object") bad("arguments are missing");
|
|
535
|
+
for (const [k, v] of [["depositor", a.depositor], ["recipient", a.recipient], ["inputToken", a.inputToken], ["outputToken", a.outputToken], ["exclusiveRelayer", a.exclusiveRelayer]]) {
|
|
536
|
+
if (typeof v !== "string" || !ADDRESS2.test(v)) bad(`${k} is not an EVM address`);
|
|
537
|
+
}
|
|
538
|
+
for (const [k, v] of [["inputAmount", a.inputAmount], ["outputAmount", a.outputAmount], ["destinationChainId", a.destinationChainId]]) {
|
|
539
|
+
if (typeof v !== "bigint" || v < 0n || v > U256_MAX) bad(`${k} is not a uint256`);
|
|
540
|
+
}
|
|
541
|
+
for (const [k, v] of [["quoteTimestamp", a.quoteTimestamp], ["fillDeadline", a.fillDeadline], ["exclusivityParameter", a.exclusivityParameter]]) {
|
|
542
|
+
if (!Number.isInteger(v) || v < 0 || v > U32_MAX) bad(`${k} is not a uint32`);
|
|
543
|
+
}
|
|
544
|
+
if (typeof a.message !== "string" || !HEX.test(a.message) || (a.message.length - 2) / 2 > ACROSS_MAX_MESSAGE_BYTES) bad("message is not bytes");
|
|
545
|
+
}
|
|
546
|
+
function encodeAcrossDeposit(a) {
|
|
547
|
+
checkArgs(a);
|
|
548
|
+
return (0, import_viem.encodeFunctionData)({
|
|
549
|
+
abi: SPOKE_POOL_ABI,
|
|
550
|
+
functionName: "deposit",
|
|
551
|
+
args: [
|
|
552
|
+
acrossBytes32(a.depositor),
|
|
553
|
+
acrossBytes32(a.recipient),
|
|
554
|
+
acrossBytes32(a.inputToken),
|
|
555
|
+
acrossBytes32(a.outputToken),
|
|
556
|
+
a.inputAmount,
|
|
557
|
+
a.outputAmount,
|
|
558
|
+
a.destinationChainId,
|
|
559
|
+
acrossBytes32(a.exclusiveRelayer),
|
|
560
|
+
a.quoteTimestamp,
|
|
561
|
+
a.fillDeadline,
|
|
562
|
+
a.exclusivityParameter,
|
|
563
|
+
a.message.toLowerCase()
|
|
564
|
+
]
|
|
565
|
+
}).toLowerCase();
|
|
566
|
+
}
|
|
567
|
+
function word32(word) {
|
|
568
|
+
return /^0{56}[0-9a-f]{8}$/.test(word) ? parseInt(word.slice(56), 16) : null;
|
|
569
|
+
}
|
|
570
|
+
function decodeAcrossDeposit(data) {
|
|
571
|
+
const malformed = (what) => {
|
|
572
|
+
throw new AcrossRefusal("tx-calldata", `the deposit calldata ${what}`, "policy_refused");
|
|
573
|
+
};
|
|
574
|
+
if (typeof data !== "string" || !HEX.test(data) || data.length < 10) malformed("is not hex calldata");
|
|
575
|
+
const hex = data.toLowerCase();
|
|
576
|
+
const selector = hex.slice(0, 10);
|
|
577
|
+
if (selector !== ACROSS_DEPOSIT) {
|
|
578
|
+
const name = Object.prototype.hasOwnProperty.call(ACROSS_REFUSED_SELECTORS, selector) ? ACROSS_REFUSED_SELECTORS[selector] : void 0;
|
|
579
|
+
throw new AcrossRefusal("tx-selector", name ? `the call is ${name} (${selector}), which this module never signs` : `the call is ${selector}, not deposit (${ACROSS_DEPOSIT})`, "policy_refused");
|
|
580
|
+
}
|
|
581
|
+
const body = hex.slice(10);
|
|
582
|
+
if (body.length < (HEAD_WORDS + 1) * 64) malformed(`is ${(hex.length - 2) / 2} bytes, shorter than a deposit`);
|
|
583
|
+
const word = (i) => body.slice(64 * i, 64 * i + 64);
|
|
584
|
+
const addr = (i, what) => acrossAddressOf(word(i)) ?? malformed(`carries a ${what} that is not an EVM address`);
|
|
585
|
+
const u32 = (i, what) => word32(word(i)) ?? malformed(`carries a ${what} wider than 32 bits`);
|
|
586
|
+
const offset = BigInt(`0x${word(11)}`);
|
|
587
|
+
if (offset !== BigInt(MESSAGE_OFFSET)) malformed(`puts the message at offset ${offset}, not ${MESSAGE_OFFSET}`);
|
|
588
|
+
const lengthWord = word(HEAD_WORDS);
|
|
589
|
+
if (!/^0{56}/.test(lengthWord)) malformed("states an impossible message length");
|
|
590
|
+
const length = parseInt(lengthWord.slice(56), 16);
|
|
591
|
+
if (length > ACROSS_MAX_MESSAGE_BYTES) malformed(`carries a ${length}-byte message, over ${ACROSS_MAX_MESSAGE_BYTES}`);
|
|
592
|
+
const padded = Math.ceil(length / 32) * 64;
|
|
593
|
+
const expected = (HEAD_WORDS + 1) * 64 + padded;
|
|
594
|
+
if (body.length !== expected) {
|
|
595
|
+
malformed(body.length > expected ? `has ${(body.length - expected) / 2} bytes after the encoded call` : `is ${(hex.length - 2) / 2} bytes, the encoding needs ${4 + expected / 2}`);
|
|
596
|
+
}
|
|
597
|
+
const tail = body.slice((HEAD_WORDS + 1) * 64);
|
|
598
|
+
if (!/^0*$/.test(tail.slice(length * 2))) malformed("pads the message with non-zero bytes");
|
|
599
|
+
const args = {
|
|
600
|
+
depositor: addr(0, "depositor"),
|
|
601
|
+
recipient: addr(1, "recipient"),
|
|
602
|
+
inputToken: addr(2, "input token"),
|
|
603
|
+
outputToken: addr(3, "output token"),
|
|
604
|
+
inputAmount: BigInt(`0x${word(4)}`),
|
|
605
|
+
outputAmount: BigInt(`0x${word(5)}`),
|
|
606
|
+
destinationChainId: BigInt(`0x${word(6)}`),
|
|
607
|
+
exclusiveRelayer: addr(7, "exclusive relayer"),
|
|
608
|
+
quoteTimestamp: u32(8, "quote timestamp"),
|
|
609
|
+
fillDeadline: u32(9, "fill deadline"),
|
|
610
|
+
exclusivityParameter: u32(10, "exclusivity parameter"),
|
|
611
|
+
message: `0x${tail.slice(0, length * 2)}`
|
|
612
|
+
};
|
|
613
|
+
if (encodeAcrossDeposit(args) !== hex) malformed("is not the canonical encoding of its arguments");
|
|
614
|
+
return args;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// src/verify.ts
|
|
618
|
+
var import_viem2 = require("viem");
|
|
619
|
+
var import_core = require("@anywalletkit/core");
|
|
620
|
+
var import_errors3 = require("@anywalletkit/protocol-swap2-core/errors");
|
|
621
|
+
var import_util2 = require("@anywalletkit/protocol-swap2-core/util");
|
|
622
|
+
|
|
623
|
+
// src/pricing.ts
|
|
624
|
+
var ACROSS_FILL_WINDOW_S = 7200;
|
|
625
|
+
var ACROSS_QUOTE_TIME_LAG_S = 60;
|
|
626
|
+
var ACROSS_FLOOR_CBPS = Object.freeze({ stable: 100, wbtc: 310, ethFromEthereum: 100 });
|
|
627
|
+
var ACROSS_ETH_L2_CURVE = Object.freeze([
|
|
628
|
+
[0, 477],
|
|
629
|
+
[1e3, 515],
|
|
630
|
+
[2e3, 540],
|
|
631
|
+
[4e3, 605],
|
|
632
|
+
[8e3, 715],
|
|
633
|
+
[16e3, 850],
|
|
634
|
+
[36e3, 920]
|
|
635
|
+
].map((p) => Object.freeze(p)));
|
|
636
|
+
var ACROSS_ETH_L2_FLOOR_MAX_USD = 36e3;
|
|
637
|
+
var ACROSS_FLOOR_ORIGINS = Object.freeze([1, 10, 8453, 42161]);
|
|
638
|
+
var ACROSS_FLOOR_DESTINATIONS = Object.freeze([10, 8453, 42161]);
|
|
639
|
+
function acrossFloorCovers(route) {
|
|
640
|
+
return ACROSS_FLOOR_ORIGINS.includes(route.input.chain.chainId) && ACROSS_FLOOR_DESTINATIONS.includes(route.output.chain.chainId);
|
|
641
|
+
}
|
|
642
|
+
var ACROSS_V5_OTHER_RAIL_FILL_MS = 6e4;
|
|
643
|
+
var acrossV5OtherRail = (expectedFillTimeMs) => expectedFillTimeMs > ACROSS_V5_OTHER_RAIL_FILL_MS;
|
|
644
|
+
function acrossRouteUnpriced(route) {
|
|
645
|
+
if (route.output.chain.chainId === 1) return "plain deposits to Ethereum are not priced yet \u2014 small ones went unfilled in the 2026-11-14 study for reasons the data does not show";
|
|
646
|
+
return null;
|
|
647
|
+
}
|
|
648
|
+
function acrossFloorCbps(route, amountUsd) {
|
|
649
|
+
const src = route.input.chain.chainId;
|
|
650
|
+
if (!acrossFloorCovers(route)) {
|
|
651
|
+
return `without Across's relayer fee quote there is no relayer price for ${route.input.chain.name} \u2192 ${route.output.chain.name} (the pinned floor covers Ethereum, Optimism, Base and Arbitrum to Optimism, Base and Arbitrum)`;
|
|
652
|
+
}
|
|
653
|
+
if (route.asset === "USDC" || route.asset === "USDT") return ACROSS_FLOOR_CBPS.stable;
|
|
654
|
+
if (route.asset === "WBTC") return ACROSS_FLOOR_CBPS.wbtc;
|
|
655
|
+
if (src === 1) return ACROSS_FLOOR_CBPS.ethFromEthereum;
|
|
656
|
+
if (amountUsd === void 0 || !Number.isFinite(amountUsd) || amountUsd < 0) return "without Across's relayer fee quote the ETH floor needs the transfer's size in dollars, and the V5 quote states none";
|
|
657
|
+
if (amountUsd > ACROSS_ETH_L2_FLOOR_MAX_USD) return `without Across's relayer fee quote ETH from an L2 is priced up to $${ACROSS_ETH_L2_FLOOR_MAX_USD} (no larger plain deposit was seen)`;
|
|
658
|
+
const c = ACROSS_ETH_L2_CURVE;
|
|
659
|
+
for (let i = 1; i < c.length; i++) {
|
|
660
|
+
const [x1, y1] = c[i];
|
|
661
|
+
if (amountUsd <= x1) {
|
|
662
|
+
const [x0, y0] = c[i - 1];
|
|
663
|
+
return Math.ceil(y0 + (y1 - y0) * (amountUsd - x0) / (x1 - x0));
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return c[c.length - 1][1];
|
|
667
|
+
}
|
|
668
|
+
var acrossCbpsOf = (amount, cbps) => (amount * BigInt(cbps) + 999999n) / 1000000n;
|
|
669
|
+
function acrossFloorFee(route, amount, amountUsd, destinationGas) {
|
|
670
|
+
const cbps = acrossFloorCbps(route, amountUsd);
|
|
671
|
+
if (typeof cbps === "string") {
|
|
672
|
+
const tooLarge = acrossFloorCovers(route) && route.asset === "ETH" && route.input.chain.chainId !== 1 && amountUsd !== void 0 && amountUsd > ACROSS_ETH_L2_FLOOR_MAX_USD;
|
|
673
|
+
throw new AcrossRefusal("relayer-price", cbps, tooLarge ? "amount_too_large" : "upstream_unavailable");
|
|
674
|
+
}
|
|
675
|
+
if (destinationGas === null) throw new AcrossRefusal("relayer-price", "without Across's relayer fee quote the floor needs V5's destination gas, and it does not read", "upstream_unavailable");
|
|
676
|
+
return acrossCbpsOf(amount, cbps) + (destinationGas * 3n + 1n) / 2n;
|
|
677
|
+
}
|
|
678
|
+
function acrossPlainFee(amount, v5, need, otherRail = false) {
|
|
679
|
+
const f5 = v5.totalFee - (v5.originGas > v5.totalFee ? v5.totalFee : v5.originGas);
|
|
680
|
+
const fee = otherRail || need > f5 ? need : f5;
|
|
681
|
+
if (fee >= amount) throw new AcrossRefusal("relayer-price", `relayers would keep all of the ${amount} sent (fee ${fee})`, "amount_too_small");
|
|
682
|
+
return { fee, f5, need };
|
|
683
|
+
}
|
|
684
|
+
function acrossQuoteTimeOf(ethereumBlockTime, originBlockTime) {
|
|
685
|
+
return Math.min(ethereumBlockTime - ACROSS_QUOTE_TIME_LAG_S, originBlockTime);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// src/verify.ts
|
|
689
|
+
var ACROSS_DEFAULT_MAX_FEE_BPS = 1e3;
|
|
690
|
+
var ACROSS_MAX_FEE_BPS_LIMIT = 5e3;
|
|
691
|
+
var ACROSS_CLOCK_SKEW_S = 120;
|
|
692
|
+
var ACROSS_QUOTE_TIME_AHEAD_S = 15;
|
|
693
|
+
var ACROSS_LANDING_WINDOW_S = 300;
|
|
694
|
+
var ACROSS_MIN_FILL_WINDOW_S = 1800;
|
|
695
|
+
var ACROSS_MAX_FILL_WINDOW_S = 7800;
|
|
696
|
+
var ACROSS_MIN_FEE_PPM = Object.freeze({ stable: 100, ethFromEthereum: 70, ethFromL2: 450, ethFromOtherL2: 70, wbtc: 250 });
|
|
697
|
+
function acrossMinFeePpm(route) {
|
|
698
|
+
if (route.asset === "ETH") {
|
|
699
|
+
const src = route.input.chain.chainId;
|
|
700
|
+
if (src === 1) return ACROSS_MIN_FEE_PPM.ethFromEthereum;
|
|
701
|
+
return ACROSS_FLOOR_ORIGINS.includes(src) ? ACROSS_MIN_FEE_PPM.ethFromL2 : ACROSS_MIN_FEE_PPM.ethFromOtherL2;
|
|
702
|
+
}
|
|
703
|
+
if (route.asset === "WBTC") return ACROSS_MIN_FEE_PPM.wbtc;
|
|
704
|
+
return ACROSS_MIN_FEE_PPM.stable;
|
|
705
|
+
}
|
|
706
|
+
var ACROSS_GAS_FLOOR = 90000n;
|
|
707
|
+
var ACROSS_GAS_CAP = 60000000n;
|
|
708
|
+
var ACROSS_MAX_QUOTE_LIFE_MS = 3e5 + ACROSS_CLOCK_SKEW_S * 1e3;
|
|
709
|
+
var acrossQuoteTimeLimitMs = (quoteTimestamp) => (quoteTimestamp + ACROSS_DEPOSIT_QUOTE_TIME_BUFFER_S - ACROSS_LANDING_WINDOW_S) * 1e3;
|
|
710
|
+
var ACROSS_PLACEHOLDER = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045";
|
|
711
|
+
var ADDRESS3 = /^0x[0-9a-fA-F]{40}$/;
|
|
712
|
+
var ZERO3 = /^0x0{40}$/;
|
|
713
|
+
var U256_MAX2 = (1n << 256n) - 1n;
|
|
714
|
+
var UINT2 = /^(?:0|[1-9]\d{0,77})$/;
|
|
715
|
+
var lower = (s) => s.toLowerCase();
|
|
716
|
+
function checkAcrossRequest(r) {
|
|
717
|
+
const invalid = (what, reason) => {
|
|
718
|
+
throw new AcrossRefusal("request-invalid", what, reason);
|
|
719
|
+
};
|
|
720
|
+
if (r === null || typeof r !== "object") invalid("no request to check the deposit against");
|
|
721
|
+
for (const [what, v] of [["input token", r.sourceToken], ["output token", r.destToken], ["depositor", r.depositor], ["recipient", r.recipient]]) {
|
|
722
|
+
if (typeof v !== "string" || !ADDRESS3.test(v)) invalid(`the ${what} is not an address`);
|
|
723
|
+
}
|
|
724
|
+
const route = acrossRouteOf(r.sourceChain, r.sourceToken, r.destChain, r.destToken);
|
|
725
|
+
if ("code" in route) throw new AcrossRefusal(route.code, route.detail, "unsupported_pair");
|
|
726
|
+
if (ZERO3.test(r.depositor)) invalid("the depositor is the zero address", "recipient_mismatch");
|
|
727
|
+
if (ZERO3.test(r.recipient)) invalid("the recipient is the zero address", "recipient_mismatch");
|
|
728
|
+
if (typeof r.amount !== "bigint" || r.amount <= 0n || r.amount > U256_MAX2) invalid("the amount is not a positive integer");
|
|
729
|
+
if (r.minAmountOut !== void 0 && (typeof r.minAmountOut !== "bigint" || r.minAmountOut < 0n || r.minAmountOut > U256_MAX2)) invalid("the output floor is not an unsigned integer");
|
|
730
|
+
const maxFeeBps = r.maxFeeBps ?? ACROSS_DEFAULT_MAX_FEE_BPS;
|
|
731
|
+
if (!Number.isInteger(maxFeeBps) || maxFeeBps < 0 || maxFeeBps > ACROSS_MAX_FEE_BPS_LIMIT) {
|
|
732
|
+
invalid(`the fee cap must be a whole number of basis points up to ${ACROSS_MAX_FEE_BPS_LIMIT}`, "policy_refused");
|
|
733
|
+
}
|
|
734
|
+
const nowMs = r.nowMs ?? Date.now();
|
|
735
|
+
if (!Number.isFinite(nowMs) || nowMs <= 0) invalid("the clock is not a time");
|
|
736
|
+
return { route, nowS: Math.floor(nowMs / 1e3), maxFeeBps };
|
|
737
|
+
}
|
|
738
|
+
function checkTarget(tx, route) {
|
|
739
|
+
if (tx === null || typeof tx !== "object") throw new AcrossRefusal("tx-shape", "there is no deposit transaction", "policy_refused");
|
|
740
|
+
const src = route.input.chain;
|
|
741
|
+
if (tx.chainId !== src.chainId) throw new AcrossRefusal("tx-chain", `the deposit is for chain ${String(tx.chainId)}, not ${src.name} (${src.chainId})`, "vault_mismatch");
|
|
742
|
+
if (typeof tx.to !== "string" || !ADDRESS3.test(tx.to) || lower(tx.to) !== src.spokePool) {
|
|
743
|
+
throw new AcrossRefusal("tx-target", `the deposit calls ${String(tx.to)}, not the ${src.name} SpokePool ${src.spokePool} \u2014 periphery, swap and CCTP / OFT routes are not signed by this module`, "vault_mismatch");
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
function checkExclusivity(a) {
|
|
747
|
+
if (!ZERO3.test(a.exclusiveRelayer) || a.exclusivityParameter !== 0) {
|
|
748
|
+
throw new AcrossRefusal("tx-exclusivity", `the deposit names an exclusive relayer or window (${a.exclusiveRelayer}, ${a.exclusivityParameter}) \u2014 this module signs plain deposits any relayer may fill`, "policy_refused");
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
function checkDeadlines(a, nowS) {
|
|
752
|
+
const age = nowS - a.quoteTimestamp;
|
|
753
|
+
if (age < -ACROSS_QUOTE_TIME_AHEAD_S) throw new AcrossRefusal("tx-quote-time", `the quote time is ${-age} s in the future (the deposit reverts)`, "policy_refused");
|
|
754
|
+
if (age > ACROSS_DEPOSIT_QUOTE_TIME_BUFFER_S - ACROSS_LANDING_WINDOW_S) {
|
|
755
|
+
throw new AcrossRefusal("tx-quote-time", `the quote time is ${age} s old: the SpokePool takes at most ${ACROSS_DEPOSIT_QUOTE_TIME_BUFFER_S} s, with ${ACROSS_LANDING_WINDOW_S} s kept to land`, "quote_expired");
|
|
756
|
+
}
|
|
757
|
+
const left = a.fillDeadline - nowS;
|
|
758
|
+
if (left > ACROSS_FILL_DEADLINE_BUFFER_S - ACROSS_CLOCK_SKEW_S) {
|
|
759
|
+
throw new AcrossRefusal("tx-fill-deadline", `the fill deadline is ${left} s away, past the ${ACROSS_FILL_DEADLINE_BUFFER_S} s the SpokePool allows`, "policy_refused");
|
|
760
|
+
}
|
|
761
|
+
const window = a.fillDeadline - a.quoteTimestamp;
|
|
762
|
+
if (window > ACROSS_MAX_FILL_WINDOW_S) {
|
|
763
|
+
throw new AcrossRefusal("tx-fill-deadline", `the fill deadline is ${window} s after the quote time, more than the ${ACROSS_MAX_FILL_WINDOW_S} s an Across quote gives \u2014 unfilled, the deposit would hold the funds that long before its refund`, "policy_refused");
|
|
764
|
+
}
|
|
765
|
+
if (left < ACROSS_MIN_FILL_WINDOW_S) {
|
|
766
|
+
throw new AcrossRefusal("tx-fill-deadline", `the fill deadline is ${left} s away, under the ${ACROSS_MIN_FILL_WINDOW_S} s a relayer is given \u2014 the deposit would expire into a refund`, "quote_expired");
|
|
767
|
+
}
|
|
768
|
+
if (window < ACROSS_DEPOSIT_QUOTE_TIME_BUFFER_S + ACROSS_MIN_FILL_WINDOW_S) {
|
|
769
|
+
throw new AcrossRefusal("tx-fill-deadline", `the fill deadline is ${window} s after the quote time: a deposit landing as late as the SpokePool takes it (${ACROSS_DEPOSIT_QUOTE_TIME_BUFFER_S} s) would leave a relayer under ${ACROSS_MIN_FILL_WINDOW_S} s`, "policy_refused");
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
function verifyAcrossDeposit(request, tx) {
|
|
773
|
+
const { route, nowS, maxFeeBps } = checkAcrossRequest(request);
|
|
774
|
+
checkTarget(tx, route);
|
|
775
|
+
const a = decodeAcrossDeposit(tx.data);
|
|
776
|
+
const src = route.input.chain;
|
|
777
|
+
const dst = route.output.chain;
|
|
778
|
+
if (a.depositor !== lower(request.depositor)) {
|
|
779
|
+
throw new AcrossRefusal("tx-depositor", `the deposit is credited to ${a.depositor}, not to the signing account ${lower(request.depositor)} \u2014 the depositor is refunded and can redirect the output`, "recipient_mismatch");
|
|
780
|
+
}
|
|
781
|
+
if (a.recipient !== lower(request.recipient)) throw new AcrossRefusal("tx-recipient", `the deposit pays ${a.recipient}, not the recipient ${lower(request.recipient)}`, "recipient_mismatch");
|
|
782
|
+
if (a.destinationChainId !== BigInt(dst.chainId)) {
|
|
783
|
+
throw new AcrossRefusal("tx-destination", `the deposit is for chain ${a.destinationChainId}, not ${dst.name} (${dst.chainId})`, "recipient_mismatch");
|
|
784
|
+
}
|
|
785
|
+
if (a.inputToken !== route.input.token) throw new AcrossRefusal("tx-input-token", `the deposit takes ${a.inputToken}, the request sends ${route.input.token}${route.input.native ? " (the wrapped native token, for the native coin)" : ""}`, "policy_refused");
|
|
786
|
+
if (a.inputAmount !== request.amount) throw new AcrossRefusal("tx-input-amount", `the deposit takes ${a.inputAmount}, the request sends ${request.amount}`, "policy_refused");
|
|
787
|
+
if (a.outputToken !== route.output.token) throw new AcrossRefusal("tx-output-token", `the deposit pays ${a.outputToken} on ${dst.name}, the request is for ${route.output.token}${route.output.native ? " (the wrapped native token, paid out as the native coin)" : ""}`, "price_check_failed");
|
|
788
|
+
if (a.outputAmount <= 0n) throw new AcrossRefusal("tx-output-amount", "the deposit's output is zero", "price_check_failed");
|
|
789
|
+
if (request.minAmountOut !== void 0 && a.outputAmount < request.minAmountOut) {
|
|
790
|
+
throw new AcrossRefusal("tx-output-amount", `the deposit pays ${a.outputAmount}, under the caller's floor ${request.minAmountOut}`, "price_check_failed");
|
|
791
|
+
}
|
|
792
|
+
if (a.outputAmount > a.inputAmount) {
|
|
793
|
+
throw new AcrossRefusal("tx-output-amount", `the deposit asks relayers for ${a.outputAmount}, more than its ${a.inputAmount} input \u2014 nobody fills it, and the funds wait for a refund`, "price_check_failed");
|
|
794
|
+
}
|
|
795
|
+
const fee = a.inputAmount - a.outputAmount;
|
|
796
|
+
if (fee === 0n) {
|
|
797
|
+
throw new AcrossRefusal("tx-fee", "the deposit leaves relayers no fee \u2014 nobody fills it, and the funds wait for a refund", "price_check_failed");
|
|
798
|
+
}
|
|
799
|
+
const minPpm = acrossMinFeePpm(route);
|
|
800
|
+
if (fee * 1000000n < a.inputAmount * BigInt(minPpm)) {
|
|
801
|
+
throw new AcrossRefusal("tx-fee", `the deposit leaves relayers ${fee} of ${a.inputAmount}, under the ${minPpm}-per-million floor for ${route.asset} from ${src.name} \u2014 relayers do not fill it, and the funds wait for a refund`, "price_check_failed");
|
|
802
|
+
}
|
|
803
|
+
if (fee * 10000n > a.inputAmount * BigInt(maxFeeBps)) {
|
|
804
|
+
throw new AcrossRefusal("tx-fee", `the deposit leaves ${fee} of ${a.inputAmount} as fees, over the ${maxFeeBps} bps cap`, "price_check_failed");
|
|
805
|
+
}
|
|
806
|
+
if (a.message !== "0x") {
|
|
807
|
+
if (a.message.length >= 66 && a.message.slice(0, 66) === ACROSS_V5_MESSAGE_PREFIX) {
|
|
808
|
+
throw new AcrossRefusal("tx-message-v5", "the deposit carries an Across V5 witness message, consumable only through the V5 Gateway", "policy_refused");
|
|
809
|
+
}
|
|
810
|
+
throw new AcrossRefusal("tx-message", `the deposit carries a ${(a.message.length - 2) / 2}-byte message for the destination \u2014 only plain transfers are signed`, "policy_refused");
|
|
811
|
+
}
|
|
812
|
+
checkExclusivity(a);
|
|
813
|
+
checkDeadlines(a, nowS);
|
|
814
|
+
const value = typeof tx.value === "string" && UINT2.test(tx.value) ? BigInt(tx.value) : null;
|
|
815
|
+
const wantValue = route.input.native ? a.inputAmount : 0n;
|
|
816
|
+
if (value === null || value !== wantValue) throw new AcrossRefusal("tx-value", `the deposit sends ${String(tx.value)} wei, it must send ${wantValue}`, "policy_refused");
|
|
817
|
+
const approval = tx.approvalAddress;
|
|
818
|
+
if (route.input.native) {
|
|
819
|
+
if (approval !== void 0 && approval !== "") throw new AcrossRefusal("tx-approval", `a native deposit approves nothing, the transaction approves ${String(approval)}`, "vault_mismatch");
|
|
820
|
+
} else if (typeof approval !== "string" || lower(approval) !== src.spokePool) {
|
|
821
|
+
throw new AcrossRefusal("tx-approval", `the deposit approves ${String(approval)}, it must approve the ${src.name} SpokePool ${src.spokePool}`, "vault_mismatch");
|
|
822
|
+
}
|
|
823
|
+
return {
|
|
824
|
+
route,
|
|
825
|
+
args: a,
|
|
826
|
+
deposit: {
|
|
827
|
+
to: src.spokePool,
|
|
828
|
+
data: lower(tx.data),
|
|
829
|
+
value: wantValue.toString(10),
|
|
830
|
+
chainId: src.chainId,
|
|
831
|
+
...route.input.native ? {} : { approvalAddress: src.spokePool }
|
|
832
|
+
},
|
|
833
|
+
fee
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
function acrossIntentId(sourceChainId, destChainId, data) {
|
|
837
|
+
return `across:${sourceChainId}:${destChainId}:${(0, import_viem2.keccak256)(lower(data)).slice(2, 34)}`;
|
|
838
|
+
}
|
|
839
|
+
function parseAcrossIntentId(intentId) {
|
|
840
|
+
if (typeof intentId !== "string") return null;
|
|
841
|
+
const m = /^across:([1-9]\d{0,15}):([1-9]\d{0,15}):([0-9a-f]{32})(?:~[0-9a-f]{32})?$/.exec(intentId);
|
|
842
|
+
if (!m) return null;
|
|
843
|
+
return { sourceChainId: Number(m[1]), destChainId: Number(m[2]), digest: m[3] };
|
|
844
|
+
}
|
|
845
|
+
function isAcrossSpeedUpTypedData(typedData) {
|
|
846
|
+
let v = typedData;
|
|
847
|
+
if (typeof v === "string") {
|
|
848
|
+
try {
|
|
849
|
+
v = JSON.parse(v);
|
|
850
|
+
} catch {
|
|
851
|
+
return /UpdateDepositDetails|ACROSS-V2/.test(v);
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
if (v === null || typeof v !== "object") return false;
|
|
855
|
+
const t = v;
|
|
856
|
+
if (t.primaryType === ACROSS_SPEED_UP_TYPE) return true;
|
|
857
|
+
if (t.types !== null && typeof t.types === "object" && Object.prototype.hasOwnProperty.call(t.types, ACROSS_SPEED_UP_TYPE)) return true;
|
|
858
|
+
return t.domain !== null && typeof t.domain === "object" && t.domain.name === ACROSS_SPEED_UP_DOMAIN;
|
|
859
|
+
}
|
|
860
|
+
function checkAcrossTxShape(tx) {
|
|
861
|
+
if (tx.typedData !== void 0) {
|
|
862
|
+
if (isAcrossSpeedUpTypedData(tx.typedData)) throw new AcrossRefusal("speed-up", "the request is an Across speed-up signature, which can redirect a deposit's output \u2014 never signed", "policy_refused");
|
|
863
|
+
throw new AcrossRefusal("tx-shape", "an Across deposit is one EVM call, not typed data", "policy_refused");
|
|
864
|
+
}
|
|
865
|
+
if (tx.serializedTx !== void 0 || tx.memo !== void 0 || tx.bodyBoc !== void 0 || tx.stateInitBoc !== void 0 || tx.orderExtension !== void 0) {
|
|
866
|
+
throw new AcrossRefusal("tx-shape", "an Across deposit is one EVM call", "policy_refused");
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
function acrossRefusalReason(err) {
|
|
870
|
+
if (err instanceof AcrossRefusal) return err.message;
|
|
871
|
+
throw err;
|
|
872
|
+
}
|
|
873
|
+
function acrossRequestOf(params, opts = {}) {
|
|
874
|
+
const invalid = (what, reason) => {
|
|
875
|
+
throw new AcrossRefusal("request-invalid", what, reason);
|
|
876
|
+
};
|
|
877
|
+
if (params === null || typeof params !== "object") invalid("no request");
|
|
878
|
+
if (params.flex) invalid("the amount is part of the deposit (no flexible deposits)", "unsupported_pair");
|
|
879
|
+
if (!acrossChain(params.sourceChain)) throw new AcrossRefusal("chain-unsupported", `source chain ${String(params.sourceChain)} is not a pinned Across chain`, "unsupported_pair");
|
|
880
|
+
if (!acrossChain(params.destChain)) throw new AcrossRefusal("chain-unsupported", `destination chain ${String(params.destChain)} is not a pinned Across chain`, "unsupported_pair");
|
|
881
|
+
if (params.sourceChain === params.destChain) throw new AcrossRefusal("chain-unsupported", "same-chain swaps are not served through a SpokePool", "unsupported_pair");
|
|
882
|
+
let sourceToken;
|
|
883
|
+
if (typeof params.sourceToken === "string" && ADDRESS3.test(params.sourceToken)) sourceToken = params.sourceToken;
|
|
884
|
+
else {
|
|
885
|
+
const asset = (0, import_util2.sourceAssetOf)(params);
|
|
886
|
+
if (!asset) invalid(`source token ${String(params.sourceToken)} is not known on ${params.sourceChain}`, "unsupported_pair");
|
|
887
|
+
sourceToken = asset.contract ?? ACROSS_NATIVE;
|
|
888
|
+
if (!ADDRESS3.test(sourceToken)) invalid(`source token ${String(params.sourceToken)} has no EVM contract`, "unsupported_pair");
|
|
889
|
+
}
|
|
890
|
+
if (typeof params.destToken !== "string" || !ADDRESS3.test(params.destToken)) invalid("the destination token must be an EVM address (zero for the native coin)", "unsupported_pair");
|
|
891
|
+
const route = acrossRouteOf(params.sourceChain, sourceToken, params.destChain, params.destToken);
|
|
892
|
+
if ("code" in route) throw new AcrossRefusal(route.code, route.detail, "unsupported_pair");
|
|
893
|
+
const unpriced = acrossRouteUnpriced(route);
|
|
894
|
+
if (unpriced) throw new AcrossRefusal("route-unpriced", unpriced, "unsupported_pair");
|
|
895
|
+
if (typeof params.amountIn !== "string" || !/^[1-9]\d{0,77}$/.test(params.amountIn)) invalid("amount must be a positive base-unit integer");
|
|
896
|
+
if (params.minAmountOut !== void 0 && !UINT2.test(params.minAmountOut)) invalid("the output floor must be a base-unit integer");
|
|
897
|
+
const recipient = params.destAddress || opts.placeholder || "";
|
|
898
|
+
if (!recipient) invalid("a live quote needs a recipient");
|
|
899
|
+
if (!ADDRESS3.test(recipient)) invalid("the recipient must be an EVM address");
|
|
900
|
+
const sender = params.sender || "";
|
|
901
|
+
const refund = params.refundAddress || "";
|
|
902
|
+
if (sender && !ADDRESS3.test(sender)) invalid("the signing account (sender) must be an EVM address");
|
|
903
|
+
if (refund && !ADDRESS3.test(refund)) invalid("the refund address must be an EVM address");
|
|
904
|
+
if (sender && refund && lower(sender) !== lower(refund)) {
|
|
905
|
+
throw new AcrossRefusal("request-invalid", `an Across deposit refunds its depositor, the signing account ${lower(sender)}: refund address ${lower(refund)} is another account, and as the depositor it could also sign a speed-up that re-points the output`, "recipient_mismatch");
|
|
906
|
+
}
|
|
907
|
+
const depositor = sender || (opts.placeholder ? refund || opts.placeholder : "");
|
|
908
|
+
if (!depositor) invalid("a live quote needs the signing account (sender)");
|
|
909
|
+
if (!ADDRESS3.test(depositor)) invalid("the depositor must be an EVM address");
|
|
910
|
+
return {
|
|
911
|
+
sourceChain: params.sourceChain,
|
|
912
|
+
destChain: params.destChain,
|
|
913
|
+
sourceToken,
|
|
914
|
+
destToken: params.destToken,
|
|
915
|
+
amount: BigInt(params.amountIn),
|
|
916
|
+
depositor,
|
|
917
|
+
recipient,
|
|
918
|
+
...params.minAmountOut !== void 0 ? { minAmountOut: BigInt(params.minAmountOut) } : {},
|
|
919
|
+
...opts.maxFeeBps !== void 0 ? { maxFeeBps: opts.maxFeeBps } : {},
|
|
920
|
+
...opts.nowMs !== void 0 ? { nowMs: opts.nowMs } : {}
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
function acrossQuoteFeesOf(route, fee) {
|
|
924
|
+
const usd = route.asset === "USDC" || route.asset === "USDT";
|
|
925
|
+
return {
|
|
926
|
+
feeUsd: usd ? (0, import_core.bigintToUnits)(fee, route.input.decimals) : 0,
|
|
927
|
+
fees: fee > 0n ? [{ type: "protocol", amount: fee.toString(10), token: route.input.native ? ACROSS_NATIVE : route.input.token, included: true, description: "Across relayer and LP fee" }] : []
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
function checkAcrossQuote(request, quote, tx) {
|
|
931
|
+
if (quote === null || typeof quote !== "object" || quote.provider !== "across") throw new AcrossRefusal("quote-shape", "not an Across quote", "policy_refused");
|
|
932
|
+
const t = tx ?? quote.txRequest;
|
|
933
|
+
if (!t) throw new AcrossRefusal("quote-shape", "the quote has no transaction", "policy_refused");
|
|
934
|
+
if (quote.depositAddress) throw new AcrossRefusal("quote-shape", "an Across quote pays the SpokePool through its calldata, never a deposit address", "vault_mismatch");
|
|
935
|
+
const extra = quote.txRequest;
|
|
936
|
+
if (extra?.serializedTx !== void 0 || extra?.nativeFee !== void 0) {
|
|
937
|
+
throw new AcrossRefusal("quote-shape", "an Across deposit carries no extra native fee and no serialized transaction", "policy_refused");
|
|
938
|
+
}
|
|
939
|
+
const v = verifyAcrossDeposit(request, t);
|
|
940
|
+
if (quote.sourceAmount !== v.args.inputAmount.toString(10) || quote.minDestAmount !== v.args.outputAmount.toString(10) || quote.destAmount !== v.args.outputAmount.toString(10) || quote.destDecimals !== v.route.output.decimals) {
|
|
941
|
+
throw new AcrossRefusal("quote-amounts", "the amounts the quote shows are not the deposit's", "price_check_failed");
|
|
942
|
+
}
|
|
943
|
+
const shown = acrossQuoteFeesOf(v.route, v.fee);
|
|
944
|
+
const w = shown.fees[0];
|
|
945
|
+
const g = Array.isArray(quote.fees) && quote.fees.length === 1 ? quote.fees[0] : void 0;
|
|
946
|
+
if (!g || g.type !== w.type || g.amount !== w.amount || typeof g.token !== "string" || lower(g.token) !== w.token || g.included !== true || quote.feeUsd !== shown.feeUsd) {
|
|
947
|
+
throw new AcrossRefusal("quote-amounts", `the fees the quote shows are not the deposit's fee of ${v.fee} (the engine's fee caps read them)`, "price_check_failed");
|
|
948
|
+
}
|
|
949
|
+
const gas = t.gasLimit;
|
|
950
|
+
if (gas !== void 0) {
|
|
951
|
+
if (typeof gas !== "string" || !/^[1-9]\d{0,10}$/.test(gas) || BigInt(gas) < ACROSS_GAS_FLOOR || BigInt(gas) > ACROSS_GAS_CAP) {
|
|
952
|
+
throw new AcrossRefusal("quote-gas", `the gas limit ${String(gas).slice(0, 40)} is outside ${ACROSS_GAS_FLOOR}\u2013${ACROSS_GAS_CAP}`, "policy_refused");
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
const now = request.nowMs ?? Date.now();
|
|
956
|
+
if (typeof quote.validUntilMs !== "number" || !Number.isFinite(quote.validUntilMs) || quote.validUntilMs > now + ACROSS_MAX_QUOTE_LIFE_MS) {
|
|
957
|
+
throw new AcrossRefusal("quote-expiry", "the quote claims to live longer than an Across quote may", "policy_refused");
|
|
958
|
+
}
|
|
959
|
+
if (quote.validUntilMs > acrossQuoteTimeLimitMs(v.args.quoteTimestamp)) {
|
|
960
|
+
throw new AcrossRefusal("quote-expiry", `the quote claims to live past ${ACROSS_DEPOSIT_QUOTE_TIME_BUFFER_S - ACROSS_LANDING_WINDOW_S} s after its quote time \u2014 signed then, the deposit would revert on it`, "policy_refused");
|
|
961
|
+
}
|
|
962
|
+
const intent = parseAcrossIntentId(quote.intentId);
|
|
963
|
+
const want = acrossIntentId(v.route.input.chain.chainId, v.route.output.chain.chainId, v.deposit.data);
|
|
964
|
+
if (!intent || `across:${intent.sourceChainId}:${intent.destChainId}:${intent.digest}` !== want) {
|
|
965
|
+
throw new AcrossRefusal("quote-intent", "the quote's id does not name its deposit", "policy_refused");
|
|
966
|
+
}
|
|
967
|
+
return v;
|
|
968
|
+
}
|
|
969
|
+
var pinNotes = (0, import_errors3.refusalNotes)();
|
|
970
|
+
function notedReason(err) {
|
|
971
|
+
const text2 = acrossRefusalReason(err);
|
|
972
|
+
const info = (0, import_errors3.refusalOf)(err);
|
|
973
|
+
return info ? pinNotes.note(text2, info) : text2;
|
|
974
|
+
}
|
|
975
|
+
var acrossPinsRequestOf = (params, cap = {}) => acrossRequestOf(params, params.dry !== false ? { ...cap, placeholder: ACROSS_PLACEHOLDER } : cap);
|
|
976
|
+
function verifyQuoteWith(params, quote, cap) {
|
|
977
|
+
try {
|
|
978
|
+
checkAcrossQuote(acrossPinsRequestOf(params, cap), quote);
|
|
979
|
+
return null;
|
|
980
|
+
} catch (err) {
|
|
981
|
+
return notedReason(err);
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
function acrossCheckBuild(quote, tx, params, cap = {}) {
|
|
985
|
+
if (!params) throw new AcrossRefusal("request-invalid", "the request this quote answered is not known on this side \u2014 quote again", "policy_refused");
|
|
986
|
+
if (tx.chain !== params.sourceChain) throw new AcrossRefusal("tx-chain", `the build is for ${tx.chain}, not ${params.sourceChain}`, "vault_mismatch");
|
|
987
|
+
checkAcrossTxShape(tx);
|
|
988
|
+
return checkAcrossQuote(acrossRequestOf(params, cap), quote, tx);
|
|
989
|
+
}
|
|
990
|
+
function verifyBuildWith(quote, tx, params, cap) {
|
|
991
|
+
try {
|
|
992
|
+
acrossCheckBuild(quote, tx, params, cap);
|
|
993
|
+
return null;
|
|
994
|
+
} catch (err) {
|
|
995
|
+
return notedReason(err);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
function acrossPinsWith(opts = {}) {
|
|
999
|
+
const maxFeeBps = opts.maxFeeBps;
|
|
1000
|
+
if (maxFeeBps !== void 0 && (!Number.isInteger(maxFeeBps) || maxFeeBps < 0 || maxFeeBps > ACROSS_MAX_FEE_BPS_LIMIT)) {
|
|
1001
|
+
throw new Error(`across: maxFeeBps must be an integer between 0 and ${ACROSS_MAX_FEE_BPS_LIMIT}`);
|
|
1002
|
+
}
|
|
1003
|
+
const cap = Object.freeze(maxFeeBps !== void 0 ? { maxFeeBps } : {});
|
|
1004
|
+
return Object.freeze({
|
|
1005
|
+
callTargets: (chain2) => {
|
|
1006
|
+
const c = acrossChain(chain2);
|
|
1007
|
+
return c ? [c.spokePool] : [];
|
|
1008
|
+
},
|
|
1009
|
+
spenders: (chain2) => {
|
|
1010
|
+
const c = acrossChain(chain2);
|
|
1011
|
+
return c ? [c.spokePool] : [];
|
|
1012
|
+
},
|
|
1013
|
+
verifyQuote: (params, quote) => verifyQuoteWith(params, quote, cap),
|
|
1014
|
+
verifyBuild: (quote, tx, params) => verifyBuildWith(quote, tx, params, cap),
|
|
1015
|
+
reasonOf: pinNotes.reasonOf
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
var acrossPins = acrossPinsWith();
|
|
1019
|
+
|
|
1020
|
+
// src/build.ts
|
|
1021
|
+
var UINT3 = /^(?:0|[1-9]\d{0,77})$/;
|
|
1022
|
+
var ADDRESS4 = /^0x[0-9a-fA-F]{40}$/;
|
|
1023
|
+
var U32_MAX2 = 4294967295;
|
|
1024
|
+
function checkNormalized(request, q, sourceChainId, destChainId) {
|
|
1025
|
+
const bad = (what) => {
|
|
1026
|
+
throw new AcrossRefusal("quote-normalized", `the quote ${what}`, "upstream_unavailable");
|
|
1027
|
+
};
|
|
1028
|
+
if (q === null || typeof q !== "object") bad("is missing");
|
|
1029
|
+
if (q.sourceChainId !== sourceChainId || q.destinationChainId !== destChainId) {
|
|
1030
|
+
throw new AcrossRefusal("quote-normalized", `the quote is for ${String(q.sourceChainId)} \u2192 ${String(q.destinationChainId)}, the request for ${sourceChainId} \u2192 ${destChainId}`, "policy_refused");
|
|
1031
|
+
}
|
|
1032
|
+
for (const [k, v] of [["input token", q.inputToken], ["output token", q.outputToken], ["exclusive relayer", q.exclusiveRelayer]]) {
|
|
1033
|
+
if (typeof v !== "string" || !ADDRESS4.test(v)) bad(`names a ${k} that is not an address`);
|
|
1034
|
+
}
|
|
1035
|
+
if (q.inputToken.toLowerCase() !== request.sourceToken.toLowerCase() || q.outputToken.toLowerCase() !== request.destToken.toLowerCase()) {
|
|
1036
|
+
throw new AcrossRefusal("quote-normalized", "the quote is for other tokens than the request", "policy_refused");
|
|
1037
|
+
}
|
|
1038
|
+
for (const [k, v] of [["input amount", q.inputAmount], ["output amount", q.outputAmount]]) {
|
|
1039
|
+
if (typeof v !== "string" || !UINT3.test(v)) bad(`states an ${k} that is not a base-unit integer`);
|
|
1040
|
+
}
|
|
1041
|
+
if (BigInt(q.inputAmount) !== request.amount) throw new AcrossRefusal("quote-normalized", `the quote sends ${q.inputAmount}, the request ${request.amount}`, "policy_refused");
|
|
1042
|
+
if (q.expectedOutputAmount !== void 0 && (typeof q.expectedOutputAmount !== "string" || !UINT3.test(q.expectedOutputAmount))) bad("states an expected output that is not a base-unit integer");
|
|
1043
|
+
if (q.expectedOutputAmount !== void 0 && BigInt(q.expectedOutputAmount) > BigInt(q.outputAmount)) {
|
|
1044
|
+
throw new AcrossRefusal("quote-normalized", `the quote expects ${q.expectedOutputAmount} to arrive, more than the ${q.outputAmount} the deposit asks relayers for`, "price_check_failed");
|
|
1045
|
+
}
|
|
1046
|
+
for (const [k, v] of [["quote time", q.quoteTimestamp], ["fill deadline", q.fillDeadline], ["exclusivity", q.exclusivityParameter]]) {
|
|
1047
|
+
if (!Number.isInteger(v) || v < 0 || v > U32_MAX2) bad(`states a ${k} that is not a uint32`);
|
|
1048
|
+
}
|
|
1049
|
+
if (!Number.isFinite(q.expectedFillTimeSec) || q.expectedFillTimeSec < 0) bad("states no fill time");
|
|
1050
|
+
if (q.expiresAtMs !== void 0 && (!Number.isFinite(q.expiresAtMs) || q.expiresAtMs <= 0)) bad("states an expiry that is not a time");
|
|
1051
|
+
if (q.orderId !== void 0 && (typeof q.orderId !== "string" || !/^[\x21-\x7e]{1,128}$/.test(q.orderId))) bad("carries an order id that is not printable");
|
|
1052
|
+
const f = q.fees;
|
|
1053
|
+
if (f !== void 0) {
|
|
1054
|
+
if (f === null || typeof f !== "object" || typeof f.total !== "string" || !UINT3.test(f.total)) bad("itemizes fees without a total");
|
|
1055
|
+
for (const v of [f.relayerCapital, f.destinationGas, f.lp]) if (v !== void 0 && (typeof v !== "string" || !UINT3.test(v))) bad("itemizes a fee that is not a base-unit integer");
|
|
1056
|
+
if (f.totalUsd !== void 0 && (!Number.isFinite(f.totalUsd) || f.totalUsd < 0)) bad("prices its fees in a number that is not a price");
|
|
1057
|
+
if (BigInt(q.outputAmount) <= BigInt(q.inputAmount) && BigInt(f.total) !== BigInt(q.inputAmount) - BigInt(q.outputAmount)) {
|
|
1058
|
+
throw new AcrossRefusal("quote-normalized", "the quote's fee total is not its input minus its output", "price_check_failed");
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
function buildAcrossDeposit(request, quote) {
|
|
1063
|
+
const { route } = checkAcrossRequest(request);
|
|
1064
|
+
const src = route.input.chain;
|
|
1065
|
+
const dst = route.output.chain;
|
|
1066
|
+
checkNormalized(request, quote, src.chainId, dst.chainId);
|
|
1067
|
+
const data = encodeAcrossDeposit({
|
|
1068
|
+
depositor: request.depositor.toLowerCase(),
|
|
1069
|
+
recipient: request.recipient.toLowerCase(),
|
|
1070
|
+
inputToken: route.input.token,
|
|
1071
|
+
outputToken: route.output.token,
|
|
1072
|
+
inputAmount: request.amount,
|
|
1073
|
+
outputAmount: BigInt(quote.outputAmount),
|
|
1074
|
+
destinationChainId: BigInt(dst.chainId),
|
|
1075
|
+
exclusiveRelayer: quote.exclusiveRelayer.toLowerCase(),
|
|
1076
|
+
quoteTimestamp: quote.quoteTimestamp,
|
|
1077
|
+
fillDeadline: quote.fillDeadline,
|
|
1078
|
+
exclusivityParameter: quote.exclusivityParameter,
|
|
1079
|
+
message: "0x"
|
|
1080
|
+
});
|
|
1081
|
+
return verifyAcrossDeposit(request, {
|
|
1082
|
+
to: src.spokePool,
|
|
1083
|
+
data,
|
|
1084
|
+
value: route.input.native ? request.amount.toString(10) : "0",
|
|
1085
|
+
chainId: src.chainId,
|
|
1086
|
+
...route.input.native ? {} : { approvalAddress: src.spokePool }
|
|
1087
|
+
});
|
|
1088
|
+
}
|
|
1089
|
+
function acrossQuoteOf(request, quote, opts = {}) {
|
|
1090
|
+
const v = buildAcrossDeposit(request, quote);
|
|
1091
|
+
const ttl = opts.quoteTtlMs ?? 6e4;
|
|
1092
|
+
if (!Number.isInteger(ttl) || ttl <= 0 || ttl > 3e5) throw new AcrossRefusal("request-invalid", "quoteTtlMs must be an integer between 1 and 300000");
|
|
1093
|
+
const now = request.nowMs ?? Date.now();
|
|
1094
|
+
const validUntilMs = Math.min(now + ttl, now + ACROSS_MAX_QUOTE_LIFE_MS, quote.expiresAtMs ?? Number.POSITIVE_INFINITY, acrossQuoteTimeLimitMs(v.args.quoteTimestamp));
|
|
1095
|
+
const reliability = opts.reliability ?? 0.97;
|
|
1096
|
+
return {
|
|
1097
|
+
provider: "across",
|
|
1098
|
+
intentId: acrossIntentId(v.route.input.chain.chainId, v.route.output.chain.chainId, v.deposit.data),
|
|
1099
|
+
depositAddress: "",
|
|
1100
|
+
depositMemo: null,
|
|
1101
|
+
txRequest: {
|
|
1102
|
+
to: v.deposit.to,
|
|
1103
|
+
data: v.deposit.data,
|
|
1104
|
+
value: v.deposit.value,
|
|
1105
|
+
chainId: v.deposit.chainId,
|
|
1106
|
+
...v.deposit.approvalAddress ? { approvalAddress: v.deposit.approvalAddress } : {}
|
|
1107
|
+
},
|
|
1108
|
+
sourceAmount: v.args.inputAmount.toString(10),
|
|
1109
|
+
destAmount: v.args.outputAmount.toString(10),
|
|
1110
|
+
minDestAmount: v.args.outputAmount.toString(10),
|
|
1111
|
+
destDecimals: v.route.output.decimals,
|
|
1112
|
+
...acrossQuoteFeesOf(v.route, v.fee),
|
|
1113
|
+
etaSeconds: Math.min(Math.max(Math.ceil(quote.expectedFillTimeSec), 1), 86400),
|
|
1114
|
+
reliability: Number.isFinite(reliability) && reliability >= 0 && reliability <= 1 ? reliability : 0.97,
|
|
1115
|
+
validUntilMs,
|
|
1116
|
+
providerData: {
|
|
1117
|
+
sourceChain: request.sourceChain,
|
|
1118
|
+
destChain: request.destChain,
|
|
1119
|
+
sourceToken: request.sourceToken.toLowerCase(),
|
|
1120
|
+
destToken: request.destToken.toLowerCase(),
|
|
1121
|
+
amount: request.amount.toString(10),
|
|
1122
|
+
depositor: request.depositor.toLowerCase(),
|
|
1123
|
+
recipient: request.recipient.toLowerCase(),
|
|
1124
|
+
outputAmount: v.args.outputAmount.toString(10),
|
|
1125
|
+
quoteTimestamp: String(v.args.quoteTimestamp),
|
|
1126
|
+
fillDeadline: String(v.args.fillDeadline),
|
|
1127
|
+
exclusiveRelayer: v.args.exclusiveRelayer,
|
|
1128
|
+
exclusivityParameter: String(v.args.exclusivityParameter),
|
|
1129
|
+
...request.minAmountOut !== void 0 ? { minAmountOut: request.minAmountOut.toString(10) } : {},
|
|
1130
|
+
...request.maxFeeBps !== void 0 ? { maxFeeBps: String(request.maxFeeBps) } : {},
|
|
1131
|
+
...quote.expectedOutputAmount !== void 0 ? { expectedOutputAmount: quote.expectedOutputAmount } : {},
|
|
1132
|
+
...quote.orderId !== void 0 ? { orderId: quote.orderId } : {},
|
|
1133
|
+
...opts.placeholder ? { placeholder: "1" } : {}
|
|
1134
|
+
}
|
|
1135
|
+
};
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// src/status.ts
|
|
1139
|
+
var import_viem3 = require("viem");
|
|
1140
|
+
var import_util3 = require("@anywalletkit/protocol-swap2-core/util");
|
|
1141
|
+
var ACROSS_FILL_STATUS = Object.freeze({ UNFILLED: 0, REQUESTED_SLOW_FILL: 1, FILLED: 2 });
|
|
1142
|
+
var EVENT_DATA = [
|
|
1143
|
+
{ name: "inputToken", type: "bytes32" },
|
|
1144
|
+
{ name: "outputToken", type: "bytes32" },
|
|
1145
|
+
{ name: "inputAmount", type: "uint256" },
|
|
1146
|
+
{ name: "outputAmount", type: "uint256" },
|
|
1147
|
+
{ name: "quoteTimestamp", type: "uint32" },
|
|
1148
|
+
{ name: "fillDeadline", type: "uint32" },
|
|
1149
|
+
{ name: "exclusivityDeadline", type: "uint32" },
|
|
1150
|
+
{ name: "recipient", type: "bytes32" },
|
|
1151
|
+
{ name: "exclusiveRelayer", type: "bytes32" },
|
|
1152
|
+
{ name: "message", type: "bytes" }
|
|
1153
|
+
];
|
|
1154
|
+
var RELAY_DATA = {
|
|
1155
|
+
type: "tuple",
|
|
1156
|
+
components: [
|
|
1157
|
+
{ name: "depositor", type: "bytes32" },
|
|
1158
|
+
{ name: "recipient", type: "bytes32" },
|
|
1159
|
+
{ name: "exclusiveRelayer", type: "bytes32" },
|
|
1160
|
+
{ name: "inputToken", type: "bytes32" },
|
|
1161
|
+
{ name: "outputToken", type: "bytes32" },
|
|
1162
|
+
{ name: "inputAmount", type: "uint256" },
|
|
1163
|
+
{ name: "outputAmount", type: "uint256" },
|
|
1164
|
+
{ name: "originChainId", type: "uint256" },
|
|
1165
|
+
{ name: "depositId", type: "uint256" },
|
|
1166
|
+
{ name: "fillDeadline", type: "uint32" },
|
|
1167
|
+
{ name: "exclusivityDeadline", type: "uint32" },
|
|
1168
|
+
{ name: "message", type: "bytes" }
|
|
1169
|
+
]
|
|
1170
|
+
};
|
|
1171
|
+
var WORD = /^0x[0-9a-fA-F]{64}$/;
|
|
1172
|
+
var HEX2 = /^0x(?:[0-9a-fA-F]{2})*$/;
|
|
1173
|
+
var DIGEST = /^[0-9a-f]{32}$/;
|
|
1174
|
+
var QUANTITY = /^0x[0-9a-fA-F]{1,16}$/;
|
|
1175
|
+
var lowerHex = (s) => s.toLowerCase();
|
|
1176
|
+
function acrossDepositsInReceipt(receipt, source) {
|
|
1177
|
+
const logs = receipt?.logs;
|
|
1178
|
+
if (!Array.isArray(logs)) return [];
|
|
1179
|
+
const out = [];
|
|
1180
|
+
for (const log of logs) {
|
|
1181
|
+
if (log === null || typeof log !== "object" || log.removed === true) continue;
|
|
1182
|
+
if (typeof log.address !== "string" || log.address.toLowerCase() !== source.spokePool) continue;
|
|
1183
|
+
const topics = log.topics;
|
|
1184
|
+
if (!Array.isArray(topics) || topics.length !== 4 || !topics.every((t) => typeof t === "string" && WORD.test(t))) continue;
|
|
1185
|
+
if (topics[0].toLowerCase() !== ACROSS_FUNDS_DEPOSITED) continue;
|
|
1186
|
+
if (typeof log.data !== "string" || !HEX2.test(log.data)) continue;
|
|
1187
|
+
let d;
|
|
1188
|
+
try {
|
|
1189
|
+
d = (0, import_viem3.decodeAbiParameters)(EVENT_DATA, log.data);
|
|
1190
|
+
} catch {
|
|
1191
|
+
continue;
|
|
1192
|
+
}
|
|
1193
|
+
out.push({
|
|
1194
|
+
originChainId: source.chainId,
|
|
1195
|
+
destinationChainId: BigInt(topics[1]),
|
|
1196
|
+
depositId: BigInt(topics[2]),
|
|
1197
|
+
depositor: lowerHex(topics[3]),
|
|
1198
|
+
inputToken: lowerHex(d[0]),
|
|
1199
|
+
outputToken: lowerHex(d[1]),
|
|
1200
|
+
inputAmount: d[2],
|
|
1201
|
+
outputAmount: d[3],
|
|
1202
|
+
quoteTimestamp: d[4],
|
|
1203
|
+
fillDeadline: d[5],
|
|
1204
|
+
exclusivityDeadline: d[6],
|
|
1205
|
+
recipient: lowerHex(d[7]),
|
|
1206
|
+
exclusiveRelayer: lowerHex(d[8]),
|
|
1207
|
+
message: lowerHex(d[9])
|
|
1208
|
+
});
|
|
1209
|
+
}
|
|
1210
|
+
return out;
|
|
1211
|
+
}
|
|
1212
|
+
function depositDataOf(e, exclusivityParameter) {
|
|
1213
|
+
const depositor = acrossAddressOf(e.depositor);
|
|
1214
|
+
const recipient = acrossAddressOf(e.recipient);
|
|
1215
|
+
const inputToken = acrossAddressOf(e.inputToken);
|
|
1216
|
+
const outputToken = acrossAddressOf(e.outputToken);
|
|
1217
|
+
const exclusiveRelayer = acrossAddressOf(e.exclusiveRelayer);
|
|
1218
|
+
if (!depositor || !recipient || !inputToken || !outputToken || !exclusiveRelayer) return null;
|
|
1219
|
+
try {
|
|
1220
|
+
return encodeAcrossDeposit({
|
|
1221
|
+
depositor,
|
|
1222
|
+
recipient,
|
|
1223
|
+
inputToken,
|
|
1224
|
+
outputToken,
|
|
1225
|
+
inputAmount: e.inputAmount,
|
|
1226
|
+
outputAmount: e.outputAmount,
|
|
1227
|
+
destinationChainId: e.destinationChainId,
|
|
1228
|
+
exclusiveRelayer,
|
|
1229
|
+
quoteTimestamp: e.quoteTimestamp,
|
|
1230
|
+
fillDeadline: e.fillDeadline,
|
|
1231
|
+
exclusivityParameter,
|
|
1232
|
+
message: e.message
|
|
1233
|
+
});
|
|
1234
|
+
} catch {
|
|
1235
|
+
return null;
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
function acrossDepositIsIntent(e, digest, sourceBlockTime) {
|
|
1239
|
+
if (typeof digest !== "string" || !DIGEST.test(digest)) return false;
|
|
1240
|
+
const d = e.exclusivityDeadline;
|
|
1241
|
+
const candidates = [];
|
|
1242
|
+
if (d === 0) candidates.push(0);
|
|
1243
|
+
else {
|
|
1244
|
+
if (d > ACROSS_MAX_EXCLUSIVITY_PERIOD_S) candidates.push(d);
|
|
1245
|
+
if (sourceBlockTime !== void 0 && d - sourceBlockTime > 0 && d - sourceBlockTime <= ACROSS_MAX_EXCLUSIVITY_PERIOD_S) candidates.push(d - sourceBlockTime);
|
|
1246
|
+
}
|
|
1247
|
+
return candidates.some((p) => {
|
|
1248
|
+
const data = depositDataOf(e, p);
|
|
1249
|
+
return data !== null && (0, import_viem3.keccak256)(data).slice(2, 34) === digest;
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
function acrossRelayHash(e) {
|
|
1253
|
+
return (0, import_viem3.keccak256)((0, import_viem3.encodeAbiParameters)([RELAY_DATA, { type: "uint256" }], [{
|
|
1254
|
+
depositor: e.depositor,
|
|
1255
|
+
recipient: e.recipient,
|
|
1256
|
+
exclusiveRelayer: e.exclusiveRelayer,
|
|
1257
|
+
inputToken: e.inputToken,
|
|
1258
|
+
outputToken: e.outputToken,
|
|
1259
|
+
inputAmount: e.inputAmount,
|
|
1260
|
+
outputAmount: e.outputAmount,
|
|
1261
|
+
originChainId: BigInt(e.originChainId),
|
|
1262
|
+
depositId: e.depositId,
|
|
1263
|
+
fillDeadline: e.fillDeadline,
|
|
1264
|
+
exclusivityDeadline: e.exclusivityDeadline,
|
|
1265
|
+
message: e.message
|
|
1266
|
+
}, e.destinationChainId]));
|
|
1267
|
+
}
|
|
1268
|
+
function acrossFillStatusCall(relayHash) {
|
|
1269
|
+
if (!WORD.test(relayHash)) throw new Error("across: a relay hash is 32 bytes");
|
|
1270
|
+
return `${ACROSS_FILL_STATUSES}${relayHash.slice(2).toLowerCase()}`;
|
|
1271
|
+
}
|
|
1272
|
+
function parseAcrossFillStatus(answer) {
|
|
1273
|
+
if (typeof answer !== "string" || !/^0x0{63}[0-2]$/i.test(answer)) return null;
|
|
1274
|
+
return Number(answer.slice(-1));
|
|
1275
|
+
}
|
|
1276
|
+
function acrossFillState(status, fillDeadline, blockTime) {
|
|
1277
|
+
if (status === ACROSS_FILL_STATUS.FILLED) return "filled";
|
|
1278
|
+
if (blockTime > fillDeadline) return "expired";
|
|
1279
|
+
return status === ACROSS_FILL_STATUS.REQUESTED_SLOW_FILL ? "slow-fill-requested" : "unfilled";
|
|
1280
|
+
}
|
|
1281
|
+
var MAX_RPC_BODY = 8 * 1024 * 1024;
|
|
1282
|
+
function acrossRpc(url, fetchImpl, timeoutMs = 12e3) {
|
|
1283
|
+
if (typeof url !== "string" || !/^https?:\/\//.test(url)) throw new Error("across: an RPC URL must use http or https");
|
|
1284
|
+
let id = 0;
|
|
1285
|
+
return async (method, params) => {
|
|
1286
|
+
let text2;
|
|
1287
|
+
try {
|
|
1288
|
+
const res = await (fetchImpl ?? fetch)(url, {
|
|
1289
|
+
method: "POST",
|
|
1290
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
1291
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params }),
|
|
1292
|
+
signal: (0, import_util3.timeoutSignal)(timeoutMs)
|
|
1293
|
+
});
|
|
1294
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
1295
|
+
text2 = await res.text();
|
|
1296
|
+
} catch (err) {
|
|
1297
|
+
throw new Error(`across: ${method} failed \u2014 ${(0, import_util3.redactUrls)(err instanceof Error ? err.message : String(err)).slice(0, 160)}`);
|
|
1298
|
+
}
|
|
1299
|
+
if (text2.length > MAX_RPC_BODY) throw new Error(`across: ${method} answered more than ${MAX_RPC_BODY} bytes`);
|
|
1300
|
+
let body;
|
|
1301
|
+
try {
|
|
1302
|
+
body = JSON.parse(text2);
|
|
1303
|
+
} catch {
|
|
1304
|
+
throw new Error(`across: ${method} answered something that is not JSON`);
|
|
1305
|
+
}
|
|
1306
|
+
if (body === null || typeof body !== "object") throw new Error(`across: ${method} answered something that is not JSON-RPC`);
|
|
1307
|
+
if (body.error !== void 0) throw new Error(`across: ${method} failed \u2014 ${(0, import_util3.redactUrls)(String(body.error?.message ?? "error")).slice(0, 160)}`);
|
|
1308
|
+
if (!Object.prototype.hasOwnProperty.call(body, "result")) throw new Error(`across: ${method} answered no result`);
|
|
1309
|
+
return body.result;
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
async function blockTimeOf(rpc, number) {
|
|
1313
|
+
if (typeof number !== "string" || !QUANTITY.test(number)) return null;
|
|
1314
|
+
try {
|
|
1315
|
+
const block = await rpc("eth_getBlockByNumber", [number, false]);
|
|
1316
|
+
const timestamp = block?.timestamp;
|
|
1317
|
+
if (typeof block?.number !== "string" || block.number.toLowerCase() !== number.toLowerCase()) return null;
|
|
1318
|
+
if (typeof timestamp !== "string" || !/^0x[0-9a-fA-F]{1,12}$/.test(timestamp)) return null;
|
|
1319
|
+
return parseInt(timestamp, 16);
|
|
1320
|
+
} catch {
|
|
1321
|
+
return null;
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
async function trackAcrossDeposit(input) {
|
|
1325
|
+
const { source, dest, sourceRpc, destRpc } = input;
|
|
1326
|
+
if (typeof input.sourceTxHash !== "string" || !WORD.test(input.sourceTxHash) || !sourceRpc) return { status: { state: "pending" } };
|
|
1327
|
+
if (typeof input.intentDigest !== "string" || !DIGEST.test(input.intentDigest)) return { status: { state: "pending" } };
|
|
1328
|
+
let receipt;
|
|
1329
|
+
try {
|
|
1330
|
+
receipt = await sourceRpc("eth_getTransactionReceipt", [input.sourceTxHash]);
|
|
1331
|
+
} catch {
|
|
1332
|
+
return { status: { state: "pending" } };
|
|
1333
|
+
}
|
|
1334
|
+
if (receipt === null || receipt === void 0) return { status: { state: "pending" } };
|
|
1335
|
+
if (typeof receipt !== "object") return { status: { state: "pending" } };
|
|
1336
|
+
const status = receipt.status;
|
|
1337
|
+
if (status === "0x0") return { status: { state: "failed" } };
|
|
1338
|
+
if (status !== "0x1") return { status: { state: "pending" } };
|
|
1339
|
+
const txHash = receipt.transactionHash;
|
|
1340
|
+
if (txHash !== void 0 && (typeof txHash !== "string" || txHash.toLowerCase() !== input.sourceTxHash.toLowerCase())) return { status: { state: "pending" } };
|
|
1341
|
+
const onRoute = acrossDepositsInReceipt(receipt, source).filter((d) => d.destinationChainId === BigInt(dest.chainId));
|
|
1342
|
+
let mine = onRoute.filter((d) => acrossDepositIsIntent(d, input.intentDigest));
|
|
1343
|
+
if (mine.length === 0 && onRoute.some((d) => d.exclusivityDeadline !== 0)) {
|
|
1344
|
+
const blockTime = await blockTimeOf(sourceRpc, receipt.blockNumber);
|
|
1345
|
+
if (blockTime === null) return { status: { state: "pending" } };
|
|
1346
|
+
mine = onRoute.filter((d) => acrossDepositIsIntent(d, input.intentDigest, blockTime));
|
|
1347
|
+
}
|
|
1348
|
+
if (mine.length !== 1) return { status: { state: "pending" } };
|
|
1349
|
+
const deposit = mine[0];
|
|
1350
|
+
const relayHash = acrossRelayHash(deposit);
|
|
1351
|
+
const seen = { status: { state: "pending", depositReceived: true }, deposit, relayHash };
|
|
1352
|
+
if (!destRpc) return seen;
|
|
1353
|
+
try {
|
|
1354
|
+
const block = await destRpc("eth_getBlockByNumber", ["latest", false]);
|
|
1355
|
+
const number = block?.number;
|
|
1356
|
+
const timestamp = block?.timestamp;
|
|
1357
|
+
if (typeof number !== "string" || !/^0x[0-9a-fA-F]{1,16}$/.test(number) || typeof timestamp !== "string" || !/^0x[0-9a-fA-F]{1,12}$/.test(timestamp)) return seen;
|
|
1358
|
+
const blockTime = parseInt(timestamp, 16);
|
|
1359
|
+
const fillStatus = parseAcrossFillStatus(await destRpc("eth_call", [{ to: dest.spokePool, data: acrossFillStatusCall(relayHash) }, number]));
|
|
1360
|
+
if (fillStatus === null) return seen;
|
|
1361
|
+
const fill = acrossFillState(fillStatus, deposit.fillDeadline, blockTime);
|
|
1362
|
+
const destBlock = { number: number.toLowerCase(), timestamp: blockTime };
|
|
1363
|
+
if (fill === "filled") return { status: { state: "completed", depositReceived: true }, deposit, relayHash, fill, destBlock };
|
|
1364
|
+
if (fill === "expired") return { status: { state: "expired", depositReceived: true }, deposit, relayHash, fill, destBlock };
|
|
1365
|
+
return { status: { state: "pending", depositReceived: true }, deposit, relayHash, fill, destBlock };
|
|
1366
|
+
} catch {
|
|
1367
|
+
return seen;
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
// src/provider.ts
|
|
1372
|
+
var ADDRESS5 = /^0x[0-9a-fA-F]{40}$/;
|
|
1373
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
1374
|
+
var DEFAULT_QUOTE_TTL_MS = 6e4;
|
|
1375
|
+
function readKey(source) {
|
|
1376
|
+
let key = source;
|
|
1377
|
+
if (typeof source === "function") {
|
|
1378
|
+
try {
|
|
1379
|
+
key = source();
|
|
1380
|
+
} catch {
|
|
1381
|
+
return void 0;
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
return typeof key === "string" && /^[\x21-\x7e]{1,256}$/.test(key) ? key : void 0;
|
|
1385
|
+
}
|
|
1386
|
+
function onReactNative() {
|
|
1387
|
+
const g = globalThis;
|
|
1388
|
+
return g.HermesInternal !== void 0 || g.navigator?.product === "ReactNative";
|
|
1389
|
+
}
|
|
1390
|
+
function acrossServesRoute(from, to) {
|
|
1391
|
+
if (!across.supports(from.chain, to.chain)) return false;
|
|
1392
|
+
let token;
|
|
1393
|
+
if (ADDRESS5.test(from.token)) token = from.token;
|
|
1394
|
+
else {
|
|
1395
|
+
const asset = (0, import_swap2_assets.ccAsset)(from.chain, from.token);
|
|
1396
|
+
if (!asset) return false;
|
|
1397
|
+
token = asset.contract ?? ACROSS_NATIVE;
|
|
1398
|
+
}
|
|
1399
|
+
const route = acrossRouteOf(from.chain, token, to.chain, to.token);
|
|
1400
|
+
return !("code" in route) && acrossRouteUnpriced(route) === null;
|
|
1401
|
+
}
|
|
1402
|
+
function acrossProvider(config = {}) {
|
|
1403
|
+
config = Object.freeze({ ...config });
|
|
1404
|
+
if (config.apiKey !== void 0 && onReactNative()) {
|
|
1405
|
+
throw new Error("across: the Across API key belongs on a server \u2014 in a React Native app it would ship in the bundle, and React Native's fetch follows redirects with the key attached. Run acrossProvider({apiKey}) on your backend (createSwap2Handler) and acrossRemoteProvider({baseUrl}) in the app.");
|
|
1406
|
+
}
|
|
1407
|
+
const maxFeeBps = config.maxFeeBps;
|
|
1408
|
+
if (maxFeeBps !== void 0 && (!Number.isInteger(maxFeeBps) || maxFeeBps < 0 || maxFeeBps > ACROSS_MAX_FEE_BPS_LIMIT)) {
|
|
1409
|
+
throw new Error(`across: maxFeeBps must be an integer between 0 and ${ACROSS_MAX_FEE_BPS_LIMIT}`);
|
|
1410
|
+
}
|
|
1411
|
+
const quoteTtlMs = config.quoteTtlMs ?? DEFAULT_QUOTE_TTL_MS;
|
|
1412
|
+
if (!Number.isInteger(quoteTtlMs) || quoteTtlMs <= 0 || quoteTtlMs > 3e5) throw new Error("across: quoteTtlMs must be an integer between 1 and 300000");
|
|
1413
|
+
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1414
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 6e4) throw new Error("across: timeoutMs must be an integer between 1 and 60000");
|
|
1415
|
+
const v5Url = `${acrossApiUrl(config.baseUrl ?? ACROSS_API, "baseUrl")}/v1/quotes`;
|
|
1416
|
+
const feesUrl = config.suggestedFeesUrl === null ? null : acrossApiUrl(config.suggestedFeesUrl ?? ACROSS_SUGGESTED_FEES_URL, "suggestedFeesUrl");
|
|
1417
|
+
const rpcUrls = Object.freeze(Object.assign(/* @__PURE__ */ Object.create(null), config.rpcUrls ?? {}));
|
|
1418
|
+
for (const [chain2, url] of Object.entries(rpcUrls)) {
|
|
1419
|
+
if (typeof url !== "string" || !/^https?:\/\//.test(url)) throw new Error(`across: the RPC URL for ${chain2} must use http or https`);
|
|
1420
|
+
}
|
|
1421
|
+
const rpcFor = (caip2) => Object.prototype.hasOwnProperty.call(rpcUrls, caip2) ? acrossRpc(rpcUrls[caip2], config.fetchImpl) : void 0;
|
|
1422
|
+
function requestOf(quote) {
|
|
1423
|
+
const pd = quote.providerData ?? {};
|
|
1424
|
+
const sealed = {
|
|
1425
|
+
sourceChain: pd.sourceChain ?? "",
|
|
1426
|
+
destChain: pd.destChain ?? "",
|
|
1427
|
+
sourceToken: pd.sourceToken ?? "",
|
|
1428
|
+
destToken: pd.destToken ?? "",
|
|
1429
|
+
amount: /^[1-9]\d{0,77}$/.test(pd.amount ?? "") ? BigInt(pd.amount) : 0n,
|
|
1430
|
+
depositor: pd.depositor ?? "",
|
|
1431
|
+
recipient: pd.recipient ?? "",
|
|
1432
|
+
.../^\d{1,78}$/.test(pd.minAmountOut ?? "") ? { minAmountOut: BigInt(pd.minAmountOut) } : {},
|
|
1433
|
+
...maxFeeBps !== void 0 ? { maxFeeBps } : {}
|
|
1434
|
+
};
|
|
1435
|
+
if (pd.placeholder === "1" || sealed.depositor.toLowerCase() === ACROSS_PLACEHOLDER.toLowerCase() || sealed.recipient.toLowerCase() === ACROSS_PLACEHOLDER.toLowerCase()) {
|
|
1436
|
+
throw new AcrossRefusal("request-invalid", "a quote priced for display (a dry quote) is never built or signed \u2014 quote again with the signing account", "policy_refused");
|
|
1437
|
+
}
|
|
1438
|
+
return sealed;
|
|
1439
|
+
}
|
|
1440
|
+
async function suggestedFees(request, route, signal) {
|
|
1441
|
+
if (feesUrl === null) return { kind: "unavailable", detail: "it is turned off" };
|
|
1442
|
+
try {
|
|
1443
|
+
const a = await acrossHttp(`${feesUrl}?${acrossSuggestedFeesQuery(request, route)}`, { method: "GET", headers: { accept: "application/json" } }, { fetchImpl: config.fetchImpl, timeoutMs, signal, what: "Across's relayer fee quote" });
|
|
1444
|
+
return readAcrossSuggestedFees(request, route, a.status, a.body, Math.floor(Date.now() / 1e3));
|
|
1445
|
+
} catch (err) {
|
|
1446
|
+
if (signal?.aborted) throw err;
|
|
1447
|
+
return { kind: "unavailable", detail: err instanceof Error ? err.message.replace(/^across: /, "") : "no answer" };
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
async function quoteTimeFromChains(route) {
|
|
1451
|
+
const eth = rpcFor("eip155:1");
|
|
1452
|
+
const origin = rpcFor(route.input.chain.caip2);
|
|
1453
|
+
if (!eth || !origin) {
|
|
1454
|
+
throw new AcrossRefusal("relayer-price", "Across's relayer fee quote did not answer, and the quote time then needs rpcUrls for Ethereum and the source chain", "upstream_unavailable");
|
|
1455
|
+
}
|
|
1456
|
+
const timeOf = async (rpc) => {
|
|
1457
|
+
const block = await rpc("eth_getBlockByNumber", ["latest", false]);
|
|
1458
|
+
const t = typeof block?.timestamp === "string" && /^0x[0-9a-fA-F]{1,10}$/.test(block.timestamp) ? parseInt(block.timestamp, 16) : NaN;
|
|
1459
|
+
if (!Number.isInteger(t) || t <= 0) throw new Error("no block time");
|
|
1460
|
+
return t;
|
|
1461
|
+
};
|
|
1462
|
+
try {
|
|
1463
|
+
const [e, o] = await Promise.all([timeOf(eth), route.input.chain.chainId === 1 ? Promise.resolve(null) : timeOf(origin)]);
|
|
1464
|
+
return acrossQuoteTimeOf(e, o ?? e);
|
|
1465
|
+
} catch {
|
|
1466
|
+
throw new AcrossRefusal("relayer-price", "Across's relayer fee quote did not answer, and the chains' latest block times could not be read for the quote time", "upstream_unavailable");
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
return {
|
|
1470
|
+
name: "across",
|
|
1471
|
+
describeActivity: describeAcrossActivity,
|
|
1472
|
+
enabled: () => (config.enabled ?? true) && readKey(config.apiKey) !== void 0,
|
|
1473
|
+
supportsChain: (chain2) => across.supportsChain(chain2),
|
|
1474
|
+
supportsChainPair: (from, to) => across.supports(from, to),
|
|
1475
|
+
supportsRoute: (from, to) => acrossServesRoute(from, to),
|
|
1476
|
+
async getQuote(params, signal) {
|
|
1477
|
+
const refuse = (reason, info) => {
|
|
1478
|
+
params.onRefusal?.(reason, info);
|
|
1479
|
+
return null;
|
|
1480
|
+
};
|
|
1481
|
+
const dry = params.dry !== false;
|
|
1482
|
+
try {
|
|
1483
|
+
const request = acrossRequestOf(params, {
|
|
1484
|
+
...dry ? { placeholder: ACROSS_PLACEHOLDER } : {},
|
|
1485
|
+
...maxFeeBps !== void 0 ? { maxFeeBps } : {}
|
|
1486
|
+
});
|
|
1487
|
+
const route = acrossRouteOf(request.sourceChain, request.sourceToken, request.destChain, request.destToken);
|
|
1488
|
+
const key = readKey(config.apiKey);
|
|
1489
|
+
if (key === void 0) throw new AcrossRefusal("quote-unavailable", "no Across API key is configured \u2014 give the server's acrossProvider an apiKey, and run acrossRemoteProvider in the app", "key_rejected");
|
|
1490
|
+
const [v5, fees] = await Promise.all([
|
|
1491
|
+
acrossHttp(v5Url, {
|
|
1492
|
+
method: "POST",
|
|
1493
|
+
headers: { accept: "application/json", "content-type": "application/json", authorization: `Bearer ${key}` },
|
|
1494
|
+
body: JSON.stringify(acrossV5QuoteRequest(request))
|
|
1495
|
+
}, { fetchImpl: config.fetchImpl, timeoutMs, signal, what: "Across API V5" }),
|
|
1496
|
+
suggestedFees(request, route, signal)
|
|
1497
|
+
]);
|
|
1498
|
+
if (v5.status < 200 || v5.status >= 300) {
|
|
1499
|
+
const e = parseAcrossV5Error(v5.status, v5.body, v5.retryAfter);
|
|
1500
|
+
const bound = e.amountLimit?.amount ? ` (the amount must be ${e.amountLimit.side === "min" ? "at least" : "at most"} ${e.amountLimit.amount} base units)` : "";
|
|
1501
|
+
throw new AcrossRefusal("api-error", `Across API V5 answered HTTP ${e.status}${e.code ? ` ${e.code}` : ""}${bound}`, e.info?.reason);
|
|
1502
|
+
}
|
|
1503
|
+
const price = readAcrossV5Quote(request, route, v5.body);
|
|
1504
|
+
if (fees.kind === "refused") throw new AcrossRefusal("relayer-price", fees.detail, fees.reason);
|
|
1505
|
+
const otherRail = acrossV5OtherRail(price.expectedFillTimeMs);
|
|
1506
|
+
if (otherRail && fees.kind !== "fees") {
|
|
1507
|
+
throw new AcrossRefusal("route-unpriced", `Across API V5 prices this transfer on another rail (fill ~${Math.round(price.expectedFillTimeMs / 1e3)} s), and Across's relayer fee quote did not answer (${fees.detail.slice(0, 120)}) \u2014 no price for a plain deposit`, "upstream_unavailable");
|
|
1508
|
+
}
|
|
1509
|
+
let need;
|
|
1510
|
+
let quoteTimestamp;
|
|
1511
|
+
let etaSec;
|
|
1512
|
+
if (fees.kind === "fees") {
|
|
1513
|
+
need = fees.totalRelayFee;
|
|
1514
|
+
quoteTimestamp = fees.timestamp;
|
|
1515
|
+
etaSec = fees.estimatedFillTimeSec;
|
|
1516
|
+
} else {
|
|
1517
|
+
need = acrossFloorFee(route, request.amount, price.amountUsd, price.destinationGas);
|
|
1518
|
+
quoteTimestamp = await quoteTimeFromChains(route);
|
|
1519
|
+
etaSec = price.expectedFillTimeMs / 1e3;
|
|
1520
|
+
}
|
|
1521
|
+
const fee = acrossPlainFee(request.amount, price, need, otherRail);
|
|
1522
|
+
const nq = {
|
|
1523
|
+
sourceChainId: route.input.chain.chainId,
|
|
1524
|
+
destinationChainId: route.output.chain.chainId,
|
|
1525
|
+
inputToken: request.sourceToken,
|
|
1526
|
+
outputToken: request.destToken,
|
|
1527
|
+
inputAmount: request.amount.toString(10),
|
|
1528
|
+
outputAmount: (request.amount - fee.fee).toString(10),
|
|
1529
|
+
quoteTimestamp,
|
|
1530
|
+
fillDeadline: quoteTimestamp + ACROSS_FILL_WINDOW_S,
|
|
1531
|
+
exclusiveRelayer: ACROSS_NATIVE,
|
|
1532
|
+
exclusivityParameter: 0,
|
|
1533
|
+
expectedFillTimeSec: etaSec,
|
|
1534
|
+
fees: { total: fee.fee.toString(10) }
|
|
1535
|
+
};
|
|
1536
|
+
const quote = acrossQuoteOf(request, nq, { quoteTtlMs, ...dry ? { placeholder: true } : {} });
|
|
1537
|
+
const priceSource = otherRail ? "suggested-fees (V5 other rail)" : fees.kind === "fees" ? "suggested-fees" : "floor";
|
|
1538
|
+
return { ...quote, providerData: { ...quote.providerData, priceSource, v5Fee: fee.f5.toString(10), relayerFee: fee.need.toString(10) } };
|
|
1539
|
+
} catch (err) {
|
|
1540
|
+
if (err instanceof AcrossRefusal) return refuse(err.message, (0, import_errors4.refusalOf)(err));
|
|
1541
|
+
throw err;
|
|
1542
|
+
}
|
|
1543
|
+
},
|
|
1544
|
+
/** The quote's own transaction — after the deposit it carries has been verified once more. */
|
|
1545
|
+
async buildDeposit(quote) {
|
|
1546
|
+
const tx = quote.txRequest;
|
|
1547
|
+
if (!tx || !parseAcrossIntentId(quote.intentId)) throw (0, import_errors4.refusal)("policy_refused", "swap2: Across quote has no transaction request");
|
|
1548
|
+
const request = requestOf(quote);
|
|
1549
|
+
const v = checkAcrossQuote(request, quote);
|
|
1550
|
+
return {
|
|
1551
|
+
chain: request.sourceChain,
|
|
1552
|
+
to: v.deposit.to,
|
|
1553
|
+
value: v.deposit.value,
|
|
1554
|
+
data: v.deposit.data,
|
|
1555
|
+
chainId: v.deposit.chainId,
|
|
1556
|
+
...tx.gasLimit ? { gasLimit: tx.gasLimit } : {},
|
|
1557
|
+
...v.deposit.approvalAddress ? { approvalAddress: v.deposit.approvalAddress } : {}
|
|
1558
|
+
};
|
|
1559
|
+
},
|
|
1560
|
+
/** Right before signing: the whole verification again, against the request and the exact transaction about to be signed. */
|
|
1561
|
+
async preflightDeposit(quote, tx) {
|
|
1562
|
+
const request = requestOf(quote);
|
|
1563
|
+
if (tx.chain !== request.sourceChain) throw new AcrossRefusal("tx-chain", `the deposit is for ${tx.chain}, not ${request.sourceChain}`, "vault_mismatch");
|
|
1564
|
+
checkAcrossTxShape(tx);
|
|
1565
|
+
checkAcrossQuote(request, quote, tx);
|
|
1566
|
+
},
|
|
1567
|
+
async trackIntent(ref) {
|
|
1568
|
+
const intent = parseAcrossIntentId(ref.intentId);
|
|
1569
|
+
if (!intent) return { state: "failed" };
|
|
1570
|
+
const source = acrossChain(`eip155:${intent.sourceChainId}`);
|
|
1571
|
+
const dest = acrossChain(`eip155:${intent.destChainId}`);
|
|
1572
|
+
if (!source || !dest || source === dest) return { state: "failed" };
|
|
1573
|
+
if (!ref.sourceTxHash) return { state: "pending" };
|
|
1574
|
+
const sourceRpc = rpcFor(source.caip2);
|
|
1575
|
+
const destRpc = rpcFor(dest.caip2);
|
|
1576
|
+
const t = await trackAcrossDeposit({ sourceTxHash: ref.sourceTxHash, intentDigest: intent.digest, source, dest, ...sourceRpc ? { sourceRpc } : {}, ...destRpc ? { destRpc } : {} });
|
|
1577
|
+
return t.status;
|
|
1578
|
+
}
|
|
1579
|
+
};
|
|
1580
|
+
}
|
|
1581
|
+
//# sourceMappingURL=provider.cjs.map
|