@anywalletkit/protocol-swap2-across 0.0.0-stage → 0.1.1

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,265 @@
1
+ import {
2
+ describeAcrossActivity
3
+ } from "./chunk-5BDZXOOP.js";
4
+ import {
5
+ acrossQuoteOf
6
+ } from "./chunk-SJOFLM27.js";
7
+ import {
8
+ ACROSS_MAX_FEE_BPS_LIMIT,
9
+ ACROSS_PLACEHOLDER,
10
+ acrossRequestOf,
11
+ checkAcrossQuote,
12
+ checkAcrossTxShape,
13
+ parseAcrossIntentId
14
+ } from "./chunk-KATEONJQ.js";
15
+ import {
16
+ acrossRpc,
17
+ trackAcrossDeposit
18
+ } from "./chunk-3UBRQ3ZE.js";
19
+ import {
20
+ ACROSS_SUGGESTED_FEES_URL,
21
+ acrossApiUrl,
22
+ acrossHttp,
23
+ acrossSuggestedFeesQuery,
24
+ acrossV5QuoteRequest,
25
+ parseAcrossV5Error,
26
+ readAcrossSuggestedFees,
27
+ readAcrossV5Quote
28
+ } from "./chunk-YGNP7KPL.js";
29
+ import {
30
+ ACROSS_API,
31
+ ACROSS_NATIVE,
32
+ across,
33
+ acrossChain,
34
+ acrossRouteOf
35
+ } from "./chunk-GX67FRPG.js";
36
+ import {
37
+ ACROSS_FILL_WINDOW_S,
38
+ acrossFloorFee,
39
+ acrossPlainFee,
40
+ acrossQuoteTimeOf,
41
+ acrossRouteUnpriced,
42
+ acrossV5OtherRail
43
+ } from "./chunk-6Z4GXNLE.js";
44
+ import {
45
+ AcrossRefusal
46
+ } from "./chunk-E5WFOPN2.js";
47
+
48
+ // src/provider.ts
49
+ import { refusal, refusalOf } from "@anywalletkit/protocol-swap2-core/errors";
50
+ import { ccAsset } from "@anywalletkit/swap2-assets";
51
+ var ADDRESS = /^0x[0-9a-fA-F]{40}$/;
52
+ var DEFAULT_TIMEOUT_MS = 1e4;
53
+ var DEFAULT_QUOTE_TTL_MS = 6e4;
54
+ function readKey(source) {
55
+ let key = source;
56
+ if (typeof source === "function") {
57
+ try {
58
+ key = source();
59
+ } catch {
60
+ return void 0;
61
+ }
62
+ }
63
+ return typeof key === "string" && /^[\x21-\x7e]{1,256}$/.test(key) ? key : void 0;
64
+ }
65
+ function onReactNative() {
66
+ const g = globalThis;
67
+ return g.HermesInternal !== void 0 || g.navigator?.product === "ReactNative";
68
+ }
69
+ function acrossServesRoute(from, to) {
70
+ if (!across.supports(from.chain, to.chain)) return false;
71
+ let token;
72
+ if (ADDRESS.test(from.token)) token = from.token;
73
+ else {
74
+ const asset = ccAsset(from.chain, from.token);
75
+ if (!asset) return false;
76
+ token = asset.contract ?? ACROSS_NATIVE;
77
+ }
78
+ const route = acrossRouteOf(from.chain, token, to.chain, to.token);
79
+ return !("code" in route) && acrossRouteUnpriced(route) === null;
80
+ }
81
+ function acrossProvider(config = {}) {
82
+ config = Object.freeze({ ...config });
83
+ if (config.apiKey !== void 0 && onReactNative()) {
84
+ 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.");
85
+ }
86
+ const maxFeeBps = config.maxFeeBps;
87
+ if (maxFeeBps !== void 0 && (!Number.isInteger(maxFeeBps) || maxFeeBps < 0 || maxFeeBps > ACROSS_MAX_FEE_BPS_LIMIT)) {
88
+ throw new Error(`across: maxFeeBps must be an integer between 0 and ${ACROSS_MAX_FEE_BPS_LIMIT}`);
89
+ }
90
+ const quoteTtlMs = config.quoteTtlMs ?? DEFAULT_QUOTE_TTL_MS;
91
+ if (!Number.isInteger(quoteTtlMs) || quoteTtlMs <= 0 || quoteTtlMs > 3e5) throw new Error("across: quoteTtlMs must be an integer between 1 and 300000");
92
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
93
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 6e4) throw new Error("across: timeoutMs must be an integer between 1 and 60000");
94
+ const v5Url = `${acrossApiUrl(config.baseUrl ?? ACROSS_API, "baseUrl")}/v1/quotes`;
95
+ const feesUrl = config.suggestedFeesUrl === null ? null : acrossApiUrl(config.suggestedFeesUrl ?? ACROSS_SUGGESTED_FEES_URL, "suggestedFeesUrl");
96
+ const rpcUrls = Object.freeze(Object.assign(/* @__PURE__ */ Object.create(null), config.rpcUrls ?? {}));
97
+ for (const [chain, url] of Object.entries(rpcUrls)) {
98
+ if (typeof url !== "string" || !/^https?:\/\//.test(url)) throw new Error(`across: the RPC URL for ${chain} must use http or https`);
99
+ }
100
+ const rpcFor = (caip2) => Object.prototype.hasOwnProperty.call(rpcUrls, caip2) ? acrossRpc(rpcUrls[caip2], config.fetchImpl) : void 0;
101
+ function requestOf(quote) {
102
+ const pd = quote.providerData ?? {};
103
+ const sealed = {
104
+ sourceChain: pd.sourceChain ?? "",
105
+ destChain: pd.destChain ?? "",
106
+ sourceToken: pd.sourceToken ?? "",
107
+ destToken: pd.destToken ?? "",
108
+ amount: /^[1-9]\d{0,77}$/.test(pd.amount ?? "") ? BigInt(pd.amount) : 0n,
109
+ depositor: pd.depositor ?? "",
110
+ recipient: pd.recipient ?? "",
111
+ .../^\d{1,78}$/.test(pd.minAmountOut ?? "") ? { minAmountOut: BigInt(pd.minAmountOut) } : {},
112
+ ...maxFeeBps !== void 0 ? { maxFeeBps } : {}
113
+ };
114
+ if (pd.placeholder === "1" || sealed.depositor.toLowerCase() === ACROSS_PLACEHOLDER.toLowerCase() || sealed.recipient.toLowerCase() === ACROSS_PLACEHOLDER.toLowerCase()) {
115
+ 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");
116
+ }
117
+ return sealed;
118
+ }
119
+ async function suggestedFees(request, route, signal) {
120
+ if (feesUrl === null) return { kind: "unavailable", detail: "it is turned off" };
121
+ try {
122
+ 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" });
123
+ return readAcrossSuggestedFees(request, route, a.status, a.body, Math.floor(Date.now() / 1e3));
124
+ } catch (err) {
125
+ if (signal?.aborted) throw err;
126
+ return { kind: "unavailable", detail: err instanceof Error ? err.message.replace(/^across: /, "") : "no answer" };
127
+ }
128
+ }
129
+ async function quoteTimeFromChains(route) {
130
+ const eth = rpcFor("eip155:1");
131
+ const origin = rpcFor(route.input.chain.caip2);
132
+ if (!eth || !origin) {
133
+ 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");
134
+ }
135
+ const timeOf = async (rpc) => {
136
+ const block = await rpc("eth_getBlockByNumber", ["latest", false]);
137
+ const t = typeof block?.timestamp === "string" && /^0x[0-9a-fA-F]{1,10}$/.test(block.timestamp) ? parseInt(block.timestamp, 16) : NaN;
138
+ if (!Number.isInteger(t) || t <= 0) throw new Error("no block time");
139
+ return t;
140
+ };
141
+ try {
142
+ const [e, o] = await Promise.all([timeOf(eth), route.input.chain.chainId === 1 ? Promise.resolve(null) : timeOf(origin)]);
143
+ return acrossQuoteTimeOf(e, o ?? e);
144
+ } catch {
145
+ 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");
146
+ }
147
+ }
148
+ return {
149
+ name: "across",
150
+ describeActivity: describeAcrossActivity,
151
+ enabled: () => (config.enabled ?? true) && readKey(config.apiKey) !== void 0,
152
+ supportsChain: (chain) => across.supportsChain(chain),
153
+ supportsChainPair: (from, to) => across.supports(from, to),
154
+ supportsRoute: (from, to) => acrossServesRoute(from, to),
155
+ async getQuote(params, signal) {
156
+ const refuse = (reason, info) => {
157
+ params.onRefusal?.(reason, info);
158
+ return null;
159
+ };
160
+ const dry = params.dry !== false;
161
+ try {
162
+ const request = acrossRequestOf(params, {
163
+ ...dry ? { placeholder: ACROSS_PLACEHOLDER } : {},
164
+ ...maxFeeBps !== void 0 ? { maxFeeBps } : {}
165
+ });
166
+ const route = acrossRouteOf(request.sourceChain, request.sourceToken, request.destChain, request.destToken);
167
+ const key = readKey(config.apiKey);
168
+ 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");
169
+ const [v5, fees] = await Promise.all([
170
+ acrossHttp(v5Url, {
171
+ method: "POST",
172
+ headers: { accept: "application/json", "content-type": "application/json", authorization: `Bearer ${key}` },
173
+ body: JSON.stringify(acrossV5QuoteRequest(request))
174
+ }, { fetchImpl: config.fetchImpl, timeoutMs, signal, what: "Across API V5" }),
175
+ suggestedFees(request, route, signal)
176
+ ]);
177
+ if (v5.status < 200 || v5.status >= 300) {
178
+ const e = parseAcrossV5Error(v5.status, v5.body, v5.retryAfter);
179
+ const bound = e.amountLimit?.amount ? ` (the amount must be ${e.amountLimit.side === "min" ? "at least" : "at most"} ${e.amountLimit.amount} base units)` : "";
180
+ throw new AcrossRefusal("api-error", `Across API V5 answered HTTP ${e.status}${e.code ? ` ${e.code}` : ""}${bound}`, e.info?.reason);
181
+ }
182
+ const price = readAcrossV5Quote(request, route, v5.body);
183
+ if (fees.kind === "refused") throw new AcrossRefusal("relayer-price", fees.detail, fees.reason);
184
+ const otherRail = acrossV5OtherRail(price.expectedFillTimeMs);
185
+ if (otherRail && fees.kind !== "fees") {
186
+ 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");
187
+ }
188
+ let need;
189
+ let quoteTimestamp;
190
+ let etaSec;
191
+ if (fees.kind === "fees") {
192
+ need = fees.totalRelayFee;
193
+ quoteTimestamp = fees.timestamp;
194
+ etaSec = fees.estimatedFillTimeSec;
195
+ } else {
196
+ need = acrossFloorFee(route, request.amount, price.amountUsd, price.destinationGas);
197
+ quoteTimestamp = await quoteTimeFromChains(route);
198
+ etaSec = price.expectedFillTimeMs / 1e3;
199
+ }
200
+ const fee = acrossPlainFee(request.amount, price, need, otherRail);
201
+ const nq = {
202
+ sourceChainId: route.input.chain.chainId,
203
+ destinationChainId: route.output.chain.chainId,
204
+ inputToken: request.sourceToken,
205
+ outputToken: request.destToken,
206
+ inputAmount: request.amount.toString(10),
207
+ outputAmount: (request.amount - fee.fee).toString(10),
208
+ quoteTimestamp,
209
+ fillDeadline: quoteTimestamp + ACROSS_FILL_WINDOW_S,
210
+ exclusiveRelayer: ACROSS_NATIVE,
211
+ exclusivityParameter: 0,
212
+ expectedFillTimeSec: etaSec,
213
+ fees: { total: fee.fee.toString(10) }
214
+ };
215
+ const quote = acrossQuoteOf(request, nq, { quoteTtlMs, ...dry ? { placeholder: true } : {} });
216
+ const priceSource = otherRail ? "suggested-fees (V5 other rail)" : fees.kind === "fees" ? "suggested-fees" : "floor";
217
+ return { ...quote, providerData: { ...quote.providerData, priceSource, v5Fee: fee.f5.toString(10), relayerFee: fee.need.toString(10) } };
218
+ } catch (err) {
219
+ if (err instanceof AcrossRefusal) return refuse(err.message, refusalOf(err));
220
+ throw err;
221
+ }
222
+ },
223
+ /** The quote's own transaction — after the deposit it carries has been verified once more. */
224
+ async buildDeposit(quote) {
225
+ const tx = quote.txRequest;
226
+ if (!tx || !parseAcrossIntentId(quote.intentId)) throw refusal("policy_refused", "swap2: Across quote has no transaction request");
227
+ const request = requestOf(quote);
228
+ const v = checkAcrossQuote(request, quote);
229
+ return {
230
+ chain: request.sourceChain,
231
+ to: v.deposit.to,
232
+ value: v.deposit.value,
233
+ data: v.deposit.data,
234
+ chainId: v.deposit.chainId,
235
+ ...tx.gasLimit ? { gasLimit: tx.gasLimit } : {},
236
+ ...v.deposit.approvalAddress ? { approvalAddress: v.deposit.approvalAddress } : {}
237
+ };
238
+ },
239
+ /** Right before signing: the whole verification again, against the request and the exact transaction about to be signed. */
240
+ async preflightDeposit(quote, tx) {
241
+ const request = requestOf(quote);
242
+ if (tx.chain !== request.sourceChain) throw new AcrossRefusal("tx-chain", `the deposit is for ${tx.chain}, not ${request.sourceChain}`, "vault_mismatch");
243
+ checkAcrossTxShape(tx);
244
+ checkAcrossQuote(request, quote, tx);
245
+ },
246
+ async trackIntent(ref) {
247
+ const intent = parseAcrossIntentId(ref.intentId);
248
+ if (!intent) return { state: "failed" };
249
+ const source = acrossChain(`eip155:${intent.sourceChainId}`);
250
+ const dest = acrossChain(`eip155:${intent.destChainId}`);
251
+ if (!source || !dest || source === dest) return { state: "failed" };
252
+ if (!ref.sourceTxHash) return { state: "pending" };
253
+ const sourceRpc = rpcFor(source.caip2);
254
+ const destRpc = rpcFor(dest.caip2);
255
+ const t = await trackAcrossDeposit({ sourceTxHash: ref.sourceTxHash, intentDigest: intent.digest, source, dest, ...sourceRpc ? { sourceRpc } : {}, ...destRpc ? { destRpc } : {} });
256
+ return t.status;
257
+ }
258
+ };
259
+ }
260
+
261
+ export {
262
+ acrossServesRoute,
263
+ acrossProvider
264
+ };
265
+ //# sourceMappingURL=chunk-PPPZIG7S.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/provider.ts"],"sourcesContent":["import type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {refusal, refusalOf, type Swap2RefusalInfo} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {ccAsset} from \"@anywalletkit/swap2-assets\";\nimport {describeAcrossActivity} from \"./activity.js\";\nimport {\n ACROSS_SUGGESTED_FEES_URL, acrossApiUrl, acrossHttp, acrossSuggestedFeesQuery, acrossV5QuoteRequest, parseAcrossV5Error, readAcrossSuggestedFees, readAcrossV5Quote,\n type AcrossSuggestedFees,\n} from \"./api.js\";\nimport {acrossQuoteOf, type NormalizedAcrossQuote} from \"./build.js\";\nimport {ACROSS_API, ACROSS_NATIVE, across as acrossCfg, acrossChain, acrossRouteOf, type AcrossRoute} from \"./config.js\";\nimport {ACROSS_FILL_WINDOW_S, acrossFloorFee, acrossPlainFee, acrossQuoteTimeOf, acrossRouteUnpriced, acrossV5OtherRail} from \"./pricing.js\";\nimport {AcrossRefusal} from \"./refusal.js\";\nimport {acrossRpc, trackAcrossDeposit, type AcrossRpc} from \"./status.js\";\nimport {ACROSS_MAX_FEE_BPS_LIMIT, ACROSS_PLACEHOLDER, acrossRequestOf, checkAcrossQuote, checkAcrossTxShape, parseAcrossIntentId, type AcrossRequest} from \"./verify.js\";\n\n/**\n * Across Protocol — an intent bridge. ONE source transaction: `deposit(...)` on the source chain's SpokePool, whose\n * arguments name the recipient, the output token and amount, the destination chain and the fill deadline; a relayer\n * pays the recipient on the destination from its own funds, or the deposit is refunded to the depositor on the source\n * chain after the deadline.\n *\n * - The deposit is built HERE (`build.ts`) from the pins and the user's request; the quote source only supplies the\n * numbers, and `verify.ts` holds every argument to the request again at build time and right before signing. An\n * ERC-20 input sets `approvalAddress` to the pinned SpokePool and the engine approves exactly the input amount.\n * - EVM → EVM, exact input, the same asset on both sides (USDC, USDT / USDT0, ETH / WETH, WBTC), empty message only.\n * Periphery calls (origin swaps, `depositNative`), CCTP / OFT routes, destination actions, speed-up signatures and\n * integrator fees are refused by name.\n * - Pricing (`pricing.ts`): Across API V5 is the price source and `/suggested-fees` (keyless) what a relayer needs;\n * the deposit leaves `max(V5's fee net of its origin step, the relayer need)` — the relayer need alone when V5\n * prices another rail. V5's `nextActions` are never executed. The V5 key is server-only: under React Native an\n * `apiKey` is refused — the app runs `acrossRemoteProvider` against a backend that runs this provider\n * (`createSwap2Handler`), and reads Across's keyless relayer fee itself to hold the backend's price to it.\n * - Status is read on chain (`status.ts`): the intent's own deposit from the source receipt, its relay hash, the\n * destination's `fillStatuses` — with an RPC URL per chain in `rpcUrls`. Unfilled past its fill deadline it is\n * `expired` (Across refunds it). Display only, nothing is signed on its word.\n * - The depositor is the signing account (`QuoteParams.sender`, set by the engine), never a `refundAddress` the caller\n * names: an Across depositor can sign a speed-up that re-points the output, so a different refund address is refused.\n */\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_QUOTE_TTL_MS = 60_000;\n\nexport interface AcrossProviderConfig {\n /** Dark flag (the app convention is `ACROSS_ENABLED`). Default true; without an `apiKey` the provider is disabled anyway. */\n enabled?: boolean | undefined;\n /**\n * The Across API V5 key (dashboard.across.to) — server only; the app convention is `ACROSS_API_KEY`. Best as a\n * getter read on every request, so the key lives where you keep secrets; a string is accepted too. It is sent only\n * as the `Authorization: Bearer` header to `baseUrl`, never put in a URL, a refusal or a quote, and an answer that\n * came through a redirect is refused. Without one (or one that is not printable ASCII) the provider quotes nothing\n * and reports itself disabled — it still builds, verifies and tracks. Under React Native a key is refused outright\n * (the constructor throws): use `acrossRemoteProvider` in the app. Across's older integrator id and V4 key are not\n * used by this module.\n */\n apiKey?: string | (() => string | undefined) | undefined;\n /** V5 origin. Default `https://api.across.to`. Must be https (http only for localhost): the key rides on it. */\n baseUrl?: string | undefined;\n /**\n * Across's keyless relayer-fee quote (default {@link ACROSS_SUGGESTED_FEES_URL}); `null` turns it off and prices\n * every quote with the pinned floor (which needs `rpcUrls` for Ethereum and the source chain, for the quote time).\n */\n suggestedFeesUrl?: string | null | undefined;\n /**\n * JSON-RPC URLs per CAIP-2 chain: status (the source chain's to read the deposit, the destination's to read its\n * fill), and the quote time when `/suggested-fees` does not answer (Ethereum's and the source chain's latest block).\n */\n rpcUrls?: Readonly<Record<string, string>> | undefined;\n /** Fee cap in bps of the input that a deposit may leave to relayers (default 1000 = 10 %, at most 5000). */\n maxFeeBps?: number | undefined;\n /** Local lifetime of a quote (default 60 s, at most 5 min). */\n quoteTtlMs?: number | undefined;\n /** Per API request, ms (default 10 000). */\n timeoutMs?: number | undefined;\n /** Injectable for tests and for runtimes that bring their own. */\n fetchImpl?: typeof fetch | undefined;\n}\n\n/** The key for one request: printable ASCII without spaces, or nothing. A throwing getter is \"no key\". */\nfunction readKey(source: AcrossProviderConfig[\"apiKey\"]): string | undefined {\n let key: unknown = source;\n if (typeof source === \"function\") {\n try {\n key = source();\n } catch {\n return undefined;\n }\n }\n return typeof key === \"string\" && /^[\\x21-\\x7e]{1,256}$/.test(key) ? key : undefined;\n}\n\n/**\n * React Native (Hermes or JSC): an app bundle keeps no secret, and its fetch (OkHttp / NSURLSession) follows redirects\n * — carrying the key header along — whatever `redirect` says.\n */\nfunction onReactNative(): boolean {\n const g = globalThis as {HermesInternal?: unknown; navigator?: {product?: unknown}};\n return g.HermesInternal !== undefined || g.navigator?.product === \"ReactNative\";\n}\n\n/**\n * Whether this module serves a route — the source a catalog symbol (or a contract), the destination an address (zero\n * for the native coin): pinned chains and tokens, the same asset, and a route the pricing covers (not Ethereum as the\n * destination). The local and the remote provider answer alike.\n */\nexport function acrossServesRoute(from: Asset, to: Asset): boolean {\n if (!acrossCfg.supports(from.chain, to.chain)) return false;\n let token: string;\n if (ADDRESS.test(from.token)) token = from.token;\n else {\n const asset = ccAsset(from.chain, from.token);\n if (!asset) return false;\n token = asset.contract ?? ACROSS_NATIVE;\n }\n const route = acrossRouteOf(from.chain, token, to.chain, to.token);\n return !(\"code\" in route) && acrossRouteUnpriced(route) === null;\n}\n\nexport function acrossProvider(config: AcrossProviderConfig = {}): CrossChainProvider {\n config = Object.freeze({...config});\n if (config.apiKey !== undefined && onReactNative()) {\n throw new Error(\"across: the Across API key belongs on a server — 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.\");\n }\n const maxFeeBps = config.maxFeeBps;\n if (maxFeeBps !== undefined && (!Number.isInteger(maxFeeBps) || maxFeeBps < 0 || maxFeeBps > ACROSS_MAX_FEE_BPS_LIMIT)) {\n throw new Error(`across: maxFeeBps must be an integer between 0 and ${ACROSS_MAX_FEE_BPS_LIMIT}`);\n }\n const quoteTtlMs = config.quoteTtlMs ?? DEFAULT_QUOTE_TTL_MS;\n if (!Number.isInteger(quoteTtlMs) || quoteTtlMs <= 0 || quoteTtlMs > 300_000) throw new Error(\"across: quoteTtlMs must be an integer between 1 and 300000\");\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 60_000) throw new Error(\"across: timeoutMs must be an integer between 1 and 60000\");\n const v5Url = `${acrossApiUrl(config.baseUrl ?? ACROSS_API, \"baseUrl\")}/v1/quotes`;\n const feesUrl = config.suggestedFeesUrl === null ? null : acrossApiUrl(config.suggestedFeesUrl ?? ACROSS_SUGGESTED_FEES_URL, \"suggestedFeesUrl\");\n const rpcUrls: Readonly<Record<string, string>> = Object.freeze(Object.assign(Object.create(null) as Record<string, string>, config.rpcUrls ?? {}));\n for (const [chain, url] of Object.entries(rpcUrls)) {\n if (typeof url !== \"string\" || !/^https?:\\/\\//.test(url)) throw new Error(`across: the RPC URL for ${chain} must use http or https`);\n }\n const rpcFor = (caip2: string): AcrossRpc | undefined => (Object.prototype.hasOwnProperty.call(rpcUrls, caip2) ? acrossRpc(rpcUrls[caip2]!, config.fetchImpl) : undefined);\n\n /** The request a quote is checked against before a build or a signature: the one its `providerData` seals. */\n function requestOf(quote: Quote): AcrossRequest {\n const pd = quote.providerData ?? {};\n const sealed: AcrossRequest = {\n sourceChain: pd.sourceChain ?? \"\", destChain: pd.destChain ?? \"\", sourceToken: pd.sourceToken ?? \"\", destToken: pd.destToken ?? \"\",\n amount: /^[1-9]\\d{0,77}$/.test(pd.amount ?? \"\") ? BigInt(pd.amount!) : 0n,\n depositor: pd.depositor ?? \"\", recipient: pd.recipient ?? \"\",\n ...(/^\\d{1,78}$/.test(pd.minAmountOut ?? \"\") ? {minAmountOut: BigInt(pd.minAmountOut!)} : {}),\n ...(maxFeeBps !== undefined ? {maxFeeBps} : {}),\n };\n // A dry quote (pricing only) is never a deposit to sign, whatever addresses it was priced for.\n if (pd.placeholder === \"1\" || sealed.depositor.toLowerCase() === ACROSS_PLACEHOLDER.toLowerCase() || sealed.recipient.toLowerCase() === ACROSS_PLACEHOLDER.toLowerCase()) {\n throw new AcrossRefusal(\"request-invalid\", \"a quote priced for display (a dry quote) is never built or signed — quote again with the signing account\", \"policy_refused\");\n }\n return sealed;\n }\n\n /** `/suggested-fees` for a request, read; a failure is `unavailable`, never a throw (but the caller's own abort). */\n async function suggestedFees(request: AcrossRequest, route: AcrossRoute, signal: AbortSignal | undefined): Promise<AcrossSuggestedFees> {\n if (feesUrl === null) return {kind: \"unavailable\", detail: \"it is turned off\"};\n try {\n 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\"});\n return readAcrossSuggestedFees(request, route, a.status, a.body, Math.floor(Date.now() / 1000));\n } catch (err) {\n if (signal?.aborted) throw err;\n return {kind: \"unavailable\", detail: err instanceof Error ? err.message.replace(/^across: /, \"\") : \"no answer\"};\n }\n }\n\n /** The quote time without `/suggested-fees`: from the chains' latest blocks over the configured RPCs. */\n async function quoteTimeFromChains(route: AcrossRoute): Promise<number> {\n const eth = rpcFor(\"eip155:1\");\n const origin = rpcFor(route.input.chain.caip2);\n if (!eth || !origin) {\n 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\");\n }\n const timeOf = async (rpc: AcrossRpc): Promise<number> => {\n const block = (await rpc(\"eth_getBlockByNumber\", [\"latest\", false])) as {timestamp?: unknown} | null;\n const t = typeof block?.timestamp === \"string\" && /^0x[0-9a-fA-F]{1,10}$/.test(block.timestamp) ? parseInt(block.timestamp, 16) : NaN;\n if (!Number.isInteger(t) || t <= 0) throw new Error(\"no block time\");\n return t;\n };\n try {\n const [e, o] = await Promise.all([timeOf(eth), route.input.chain.chainId === 1 ? Promise.resolve(null) : timeOf(origin)]);\n return acrossQuoteTimeOf(e, o ?? e);\n } catch {\n 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\");\n }\n }\n\n return {\n name: \"across\",\n describeActivity: describeAcrossActivity,\n enabled: () => (config.enabled ?? true) && readKey(config.apiKey) !== undefined,\n supportsChain: (chain: string) => acrossCfg.supportsChain(chain),\n supportsChainPair: (from: string, to: string) => acrossCfg.supports(from, to),\n supportsRoute: (from: Asset, to: Asset) => acrossServesRoute(from, to),\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (reason: string, info?: Swap2RefusalInfo) => { params.onRefusal?.(reason, info); return null; };\n const dry = params.dry !== false;\n try {\n const request = acrossRequestOf(params, {\n ...(dry ? {placeholder: ACROSS_PLACEHOLDER} : {}),\n ...(maxFeeBps !== undefined ? {maxFeeBps} : {}),\n });\n const route = acrossRouteOf(request.sourceChain, request.sourceToken, request.destChain, request.destToken) as AcrossRoute;\n const key = readKey(config.apiKey);\n if (key === undefined) throw new AcrossRefusal(\"quote-unavailable\", \"no Across API key is configured — give the server's acrossProvider an apiKey, and run acrossRemoteProvider in the app\", \"key_rejected\");\n\n const [v5, fees] = await Promise.all([\n acrossHttp(v5Url, {\n method: \"POST\",\n headers: {accept: \"application/json\", \"content-type\": \"application/json\", authorization: `Bearer ${key}`},\n body: JSON.stringify(acrossV5QuoteRequest(request)),\n }, {fetchImpl: config.fetchImpl, timeoutMs, signal, what: \"Across API V5\"}),\n suggestedFees(request, route, signal),\n ]);\n if (v5.status < 200 || v5.status >= 300) {\n const e = parseAcrossV5Error(v5.status, v5.body, v5.retryAfter);\n const bound = e.amountLimit?.amount ? ` (the amount must be ${e.amountLimit.side === \"min\" ? \"at least\" : \"at most\"} ${e.amountLimit.amount} base units)` : \"\";\n throw new AcrossRefusal(\"api-error\", `Across API V5 answered HTTP ${e.status}${e.code ? ` ${e.code}` : \"\"}${bound}`, e.info?.reason);\n }\n const price = readAcrossV5Quote(request, route, v5.body);\n\n // What a relayer needs, and the quote time the deposit carries.\n if (fees.kind === \"refused\") throw new AcrossRefusal(\"relayer-price\", fees.detail, fees.reason);\n // V5 priced another rail (a fill estimate over a minute): its fee is no bound on a plain deposit, Across's\n // relayer fee alone prices it — and without that answer there is no price this module stands behind.\n const otherRail = acrossV5OtherRail(price.expectedFillTimeMs);\n if (otherRail && fees.kind !== \"fees\") {\n throw new AcrossRefusal(\"route-unpriced\", `Across API V5 prices this transfer on another rail (fill ~${Math.round(price.expectedFillTimeMs / 1000)} s), and Across's relayer fee quote did not answer (${fees.detail.slice(0, 120)}) — no price for a plain deposit`, \"upstream_unavailable\");\n }\n let need: bigint;\n let quoteTimestamp: number;\n let etaSec: number;\n if (fees.kind === \"fees\") {\n need = fees.totalRelayFee;\n quoteTimestamp = fees.timestamp;\n etaSec = fees.estimatedFillTimeSec;\n } else {\n need = acrossFloorFee(route, request.amount, price.amountUsd, price.destinationGas);\n quoteTimestamp = await quoteTimeFromChains(route);\n etaSec = price.expectedFillTimeMs / 1000;\n }\n const fee = acrossPlainFee(request.amount, price, need, otherRail);\n const nq: NormalizedAcrossQuote = {\n sourceChainId: route.input.chain.chainId,\n destinationChainId: route.output.chain.chainId,\n inputToken: request.sourceToken,\n outputToken: request.destToken,\n inputAmount: request.amount.toString(10),\n outputAmount: (request.amount - fee.fee).toString(10),\n quoteTimestamp,\n fillDeadline: quoteTimestamp + ACROSS_FILL_WINDOW_S,\n exclusiveRelayer: ACROSS_NATIVE,\n exclusivityParameter: 0,\n expectedFillTimeSec: etaSec,\n fees: {total: fee.fee.toString(10)},\n };\n const quote = acrossQuoteOf(request, nq, {quoteTtlMs, ...(dry ? {placeholder: true} : {})});\n // How the number was reached (display and support): the price source, V5's net fee, the relayer need.\n const priceSource = otherRail ? \"suggested-fees (V5 other rail)\" : fees.kind === \"fees\" ? \"suggested-fees\" : \"floor\";\n return {...quote, providerData: {...quote.providerData, priceSource, v5Fee: fee.f5.toString(10), relayerFee: fee.need.toString(10)}};\n } catch (err) {\n if (err instanceof AcrossRefusal) return refuse(err.message, refusalOf(err));\n throw err;\n }\n },\n\n /** The quote's own transaction — after the deposit it carries has been verified once more. */\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n if (!tx || !parseAcrossIntentId(quote.intentId)) throw refusal(\"policy_refused\", \"swap2: Across quote has no transaction request\");\n const request = requestOf(quote);\n const v = checkAcrossQuote(request, quote);\n return {\n chain: request.sourceChain,\n to: v.deposit.to,\n value: v.deposit.value,\n data: v.deposit.data,\n chainId: v.deposit.chainId,\n ...(tx.gasLimit ? {gasLimit: tx.gasLimit} : {}),\n ...(v.deposit.approvalAddress ? {approvalAddress: v.deposit.approvalAddress} : {}),\n };\n },\n\n /** Right before signing: the whole verification again, against the request and the exact transaction about to be signed. */\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n const request = requestOf(quote);\n if (tx.chain !== request.sourceChain) throw new AcrossRefusal(\"tx-chain\", `the deposit is for ${tx.chain}, not ${request.sourceChain}`, \"vault_mismatch\");\n checkAcrossTxShape(tx);\n checkAcrossQuote(request, quote, tx);\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n const intent = parseAcrossIntentId(ref.intentId);\n if (!intent) return {state: \"failed\"};\n const source = acrossChain(`eip155:${intent.sourceChainId}`);\n const dest = acrossChain(`eip155:${intent.destChainId}`);\n if (!source || !dest || source === dest) return {state: \"failed\"};\n // Nothing was sent yet.\n if (!ref.sourceTxHash) return {state: \"pending\"};\n const sourceRpc = rpcFor(source.caip2);\n const destRpc = rpcFor(dest.caip2);\n const t = await trackAcrossDeposit({sourceTxHash: ref.sourceTxHash, intentDigest: intent.digest, source, dest, ...(sourceRpc ? {sourceRpc} : {}), ...(destRpc ? {destRpc} : {})});\n return t.status;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAQ,SAAS,iBAAuC;AACxD,SAAQ,eAAc;AAqCtB,IAAM,UAAU;AAChB,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAsC7B,SAAS,QAAQ,QAA4D;AAC3E,MAAI,MAAe;AACnB,MAAI,OAAO,WAAW,YAAY;AAChC,QAAI;AACF,YAAM,OAAO;AAAA,IACf,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO,OAAO,QAAQ,YAAY,uBAAuB,KAAK,GAAG,IAAI,MAAM;AAC7E;AAMA,SAAS,gBAAyB;AAChC,QAAM,IAAI;AACV,SAAO,EAAE,mBAAmB,UAAa,EAAE,WAAW,YAAY;AACpE;AAOO,SAAS,kBAAkB,MAAa,IAAoB;AACjE,MAAI,CAAC,OAAU,SAAS,KAAK,OAAO,GAAG,KAAK,EAAG,QAAO;AACtD,MAAI;AACJ,MAAI,QAAQ,KAAK,KAAK,KAAK,EAAG,SAAQ,KAAK;AAAA,OACtC;AACH,UAAM,QAAQ,QAAQ,KAAK,OAAO,KAAK,KAAK;AAC5C,QAAI,CAAC,MAAO,QAAO;AACnB,YAAQ,MAAM,YAAY;AAAA,EAC5B;AACA,QAAM,QAAQ,cAAc,KAAK,OAAO,OAAO,GAAG,OAAO,GAAG,KAAK;AACjE,SAAO,EAAE,UAAU,UAAU,oBAAoB,KAAK,MAAM;AAC9D;AAEO,SAAS,eAAe,SAA+B,CAAC,GAAuB;AACpF,WAAS,OAAO,OAAO,E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AEhE,UAAI,CAAC,IAAI,aAAc,QAAO,EAAC,OAAO,UAAS;AAC/C,YAAM,YAAY,OAAO,OAAO,KAAK;AACrC,YAAM,UAAU,OAAO,KAAK,KAAK;AACjC,YAAM,IAAI,MAAM,mBAAmB,EAAC,cAAc,IAAI,cAAc,cAAc,OAAO,QAAQ,QAAQ,MAAM,GAAI,YAAY,EAAC,UAAS,IAAI,CAAC,GAAI,GAAI,UAAU,EAAC,QAAO,IAAI,CAAC,EAAE,CAAC;AAChL,aAAO,EAAE;AAAA,IACX;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,138 @@
1
+ import {
2
+ ACROSS_MAX_QUOTE_LIFE_MS,
3
+ acrossIntentId,
4
+ acrossQuoteFeesOf,
5
+ acrossQuoteTimeLimitMs,
6
+ checkAcrossRequest,
7
+ verifyAcrossDeposit
8
+ } from "./chunk-KATEONJQ.js";
9
+ import {
10
+ encodeAcrossDeposit
11
+ } from "./chunk-32YJEBZX.js";
12
+ import {
13
+ AcrossRefusal
14
+ } from "./chunk-E5WFOPN2.js";
15
+
16
+ // src/build.ts
17
+ var UINT = /^(?:0|[1-9]\d{0,77})$/;
18
+ var ADDRESS = /^0x[0-9a-fA-F]{40}$/;
19
+ var U32_MAX = 4294967295;
20
+ function checkNormalized(request, q, sourceChainId, destChainId) {
21
+ const bad = (what) => {
22
+ throw new AcrossRefusal("quote-normalized", `the quote ${what}`, "upstream_unavailable");
23
+ };
24
+ if (q === null || typeof q !== "object") bad("is missing");
25
+ if (q.sourceChainId !== sourceChainId || q.destinationChainId !== destChainId) {
26
+ throw new AcrossRefusal("quote-normalized", `the quote is for ${String(q.sourceChainId)} \u2192 ${String(q.destinationChainId)}, the request for ${sourceChainId} \u2192 ${destChainId}`, "policy_refused");
27
+ }
28
+ for (const [k, v] of [["input token", q.inputToken], ["output token", q.outputToken], ["exclusive relayer", q.exclusiveRelayer]]) {
29
+ if (typeof v !== "string" || !ADDRESS.test(v)) bad(`names a ${k} that is not an address`);
30
+ }
31
+ if (q.inputToken.toLowerCase() !== request.sourceToken.toLowerCase() || q.outputToken.toLowerCase() !== request.destToken.toLowerCase()) {
32
+ throw new AcrossRefusal("quote-normalized", "the quote is for other tokens than the request", "policy_refused");
33
+ }
34
+ for (const [k, v] of [["input amount", q.inputAmount], ["output amount", q.outputAmount]]) {
35
+ if (typeof v !== "string" || !UINT.test(v)) bad(`states an ${k} that is not a base-unit integer`);
36
+ }
37
+ if (BigInt(q.inputAmount) !== request.amount) throw new AcrossRefusal("quote-normalized", `the quote sends ${q.inputAmount}, the request ${request.amount}`, "policy_refused");
38
+ if (q.expectedOutputAmount !== void 0 && (typeof q.expectedOutputAmount !== "string" || !UINT.test(q.expectedOutputAmount))) bad("states an expected output that is not a base-unit integer");
39
+ if (q.expectedOutputAmount !== void 0 && BigInt(q.expectedOutputAmount) > BigInt(q.outputAmount)) {
40
+ 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");
41
+ }
42
+ for (const [k, v] of [["quote time", q.quoteTimestamp], ["fill deadline", q.fillDeadline], ["exclusivity", q.exclusivityParameter]]) {
43
+ if (!Number.isInteger(v) || v < 0 || v > U32_MAX) bad(`states a ${k} that is not a uint32`);
44
+ }
45
+ if (!Number.isFinite(q.expectedFillTimeSec) || q.expectedFillTimeSec < 0) bad("states no fill time");
46
+ if (q.expiresAtMs !== void 0 && (!Number.isFinite(q.expiresAtMs) || q.expiresAtMs <= 0)) bad("states an expiry that is not a time");
47
+ 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");
48
+ const f = q.fees;
49
+ if (f !== void 0) {
50
+ if (f === null || typeof f !== "object" || typeof f.total !== "string" || !UINT.test(f.total)) bad("itemizes fees without a total");
51
+ for (const v of [f.relayerCapital, f.destinationGas, f.lp]) if (v !== void 0 && (typeof v !== "string" || !UINT.test(v))) bad("itemizes a fee that is not a base-unit integer");
52
+ if (f.totalUsd !== void 0 && (!Number.isFinite(f.totalUsd) || f.totalUsd < 0)) bad("prices its fees in a number that is not a price");
53
+ if (BigInt(q.outputAmount) <= BigInt(q.inputAmount) && BigInt(f.total) !== BigInt(q.inputAmount) - BigInt(q.outputAmount)) {
54
+ throw new AcrossRefusal("quote-normalized", "the quote's fee total is not its input minus its output", "price_check_failed");
55
+ }
56
+ }
57
+ }
58
+ function buildAcrossDeposit(request, quote) {
59
+ const { route } = checkAcrossRequest(request);
60
+ const src = route.input.chain;
61
+ const dst = route.output.chain;
62
+ checkNormalized(request, quote, src.chainId, dst.chainId);
63
+ const data = encodeAcrossDeposit({
64
+ depositor: request.depositor.toLowerCase(),
65
+ recipient: request.recipient.toLowerCase(),
66
+ inputToken: route.input.token,
67
+ outputToken: route.output.token,
68
+ inputAmount: request.amount,
69
+ outputAmount: BigInt(quote.outputAmount),
70
+ destinationChainId: BigInt(dst.chainId),
71
+ exclusiveRelayer: quote.exclusiveRelayer.toLowerCase(),
72
+ quoteTimestamp: quote.quoteTimestamp,
73
+ fillDeadline: quote.fillDeadline,
74
+ exclusivityParameter: quote.exclusivityParameter,
75
+ message: "0x"
76
+ });
77
+ return verifyAcrossDeposit(request, {
78
+ to: src.spokePool,
79
+ data,
80
+ value: route.input.native ? request.amount.toString(10) : "0",
81
+ chainId: src.chainId,
82
+ ...route.input.native ? {} : { approvalAddress: src.spokePool }
83
+ });
84
+ }
85
+ function acrossQuoteOf(request, quote, opts = {}) {
86
+ const v = buildAcrossDeposit(request, quote);
87
+ const ttl = opts.quoteTtlMs ?? 6e4;
88
+ if (!Number.isInteger(ttl) || ttl <= 0 || ttl > 3e5) throw new AcrossRefusal("request-invalid", "quoteTtlMs must be an integer between 1 and 300000");
89
+ const now = request.nowMs ?? Date.now();
90
+ const validUntilMs = Math.min(now + ttl, now + ACROSS_MAX_QUOTE_LIFE_MS, quote.expiresAtMs ?? Number.POSITIVE_INFINITY, acrossQuoteTimeLimitMs(v.args.quoteTimestamp));
91
+ const reliability = opts.reliability ?? 0.97;
92
+ return {
93
+ provider: "across",
94
+ intentId: acrossIntentId(v.route.input.chain.chainId, v.route.output.chain.chainId, v.deposit.data),
95
+ depositAddress: "",
96
+ depositMemo: null,
97
+ txRequest: {
98
+ to: v.deposit.to,
99
+ data: v.deposit.data,
100
+ value: v.deposit.value,
101
+ chainId: v.deposit.chainId,
102
+ ...v.deposit.approvalAddress ? { approvalAddress: v.deposit.approvalAddress } : {}
103
+ },
104
+ sourceAmount: v.args.inputAmount.toString(10),
105
+ destAmount: v.args.outputAmount.toString(10),
106
+ minDestAmount: v.args.outputAmount.toString(10),
107
+ destDecimals: v.route.output.decimals,
108
+ ...acrossQuoteFeesOf(v.route, v.fee),
109
+ etaSeconds: Math.min(Math.max(Math.ceil(quote.expectedFillTimeSec), 1), 86400),
110
+ reliability: Number.isFinite(reliability) && reliability >= 0 && reliability <= 1 ? reliability : 0.97,
111
+ validUntilMs,
112
+ providerData: {
113
+ sourceChain: request.sourceChain,
114
+ destChain: request.destChain,
115
+ sourceToken: request.sourceToken.toLowerCase(),
116
+ destToken: request.destToken.toLowerCase(),
117
+ amount: request.amount.toString(10),
118
+ depositor: request.depositor.toLowerCase(),
119
+ recipient: request.recipient.toLowerCase(),
120
+ outputAmount: v.args.outputAmount.toString(10),
121
+ quoteTimestamp: String(v.args.quoteTimestamp),
122
+ fillDeadline: String(v.args.fillDeadline),
123
+ exclusiveRelayer: v.args.exclusiveRelayer,
124
+ exclusivityParameter: String(v.args.exclusivityParameter),
125
+ ...request.minAmountOut !== void 0 ? { minAmountOut: request.minAmountOut.toString(10) } : {},
126
+ ...request.maxFeeBps !== void 0 ? { maxFeeBps: String(request.maxFeeBps) } : {},
127
+ ...quote.expectedOutputAmount !== void 0 ? { expectedOutputAmount: quote.expectedOutputAmount } : {},
128
+ ...quote.orderId !== void 0 ? { orderId: quote.orderId } : {},
129
+ ...opts.placeholder ? { placeholder: "1" } : {}
130
+ }
131
+ };
132
+ }
133
+
134
+ export {
135
+ buildAcrossDeposit,
136
+ acrossQuoteOf
137
+ };
138
+ //# sourceMappingURL=chunk-SJOFLM27.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/build.ts"],"sourcesContent":["/**\n * The deposit, built on the device.\n *\n * A quote source (`provider.ts`, priced by `pricing.ts` from the Across APIs) only supplies NUMBERS: how much the deposit asks relayers\n * to pay, the quote time, the fill deadline and the exclusivity terms. Everything that decides where the money goes —\n * the SpokePool, the depositor, the recipient, the tokens, the destination chain, the message — comes from the user's\n * request and the pins in `config.ts`. {@link buildAcrossDeposit} encodes the call from those and runs\n * {@link verifyAcrossDeposit} on its own result before handing it out, so a deposit leaves this file only in the shape\n * the verifier signs.\n */\nimport type {Quote} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {encodeAcrossDeposit} from \"./deposit.js\";\nimport {AcrossRefusal} from \"./refusal.js\";\nimport {\n ACROSS_MAX_QUOTE_LIFE_MS, acrossIntentId, acrossQuoteFeesOf, acrossQuoteTimeLimitMs, checkAcrossRequest, verifyAcrossDeposit, type AcrossRequest,\n type VerifiedAcrossDeposit,\n} from \"./verify.js\";\n\n/**\n * What a quote source must say about one Across transfer, normalized from whatever it answers. Integers that can\n * exceed 2^53 are canonical decimal strings (no sign, no leading zeros); times are unix seconds. Tokens are named as\n * in the request — the ERC-20 contract, or the zero address for the native coin — never as the deposit names them.\n */\nexport interface NormalizedAcrossQuote {\n /** EVM chain id the deposit is sent on. */\n sourceChainId: number;\n /** EVM chain id the output is paid on. */\n destinationChainId: number;\n /** Input token: ERC-20 contract, or the zero address for the native coin. */\n inputToken: string;\n /** Output token: ERC-20 contract, or the zero address for the native coin. */\n outputToken: string;\n /** Exact input, base units (decimal string). */\n inputAmount: string;\n /**\n * What the deposit asks relayers to pay the recipient, base units (decimal string). A relayer pays exactly this, so\n * it is both the expected and the guaranteed output of the transfer.\n */\n outputAmount: string;\n /** The quote source's own estimate of what arrives, when it gives one (display only; above `outputAmount` it is refused). */\n expectedOutputAmount?: string;\n /** The deposit's `quoteTimestamp` (unix seconds). The SpokePool accepts it for 3600 s. */\n quoteTimestamp: number;\n /** The deposit's `fillDeadline` (unix seconds, destination chain). Unfilled by then, the deposit is refunded. */\n fillDeadline: number;\n /** The relayer that alone may fill until the exclusivity ends; the zero address for none. */\n exclusiveRelayer: string;\n /** 0 (no exclusivity), an offset in seconds up to one year from the deposit's block, or a unix timestamp above that. */\n exclusivityParameter: number;\n /** Expected time from deposit to fill, seconds (display only). */\n expectedFillTimeSec: number;\n /** When the quote source stops standing by the numbers (unix ms), when it says. */\n expiresAtMs?: number;\n /** The quote source's breakdown of input − output (display only; must add up to it when given). */\n fees?: AcrossFeeBreakdown;\n /** The quote source's own id for the transfer (Across API V5 `orderId`), kept for its status endpoint. */\n orderId?: string;\n}\n\n/** Fees of one transfer, in base units of the input token. */\nexport interface AcrossFeeBreakdown {\n /** input − output. */\n total: string;\n /** Relayer capital fee, when itemized. */\n relayerCapital?: string;\n /** Destination gas the relayer is paid for, when itemized (in input-token units). */\n destinationGas?: string;\n /** LP fee, when itemized. */\n lp?: string;\n /** The total in USD, when the quote source prices it. Checked as a number and never shown: `feeUsd` is the verified fee's own. */\n totalUsd?: number;\n}\n\nconst UINT = /^(?:0|[1-9]\\d{0,77})$/;\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst U32_MAX = 0xffff_ffff;\n\nfunction checkNormalized(request: AcrossRequest, q: NormalizedAcrossQuote, sourceChainId: number, destChainId: number): void {\n const bad = (what: string): never => { throw new AcrossRefusal(\"quote-normalized\", `the quote ${what}`, \"upstream_unavailable\"); };\n if (q === null || typeof q !== \"object\") bad(\"is missing\");\n if (q.sourceChainId !== sourceChainId || q.destinationChainId !== destChainId) {\n throw new AcrossRefusal(\"quote-normalized\", `the quote is for ${String(q.sourceChainId)} → ${String(q.destinationChainId)}, the request for ${sourceChainId} → ${destChainId}`, \"policy_refused\");\n }\n for (const [k, v] of [[\"input token\", q.inputToken], [\"output token\", q.outputToken], [\"exclusive relayer\", q.exclusiveRelayer]] as const) {\n if (typeof v !== \"string\" || !ADDRESS.test(v)) bad(`names a ${k} that is not an address`);\n }\n if (q.inputToken.toLowerCase() !== request.sourceToken.toLowerCase() || q.outputToken.toLowerCase() !== request.destToken.toLowerCase()) {\n throw new AcrossRefusal(\"quote-normalized\", \"the quote is for other tokens than the request\", \"policy_refused\");\n }\n for (const [k, v] of [[\"input amount\", q.inputAmount], [\"output amount\", q.outputAmount]] as const) {\n if (typeof v !== \"string\" || !UINT.test(v)) bad(`states an ${k} that is not a base-unit integer`);\n }\n if (BigInt(q.inputAmount) !== request.amount) throw new AcrossRefusal(\"quote-normalized\", `the quote sends ${q.inputAmount}, the request ${request.amount}`, \"policy_refused\");\n if (q.expectedOutputAmount !== undefined && (typeof q.expectedOutputAmount !== \"string\" || !UINT.test(q.expectedOutputAmount))) bad(\"states an expected output that is not a base-unit integer\");\n // A relayer pays exactly the output amount: an estimate above it is a number nothing pays.\n if (q.expectedOutputAmount !== undefined && BigInt(q.expectedOutputAmount) > BigInt(q.outputAmount)) {\n 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\");\n }\n for (const [k, v] of [[\"quote time\", q.quoteTimestamp], [\"fill deadline\", q.fillDeadline], [\"exclusivity\", q.exclusivityParameter]] as const) {\n if (!Number.isInteger(v) || v < 0 || v > U32_MAX) bad(`states a ${k} that is not a uint32`);\n }\n if (!Number.isFinite(q.expectedFillTimeSec) || q.expectedFillTimeSec < 0) bad(\"states no fill time\");\n if (q.expiresAtMs !== undefined && (!Number.isFinite(q.expiresAtMs) || q.expiresAtMs <= 0)) bad(\"states an expiry that is not a time\");\n if (q.orderId !== undefined && (typeof q.orderId !== \"string\" || !/^[\\x21-\\x7e]{1,128}$/.test(q.orderId))) bad(\"carries an order id that is not printable\");\n const f = q.fees;\n if (f !== undefined) {\n if (f === null || typeof f !== \"object\" || typeof f.total !== \"string\" || !UINT.test(f.total)) bad(\"itemizes fees without a total\");\n for (const v of [f.relayerCapital, f.destinationGas, f.lp]) if (v !== undefined && (typeof v !== \"string\" || !UINT.test(v))) bad(\"itemizes a fee that is not a base-unit integer\");\n if (f.totalUsd !== undefined && (!Number.isFinite(f.totalUsd) || f.totalUsd < 0)) bad(\"prices its fees in a number that is not a price\");\n if (BigInt(q.outputAmount) <= BigInt(q.inputAmount) && BigInt(f.total) !== BigInt(q.inputAmount) - BigInt(q.outputAmount)) {\n throw new AcrossRefusal(\"quote-normalized\", \"the quote's fee total is not its input minus its output\", \"price_check_failed\");\n }\n }\n}\n\n/**\n * The deposit for a request and a quote's numbers, built from the pins and verified ({@link verifyAcrossDeposit}) before\n * it is returned. Throws {@link AcrossRefusal}.\n */\nexport function buildAcrossDeposit(request: AcrossRequest, quote: NormalizedAcrossQuote): VerifiedAcrossDeposit {\n // The route first: it is what the quote's chains and tokens are compared with.\n const {route} = checkAcrossRequest(request);\n const src = route.input.chain;\n const dst = route.output.chain;\n checkNormalized(request, quote, src.chainId, dst.chainId);\n const data = encodeAcrossDeposit({\n depositor: request.depositor.toLowerCase(),\n recipient: request.recipient.toLowerCase(),\n inputToken: route.input.token,\n outputToken: route.output.token,\n inputAmount: request.amount,\n outputAmount: BigInt(quote.outputAmount),\n destinationChainId: BigInt(dst.chainId),\n exclusiveRelayer: quote.exclusiveRelayer.toLowerCase(),\n quoteTimestamp: quote.quoteTimestamp,\n fillDeadline: quote.fillDeadline,\n exclusivityParameter: quote.exclusivityParameter,\n message: \"0x\",\n });\n return verifyAcrossDeposit(request, {\n to: src.spokePool,\n data,\n value: route.input.native ? request.amount.toString(10) : \"0\",\n chainId: src.chainId,\n ...(route.input.native ? {} : {approvalAddress: src.spokePool}),\n });\n}\n\n/** Options for {@link acrossQuoteOf}. */\nexport interface AcrossQuoteOptions {\n /** Local lifetime of the quote, ms (default 60 s, at most 5 min). */\n quoteTtlMs?: number;\n /** The quote was priced for a placeholder address: never built or signed. */\n placeholder?: boolean;\n /** Reliability hint for the router, 0..1 (default 0.97). */\n reliability?: number;\n}\n\n/**\n * A swap2 `Quote` for a request and a quote source's numbers: the deposit is built here (and verified), the amounts it\n * shows are the deposit's, and `providerData` seals the request and the numbers so the same deposit can be rebuilt and\n * checked again before a build and a signature. `fees` and `feeUsd` are the verified fee's own ({@link acrossQuoteFeesOf})\n * — never the quote source's figures — and `validUntilMs` ends while the SpokePool still takes the quote time.\n */\nexport function acrossQuoteOf(request: AcrossRequest, quote: NormalizedAcrossQuote, opts: AcrossQuoteOptions = {}): Quote {\n const v = buildAcrossDeposit(request, quote);\n const ttl = opts.quoteTtlMs ?? 60_000;\n if (!Number.isInteger(ttl) || ttl <= 0 || ttl > 300_000) throw new AcrossRefusal(\"request-invalid\", \"quoteTtlMs must be an integer between 1 and 300000\");\n const now = request.nowMs ?? Date.now();\n // Never past the moment the SpokePool stops taking the deposit's quote time (with time to land).\n const validUntilMs = Math.min(now + ttl, now + ACROSS_MAX_QUOTE_LIFE_MS, quote.expiresAtMs ?? Number.POSITIVE_INFINITY, acrossQuoteTimeLimitMs(v.args.quoteTimestamp));\n const reliability = opts.reliability ?? 0.97;\n return {\n provider: \"across\",\n intentId: acrossIntentId(v.route.input.chain.chainId, v.route.output.chain.chainId, v.deposit.data),\n depositAddress: \"\",\n depositMemo: null,\n txRequest: {\n to: v.deposit.to,\n data: v.deposit.data,\n value: v.deposit.value,\n chainId: v.deposit.chainId,\n ...(v.deposit.approvalAddress ? {approvalAddress: v.deposit.approvalAddress} : {}),\n },\n sourceAmount: v.args.inputAmount.toString(10),\n destAmount: v.args.outputAmount.toString(10),\n minDestAmount: v.args.outputAmount.toString(10),\n destDecimals: v.route.output.decimals,\n ...acrossQuoteFeesOf(v.route, v.fee),\n etaSeconds: Math.min(Math.max(Math.ceil(quote.expectedFillTimeSec), 1), 86_400),\n reliability: Number.isFinite(reliability) && reliability >= 0 && reliability <= 1 ? reliability : 0.97,\n validUntilMs,\n providerData: {\n sourceChain: request.sourceChain,\n destChain: request.destChain,\n sourceToken: request.sourceToken.toLowerCase(),\n destToken: request.destToken.toLowerCase(),\n amount: request.amount.toString(10),\n depositor: request.depositor.toLowerCase(),\n recipient: request.recipient.toLowerCase(),\n outputAmount: v.args.outputAmount.toString(10),\n quoteTimestamp: String(v.args.quoteTimestamp),\n fillDeadline: String(v.args.fillDeadline),\n exclusiveRelayer: v.args.exclusiveRelayer,\n exclusivityParameter: String(v.args.exclusivityParameter),\n ...(request.minAmountOut !== undefined ? {minAmountOut: request.minAmountOut.toString(10)} : {}),\n ...(request.maxFeeBps !== undefined ? {maxFeeBps: String(request.maxFeeBps)} : {}),\n ...(quote.expectedOutputAmount !== undefined ? {expectedOutputAmount: quote.expectedOutputAmount} : {}),\n ...(quote.orderId !== undefined ? {orderId: quote.orderId} : {}),\n ...(opts.placeholder ? {placeholder: \"1\"} : {}),\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyEA,IAAM,OAAO;AACb,IAAM,UAAU;AAChB,IAAM,UAAU;AAEhB,SAAS,gBAAgB,SAAwB,GAA0B,eAAuB,aAA2B;AAC3H,QAAM,MAAM,CAAC,SAAwB;AAAE,UAAM,IAAI,cAAc,oBAAoB,aAAa,IAAI,IAAI,sBAAsB;AAAA,EAAG;AACjI,MAAI,MAAM,QAAQ,OAAO,MAAM,SAAU,KAAI,YAAY;AACzD,MAAI,EAAE,kBAAkB,iBAAiB,EAAE,uBAAuB,aAAa;AAC7E,UAAM,IAAI,cAAc,oBAAoB,oBAAoB,OAAO,EAAE,aAAa,CAAC,WAAM,OAAO,EAAE,kBAAkB,CAAC,qBAAqB,aAAa,WAAM,WAAW,IAAI,gBAAgB;AAAA,EAClM;AACA,aAAW,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,eAAe,EAAE,UAAU,GAAG,CAAC,gBAAgB,EAAE,WAAW,GAAG,CAAC,qBAAqB,EAAE,gBAAgB,C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