@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.
Files changed (100) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +177 -2
  3. package/dist/activity.cjs +142 -0
  4. package/dist/activity.cjs.map +1 -0
  5. package/dist/activity.d.cts +16 -0
  6. package/dist/activity.d.ts +16 -0
  7. package/dist/activity.js +10 -0
  8. package/dist/activity.js.map +1 -0
  9. package/dist/api.cjs +441 -0
  10. package/dist/api.cjs.map +1 -0
  11. package/dist/api.d.cts +207 -0
  12. package/dist/api.d.ts +207 -0
  13. package/dist/api.js +35 -0
  14. package/dist/api.js.map +1 -0
  15. package/dist/build.cjs +776 -0
  16. package/dist/build.cjs.map +1 -0
  17. package/dist/build.d.cts +93 -0
  18. package/dist/build.d.ts +93 -0
  19. package/dist/build.js +14 -0
  20. package/dist/build.js.map +1 -0
  21. package/dist/chunk-32YJEBZX.js +125 -0
  22. package/dist/chunk-32YJEBZX.js.map +1 -0
  23. package/dist/chunk-3UBRQ3ZE.js +255 -0
  24. package/dist/chunk-3UBRQ3ZE.js.map +1 -0
  25. package/dist/chunk-5BDZXOOP.js +21 -0
  26. package/dist/chunk-5BDZXOOP.js.map +1 -0
  27. package/dist/chunk-6Z4GXNLE.js +102 -0
  28. package/dist/chunk-6Z4GXNLE.js.map +1 -0
  29. package/dist/chunk-AWQT5S4V.js +101 -0
  30. package/dist/chunk-AWQT5S4V.js.map +1 -0
  31. package/dist/chunk-E5WFOPN2.js +16 -0
  32. package/dist/chunk-E5WFOPN2.js.map +1 -0
  33. package/dist/chunk-GX67FRPG.js +194 -0
  34. package/dist/chunk-GX67FRPG.js.map +1 -0
  35. package/dist/chunk-KATEONJQ.js +396 -0
  36. package/dist/chunk-KATEONJQ.js.map +1 -0
  37. package/dist/chunk-P32AW6XS.js +27 -0
  38. package/dist/chunk-P32AW6XS.js.map +1 -0
  39. package/dist/chunk-PPPZIG7S.js +265 -0
  40. package/dist/chunk-PPPZIG7S.js.map +1 -0
  41. package/dist/chunk-SJOFLM27.js +138 -0
  42. package/dist/chunk-SJOFLM27.js.map +1 -0
  43. package/dist/chunk-YGNP7KPL.js +311 -0
  44. package/dist/chunk-YGNP7KPL.js.map +1 -0
  45. package/dist/config.cjs +214 -0
  46. package/dist/config.cjs.map +1 -0
  47. package/dist/config.d.cts +119 -0
  48. package/dist/config.d.ts +119 -0
  49. package/dist/config.js +47 -0
  50. package/dist/config.js.map +1 -0
  51. package/dist/deposit.cjs +252 -0
  52. package/dist/deposit.cjs.map +1 -0
  53. package/dist/deposit.d.cts +95 -0
  54. package/dist/deposit.d.ts +95 -0
  55. package/dist/deposit.js +19 -0
  56. package/dist/deposit.js.map +1 -0
  57. package/dist/index.cjs +1789 -0
  58. package/dist/index.cjs.map +1 -0
  59. package/dist/index.d.cts +34 -0
  60. package/dist/index.d.ts +34 -0
  61. package/dist/index.js +242 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/pricing.cjs +132 -0
  64. package/dist/pricing.cjs.map +1 -0
  65. package/dist/pricing.d.cts +123 -0
  66. package/dist/pricing.d.ts +123 -0
  67. package/dist/pricing.js +42 -0
  68. package/dist/pricing.js.map +1 -0
  69. package/dist/protocol.cjs +1596 -0
  70. package/dist/protocol.cjs.map +1 -0
  71. package/dist/protocol.d.cts +20 -0
  72. package/dist/protocol.d.ts +20 -0
  73. package/dist/protocol.js +17 -0
  74. package/dist/protocol.js.map +1 -0
  75. package/dist/provider.cjs +1581 -0
  76. package/dist/provider.cjs.map +1 -0
  77. package/dist/provider.d.cts +45 -0
  78. package/dist/provider.d.ts +45 -0
  79. package/dist/provider.js +18 -0
  80. package/dist/provider.js.map +1 -0
  81. package/dist/remote.cjs +1659 -0
  82. package/dist/remote.cjs.map +1 -0
  83. package/dist/remote.d.cts +55 -0
  84. package/dist/remote.d.ts +55 -0
  85. package/dist/remote.js +17 -0
  86. package/dist/remote.js.map +1 -0
  87. package/dist/status.cjs +443 -0
  88. package/dist/status.cjs.map +1 -0
  89. package/dist/status.d.cts +109 -0
  90. package/dist/status.d.ts +109 -0
  91. package/dist/status.js +26 -0
  92. package/dist/status.js.map +1 -0
  93. package/dist/verify.cjs +690 -0
  94. package/dist/verify.cjs.map +1 -0
  95. package/dist/verify.d.cts +245 -0
  96. package/dist/verify.d.ts +245 -0
  97. package/dist/verify.js +69 -0
  98. package/dist/verify.js.map +1 -0
  99. package/module.json +32 -0
  100. package/package.json +124 -3
@@ -0,0 +1,16 @@
1
+ import { ChainTx, DescribeActivityContext, ActivityItem } from '@anywalletkit/core';
2
+
3
+ /**
4
+ * Activity recognition for Across on every pinned chain: a `deposit` / `depositV3` call on the chain's SpokePool is our
5
+ * source leg ("Bridged USDC").
6
+ *
7
+ * Deposits that reach the SpokePool through another contract (Across's periphery, an aggregator, a Safe) are not
8
+ * claimed: the call the history shows is that contract's. The destination leg is not claimed either — a fill is paid
9
+ * by one of many relayers as an ordinary token transfer (or a native payment when the wrapped native token is
10
+ * unwrapped) and reads as a plain incoming transfer.
11
+ */
12
+
13
+ declare const ACROSS_MODULE = "@anywalletkit/protocol-swap2-across";
14
+ declare function describeAcrossActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null;
15
+
16
+ export { ACROSS_MODULE, describeAcrossActivity };
@@ -0,0 +1,10 @@
1
+ import {
2
+ ACROSS_MODULE,
3
+ describeAcrossActivity
4
+ } from "./chunk-5BDZXOOP.js";
5
+ import "./chunk-GX67FRPG.js";
6
+ export {
7
+ ACROSS_MODULE,
8
+ describeAcrossActivity
9
+ };
10
+ //# sourceMappingURL=activity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/dist/api.cjs ADDED
@@ -0,0 +1,441 @@
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/api.ts
21
+ var api_exports = {};
22
+ __export(api_exports, {
23
+ ACROSS_API_V1: () => ACROSS_API_V1,
24
+ ACROSS_SUGGESTED_FEES_MAX_AGE_S: () => ACROSS_SUGGESTED_FEES_MAX_AGE_S,
25
+ ACROSS_SUGGESTED_FEES_MAX_AHEAD_S: () => ACROSS_SUGGESTED_FEES_MAX_AHEAD_S,
26
+ ACROSS_SUGGESTED_FEES_URL: () => ACROSS_SUGGESTED_FEES_URL,
27
+ ACROSS_V5_PRICING_MAX_FEE_BPS: () => ACROSS_V5_PRICING_MAX_FEE_BPS,
28
+ acrossApiUrl: () => acrossApiUrl,
29
+ acrossHttp: () => acrossHttp,
30
+ acrossOriginOf: () => acrossOriginOf,
31
+ acrossSuggestedFeesQuery: () => acrossSuggestedFeesQuery,
32
+ acrossUsdToUnits: () => acrossUsdToUnits,
33
+ acrossV5QuoteRequest: () => acrossV5QuoteRequest,
34
+ parseAcrossV5Error: () => parseAcrossV5Error,
35
+ readAcrossSuggestedFees: () => readAcrossSuggestedFees,
36
+ readAcrossV5Quote: () => readAcrossV5Quote
37
+ });
38
+ module.exports = __toCommonJS(api_exports);
39
+ var import_errors2 = require("@anywalletkit/protocol-swap2-core/errors");
40
+ var import_util = require("@anywalletkit/protocol-swap2-core/util");
41
+
42
+ // src/config.ts
43
+ var USDC = (address, symbol = "USDC") => Object.freeze({ asset: "USDC", address, symbol, decimals: 6 });
44
+ var USDT = (address, symbol = "USDT") => Object.freeze({ asset: "USDT", address, symbol, decimals: 6 });
45
+ var WETH = (address) => Object.freeze({ asset: "ETH", address, symbol: "WETH", decimals: 18 });
46
+ var WBTC = (address) => Object.freeze({ asset: "WBTC", address, symbol: "WBTC", decimals: 8 });
47
+ var OP_WETH = "0x4200000000000000000000000000000000000006";
48
+ function chain(chainId, key, name, spokePool, wrappedNative, nativeIsEth, tokens) {
49
+ return Object.freeze({ caip2: `eip155:${chainId}`, chainId, key, name, spokePool, wrappedNative, nativeIsEth, tokens: Object.freeze(tokens) });
50
+ }
51
+ var ACROSS_CHAINS = Object.freeze(Object.assign(/* @__PURE__ */ Object.create(null), Object.fromEntries([
52
+ chain(1, "ethereum", "Ethereum", "0x5c7bcd6e7de5423a257d81b442095a1a6ced35c5", "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", true, [
53
+ USDC("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"),
54
+ USDT("0xdac17f958d2ee523a2206206994597c13d831ec7"),
55
+ WETH("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"),
56
+ WBTC("0x2260fac5e5542a773aa44fbcfedf7c193bc2c599")
57
+ ]),
58
+ chain(10, "optimism", "Optimism", "0x6f26bf09b1c792e3228e5467807a900a503c0281", OP_WETH, true, [
59
+ USDC("0x0b2c639c533813f4aa9d7837caf62653d097ff85"),
60
+ USDT("0x94b008aa00579c1307b0ef2c499ad98a8ce58e58"),
61
+ WETH(OP_WETH)
62
+ ]),
63
+ chain(130, "unichain", "Unichain", "0x09aea4b2242abc8bb4bb78d537a67a245a7bec64", OP_WETH, true, [
64
+ USDC("0x078d782b760474a361dda0af3839290b0ef57ad6"),
65
+ USDT("0x9151434b16b9763660705744891fa906f660ecc5", "USDT0"),
66
+ WETH(OP_WETH)
67
+ ]),
68
+ chain(137, "polygon", "Polygon", "0x9295ee1d8c5b022be115a2ad3c30c72e34e7f096", "0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270", false, [
69
+ USDC("0x3c499c542cef5e3811e1192ce70d8cc03d5c3359"),
70
+ USDT("0xc2132d05d31c914a87c6611c10748aeb04b58e8f"),
71
+ WBTC("0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6")
72
+ ]),
73
+ chain(143, "monad", "Monad", "0xd2ecb3afe598b746f8123cae365a598da831a449", "0x3bd359c1119da7da1d913d1c4d2b7c461115433a", false, [
74
+ USDC("0x754704bc059f8c67012fed69bc8a327a5aafb603"),
75
+ USDT("0xe7cd86e13ac4309349f30b3435a9d337750fc82d", "USDT0")
76
+ ]),
77
+ chain(324, "zksync", "zkSync Era", "0xe0b015e54d54fc84a6cb9b666099c46ade9335ff", "0x5aea5775959fbc2557cc8789bc1bf90a239d9a91", true, [
78
+ USDT("0x493257fd37edb34451f62edf8d2a0c418852ba4c"),
79
+ WETH("0x5aea5775959fbc2557cc8789bc1bf90a239d9a91"),
80
+ WBTC("0xbbeb516fb02a01611cbbe0453fe3c580d7281011")
81
+ ]),
82
+ chain(480, "worldchain", "World Chain", "0x09aea4b2242abc8bb4bb78d537a67a245a7bec64", OP_WETH, true, [
83
+ USDC("0x79a02482a880bce3f13e09da970dc34db4cd24d1"),
84
+ WETH(OP_WETH),
85
+ WBTC("0x03c7054bcb39f7b2e5b2c7acb37583e32d70cfa3")
86
+ ]),
87
+ chain(999, "hyperevm", "HyperEVM", "0x35e63ea3eb0fb7a3bc543c71fb66412e1f6b0e04", "0x5555555555555555555555555555555555555555", false, [
88
+ USDC("0xb88339cb7199b77e23db6e890353e22632ba630f"),
89
+ USDT("0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb", "USDT0")
90
+ ]),
91
+ chain(4326, "megaeth", "MegaETH", "0x3db06da8f0a24a525f314eec954fc5c6a973d40e", OP_WETH, true, [
92
+ USDT("0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb", "USDT0"),
93
+ WETH(OP_WETH)
94
+ ]),
95
+ chain(4663, "robinhood", "Robinhood Chain", "0xd29c85f15df544ba632c9e25829fd29d767d7978", "0x0bd7d308f8e1639fab988df18a8011f41eacad73", true, [
96
+ WETH("0x0bd7d308f8e1639fab988df18a8011f41eacad73")
97
+ ]),
98
+ // Arc's gas coin is USDC; 0x3600… is its 6-decimal ERC-20 interface, which is what Across moves. The SpokePool
99
+ // reports no wrapped native token, so no deposit or fill on Arc involves the native coin.
100
+ chain(5042, "arc", "Arc", "0x9b4a302a548c7e313c2b74c461db7b84d3074a84", null, false, [
101
+ USDC("0x3600000000000000000000000000000000000000")
102
+ ]),
103
+ chain(8453, "base", "Base", "0x09aea4b2242abc8bb4bb78d537a67a245a7bec64", OP_WETH, true, [
104
+ USDC("0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"),
105
+ USDT("0xfde4c96c8593536e31f229ea8f37b2ada2699bb2"),
106
+ WETH(OP_WETH)
107
+ ]),
108
+ chain(9745, "plasma", "Plasma", "0x50039faefebef707cfd94d6d462fe6d10b39207a", "0x6100e367285b01f48d07953803a2d8dca5d19873", false, [
109
+ USDT("0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb", "USDT0")
110
+ ]),
111
+ chain(42161, "arbitrum", "Arbitrum", "0xe35e9842fceaca96570b734083f4a58e8f7c5f2a", "0x82af49447d8a07e3bd95bd0d56f35241523fbab1", true, [
112
+ USDC("0xaf88d065e77c8cc2239327c5edb3a432268e5831"),
113
+ USDT("0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9", "USDT0"),
114
+ WETH("0x82af49447d8a07e3bd95bd0d56f35241523fbab1"),
115
+ WBTC("0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f")
116
+ ]),
117
+ chain(43114, "avalanche", "Avalanche", "0xfe9d541c92e4e90437c7152a00244886de37a658", "0xb31f66aa3c1e785363f0875a1b74e27b85fd66c7", false, [
118
+ USDC("0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e"),
119
+ USDT("0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7")
120
+ ]),
121
+ chain(57073, "ink", "Ink", "0xef684c38f94f48775959ecf2012d7e864ffb9dd4", OP_WETH, true, [
122
+ USDC("0x2d270e6886d130d724215a266106e6832161eaed"),
123
+ USDT("0x0200c29006150606b650577bbe7b6248f58470c1", "USDT0"),
124
+ WETH(OP_WETH)
125
+ ]),
126
+ chain(59144, "linea", "Linea", "0x7e63a5f1a8f0b4d0934b2f2327daed3f6bb2ee75", "0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f", true, [
127
+ USDC("0x176211869ca2b568f2a7d4ee941e073a821ee1ff"),
128
+ USDT("0xa219439258ca9da29e9cc4ce5596924745e12b93"),
129
+ WETH("0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f"),
130
+ WBTC("0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4")
131
+ ])
132
+ ].map((x) => [x.caip2, x]))));
133
+ function acrossChain(caip2) {
134
+ return typeof caip2 === "string" && Object.prototype.hasOwnProperty.call(ACROSS_CHAINS, caip2) ? ACROSS_CHAINS[caip2] : void 0;
135
+ }
136
+ var ACROSS_REFUSED_SELECTORS = Object.freeze({
137
+ "0x8b15788e": "unsafeDeposit",
138
+ "0xea86bd46": "depositNow",
139
+ "0x7aef642c": "depositV3Now",
140
+ "0xbabb6aac": "speedUpDeposit",
141
+ "0x577f51f8": "speedUpV3Deposit",
142
+ "0xac9650d8": "multicall"
143
+ });
144
+ var ACROSS_API = "https://api.across.to";
145
+
146
+ // src/refusal.ts
147
+ var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
148
+ var AcrossRefusal = class extends Error {
149
+ code;
150
+ constructor(code, detail, reason) {
151
+ super(`across: ${detail} [${code}]`);
152
+ this.name = "AcrossRefusal";
153
+ this.code = code;
154
+ if (reason !== void 0) (0, import_errors.withReason)(this, reason);
155
+ }
156
+ };
157
+
158
+ // src/api.ts
159
+ var ACROSS_API_V1 = `${ACROSS_API}/v1`;
160
+ var ACROSS_SUGGESTED_FEES_URL = "https://app.across.to/api/suggested-fees";
161
+ var ACROSS_V5_PRICING_MAX_FEE_BPS = 5e3;
162
+ var MAX_ANSWER_CHARS = 512 * 1024;
163
+ function acrossV5QuoteRequest(request) {
164
+ const src = acrossChain(request.sourceChain);
165
+ const dst = acrossChain(request.destChain);
166
+ if (!src || !dst) throw new Error("across: the request's chains are not pinned");
167
+ return {
168
+ origin: { token: { chainId: src.chainId, address: request.sourceToken.toLowerCase() }, depositor: request.depositor.toLowerCase(), amount: request.amount.toString(10) },
169
+ destination: { token: { chainId: dst.chainId, address: request.destToken.toLowerCase() }, recipient: request.recipient.toLowerCase() },
170
+ amountType: "exact_input",
171
+ capabilities: { operations: [{ kind: "approve_token", ecosystem: "evm" }, { kind: "send_transaction", ecosystem: "evm" }] },
172
+ authorizationPolicy: { allowedTypes: ["approval"], approvalAmount: "exact" },
173
+ maxFee: { bps: ACROSS_V5_PRICING_MAX_FEE_BPS }
174
+ };
175
+ }
176
+ var ADDRESS = /^0x[0-9a-fA-F]{40}$/;
177
+ var ZERO = /^0x0{40}$/;
178
+ var UINT = /^(?:0|[1-9]\d{0,77})$/;
179
+ var DECIMAL = /^(?:0|[1-9]\d{0,15})(?:\.\d{1,30})?$/;
180
+ var plain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
181
+ var own = (o, key) => Object.prototype.hasOwnProperty.call(o, key) ? o[key] : void 0;
182
+ var uint = (v) => typeof v === "string" && UINT.test(v) ? BigInt(v) : null;
183
+ var sameAddress = (a, b) => typeof a === "string" && ADDRESS.test(a) && a.toLowerCase() === b.toLowerCase();
184
+ function scaled(text2, scale) {
185
+ if (!DECIMAL.test(text2)) return null;
186
+ const [whole, frac = ""] = text2.split(".");
187
+ return BigInt(whole + frac.slice(0, scale).padEnd(scale, "0"));
188
+ }
189
+ var USD_SCALE = 18;
190
+ var PRICE_SCALE = 12;
191
+ function acrossUsdToUnits(amountUsd, priceUsd, decimals) {
192
+ if (typeof amountUsd !== "string" || typeof priceUsd !== "number" || !Number.isFinite(priceUsd) || priceUsd <= 0 || priceUsd >= 1e12) return null;
193
+ if (!Number.isInteger(decimals) || decimals < 0 || decimals > 36) return null;
194
+ const usd = scaled(amountUsd, USD_SCALE);
195
+ const price = scaled(priceUsd.toFixed(PRICE_SCALE), PRICE_SCALE);
196
+ if (usd === null || price === null || price === 0n) return null;
197
+ return usd * 10n ** BigInt(decimals) * 10n ** BigInt(PRICE_SCALE) / (price * 10n ** BigInt(USD_SCALE));
198
+ }
199
+ function readAcrossV5Quote(request, route, body) {
200
+ const malformed = (what) => {
201
+ throw new AcrossRefusal("api-answer", `the V5 quote ${what}`, "upstream_unavailable");
202
+ };
203
+ const other = (what) => {
204
+ throw new AcrossRefusal("api-answer", `the V5 quote ${what}`, "policy_refused");
205
+ };
206
+ if (!plain(body)) return malformed("is not a JSON object");
207
+ const amountType = own(body, "amountType");
208
+ if (amountType !== void 0 && amountType !== "exact_input") other(`is ${String(amountType).slice(0, 20)}, not exact input`);
209
+ const src = route.input.chain;
210
+ const dst = route.output.chain;
211
+ const origin = own(body, "origin");
212
+ const destination = own(body, "destination");
213
+ if (!plain(origin) || !plain(destination)) return malformed("has no origin or destination");
214
+ const oToken = own(origin, "token");
215
+ const dToken = own(destination, "token");
216
+ if (!plain(oToken) || !plain(dToken)) return malformed("names no tokens");
217
+ if (own(oToken, "chainId") !== src.chainId || !sameAddress(own(oToken, "address"), request.sourceToken)) other("is for another input token or chain");
218
+ if (own(dToken, "chainId") !== dst.chainId || !sameAddress(own(dToken, "address"), request.destToken)) other("is for another output token or chain");
219
+ const amountIn = uint(own(origin, "amount"));
220
+ if (amountIn === null) return malformed("states no input amount");
221
+ if (amountIn !== request.amount) other(`sends ${amountIn}, the request ${request.amount}`);
222
+ const destinationAmount = uint(own(destination, "amount"));
223
+ if (destinationAmount === null) return malformed("states no output estimate");
224
+ if (destinationAmount > request.amount) other("expects more to arrive than goes in");
225
+ const fee = own(body, "fee");
226
+ if (!plain(fee)) return malformed("has no fee");
227
+ const total = own(fee, "totalFee");
228
+ if (!plain(total)) return malformed("has no total fee");
229
+ const totalFee = uint(own(total, "amount"));
230
+ if (totalFee === null) return malformed("states a total fee that is not a base-unit integer");
231
+ const feeToken = own(total, "token");
232
+ if (!plain(feeToken) || own(feeToken, "chainId") !== dst.chainId || !sameAddress(own(feeToken, "address"), request.destToken) || own(feeToken, "decimals") !== route.output.decimals) {
233
+ malformed("states its fee in another token");
234
+ }
235
+ if (totalFee !== request.amount - destinationAmount) malformed(`fee ${totalFee} is not its input minus its estimate (${request.amount - destinationAmount})`);
236
+ const appFee = own(fee, "appFee");
237
+ if (appFee !== void 0 && appFee !== null) {
238
+ const app = plain(appFee) ? uint(own(appFee, "amount")) : null;
239
+ if (app === null) return malformed("states an app fee that does not read");
240
+ if (app > 0n) other("carries an app fee this module never asks for");
241
+ }
242
+ const fill = own(body, "expectedFillTimeMs");
243
+ if (typeof fill !== "number" || !Number.isFinite(fill) || fill < 0) return malformed("states no fill time");
244
+ const priceUsd = own(dToken, "priceUsd");
245
+ const legs = own(body, "gasEstimates");
246
+ if (!Array.isArray(legs) || legs.length > 16) return malformed("has no gas estimates");
247
+ let originGas = 0n;
248
+ let destinationGas = 0n;
249
+ for (const leg of legs) {
250
+ if (!plain(leg)) return malformed("has a gas estimate that is not an object");
251
+ if (own(leg, "effect") !== "included_in_transfer_fee") continue;
252
+ const side = own(leg, "leg");
253
+ if (side !== "origin" && side !== "destination") continue;
254
+ const units = legUnits(leg, route, priceUsd);
255
+ if (side === "origin") originGas += units ?? 0n;
256
+ else destinationGas = units === null || destinationGas === null ? null : destinationGas + units;
257
+ }
258
+ if (originGas > totalFee) originGas = totalFee;
259
+ const usdText = own(origin, "amountUsd");
260
+ const amountUsd = typeof usdText === "string" && DECIMAL.test(usdText) ? Number(usdText) : void 0;
261
+ return { totalFee, destinationAmount, originGas, destinationGas, expectedFillTimeMs: fill, ...amountUsd !== void 0 && Number.isFinite(amountUsd) ? { amountUsd } : {} };
262
+ }
263
+ function legUnits(leg, route, priceUsd) {
264
+ const token = own(leg, "token");
265
+ const amount = uint(own(leg, "amount"));
266
+ if (route.asset === "ETH" && plain(token) && amount !== null && ZERO.test(String(own(token, "address"))) && own(token, "decimals") === 18) {
267
+ const chainId = own(token, "chainId");
268
+ const side = chainId === route.input.chain.chainId ? route.input.chain : chainId === route.output.chain.chainId ? route.output.chain : void 0;
269
+ if (side?.nativeIsEth) return amount;
270
+ }
271
+ return acrossUsdToUnits(own(leg, "amountUsd"), priceUsd, route.input.decimals);
272
+ }
273
+ function acrossSuggestedFeesQuery(request, route) {
274
+ const q = [
275
+ ["inputToken", route.input.token],
276
+ ["outputToken", route.output.token],
277
+ ["originChainId", String(route.input.chain.chainId)],
278
+ ["destinationChainId", String(route.output.chain.chainId)],
279
+ ["amount", request.amount.toString(10)],
280
+ ["recipient", request.recipient.toLowerCase()]
281
+ ];
282
+ return q.map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
283
+ }
284
+ var ACROSS_SUGGESTED_FEES_MAX_AGE_S = 600;
285
+ var ACROSS_SUGGESTED_FEES_MAX_AHEAD_S = 0;
286
+ function readAcrossSuggestedFees(request, route, status, body, nowS) {
287
+ const unavailable = (detail) => ({ kind: "unavailable", detail });
288
+ const refused = (detail, reason) => ({ kind: "refused", detail, reason });
289
+ if (status !== 200) {
290
+ const code = plain(body) ? own(body, "code") : void 0;
291
+ const label = typeof code === "string" ? ` ${code.slice(0, 40)}` : "";
292
+ if (status === 400) {
293
+ if (code === "AMOUNT_TOO_LOW") return refused("Across's relayer fee quote says the amount is too low relative to fees", "amount_too_small");
294
+ if (code === "AMOUNT_TOO_HIGH") return refused("Across's relayer fee quote says the amount is higher than relayer liquidity", "amount_too_large");
295
+ if (code === "ROUTE_NOT_ENABLED") return refused("Across's relayer fee quote says this route is not enabled for relayers", "unsupported_pair");
296
+ const param = plain(body) ? own(body, "param") : void 0;
297
+ const message = plain(body) ? own(body, "message") : void 0;
298
+ if (code === "INVALID_PARAM" && /token|chain/i.test(`${typeof param === "string" ? param : ""} ${typeof message === "string" ? message : ""}`)) {
299
+ 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");
300
+ }
301
+ return refused(`Across's relayer fee quote refused the deposit (HTTP 400${label})`, "upstream_unavailable");
302
+ }
303
+ return unavailable(`it answered HTTP ${status}${label}`);
304
+ }
305
+ if (!plain(body)) return unavailable("its answer is not a JSON object");
306
+ const inputToken = own(body, "inputToken");
307
+ const outputToken = own(body, "outputToken");
308
+ if (!plain(inputToken) || !plain(outputToken)) return unavailable("its answer names no tokens");
309
+ 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) {
310
+ return unavailable("its answer is for another route");
311
+ }
312
+ const spoke = own(body, "spokePoolAddress");
313
+ const destSpoke = own(body, "destinationSpokePoolAddress");
314
+ const spokeMoved = spoke !== void 0 && !sameAddress(spoke, route.input.chain.spokePool);
315
+ if (spokeMoved || destSpoke !== void 0 && !sameAddress(destSpoke, route.output.chain.spokePool)) {
316
+ 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");
317
+ }
318
+ const totalRelay = own(body, "totalRelayFee");
319
+ const total = plain(totalRelay) ? uint(own(totalRelay, "total")) : null;
320
+ const outputAmount = uint(own(body, "outputAmount"));
321
+ if (total === null || outputAmount === null) return unavailable("its answer states no relayer fee");
322
+ if (outputAmount + total !== request.amount) return unavailable("its fee is not the amount minus its output");
323
+ 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");
324
+ const limits = own(body, "limits");
325
+ if (plain(limits)) {
326
+ const min = uint(own(limits, "minDeposit"));
327
+ const max = uint(own(limits, "maxDeposit"));
328
+ if (min !== null && request.amount < min) return refused(`Across's relayers take at least ${min} base units on this route`, "amount_too_small");
329
+ if (max !== null && request.amount > max) return refused(`Across's relayers take at most ${max} base units on this route`, "amount_too_large");
330
+ }
331
+ const ts = own(body, "timestamp");
332
+ const timestamp = typeof ts === "string" && /^[1-9]\d{8,9}$/.test(ts) ? Number(ts) : NaN;
333
+ if (!Number.isInteger(timestamp)) return unavailable("its answer states no quote time");
334
+ if (timestamp - nowS > ACROSS_SUGGESTED_FEES_MAX_AHEAD_S) return unavailable(`its quote time is ${timestamp - nowS} s ahead of this clock`);
335
+ if (nowS - timestamp > ACROSS_SUGGESTED_FEES_MAX_AGE_S) return unavailable(`its quote time is ${nowS - timestamp} s old`);
336
+ const eta = own(body, "estimatedFillTimeSec");
337
+ return { kind: "fees", totalRelayFee: total, timestamp, estimatedFillTimeSec: typeof eta === "number" && Number.isFinite(eta) && eta >= 0 ? eta : 2 };
338
+ }
339
+ var text = (v, max) => typeof v === "string" && v.length > 0 ? v.slice(0, max) : void 0;
340
+ 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/;
341
+ function reasonOfCode(code, message, param, side, status) {
342
+ switch (code) {
343
+ case "unauthenticated":
344
+ case "auth.missing_credentials":
345
+ case "auth.invalid_credentials":
346
+ // A feature the key is not entitled to (a permission Across grants per integration).
347
+ case "permission.not_entitled":
348
+ return { reason: "key_rejected", httpStatus: status };
349
+ case "policy.amount_out_of_range": {
350
+ if (side === "min") return { reason: "amount_too_small" };
351
+ if (side === "max") return { reason: "amount_too_large" };
352
+ const m = (message ?? "").toLowerCase();
353
+ if (/\b(?:raise|increase) the amount\b/.test(m)) return { reason: "amount_too_small" };
354
+ if (/\b(?:lower|reduce|decrease) the amount\b/.test(m)) return { reason: "amount_too_large" };
355
+ if (FEE_CAP.test(m)) return { reason: "price_check_failed" };
356
+ if (/\b(?:too low|too small|below|minimum|min)\b/.test(m)) return { reason: "amount_too_small" };
357
+ if (/\b(?:too high|too large|above|maximum|max|liquidity)\b/.test(m)) return { reason: "amount_too_large" };
358
+ return { reason: "price_check_failed" };
359
+ }
360
+ // The API no longer takes what this module sends (a field it does not know, or one it now requires): an API of
361
+ // another shape than the one this module was built against.
362
+ case "request.unsupported_param":
363
+ case "request.missing_field":
364
+ return { reason: "upstream_unavailable", httpStatus: status };
365
+ // Only pinned tokens and chains are sent: one V5 calls invalid ("unknown token … is not a known token") is one it
366
+ // does not serve. Any other value it no longer takes is, like the codes above, an API of another shape.
367
+ case "request.invalid_field":
368
+ return /token|chain/i.test(`${param ?? ""} ${message ?? ""}`) ? { reason: "unsupported_pair" } : { reason: "upstream_unavailable", httpStatus: status };
369
+ case "system.unavailable":
370
+ case "conflict.submission_state_unknown":
371
+ return { reason: "upstream_unavailable", httpStatus: status };
372
+ default:
373
+ return void 0;
374
+ }
375
+ }
376
+ function parseAcrossV5Error(status, body, retryAfter, nowMs = Date.now()) {
377
+ const o = plain(body) ? body : void 0;
378
+ const nested = o !== void 0 && plain(o["error"]) ? o["error"] : void 0;
379
+ const code = text(nested?.["code"], 80) ?? text(o?.["code"], 80);
380
+ const type = text(nested?.["type"], 80);
381
+ const message = text(nested?.["message"], 240) ?? text(o?.["message"], 240);
382
+ const param = text(nested?.["param"], 80);
383
+ const requestId = text(nested?.["requestId"], 120);
384
+ const details = nested !== void 0 && plain(nested["details"]) ? nested["details"] : o !== void 0 && plain(o["details"]) ? o["details"] : void 0;
385
+ const limits = details !== void 0 && plain(details["amountLimits"]) ? details["amountLimits"] : void 0;
386
+ const rawSide = limits?.["side"];
387
+ const side = rawSide === "min" || rawSide === "max" ? rawSide : void 0;
388
+ const rawBound = limits?.["amount"];
389
+ const bound = typeof rawBound === "string" && UINT.test(rawBound) ? rawBound : void 0;
390
+ const byStatus = (0, import_errors2.httpRefusal)(status, retryAfter, nowMs);
391
+ let info;
392
+ if (byStatus?.reason === "rate_limited") info = byStatus;
393
+ 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);
394
+ return {
395
+ status,
396
+ ...code !== void 0 ? { code } : {},
397
+ ...type !== void 0 ? { type } : {},
398
+ ...message !== void 0 ? { message } : {},
399
+ ...param !== void 0 ? { param } : {},
400
+ ...requestId !== void 0 ? { requestId } : {},
401
+ ...side !== void 0 ? { amountLimit: { side, ...bound !== void 0 ? { amount: bound } : {} } } : {},
402
+ ...info !== void 0 ? { info } : {},
403
+ retrySameRequest: status === 409 && code === "conflict.submission_state_unknown"
404
+ };
405
+ }
406
+ function acrossApiUrl(url, what) {
407
+ const u = String(url).trim().replace(/\/+$/, "");
408
+ if (/^https:\/\/[^\s/?#@]+(?:\/[^\s?#]*)?$/i.test(u)) return u;
409
+ if (/^http:\/\/(?:localhost|127\.0\.0\.1)(?::[0-9]{1,5})?(?:\/[^\s?#]*)?$/i.test(u)) return u;
410
+ throw new Error(`across: ${what} must be an https:// URL (http only for localhost)`);
411
+ }
412
+ var acrossOriginOf = (url) => (/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(url)?.[0] ?? "").toLowerCase();
413
+ async function acrossHttp(url, init, opts) {
414
+ const expected = acrossOriginOf(url);
415
+ let status;
416
+ let raw;
417
+ let retryAfter = null;
418
+ try {
419
+ const timeout = (0, import_util.timeoutSignal)(opts.timeoutMs);
420
+ const res = await (opts.fetchImpl ?? fetch)(url, { ...init, redirect: "error", signal: opts.signal ? (0, import_util.anySignal)([opts.signal, timeout]) : timeout });
421
+ if (res.redirected === true || typeof res.url === "string" && res.url !== "" && acrossOriginOf(res.url) !== expected) {
422
+ 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");
423
+ }
424
+ status = res.status;
425
+ retryAfter = res.headers?.get?.("retry-after") ?? null;
426
+ raw = await res.text();
427
+ } catch (err) {
428
+ if (err instanceof AcrossRefusal) throw err;
429
+ const name = err instanceof Error ? err.name.slice(0, 40) : "error";
430
+ throw new AcrossRefusal("api-answer", `${opts.what} did not answer (${name})`, opts.signal?.aborted ? void 0 : "upstream_unavailable");
431
+ }
432
+ if (raw.length > MAX_ANSWER_CHARS) throw new AcrossRefusal("api-answer", `${opts.what} answered more than any quote`, "upstream_unavailable");
433
+ let body;
434
+ try {
435
+ body = JSON.parse(raw);
436
+ } catch {
437
+ body = void 0;
438
+ }
439
+ return { status, body, retryAfter };
440
+ }
441
+ //# sourceMappingURL=api.cjs.map