@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 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/protocol.ts","../src/config.ts","../src/provider.ts","../src/activity.ts","../src/api.ts","../src/refusal.ts","../src/deposit.ts","../src/verify.ts","../src/pricing.ts","../src/build.ts","../src/status.ts"],"sourcesContent":["import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {across as acrossCfg} from \"./config.js\";\nimport {acrossProvider, type AcrossProviderConfig} from \"./provider.js\";\n\nexport interface AcrossSwap2Config extends Swap2EngineConfig, AcrossProviderConfig {}\n\n/**\n * Standalone Across swap2: EVM → EVM through the source chain's SpokePool, every deposit built and verified on the\n * device. Quoting needs the Across API V5 key, so this class quotes only on a server (`apiKey`); an app uses\n * `acrossRemoteProvider` in a router instead.\n */\nexport class AcrossSwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n constructor(account: Swap2Account | undefined, config: AcrossSwap2Config) {\n super(account, config);\n this.provider = acrossProvider(config);\n }\n protected override chainSupported(caip2: string): boolean {\n return acrossCfg.supportsChain(caip2);\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return acrossCfg.supports(fromChain, toChain);\n }\n}\n","// Across Protocol — the pins this module signs against. Nothing here is read from an API at run time: the Across API\n// (or an app's own proxy in front of it) is untrusted, and a deposit is signed only for a SpokePool, a chain and a\n// token written in this file.\n//\n// Sources, all read on 2026-11-15:\n// - github.com/across-protocol/contracts @ d652689f67cd9835b9c1ab0acc2f99236902e299, `broadcast/deployed-addresses.json`\n// (\"the current source of truth for deployed contract addresses\", deployments/README.md): `chains.<id>.contracts.\n// SpokePool.address` for every row below, `chains.1.contracts.HubPool.address` for the hub.\n// - On chain, Ethereum: `HubPool.crossChainContracts(chainId)` (selector 0x09474ae2) answers the same SpokePool for\n// every row (publicnode, block 26415696; eth.drpc.org one block later agreed on every row).\n// - On chain, each row over a public RPC: `eth_chainId` and the SpokePool's own `chainId()` are the row's id; the\n// EIP-1967 implementation slot is set (UUPS proxy, upgraded through the HubPool); `crossDomainAdmin()` is the\n// HubPool; `wrappedNativeToken()` is the value pinned below; `depositQuoteTimeBuffer()` = 3600,\n// `fillDeadlineBuffer()` = 21600 and `pausedDeposits()` = false. The implementation carries the `deposit` selector\n// as PUSH4 on every EVM-bytecode chain. zkSync Era runs EraVM bytecode, where that scan does not apply: there a real\n// deposit was traced instead (tx 0x21c702af…f0d96, `debug_traceTransaction` callTracer): a successful call into the\n// SpokePool with selector 0xad5425c6, 420 bytes (empty message), which emitted FundsDeposited.\n// - The contract: contracts/spoke-pools/SpokePool.sol and contracts/interfaces/V3SpokePoolInterface.sol at the same\n// commit (selectors, event, relay hash, fill statuses, the native-coin rules quoted where they are used).\n// - Tokens: Across's own route list (`GET /available-routes`) and token list (`GET /swap/tokens`), read 2026-11-14,\n// intersected with the SDK's asset catalog (`@anywalletkit/swap2-assets`) by address. A token is pinned only when\n// Across bridges it to the SAME asset on another pinned chain with the same decimals; routes Across lists between\n// different assets (USDC → USDC.e, USDC-BNB → USDC, USDT → USDC, USDG → USDC) are not served.\n//\n// Chains Across serves that are NOT pinned, and why:\n// - Scroll (534352): `pausedDeposits()` is true on chain (as on Lens, Mode and Zora, which the SDK does not carry) and\n// it is gone from Across's own chain page.\n// - BNB Chain (56): Across bridges its Binance-Peg USDC and USDT (18 decimals) only into other assets, and its ETH is an\n// ERC-20 the catalog does not list — no same-asset route is left.\n// - Lisk, Soneium, Tempo, Blast, Boba, Solana, Tron, HyperCore, Lighter: not EVM chains of the SDK's catalog.\n// SDK chains Across does not serve: Gnosis, Sonic, Berachain, Celo, Mantle, Katana, Morph, Flare, Elysium, Sei, Plume,\n// X Layer.\n\n/** What a token is across chains. A deposit only ever moves an asset to the same asset. */\nexport type AcrossAsset = \"USDC\" | \"USDT\" | \"ETH\" | \"WBTC\";\n\nexport interface AcrossToken {\n asset: AcrossAsset;\n /** ERC-20 contract on this chain, lowercase. */\n address: string;\n /** The catalog's symbol on this chain (Tether's USDT is `USDT0` where it is issued as USDT0). */\n symbol: string;\n decimals: number;\n}\n\nexport interface AcrossChain {\n caip2: string;\n chainId: number;\n /** The SDK's chain key (`@anywalletkit/swap2-assets`). */\n key: string;\n name: string;\n /** SpokePool proxy on that chain: the only contract a deposit calls and the only spender an approval names. */\n spokePool: string;\n /**\n * `wrappedNativeToken()` of that SpokePool. A deposit that sends the native coin names it as `inputToken`; a fill of\n * it is paid out as the native coin to an EOA. Null where the SpokePool reports the zero address (Arc).\n */\n wrappedNative: string | null;\n /** The chain's native coin is ether, bridged as the ETH asset. */\n nativeIsEth: boolean;\n /** ERC-20s Across bridges to the same asset on another pinned chain. ETH's ERC-20 is the wrapped native token. */\n tokens: readonly AcrossToken[];\n}\n\nconst USDC = (address: string, symbol = \"USDC\"): AcrossToken => Object.freeze({asset: \"USDC\", address, symbol, decimals: 6});\nconst USDT = (address: string, symbol = \"USDT\"): AcrossToken => Object.freeze({asset: \"USDT\", address, symbol, decimals: 6});\nconst WETH = (address: string): AcrossToken => Object.freeze({asset: \"ETH\", address, symbol: \"WETH\", decimals: 18});\nconst WBTC = (address: string): AcrossToken => Object.freeze({asset: \"WBTC\", address, symbol: \"WBTC\", decimals: 8});\n\n/** The OP-stack predeploy WETH9. */\nconst OP_WETH = \"0x4200000000000000000000000000000000000006\";\n\nfunction chain(\n chainId: number, key: string, name: string, spokePool: string, wrappedNative: string | null, nativeIsEth: boolean, tokens: AcrossToken[],\n): AcrossChain {\n return Object.freeze({caip2: `eip155:${chainId}`, chainId, key, name, spokePool, wrappedNative, nativeIsEth, tokens: Object.freeze(tokens)});\n}\n\n/** CAIP-2 → the chain as Across serves it. A null-prototype map: `ACROSS_CHAINS[\"constructor\"]` is undefined. */\nexport const ACROSS_CHAINS: Readonly<Record<string, AcrossChain>> = Object.freeze(Object.assign(Object.create(null) as Record<string, AcrossChain>, Object.fromEntries([\n chain(1, \"ethereum\", \"Ethereum\", \"0x5c7bcd6e7de5423a257d81b442095a1a6ced35c5\", \"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\", true, [\n USDC(\"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\"),\n USDT(\"0xdac17f958d2ee523a2206206994597c13d831ec7\"),\n WETH(\"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2\"),\n WBTC(\"0x2260fac5e5542a773aa44fbcfedf7c193bc2c599\"),\n ]),\n chain(10, \"optimism\", \"Optimism\", \"0x6f26bf09b1c792e3228e5467807a900a503c0281\", OP_WETH, true, [\n USDC(\"0x0b2c639c533813f4aa9d7837caf62653d097ff85\"),\n USDT(\"0x94b008aa00579c1307b0ef2c499ad98a8ce58e58\"),\n WETH(OP_WETH),\n ]),\n chain(130, \"unichain\", \"Unichain\", \"0x09aea4b2242abc8bb4bb78d537a67a245a7bec64\", OP_WETH, true, [\n USDC(\"0x078d782b760474a361dda0af3839290b0ef57ad6\"),\n USDT(\"0x9151434b16b9763660705744891fa906f660ecc5\", \"USDT0\"),\n WETH(OP_WETH),\n ]),\n chain(137, \"polygon\", \"Polygon\", \"0x9295ee1d8c5b022be115a2ad3c30c72e34e7f096\", \"0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270\", false, [\n USDC(\"0x3c499c542cef5e3811e1192ce70d8cc03d5c3359\"),\n USDT(\"0xc2132d05d31c914a87c6611c10748aeb04b58e8f\"),\n WBTC(\"0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6\"),\n ]),\n chain(143, \"monad\", \"Monad\", \"0xd2ecb3afe598b746f8123cae365a598da831a449\", \"0x3bd359c1119da7da1d913d1c4d2b7c461115433a\", false, [\n USDC(\"0x754704bc059f8c67012fed69bc8a327a5aafb603\"),\n USDT(\"0xe7cd86e13ac4309349f30b3435a9d337750fc82d\", \"USDT0\"),\n ]),\n chain(324, \"zksync\", \"zkSync Era\", \"0xe0b015e54d54fc84a6cb9b666099c46ade9335ff\", \"0x5aea5775959fbc2557cc8789bc1bf90a239d9a91\", true, [\n USDT(\"0x493257fd37edb34451f62edf8d2a0c418852ba4c\"),\n WETH(\"0x5aea5775959fbc2557cc8789bc1bf90a239d9a91\"),\n WBTC(\"0xbbeb516fb02a01611cbbe0453fe3c580d7281011\"),\n ]),\n chain(480, \"worldchain\", \"World Chain\", \"0x09aea4b2242abc8bb4bb78d537a67a245a7bec64\", OP_WETH, true, [\n USDC(\"0x79a02482a880bce3f13e09da970dc34db4cd24d1\"),\n WETH(OP_WETH),\n WBTC(\"0x03c7054bcb39f7b2e5b2c7acb37583e32d70cfa3\"),\n ]),\n chain(999, \"hyperevm\", \"HyperEVM\", \"0x35e63ea3eb0fb7a3bc543c71fb66412e1f6b0e04\", \"0x5555555555555555555555555555555555555555\", false, [\n USDC(\"0xb88339cb7199b77e23db6e890353e22632ba630f\"),\n USDT(\"0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb\", \"USDT0\"),\n ]),\n chain(4326, \"megaeth\", \"MegaETH\", \"0x3db06da8f0a24a525f314eec954fc5c6a973d40e\", OP_WETH, true, [\n USDT(\"0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb\", \"USDT0\"),\n WETH(OP_WETH),\n ]),\n chain(4663, \"robinhood\", \"Robinhood Chain\", \"0xd29c85f15df544ba632c9e25829fd29d767d7978\", \"0x0bd7d308f8e1639fab988df18a8011f41eacad73\", true, [\n WETH(\"0x0bd7d308f8e1639fab988df18a8011f41eacad73\"),\n ]),\n // Arc's gas coin is USDC; 0x3600… is its 6-decimal ERC-20 interface, which is what Across moves. The SpokePool\n // reports no wrapped native token, so no deposit or fill on Arc involves the native coin.\n chain(5042, \"arc\", \"Arc\", \"0x9b4a302a548c7e313c2b74c461db7b84d3074a84\", null, false, [\n USDC(\"0x3600000000000000000000000000000000000000\"),\n ]),\n chain(8453, \"base\", \"Base\", \"0x09aea4b2242abc8bb4bb78d537a67a245a7bec64\", OP_WETH, true, [\n USDC(\"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913\"),\n USDT(\"0xfde4c96c8593536e31f229ea8f37b2ada2699bb2\"),\n WETH(OP_WETH),\n ]),\n chain(9745, \"plasma\", \"Plasma\", \"0x50039faefebef707cfd94d6d462fe6d10b39207a\", \"0x6100e367285b01f48d07953803a2d8dca5d19873\", false, [\n USDT(\"0xb8ce59fc3717ada4c02eadf9682a9e934f625ebb\", \"USDT0\"),\n ]),\n chain(42161, \"arbitrum\", \"Arbitrum\", \"0xe35e9842fceaca96570b734083f4a58e8f7c5f2a\", \"0x82af49447d8a07e3bd95bd0d56f35241523fbab1\", true, [\n USDC(\"0xaf88d065e77c8cc2239327c5edb3a432268e5831\"),\n USDT(\"0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9\", \"USDT0\"),\n WETH(\"0x82af49447d8a07e3bd95bd0d56f35241523fbab1\"),\n WBTC(\"0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f\"),\n ]),\n chain(43114, \"avalanche\", \"Avalanche\", \"0xfe9d541c92e4e90437c7152a00244886de37a658\", \"0xb31f66aa3c1e785363f0875a1b74e27b85fd66c7\", false, [\n USDC(\"0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e\"),\n USDT(\"0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7\"),\n ]),\n chain(57073, \"ink\", \"Ink\", \"0xef684c38f94f48775959ecf2012d7e864ffb9dd4\", OP_WETH, true, [\n USDC(\"0x2d270e6886d130d724215a266106e6832161eaed\"),\n USDT(\"0x0200c29006150606b650577bbe7b6248f58470c1\", \"USDT0\"),\n WETH(OP_WETH),\n ]),\n chain(59144, \"linea\", \"Linea\", \"0x7e63a5f1a8f0b4d0934b2f2327daed3f6bb2ee75\", \"0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f\", true, [\n USDC(\"0x176211869ca2b568f2a7d4ee941e073a821ee1ff\"),\n USDT(\"0xa219439258ca9da29e9cc4ce5596924745e12b93\"),\n WETH(\"0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f\"),\n WBTC(\"0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4\"),\n ]),\n].map((x) => [x.caip2, x]))));\n\n/** The chain for a CAIP-2 id, or undefined — own keys only. */\nexport function acrossChain(caip2: string): AcrossChain | undefined {\n return typeof caip2 === \"string\" && Object.prototype.hasOwnProperty.call(ACROSS_CHAINS, caip2) ? ACROSS_CHAINS[caip2] : undefined;\n}\n\n/** The pinned token at `address` on `chain` (any casing), or undefined. */\nexport function acrossToken(chain: AcrossChain, address: string): AcrossToken | undefined {\n if (typeof address !== \"string\") return undefined;\n const a = address.toLowerCase();\n return chain.tokens.find((t) => t.address === a);\n}\n\n/**\n * The HubPool on Ethereum: `crossChainContracts(chainId)` is the registry every pinned SpokePool was checked against.\n * Not a proxy; owned by a 3-of-5 Safe that can re-point the registry and upgrade every SpokePool — a watched fact.\n */\nexport const ACROSS_HUB_POOL = \"0xc186fa914353c44b2e33ebe05f21846f1048beda\";\n/** `crossChainContracts(uint256)` on the HubPool → `(address adapter, address spokePool)`. */\nexport const ACROSS_HUB_CROSS_CHAIN_CONTRACTS = \"0x09474ae2\";\n\n/**\n * `deposit(bytes32 depositor, bytes32 recipient, bytes32 inputToken, bytes32 outputToken, uint256 inputAmount,\n * uint256 outputAmount, uint256 destinationChainId, bytes32 exclusiveRelayer, uint32 quoteTimestamp,\n * uint32 fillDeadline, uint32 exclusivityParameter, bytes message)` payable — the only call this module builds or signs.\n */\nexport const ACROSS_DEPOSIT = \"0xad5425c6\";\n/** `depositV3(address …)`: the address-typed wrapper of `deposit`. Read in history, never built or signed. */\nexport const ACROSS_DEPOSIT_V3 = \"0x7b939232\";\n/**\n * Calls on a SpokePool that are always refused: `unsafeDeposit` (a caller-chosen deposit id that can collide),\n * `depositNow` / `depositV3Now` (the fill deadline set on chain), `speedUpDeposit` / `speedUpV3Deposit` (a depositor\n * signature that lets a relayer pay another recipient or a lower amount), and `multicall`.\n */\nexport const ACROSS_REFUSED_SELECTORS: Readonly<Record<string, string>> = Object.freeze({\n \"0x8b15788e\": \"unsafeDeposit\",\n \"0xea86bd46\": \"depositNow\",\n \"0x7aef642c\": \"depositV3Now\",\n \"0xbabb6aac\": \"speedUpDeposit\",\n \"0x577f51f8\": \"speedUpV3Deposit\",\n \"0xac9650d8\": \"multicall\",\n});\n\n/**\n * `UpdateDepositDetails(uint256 depositId,uint256 originChainId,uint256 updatedOutputAmount,bytes32 updatedRecipient,\n * bytes updatedMessage)` under the domain `ACROSS-V2` / `1.0.0`: the speed-up signature. It can move a deposit's\n * output to another recipient, so nothing carrying this type (or that domain) is ever signed through this module.\n */\nexport const ACROSS_SPEED_UP_TYPEHASH = \"0x8d1994e2bbbd77564cdca06dd819e7ee2a5efa06c80dcb59a4a7b6e39edc538f\";\nexport const ACROSS_SPEED_UP_TYPE = \"UpdateDepositDetails\";\nexport const ACROSS_SPEED_UP_DOMAIN = \"ACROSS-V2\";\n\n/**\n * `FundsDeposited(bytes32 inputToken, bytes32 outputToken, uint256 inputAmount, uint256 outputAmount,\n * uint256 indexed destinationChainId, uint256 indexed depositId, uint32 quoteTimestamp, uint32 fillDeadline,\n * uint32 exclusivityDeadline, bytes32 indexed depositor, bytes32 recipient, bytes32 exclusiveRelayer, bytes message)`.\n */\nexport const ACROSS_FUNDS_DEPOSITED = \"0x32ed1a409ef04c7b0227189c3a103dc5ac10e775a15b785dcc510201f7c25ad3\";\n/** `fillStatuses(bytes32 relayHash)` → 0 unfilled, 1 slow fill requested, 2 filled. */\nexport const ACROSS_FILL_STATUSES = \"0xc35c83fc\";\n\n/**\n * `keccak256(\"AcrossV5MessagePrefix.V1\")`: a deposit message starting with these 32 bytes is an Across V5 witness,\n * consumable only through the Gateway's V5 fill entry points (SpokePool.sol `V5_MAGIC_PREFIX`). Refused by name —\n * this module signs empty messages only.\n */\nexport const ACROSS_V5_MESSAGE_PREFIX = \"0x89ae4bc75915265a3f10e926c3894a29534f1d6362ee8959cb0e5be00f3527fd\";\n\n/** `depositQuoteTimeBuffer()` on every pinned SpokePool: a deposit's `quoteTimestamp` may be at most this old. */\nexport const ACROSS_DEPOSIT_QUOTE_TIME_BUFFER_S = 3600;\n/** `fillDeadlineBuffer()` on every pinned SpokePool: a deposit's `fillDeadline` may be at most this far ahead. */\nexport const ACROSS_FILL_DEADLINE_BUFFER_S = 21_600;\n/** SpokePool `MAX_EXCLUSIVITY_PERIOD_SECONDS`: an `exclusivityParameter` up to this is an offset, above it a timestamp. */\nexport const ACROSS_MAX_EXCLUSIVITY_PERIOD_S = 31_536_000;\n\n/** The native coin in a request (and in Across's own token lists): twenty zero bytes. */\nexport const ACROSS_NATIVE = \"0x0000000000000000000000000000000000000000\";\n\n/** Across API V5: the price source (`api.ts`), with a key from dashboard.across.to kept on a server. */\nexport const ACROSS_API = \"https://api.across.to\";\n\nconst ZERO = /^0x0{40}$/;\nconst isNativeRef = (token: string): boolean => ZERO.test(token);\n\n/** One side of a route: the token as the deposit names it, and whether the user's side of it is the native coin. */\nexport interface AcrossRouteSide {\n chain: AcrossChain;\n /** The token the deposit names: the ERC-20, or the wrapped native token when `native`. */\n token: string;\n native: boolean;\n decimals: number;\n}\n\nexport interface AcrossRoute {\n asset: AcrossAsset;\n input: AcrossRouteSide;\n output: AcrossRouteSide;\n}\n\n/** Why a pair is not served, for a refusal. */\nexport interface AcrossRouteMiss {\n code: \"chain-unsupported\" | \"token-unsupported\" | \"pair-unsupported\" | \"native-unsupported\" | \"wrapped-native-destination\";\n detail: string;\n}\n\n/**\n * The route a request names, or why it is not served. `sourceToken` / `destToken` are contracts (any casing) or the\n * zero address for the native coin. Served: two different pinned chains, the same asset on both sides, the native coin\n * only where it is ether and the SpokePool wraps it, and never the wrapped native token as a destination ERC-20 — an\n * empty-message fill of it pays an EOA the native coin, which is not what was asked for.\n */\nexport function acrossRouteOf(sourceChain: string, sourceToken: string, destChain: string, destToken: string): AcrossRoute | AcrossRouteMiss {\n const src = acrossChain(sourceChain);\n const dst = acrossChain(destChain);\n if (!src) return {code: \"chain-unsupported\", detail: `source chain ${String(sourceChain)} is not a pinned Across chain`};\n if (!dst) return {code: \"chain-unsupported\", detail: `destination chain ${String(destChain)} is not a pinned Across chain`};\n if (src === dst) return {code: \"chain-unsupported\", detail: \"source and destination are the same chain\"};\n if (typeof sourceToken !== \"string\" || typeof destToken !== \"string\") return {code: \"token-unsupported\", detail: \"the tokens are not addresses\"};\n let input: AcrossRouteSide;\n let asset: AcrossAsset;\n if (isNativeRef(sourceToken)) {\n if (!src.nativeIsEth || !src.wrappedNative) return {code: \"native-unsupported\", detail: `${src.name}'s native coin is not bridged by Across`};\n input = {chain: src, token: src.wrappedNative, native: true, decimals: 18};\n asset = \"ETH\";\n } else {\n const t = acrossToken(src, sourceToken);\n if (!t) return {code: \"token-unsupported\", detail: `${sourceToken.toLowerCase()} is not a token pinned on ${src.name}`};\n input = {chain: src, token: t.address, native: false, decimals: t.decimals};\n asset = t.asset;\n }\n let output: AcrossRouteSide;\n if (isNativeRef(destToken)) {\n if (!dst.nativeIsEth || !dst.wrappedNative) return {code: \"native-unsupported\", detail: `${dst.name}'s native coin is not bridged by Across`};\n if (asset !== \"ETH\") return {code: \"pair-unsupported\", detail: `${asset} on ${src.name} is not bridged to ${dst.name}'s native coin`};\n output = {chain: dst, token: dst.wrappedNative, native: true, decimals: 18};\n } else {\n const t = acrossToken(dst, destToken);\n if (!t) return {code: \"token-unsupported\", detail: `${destToken.toLowerCase()} is not a token pinned on ${dst.name}`};\n if (dst.wrappedNative !== null && t.address === dst.wrappedNative) {\n return {code: \"wrapped-native-destination\", detail: `a fill of ${t.symbol} on ${dst.name} pays an EOA the native coin, not ${t.symbol} — ask for the native coin`};\n }\n if (t.asset !== asset) return {code: \"pair-unsupported\", detail: `${asset} is only bridged to ${asset}, not to ${t.symbol}`};\n output = {chain: dst, token: t.address, native: false, decimals: t.decimals};\n }\n if (input.decimals !== output.decimals) return {code: \"pair-unsupported\", detail: \"the two sides have different decimals\"};\n return {asset, input, output};\n}\n\nexport const across = {\n supportsChain(chain: string): boolean {\n return acrossChain(chain) !== undefined;\n },\n /** Two different pinned EVM chains. */\n supports(from: string, to: string): boolean {\n return from !== to && acrossChain(from) !== undefined && acrossChain(to) !== undefined;\n },\n};\n","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","/**\n * Activity recognition for Across on every pinned chain: a `deposit` / `depositV3` call on the chain's SpokePool is our\n * source leg (\"Bridged USDC\").\n *\n * Deposits that reach the SpokePool through another contract (Across's periphery, an aggregator, a Safe) are not\n * claimed: the call the history shows is that contract's. The destination leg is not claimed either — a fill is paid\n * by one of many relayers as an ordinary token transfer (or a native payment when the wrapped native token is\n * unwrapped) and reads as a plain incoming transfer.\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {chainLabel, describeSwapLike, matchesCall} from \"@anywalletkit/protocol-swap2-core/activity\";\nimport {ACROSS_DEPOSIT, ACROSS_DEPOSIT_V3, acrossChain} from \"./config.js\";\n\nexport const ACROSS_MODULE = \"@anywalletkit/protocol-swap2-across\";\n\nexport function describeAcrossActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n const chain = acrossChain(tx.chain);\n if (!chain) return null;\n // Both deposit functions are read here (history is not ours alone); only `deposit` is ever built or signed.\n if (!matchesCall(tx, [chain.spokePool], [ACROSS_DEPOSIT, ACROSS_DEPOSIT_V3])) return null;\n return describeSwapLike(tx, ctx, {protocol: ACROSS_MODULE, subtitle: `Across · ${chainLabel(tx.chain)}`, kind: \"bridge\", outVerb: \"Bridged\"});\n}\n","/**\n * The two Across APIs this module reads — for NUMBERS only. Nothing either one answers is signed or executed: the\n * deposit is encoded on the device from the pins and the user's request (`build.ts`) and verified (`verify.ts`).\n *\n * - **Across API V5** (`POST https://api.across.to/v1/quotes`, a key from dashboard.across.to, server-side only) is\n * the price source. A V5 quote prices V5's own route — an execution step on the origin chain (Across's Gateway),\n * sometimes another rail (CCTP, an OFT) — and funds it through `nextActions` that pay an escrow keyed by an order\n * id the device cannot open (the recipient, the destination and the floor are not in anything it would sign). So\n * `nextActions`, `orderId`, `minAmount` and the attestation are never read: only the fee, its gas legs, the fill\n * estimate and the USD prices, each read strictly ({@link readAcrossV5Quote}).\n * - **`/suggested-fees`** (`GET https://app.across.to/api/suggested-fees`, keyless, the Across app's own relayer-fee\n * quote — Across calls it legacy) is the independent statement of what an Across relayer needs to fill a plain\n * SpokePool deposit, and the `timestamp` its LP fee was priced at ({@link readAcrossSuggestedFees}).\n *\n * `pricing.ts` turns the two into the deposit's numbers. Sources: Across's V5 integration skills\n * (github.com/across-protocol/skills @ f4d425e6, `quote-and-execute`, `security`) and real answers of both APIs\n * recorded 2026-11-15 (fixtures/api).\n */\nimport {httpRefusal, type Swap2RefusalInfo, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {anySignal, timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {ACROSS_API, acrossChain, type AcrossRoute} from \"./config.js\";\nimport {AcrossRefusal} from \"./refusal.js\";\nimport type {AcrossRequest} from \"./verify.js\";\n\n/** The V5 base (`ACROSS_API` + `/v1`). */\nexport const ACROSS_API_V1 = `${ACROSS_API}/v1`;\n/** Across's keyless relayer-fee quote (the Across app's own `/suggested-fees`). */\nexport const ACROSS_SUGGESTED_FEES_URL = \"https://app.across.to/api/suggested-fees\";\n/**\n * `maxFee.bps` sent with every V5 quote request: the widest V5 takes. It only bounds V5's own guaranteed minimum,\n * which is never used here (V5's estimate does not move with it: 24 962 036 / 24 962 140 / 24 963 399 base units for\n * the same 25 USDC at three caps, 2026-11-14); at 1000 V5 refused Ethereum-origin transfers under ~$16.5–19 because\n * its own origin gas alone was over the cap. The user's own cap is held on the deposit, by the verifier.\n */\nexport const ACROSS_V5_PRICING_MAX_FEE_BPS = 5_000;\n/** Longest answer read from either API, in characters (a V5 quote is ~12 kB). */\nconst MAX_ANSWER_CHARS = 512 * 1024;\n\nexport interface AcrossV5Token {\n chainId: number;\n address: string;\n}\n\n/** `POST /v1/quotes` body, exactly the fields this module sends (the API refuses any field it does not know). */\nexport interface AcrossV5QuoteRequest {\n origin: {token: AcrossV5Token; depositor: string; amount: string};\n destination: {token: AcrossV5Token; recipient: string};\n amountType: \"exact_input\";\n /** What the client can do: approve a token and send a transaction on an EVM chain. No typed data, no submissions. */\n capabilities: {operations: readonly {kind: \"approve_token\" | \"send_transaction\"; ecosystem: \"evm\"}[]};\n /** An approval of exactly the funded amount — never `infinite`. */\n authorizationPolicy: {allowedTypes: readonly [\"approval\"]; approvalAmount: \"exact\"};\n /** {@link ACROSS_V5_PRICING_MAX_FEE_BPS}. */\n maxFee: {bps: number};\n}\n\n/**\n * The `POST /v1/quotes` body for a request. Pure. Native ETH is the zero address on both sides, as V5 names it; the\n * funding is the plain approval flow (`approve_token` + `send_transaction`, exact amount) — the one whose price was\n * studied; nothing it returns is executed.\n */\nexport function acrossV5QuoteRequest(request: AcrossRequest): AcrossV5QuoteRequest {\n const src = acrossChain(request.sourceChain);\n const dst = acrossChain(request.destChain);\n if (!src || !dst) throw new Error(\"across: the request's chains are not pinned\");\n return {\n origin: {token: {chainId: src.chainId, address: request.sourceToken.toLowerCase()}, depositor: request.depositor.toLowerCase(), amount: request.amount.toString(10)},\n destination: {token: {chainId: dst.chainId, address: request.destToken.toLowerCase()}, recipient: request.recipient.toLowerCase()},\n amountType: \"exact_input\",\n capabilities: {operations: [{kind: \"approve_token\", ecosystem: \"evm\"}, {kind: \"send_transaction\", ecosystem: \"evm\"}]},\n authorizationPolicy: {allowedTypes: [\"approval\"], approvalAmount: \"exact\"},\n maxFee: {bps: ACROSS_V5_PRICING_MAX_FEE_BPS},\n };\n}\n\n// ── reading answers ────────────────────────────────────────────────────────────\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst ZERO = /^0x0{40}$/;\nconst UINT = /^(?:0|[1-9]\\d{0,77})$/;\n/** A non-negative decimal as V5 writes USD amounts (\"0.012048778559999999\"). */\nconst DECIMAL = /^(?:0|[1-9]\\d{0,15})(?:\\.\\d{1,30})?$/;\nconst plain = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === \"object\" && !Array.isArray(v);\nconst own = (o: Record<string, unknown>, key: string): unknown => (Object.prototype.hasOwnProperty.call(o, key) ? o[key] : undefined);\nconst uint = (v: unknown): bigint | null => (typeof v === \"string\" && UINT.test(v) ? BigInt(v) : null);\nconst sameAddress = (a: unknown, b: string): boolean => typeof a === \"string\" && ADDRESS.test(a) && a.toLowerCase() === b.toLowerCase();\n\n/** A decimal string as an integer scaled by 10^`scale`, rounded down; null when it is not one. */\nfunction scaled(text: string, scale: number): bigint | null {\n if (!DECIMAL.test(text)) return null;\n const [whole, frac = \"\"] = text.split(\".\");\n return BigInt(whole! + frac.slice(0, scale).padEnd(scale, \"0\"));\n}\n\nconst USD_SCALE = 18;\nconst PRICE_SCALE = 12;\n\n/**\n * A USD amount as base units of a token priced at `priceUsd`, rounded down — integer math only (no `Number` of a big\n * value): `amountUsd × 10^decimals / priceUsd`. Null when either is not a usable number.\n */\nexport function acrossUsdToUnits(amountUsd: unknown, priceUsd: unknown, decimals: number): bigint | null {\n if (typeof amountUsd !== \"string\" || typeof priceUsd !== \"number\" || !Number.isFinite(priceUsd) || priceUsd <= 0 || priceUsd >= 1e12) return null;\n if (!Number.isInteger(decimals) || decimals < 0 || decimals > 36) return null;\n const usd = scaled(amountUsd, USD_SCALE);\n const price = scaled(priceUsd.toFixed(PRICE_SCALE), PRICE_SCALE);\n if (usd === null || price === null || price === 0n) return null;\n return (usd * 10n ** BigInt(decimals) * 10n ** BigInt(PRICE_SCALE)) / (price * 10n ** BigInt(USD_SCALE));\n}\n\n/** What a V5 quote says that the pricing rule reads — every amount in base units of the input token. */\nexport interface AcrossV5Price {\n /** `fee.totalFee.amount`: input − `destination.amount` (checked to add up). */\n totalFee: bigint;\n /** V5's estimate of what arrives (`destination.amount`). */\n destinationAmount: bigint;\n /**\n * Σ `gasEstimates[leg = \"origin\", effect = \"included_in_transfer_fee\"]`: V5's own execution step on the origin\n * chain, charged inside its fee. Exact wei on an ETH route; a token route converts its USD figure at the\n * destination token's price, rounded down. A leg that cannot be read adds nothing (the fee stays higher).\n */\n originGas: bigint;\n /** Σ `gasEstimates[leg = \"destination\", effect = \"included_in_transfer_fee\"]`, converted alike; null when a leg cannot be. */\n destinationGas: bigint | null;\n /** `expectedFillTimeMs`. Over a minute it is not an Across relayer fill: V5 prices another rail (`acrossV5OtherRail`). */\n expectedFillTimeMs: number;\n /** `origin.amountUsd`, when given: the transfer's size in dollars (the floor curve for ETH from an L2 is by size). */\n amountUsd?: number;\n}\n\n/**\n * A V5 quote answer, read strictly against the request it was asked for. Throws {@link AcrossRefusal} `api-answer`:\n * `policy_refused` for an answer about another transfer (tokens, chains, amount, an app fee nobody asked for),\n * `upstream_unavailable` for one that does not read or does not add up. `nextActions`, `orderId`, `minAmount` and any\n * attestation are not read.\n */\nexport function readAcrossV5Quote(request: AcrossRequest, route: AcrossRoute, body: unknown): AcrossV5Price {\n const malformed = (what: string): never => { throw new AcrossRefusal(\"api-answer\", `the V5 quote ${what}`, \"upstream_unavailable\"); };\n const other = (what: string): never => { throw new AcrossRefusal(\"api-answer\", `the V5 quote ${what}`, \"policy_refused\"); };\n if (!plain(body)) return malformed(\"is not a JSON object\");\n const amountType = own(body, \"amountType\");\n if (amountType !== undefined && amountType !== \"exact_input\") other(`is ${String(amountType).slice(0, 20)}, not exact input`);\n const src = route.input.chain;\n const dst = route.output.chain;\n\n const origin = own(body, \"origin\");\n const destination = own(body, \"destination\");\n if (!plain(origin) || !plain(destination)) return malformed(\"has no origin or destination\");\n const oToken = own(origin, \"token\");\n const dToken = own(destination, \"token\");\n if (!plain(oToken) || !plain(dToken)) return malformed(\"names no tokens\");\n if (own(oToken, \"chainId\") !== src.chainId || !sameAddress(own(oToken, \"address\"), request.sourceToken)) other(\"is for another input token or chain\");\n if (own(dToken, \"chainId\") !== dst.chainId || !sameAddress(own(dToken, \"address\"), request.destToken)) other(\"is for another output token or chain\");\n const amountIn = uint(own(origin, \"amount\"));\n if (amountIn === null) return malformed(\"states no input amount\");\n if (amountIn !== request.amount) other(`sends ${amountIn}, the request ${request.amount}`);\n const destinationAmount = uint(own(destination, \"amount\"));\n if (destinationAmount === null) return malformed(\"states no output estimate\");\n if (destinationAmount > request.amount) other(\"expects more to arrive than goes in\");\n\n const fee = own(body, \"fee\");\n if (!plain(fee)) return malformed(\"has no fee\");\n const total = own(fee, \"totalFee\");\n if (!plain(total)) return malformed(\"has no total fee\");\n const totalFee = uint(own(total, \"amount\"));\n if (totalFee === null) return malformed(\"states a total fee that is not a base-unit integer\");\n const feeToken = own(total, \"token\");\n if (!plain(feeToken) || own(feeToken, \"chainId\") !== dst.chainId || !sameAddress(own(feeToken, \"address\"), request.destToken) || own(feeToken, \"decimals\") !== route.output.decimals) {\n malformed(\"states its fee in another token\");\n }\n if (totalFee !== request.amount - destinationAmount) malformed(`fee ${totalFee} is not its input minus its estimate (${request.amount - destinationAmount})`);\n const appFee = own(fee, \"appFee\");\n if (appFee !== undefined && appFee !== null) {\n const app = plain(appFee) ? uint(own(appFee, \"amount\")) : null;\n if (app === null) return malformed(\"states an app fee that does not read\");\n if (app > 0n) other(\"carries an app fee this module never asks for\");\n }\n\n const fill = own(body, \"expectedFillTimeMs\");\n if (typeof fill !== \"number\" || !Number.isFinite(fill) || fill < 0) return malformed(\"states no fill time\");\n const priceUsd = own(dToken, \"priceUsd\");\n const legs = own(body, \"gasEstimates\");\n if (!Array.isArray(legs) || legs.length > 16) return malformed(\"has no gas estimates\");\n let originGas = 0n;\n let destinationGas: bigint | null = 0n;\n for (const leg of legs as unknown[]) {\n if (!plain(leg)) return malformed(\"has a gas estimate that is not an object\");\n if (own(leg, \"effect\") !== \"included_in_transfer_fee\") continue;\n const side = own(leg, \"leg\");\n if (side !== \"origin\" && side !== \"destination\") continue;\n const units = legUnits(leg, route, priceUsd);\n if (side === \"origin\") originGas += units ?? 0n;\n else destinationGas = units === null || destinationGas === null ? null : destinationGas + units;\n }\n // An add-back is never more than the fee it is taken from.\n if (originGas > totalFee) originGas = totalFee;\n\n const usdText = own(origin, \"amountUsd\");\n const amountUsd = typeof usdText === \"string\" && DECIMAL.test(usdText) ? Number(usdText) : undefined;\n return {totalFee, destinationAmount, originGas, destinationGas, expectedFillTimeMs: fill, ...(amountUsd !== undefined && Number.isFinite(amountUsd) ? {amountUsd} : {})};\n}\n\n/**\n * One gas leg in base units of the input token. On an ETH route a leg paid in the native ether of either chain is\n * exact (wei is the bridged asset's own unit); anything else is its `amountUsd` at the destination token's price.\n */\nfunction legUnits(leg: Record<string, unknown>, route: AcrossRoute, priceUsd: unknown): bigint | null {\n const token = own(leg, \"token\");\n const amount = uint(own(leg, \"amount\"));\n if (route.asset === \"ETH\" && plain(token) && amount !== null && ZERO.test(String(own(token, \"address\"))) && own(token, \"decimals\") === 18) {\n const chainId = own(token, \"chainId\");\n const side = chainId === route.input.chain.chainId ? route.input.chain : chainId === route.output.chain.chainId ? route.output.chain : undefined;\n if (side?.nativeIsEth) return amount;\n }\n return acrossUsdToUnits(own(leg, \"amountUsd\"), priceUsd, route.input.decimals);\n}\n\n/** What `/suggested-fees` answered, as the pricing rule reads it. */\nexport type AcrossSuggestedFees =\n /** A relayer fee for this exact deposit. */\n | {kind: \"fees\"; totalRelayFee: bigint; timestamp: number; estimatedFillTimeSec: number}\n /** Across says relayers will not take this deposit (too small, too large, the route not enabled): refuse. */\n | {kind: \"refused\"; detail: string; reason: Swap2RefusalReason}\n /** No usable answer (unreachable, another shape, stale): the pinned floor stands in. */\n | {kind: \"unavailable\"; detail: string};\n\n/** The `/suggested-fees` query for a request: the deposit's own tokens (the wrapped native token for ETH) and recipient. */\nexport function acrossSuggestedFeesQuery(request: AcrossRequest, route: AcrossRoute): string {\n const q: [string, string][] = [\n [\"inputToken\", route.input.token],\n [\"outputToken\", route.output.token],\n [\"originChainId\", String(route.input.chain.chainId)],\n [\"destinationChainId\", String(route.output.chain.chainId)],\n [\"amount\", request.amount.toString(10)],\n [\"recipient\", request.recipient.toLowerCase()],\n ];\n return q.map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join(\"&\");\n}\n\n/**\n * How old a `/suggested-fees` timestamp may be (s). It becomes the deposit's quote time, so it is never taken from\n * ahead of the reader's clock: the SpokePool reverts a quote time ahead of its block, and Across's are HubPool block\n * times minutes in the past (217–245 s on every recorded answer).\n */\nexport const ACROSS_SUGGESTED_FEES_MAX_AGE_S = 600;\nexport const ACROSS_SUGGESTED_FEES_MAX_AHEAD_S = 0;\n\n/**\n * A `/suggested-fees` answer for a request, at `nowS`. Across's own refusals of the deposit — any 400 it answers\n * (`AMOUNT_TOO_LOW`, `AMOUNT_TOO_HIGH`, `ROUTE_NOT_ENABLED`, `INVALID_PARAM` for a token or a chain it does not serve,\n * or a code this module does not know), `isAmountTooLow`, an amount outside `limits` — and a SpokePool other than the\n * pinned one are `refused`; no answer, another status, or one that is not a clean, consistent, fresh answer is\n * `unavailable` (the pinned floor may then stand in).\n */\nexport function readAcrossSuggestedFees(request: AcrossRequest, route: AcrossRoute, status: number, body: unknown, nowS: number): AcrossSuggestedFees {\n const unavailable = (detail: string): AcrossSuggestedFees => ({kind: \"unavailable\", detail});\n const refused = (detail: string, reason: Swap2RefusalReason): AcrossSuggestedFees => ({kind: \"refused\", detail, reason});\n if (status !== 200) {\n const code = plain(body) ? own(body, \"code\") : undefined;\n const label = typeof code === \"string\" ? ` ${code.slice(0, 40)}` : \"\";\n if (status === 400) {\n if (code === \"AMOUNT_TOO_LOW\") return refused(\"Across's relayer fee quote says the amount is too low relative to fees\", \"amount_too_small\");\n if (code === \"AMOUNT_TOO_HIGH\") return refused(\"Across's relayer fee quote says the amount is higher than relayer liquidity\", \"amount_too_large\");\n if (code === \"ROUTE_NOT_ENABLED\") return refused(\"Across's relayer fee quote says this route is not enabled for relayers\", \"unsupported_pair\");\n // Only pinned tokens and chains are asked for: one Across calls invalid (\"Unsupported token on given origin\n // chain\") is one its relayers do not serve — a deposit priced on the floor for it would never be filled.\n const param = plain(body) ? own(body, \"param\") : undefined;\n const message = plain(body) ? own(body, \"message\") : undefined;\n if (code === \"INVALID_PARAM\" && /token|chain/i.test(`${typeof param === \"string\" ? param : \"\"} ${typeof message === \"string\" ? message : \"\"}`)) {\n 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\");\n }\n // Any other refusal of this exact deposit: Across said no, so nothing stands in for its price.\n return refused(`Across's relayer fee quote refused the deposit (HTTP 400${label})`, \"upstream_unavailable\");\n }\n return unavailable(`it answered HTTP ${status}${label}`);\n }\n if (!plain(body)) return unavailable(\"its answer is not a JSON object\");\n const inputToken = own(body, \"inputToken\");\n const outputToken = own(body, \"outputToken\");\n if (!plain(inputToken) || !plain(outputToken)) return unavailable(\"its answer names no tokens\");\n if (!sameAddress(own(inputToken, \"address\"), route.input.token) || own(inputToken, \"chainId\") !== route.input.chain.chainId\n || !sameAddress(own(outputToken, \"address\"), route.output.token) || own(outputToken, \"chainId\") !== route.output.chain.chainId) {\n return unavailable(\"its answer is for another route\");\n }\n // The SpokePools relayers watch for this route: the pinned ones, or the pins are out of date.\n const spoke = own(body, \"spokePoolAddress\");\n const destSpoke = own(body, \"destinationSpokePoolAddress\");\n const spokeMoved = spoke !== undefined && !sameAddress(spoke, route.input.chain.spokePool);\n if (spokeMoved || (destSpoke !== undefined && !sameAddress(destSpoke, route.output.chain.spokePool))) {\n return refused(`Across quotes this route on another SpokePool than the one pinned for ${spokeMoved ? route.input.chain.name : route.output.chain.name} — the pins need a review`, \"vault_mismatch\");\n }\n const totalRelay = own(body, \"totalRelayFee\");\n const total = plain(totalRelay) ? uint(own(totalRelay, \"total\")) : null;\n const outputAmount = uint(own(body, \"outputAmount\"));\n if (total === null || outputAmount === null) return unavailable(\"its answer states no relayer fee\");\n if (outputAmount + total !== request.amount) return unavailable(\"its fee is not the amount minus its output\");\n 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\");\n const limits = own(body, \"limits\");\n if (plain(limits)) {\n const min = uint(own(limits, \"minDeposit\"));\n const max = uint(own(limits, \"maxDeposit\"));\n if (min !== null && request.amount < min) return refused(`Across's relayers take at least ${min} base units on this route`, \"amount_too_small\");\n if (max !== null && request.amount > max) return refused(`Across's relayers take at most ${max} base units on this route`, \"amount_too_large\");\n }\n const ts = own(body, \"timestamp\");\n const timestamp = typeof ts === \"string\" && /^[1-9]\\d{8,9}$/.test(ts) ? Number(ts) : NaN;\n if (!Number.isInteger(timestamp)) return unavailable(\"its answer states no quote time\");\n if (timestamp - nowS > ACROSS_SUGGESTED_FEES_MAX_AHEAD_S) return unavailable(`its quote time is ${timestamp - nowS} s ahead of this clock`);\n if (nowS - timestamp > ACROSS_SUGGESTED_FEES_MAX_AGE_S) return unavailable(`its quote time is ${nowS - timestamp} s old`);\n const eta = own(body, \"estimatedFillTimeSec\");\n return {kind: \"fees\", totalRelayFee: total, timestamp, estimatedFillTimeSec: typeof eta === \"number\" && Number.isFinite(eta) && eta >= 0 ? eta : 2};\n}\n\n// ── V5 errors ──────────────────────────────────────────────────────────────────\n\n/** A V5 error answer, read from either envelope, with its classification. */\nexport interface AcrossV5Error {\n /** HTTP status of the answer. */\n status: number;\n /** `error.code`, else the top-level `code` (`unauthenticated`, `policy.amount_out_of_range`, …). */\n code?: string;\n /** `error.type` (nested envelope only). */\n type?: string;\n message?: string;\n /** The field the error names (`error.param`). */\n param?: string;\n /** Across's id for the request, for support (`error.requestId`). */\n requestId?: string;\n /** `error.details.amountLimits`: which bound the amount crossed and where it lies, base units of the input token. */\n amountLimit?: {side: \"min\" | \"max\"; amount?: string};\n /** The CS-13 classification; undefined when neither the code nor the status says what it is. */\n info?: Swap2RefusalInfo;\n /**\n * `409 conflict.submission_state_unknown`: the execution's outcome is unknown — retry the SAME request with backoff,\n * never quote again (a new quote could fund the transfer twice). Quoting never meets it; kept for completeness.\n */\n retrySameRequest: boolean;\n}\n\nconst text = (v: unknown, max: number): string | undefined => (typeof v === \"string\" && v.length > 0 ? v.slice(0, max) : undefined);\n\n/**\n * A refusal over the `maxFee` cap, in Across's wording or near it: the cap named (`maxFee`, \"maximum fee\", \"fee cap\"),\n * or a fee said to be above something. \"Amount too low to cover fees\" is not one — that is the amount's own direction.\n */\nconst 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/;\n\n/** What an error code says on its own (Across's documented codes), before the HTTP status is consulted. */\nfunction reasonOfCode(code: string, message: string | undefined, param: string | undefined, side: \"min\" | \"max\" | undefined, status: number): Swap2RefusalInfo | undefined {\n switch (code) {\n case \"unauthenticated\":\n case \"auth.missing_credentials\":\n case \"auth.invalid_credentials\":\n // A feature the key is not entitled to (a permission Across grants per integration).\n case \"permission.not_entitled\":\n return {reason: \"key_rejected\", httpStatus: status};\n case \"policy.amount_out_of_range\": {\n // The bound V5 names is the answer: the real fee-cap refusal reads \"quote value loss exceeds the allowance of\n // 1000 bps plus $0; raise the amount above N base units\" with `amountLimits.side = \"min\"` — its \"above\" names\n // the amount the user must reach, not an amount that is too large.\n if (side === \"min\") return {reason: \"amount_too_small\"};\n if (side === \"max\") return {reason: \"amount_too_large\"};\n const m = (message ?? \"\").toLowerCase();\n if (/\\b(?:raise|increase) the amount\\b/.test(m)) return {reason: \"amount_too_small\"};\n if (/\\b(?:lower|reduce|decrease) the amount\\b/.test(m)) return {reason: \"amount_too_large\"};\n if (FEE_CAP.test(m)) return {reason: \"price_check_failed\"};\n if (/\\b(?:too low|too small|below|minimum|min)\\b/.test(m)) return {reason: \"amount_too_small\"};\n if (/\\b(?:too high|too large|above|maximum|max|liquidity)\\b/.test(m)) return {reason: \"amount_too_large\"};\n return {reason: \"price_check_failed\"};\n }\n // The API no longer takes what this module sends (a field it does not know, or one it now requires): an API of\n // another shape than the one this module was built against.\n case \"request.unsupported_param\":\n case \"request.missing_field\":\n return {reason: \"upstream_unavailable\", httpStatus: status};\n // Only pinned tokens and chains are sent: one V5 calls invalid (\"unknown token … is not a known token\") is one it\n // does not serve. Any other value it no longer takes is, like the codes above, an API of another shape.\n case \"request.invalid_field\":\n return /token|chain/i.test(`${param ?? \"\"} ${message ?? \"\"}`) ? {reason: \"unsupported_pair\"} : {reason: \"upstream_unavailable\", httpStatus: status};\n case \"system.unavailable\":\n case \"conflict.submission_state_unknown\":\n return {reason: \"upstream_unavailable\", httpStatus: status};\n default:\n return undefined;\n }\n}\n\n/**\n * Read a non-2xx V5 answer: the two envelopes Across uses — flat `{code, message, details}` (the gateway's 401) and\n * nested `{error: {type, code, message, param, requestId, details}}` — and its CS-13 classification. A 429 is\n * `rate_limited` with its Retry-After first; then the code (with `details.amountLimits.side` for\n * `policy.amount_out_of_range`); then the status (401 / 403 → `key_rejected`, 408 / 425 / 5xx →\n * `upstream_unavailable`); a JSON refusal neither names is a quote the API does not have (`no_route`).\n */\nexport function parseAcrossV5Error(status: number, body: unknown, retryAfter?: string | null, nowMs: number = Date.now()): AcrossV5Error {\n const o = plain(body) ? body : undefined;\n const nested = o !== undefined && plain(o[\"error\"]) ? o[\"error\"] : undefined;\n const code = text(nested?.[\"code\"], 80) ?? text(o?.[\"code\"], 80);\n const type = text(nested?.[\"type\"], 80);\n const message = text(nested?.[\"message\"], 240) ?? text(o?.[\"message\"], 240);\n const param = text(nested?.[\"param\"], 80);\n const requestId = text(nested?.[\"requestId\"], 120);\n const details = nested !== undefined && plain(nested[\"details\"]) ? nested[\"details\"] : o !== undefined && plain(o[\"details\"]) ? o[\"details\"] : undefined;\n const limits = details !== undefined && plain(details[\"amountLimits\"]) ? details[\"amountLimits\"] : undefined;\n const rawSide = limits?.[\"side\"];\n const side = rawSide === \"min\" || rawSide === \"max\" ? rawSide : undefined;\n const rawBound = limits?.[\"amount\"];\n const bound = typeof rawBound === \"string\" && UINT.test(rawBound) ? rawBound : undefined;\n const byStatus = httpRefusal(status, retryAfter, nowMs);\n let info: Swap2RefusalInfo | undefined;\n if (byStatus?.reason === \"rate_limited\") info = byStatus;\n else info = (code !== undefined ? reasonOfCode(code, message, param, side, status) : undefined) ?? byStatus ?? (o !== undefined && status >= 400 && status < 500 && status !== 404 ? {reason: \"no_route\"} : undefined);\n return {\n status,\n ...(code !== undefined ? {code} : {}),\n ...(type !== undefined ? {type} : {}),\n ...(message !== undefined ? {message} : {}),\n ...(param !== undefined ? {param} : {}),\n ...(requestId !== undefined ? {requestId} : {}),\n ...(side !== undefined ? {amountLimit: {side, ...(bound !== undefined ? {amount: bound} : {})}} : {}),\n ...(info !== undefined ? {info} : {}),\n retrySameRequest: status === 409 && code === \"conflict.submission_state_unknown\",\n };\n}\n\n// ── HTTP ───────────────────────────────────────────────────────────────────────\n\n/** An API URL, trailing slashes trimmed; throws a plain `Error` unless https (or http on this machine). */\nexport function acrossApiUrl(url: string, what: string): string {\n const u = String(url).trim().replace(/\\/+$/, \"\");\n if (/^https:\\/\\/[^\\s/?#@]+(?:\\/[^\\s?#]*)?$/i.test(u)) return u;\n if (/^http:\\/\\/(?:localhost|127\\.0\\.0\\.1)(?::[0-9]{1,5})?(?:\\/[^\\s?#]*)?$/i.test(u)) return u;\n throw new Error(`across: ${what} must be an https:// URL (http only for localhost)`);\n}\n\n/** `scheme://host[:port]` of a URL, lowercase; \"\" when it has none. No URL class: React Native's lacks `origin`. */\nexport const acrossOriginOf = (url: string): string => (/^[a-z][a-z0-9+.-]*:\\/\\/[^/?#]*/i.exec(url)?.[0] ?? \"\").toLowerCase();\n\n/** An answer as read: status, parsed body (undefined when not JSON), Retry-After. */\nexport interface AcrossHttpAnswer {\n status: number;\n body: unknown;\n retryAfter: string | null;\n}\n\n/**\n * One request to an Across API, bounded by `timeoutMs` (and the caller's signal). An answer that came through a\n * redirect, or from another origin than the URL's, is refused (`policy_refused`) — a key header must not follow one,\n * and React Native's fetch follows redirects whatever `redirect` says. Throws {@link AcrossRefusal} `api-answer` for a\n * redirect, an answer larger than any quote, or no answer (`upstream_unavailable`; unclassified when the caller's own\n * signal fired).\n */\nexport async function acrossHttp(\n url: string,\n init: {method: \"GET\" | \"POST\"; headers: Record<string, string>; body?: string},\n opts: {fetchImpl?: typeof fetch | undefined; timeoutMs: number; signal?: AbortSignal | undefined; what: string},\n): Promise<AcrossHttpAnswer> {\n const expected = acrossOriginOf(url);\n let status: number;\n let raw: string;\n let retryAfter: string | null = null;\n try {\n const timeout = timeoutSignal(opts.timeoutMs);\n const res = await (opts.fetchImpl ?? fetch)(url, {...init, redirect: \"error\", signal: opts.signal ? anySignal([opts.signal, timeout]) : timeout});\n if (res.redirected === true || (typeof res.url === \"string\" && res.url !== \"\" && acrossOriginOf(res.url) !== expected)) {\n throw new AcrossRefusal(\"api-answer\", `${opts.what} answered through a redirect or from another origin — refused (a key must not follow one)`, \"policy_refused\");\n }\n status = res.status;\n retryAfter = res.headers?.get?.(\"retry-after\") ?? null;\n raw = await res.text();\n } catch (err) {\n if (err instanceof AcrossRefusal) throw err;\n const name = err instanceof Error ? err.name.slice(0, 40) : \"error\";\n throw new AcrossRefusal(\"api-answer\", `${opts.what} did not answer (${name})`, opts.signal?.aborted ? undefined : \"upstream_unavailable\");\n }\n if (raw.length > MAX_ANSWER_CHARS) throw new AcrossRefusal(\"api-answer\", `${opts.what} answered more than any quote`, \"upstream_unavailable\");\n let body: unknown;\n try {\n body = JSON.parse(raw);\n } catch {\n body = undefined;\n }\n return {status, body, retryAfter};\n}\n","import {withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\n\n/** Why a request, a deposit, a quote or an API answer was refused. One code per check; the message says what was found. */\nexport type AcrossRefusalCode =\n | \"request-invalid\"\n | \"chain-unsupported\"\n | \"token-unsupported\"\n | \"pair-unsupported\"\n | \"native-unsupported\"\n | \"wrapped-native-destination\"\n | \"route-unpriced\"\n | \"quote-unavailable\"\n | \"quote-normalized\"\n | \"tx-shape\"\n | \"tx-chain\"\n | \"tx-target\"\n | \"tx-selector\"\n | \"tx-calldata\"\n | \"tx-depositor\"\n | \"tx-recipient\"\n | \"tx-input-token\"\n | \"tx-output-token\"\n | \"tx-input-amount\"\n | \"tx-output-amount\"\n | \"tx-fee\"\n | \"tx-destination\"\n | \"tx-message\"\n | \"tx-message-v5\"\n | \"tx-exclusivity\"\n | \"tx-quote-time\"\n | \"tx-fill-deadline\"\n | \"tx-value\"\n | \"tx-approval\"\n | \"speed-up\"\n | \"quote-shape\"\n | \"quote-amounts\"\n | \"quote-expiry\"\n | \"quote-gas\"\n | \"quote-intent\"\n | \"api-error\"\n | \"api-answer\"\n | \"relayer-price\";\n\n/**\n * `code` names the check; `reason` (a `Swap2RefusalReason` from `@anywalletkit/protocol-swap2-core`) is the stable\n * classification an app switches on. It is set where the refusal is raised, so one code can carry different reasons\n * (a fill deadline too far ahead is `policy_refused`, one already too close is `quote_expired`); a malformed request\n * from the caller (a programming error) carries none.\n */\nexport class AcrossRefusal extends Error {\n readonly code: AcrossRefusalCode;\n declare readonly reason?: Swap2RefusalReason;\n constructor(code: AcrossRefusalCode, detail: string, reason?: Swap2RefusalReason) {\n super(`across: ${detail} [${code}]`);\n this.name = \"AcrossRefusal\";\n this.code = code;\n if (reason !== undefined) withReason(this, reason);\n }\n}\n","/**\n * SpokePool `deposit` — built and read here, strictly.\n *\n * `deposit(bytes32 depositor, bytes32 recipient, bytes32 inputToken, bytes32 outputToken, uint256 inputAmount,\n * uint256 outputAmount, uint256 destinationChainId, bytes32 exclusiveRelayer, uint32 quoteTimestamp,\n * uint32 fillDeadline, uint32 exclusivityParameter, bytes message)`, selector 0xad5425c6 (SpokePool.sol at\n * across-protocol/contracts d652689f). Every party and token is a `bytes32`; on an EVM chain it holds a 20-byte address\n * left-padded with zeros, and `depositor` is required to be one on chain (`checkAddress`).\n *\n * The reader accepts exactly the canonical ABI encoding of that call: the selector, eleven static words with clean\n * padding, the one offset the encoding allows (0x180), the message length and the message padded to a word, and\n * nothing after it. Across's own API appends a marker to the calldata it hands out (`73c0de`, and `1dc0de` + an\n * integrator id before it); such bytes are not part of the call and are refused here — this module signs the calldata\n * it builds, which carries none.\n */\nimport {encodeFunctionData, parseAbi, type Hex} from \"viem\";\nimport {ACROSS_DEPOSIT, ACROSS_REFUSED_SELECTORS} from \"./config.js\";\nimport {AcrossRefusal} from \"./refusal.js\";\n\nexport const SPOKE_POOL_ABI = parseAbi([\n \"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\",\n]);\n\n/** The arguments of a deposit. Addresses are 20 bytes, lowercase; the zero address as `exclusiveRelayer` is \"none\". */\nexport interface AcrossDepositArgs {\n depositor: string;\n recipient: string;\n inputToken: string;\n outputToken: string;\n inputAmount: bigint;\n outputAmount: bigint;\n destinationChainId: bigint;\n exclusiveRelayer: string;\n /** Unix seconds. */\n quoteTimestamp: number;\n /** Unix seconds, on the destination chain. */\n fillDeadline: number;\n /** 0 (no exclusivity), an offset up to one year, or a unix timestamp above that. */\n exclusivityParameter: number;\n /** Lowercase hex, `0x` when empty. */\n message: Hex;\n}\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst HEX = /^0x(?:[0-9a-fA-F]{2})*$/;\nconst U256_MAX = (1n << 256n) - 1n;\nconst U32_MAX = 0xffff_ffff;\n/** Static words before the message: eleven arguments and the message's offset. */\nconst HEAD_WORDS = 12;\n/** The only offset a canonical encoding gives the message: right after the head. */\nconst MESSAGE_OFFSET = HEAD_WORDS * 32;\n/** Longest message read (64 KiB): this module refuses every non-empty message anyway, this only bounds the work. */\nexport const ACROSS_MAX_MESSAGE_BYTES = 65_536;\n\n/** An address as the bytes32 a deposit carries. */\nexport function acrossBytes32(address: string): Hex {\n if (typeof address !== \"string\" || !ADDRESS.test(address)) throw new AcrossRefusal(\"request-invalid\", `${String(address)} is not an EVM address`);\n return `0x${\"0\".repeat(24)}${address.slice(2).toLowerCase()}`;\n}\n\n/** The address a bytes32 word holds, or null when its upper twelve bytes are not zero (not an EVM address). */\nexport function acrossAddressOf(word: string): string | null {\n const w = word.startsWith(\"0x\") ? word.slice(2) : word;\n if (!/^[0-9a-fA-F]{64}$/.test(w) || !/^0{24}/.test(w)) return null;\n return `0x${w.slice(24).toLowerCase()}`;\n}\n\nfunction checkArgs(a: AcrossDepositArgs): void {\n const bad = (what: string): never => { throw new AcrossRefusal(\"request-invalid\", `the deposit's ${what}`); };\n if (a === null || typeof a !== \"object\") bad(\"arguments are missing\");\n for (const [k, v] of [[\"depositor\", a.depositor], [\"recipient\", a.recipient], [\"inputToken\", a.inputToken], [\"outputToken\", a.outputToken], [\"exclusiveRelayer\", a.exclusiveRelayer]] as const) {\n if (typeof v !== \"string\" || !ADDRESS.test(v)) bad(`${k} is not an EVM address`);\n }\n for (const [k, v] of [[\"inputAmount\", a.inputAmount], [\"outputAmount\", a.outputAmount], [\"destinationChainId\", a.destinationChainId]] as const) {\n if (typeof v !== \"bigint\" || v < 0n || v > U256_MAX) bad(`${k} is not a uint256`);\n }\n for (const [k, v] of [[\"quoteTimestamp\", a.quoteTimestamp], [\"fillDeadline\", a.fillDeadline], [\"exclusivityParameter\", a.exclusivityParameter]] as const) {\n if (!Number.isInteger(v) || v < 0 || v > U32_MAX) bad(`${k} is not a uint32`);\n }\n if (typeof a.message !== \"string\" || !HEX.test(a.message) || (a.message.length - 2) / 2 > ACROSS_MAX_MESSAGE_BYTES) bad(\"message is not bytes\");\n}\n\n/** The calldata of `deposit(...)` for these arguments: lowercase hex, canonical ABI encoding, nothing appended. */\nexport function encodeAcrossDeposit(a: AcrossDepositArgs): Hex {\n checkArgs(a);\n return encodeFunctionData({\n abi: SPOKE_POOL_ABI,\n functionName: \"deposit\",\n args: [\n acrossBytes32(a.depositor), acrossBytes32(a.recipient), acrossBytes32(a.inputToken), acrossBytes32(a.outputToken),\n a.inputAmount, a.outputAmount, a.destinationChainId, acrossBytes32(a.exclusiveRelayer),\n a.quoteTimestamp, a.fillDeadline, a.exclusivityParameter, a.message.toLowerCase() as Hex,\n ],\n }).toLowerCase() as Hex;\n}\n\n/** A word's value when it fits 32 bits (its upper 28 bytes zero), else null. */\nfunction word32(word: string): number | null {\n return /^0{56}[0-9a-f]{8}$/.test(word) ? parseInt(word.slice(56), 16) : null;\n}\n\n/**\n * The arguments of a `deposit` calldata, read strictly; throws {@link AcrossRefusal} (`tx-selector`, `tx-calldata`,\n * classified `policy_refused`) for anything but the canonical encoding of that one call.\n */\nexport function decodeAcrossDeposit(data: unknown): AcrossDepositArgs {\n const malformed = (what: string): never => { throw new AcrossRefusal(\"tx-calldata\", `the deposit calldata ${what}`, \"policy_refused\"); };\n if (typeof data !== \"string\" || !HEX.test(data) || data.length < 10) malformed(\"is not hex calldata\");\n const hex = (data as string).toLowerCase();\n const selector = hex.slice(0, 10);\n if (selector !== ACROSS_DEPOSIT) {\n const name = Object.prototype.hasOwnProperty.call(ACROSS_REFUSED_SELECTORS, selector) ? ACROSS_REFUSED_SELECTORS[selector] : undefined;\n 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\");\n }\n const body = hex.slice(10);\n if (body.length < (HEAD_WORDS + 1) * 64) malformed(`is ${(hex.length - 2) / 2} bytes, shorter than a deposit`);\n const word = (i: number): string => body.slice(64 * i, 64 * i + 64);\n const addr = (i: number, what: string): string => acrossAddressOf(word(i)) ?? malformed(`carries a ${what} that is not an EVM address`);\n const u32 = (i: number, what: string): number => word32(word(i)) ?? malformed(`carries a ${what} wider than 32 bits`);\n const offset = BigInt(`0x${word(11)}`);\n if (offset !== BigInt(MESSAGE_OFFSET)) malformed(`puts the message at offset ${offset}, not ${MESSAGE_OFFSET}`);\n const lengthWord = word(HEAD_WORDS);\n if (!/^0{56}/.test(lengthWord)) malformed(\"states an impossible message length\");\n const length = parseInt(lengthWord.slice(56), 16);\n if (length > ACROSS_MAX_MESSAGE_BYTES) malformed(`carries a ${length}-byte message, over ${ACROSS_MAX_MESSAGE_BYTES}`);\n const padded = Math.ceil(length / 32) * 64;\n const expected = (HEAD_WORDS + 1) * 64 + padded;\n if (body.length !== expected) {\n malformed(body.length > expected\n ? `has ${(body.length - expected) / 2} bytes after the encoded call`\n : `is ${(hex.length - 2) / 2} bytes, the encoding needs ${4 + expected / 2}`);\n }\n const tail = body.slice((HEAD_WORDS + 1) * 64);\n if (!/^0*$/.test(tail.slice(length * 2))) malformed(\"pads the message with non-zero bytes\");\n const args: AcrossDepositArgs = {\n depositor: addr(0, \"depositor\"),\n recipient: addr(1, \"recipient\"),\n inputToken: addr(2, \"input token\"),\n outputToken: addr(3, \"output token\"),\n inputAmount: BigInt(`0x${word(4)}`),\n outputAmount: BigInt(`0x${word(5)}`),\n destinationChainId: BigInt(`0x${word(6)}`),\n exclusiveRelayer: addr(7, \"exclusive relayer\"),\n quoteTimestamp: u32(8, \"quote timestamp\"),\n fillDeadline: u32(9, \"fill deadline\"),\n exclusivityParameter: u32(10, \"exclusivity parameter\"),\n message: `0x${tail.slice(0, length * 2)}`,\n };\n // Whatever the reads above let through, the bytes are the canonical encoding of what was read.\n if (encodeAcrossDeposit(args) !== hex) malformed(\"is not the canonical encoding of its arguments\");\n return args;\n}\n","/**\n * The device-side check of an Across deposit.\n *\n * An Across deposit is one call, `deposit(...)` on the source chain's SpokePool, and unlike an order-hash deposit its\n * calldata says everything: who is refunded (`depositor`), who is paid (`recipient`), in which token and how much on\n * which chain (`outputToken`, `outputAmount`, `destinationChainId`), by when (`fillDeadline`), and what runs on arrival\n * (`message`). Relayers pay the recipient `outputAmount` of `outputToken` on the destination out of their own funds and\n * are repaid from the deposit; an unfilled deposit is refunded to `depositor` on the source chain after the fill\n * deadline. The SpokePool itself checks almost none of it — no route list, no token pairing, `depositor` not bound\n * to the sender (SpokePool.sol `_depositV3`) — so {@link verifyAcrossDeposit} holds every field to the user's own\n * request and to the pins in `config.ts`, with nothing but the transaction about to be signed:\n *\n * 1. the call is `deposit` on the pinned SpokePool of the source chain, for that chain id, in its canonical encoding;\n * 2. `depositor` is the account that signs and `recipient` the user's recipient; the destination is the requested\n * pinned chain;\n * 3. the input is the pinned token for the request (the wrapped native token, with exactly the amount as value, for\n * the native coin; value 0 and an approval of the SpokePool for an ERC-20), exactly the requested amount;\n * 4. the output is the same asset on the destination (the wrapped native token for the native coin, which the\n * destination SpokePool unwraps for an EOA), at least the caller's floor, and the fee it leaves (input − output)\n * between a floor relayers can be paid with and the cap — a deposit asking relayers for all of its input or more\n * is never filled;\n * 5. the message is empty — the Across V5 witness prefix refused by name — so the tokens land on the recipient and\n * nothing runs;\n * 6. the deadlines are ones the SpokePool accepts and a relayer can still meet, wherever the deposit lands: a quote\n * time not ahead of now (the SpokePool reverts one ahead of its block) and no older than its on-chain buffer\n * allows (with a margin to land); a fill deadline no further from the quote time than an Across quote puts it (so\n * an unfilled deposit holds the funds no longer than that before its refund), and still a fill window away from\n * the last moment the SpokePool takes the deposit (the quote time + 3600 s: nothing on chain refuses a deposit that\n * lands after its own fill deadline); no exclusive relayer (this module never names one).\n *\n * Every refusal is an {@link AcrossRefusal} with its own code. Nothing here is asynchronous and nothing reads the\n * network, so the same function runs when a quote is built, again right before signing, and on the client of a\n * remote provider (`acrossPins.verifyQuote` / `verifyBuild`).\n */\nimport {keccak256, type Hex} from \"viem\";\nimport {bigintToUnits} from \"@anywalletkit/core\";\nimport type {Quote, QuoteParams, RemotePins, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {refusalNotes, refusalOf, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {\n ACROSS_DEPOSIT_QUOTE_TIME_BUFFER_S, ACROSS_FILL_DEADLINE_BUFFER_S, ACROSS_NATIVE, ACROSS_SPEED_UP_DOMAIN, ACROSS_SPEED_UP_TYPE,\n ACROSS_V5_MESSAGE_PREFIX, acrossChain, acrossRouteOf, type AcrossRoute,\n} from \"./config.js\";\nimport {decodeAcrossDeposit, type AcrossDepositArgs} from \"./deposit.js\";\nimport {ACROSS_FLOOR_ORIGINS, acrossRouteUnpriced} from \"./pricing.js\";\nimport {AcrossRefusal} from \"./refusal.js\";\n\n/** The fee cap when the caller names none: input − output at most 10 % of the input. */\nexport const ACROSS_DEFAULT_MAX_FEE_BPS = 1_000;\n/** The widest fee cap a request may ask for (the Across API's own default `maxFee.bps`). */\nexport const ACROSS_MAX_FEE_BPS_LIMIT = 5_000;\n/** Tolerated difference between the device clock and the chains'. */\nexport const ACROSS_CLOCK_SKEW_S = 120;\n/**\n * How far ahead of the device's clock a quote time may sit: the SpokePool reverts a deposit whose quote time is ahead\n * of its block, and an honest one is a HubPool block time minutes in the past (or the latest Ethereum block − 60 s),\n * so this only absorbs a device clock that runs slow.\n */\nexport const ACROSS_QUOTE_TIME_AHEAD_S = 15;\n/**\n * Time a deposit is given to land after this check. The quote time must leave at least this much of its on-chain\n * buffer (`depositQuoteTimeBuffer`, 3600 s), or the deposit reverts on the way.\n */\nexport const ACROSS_LANDING_WINDOW_S = 300;\n/** The fill deadline must leave relayers at least this long, counted from the last moment the deposit can land. */\nexport const ACROSS_MIN_FILL_WINDOW_S = 1_800;\n/**\n * The furthest a fill deadline may sit from the quote time: two hours, as Across's API puts it on every quote\n * (`fillDeadline = quoteTimestamp + 7200` on every V4 quote and API deposit read 2026-11-14), and ten minutes of margin.\n * An unfilled deposit holds the funds until then, and its refund comes after (Across's settlement bundles).\n */\nexport const ACROSS_MAX_FILL_WINDOW_S = 7_800;\n/**\n * The smallest fee a deposit may leave relayers, in millionths of the input, by what is bridged and from where. A\n * relayer pays the output from its own funds and its gas, so a deposit that leaves less than relayers take is not\n * filled and waits two hours for its deadline and then for a refund — while its output, nearly the whole input, would\n * win any comparison of routes. The floors sit at or under the lowest fees plain deposits were filled at over 24 h\n * (2026-11-14, Ethereum, Optimism, Base and Arbitrum): stablecoins 1.0 bp (Across's capital fee, every fill paid it),\n * ETH from Ethereum 0.7 bp (fills at 0.74–0.84), ETH from Optimism, Base or Arbitrum 4.5 bps (capital 3.0+ and LP\n * 1.77 from those origins: fills at 5.0 and up), WBTC 2.5 bps (fills at 3.1; one at 1.03). ETH from any other L2 is\n * 0.7 bp, the lowest any plain ETH deposit was filled at: Across's own relayer quote prices those origins far lower\n * than the studied ones (Linea → Base 1.27 bps, Ink → Base 2.71 bps, live 2026-11-15) and is what prices them, on the\n * server and on the device, so the floor there only refuses dust. A server that names less — a bug, or a hostile one\n * — is refused here, on the device.\n */\nexport const ACROSS_MIN_FEE_PPM = Object.freeze({stable: 100, ethFromEthereum: 70, ethFromL2: 450, ethFromOtherL2: 70, wbtc: 250});\n\n/** The device's fee floor for a route, millionths of the input ({@link ACROSS_MIN_FEE_PPM}). */\nexport function acrossMinFeePpm(route: AcrossRoute): number {\n if (route.asset === \"ETH\") {\n const src = route.input.chain.chainId;\n if (src === 1) return ACROSS_MIN_FEE_PPM.ethFromEthereum;\n return ACROSS_FLOOR_ORIGINS.includes(src) ? ACROSS_MIN_FEE_PPM.ethFromL2 : ACROSS_MIN_FEE_PPM.ethFromOtherL2;\n }\n if (route.asset === \"WBTC\") return ACROSS_MIN_FEE_PPM.wbtc;\n return ACROSS_MIN_FEE_PPM.stable;\n}\n/** A direct deposit used ~85k gas in Across's own estimate (2026-11-14); a gas limit under this is a paid revert. */\nexport const ACROSS_GAS_FLOOR = 90_000n;\n/** Chains that meter gas differently (zkSync) estimate far higher; a stated limit is taken up to this. */\nexport const ACROSS_GAS_CAP = 60_000_000n;\n/** The longest a quote may claim to live: five minutes plus the clock difference. */\nexport const ACROSS_MAX_QUOTE_LIFE_MS = 300_000 + ACROSS_CLOCK_SKEW_S * 1000;\n/** The latest a quote with this quote time may be signed (ms): while the SpokePool still takes it, with time to land. */\nexport const acrossQuoteTimeLimitMs = (quoteTimestamp: number): number => (quoteTimestamp + ACROSS_DEPOSIT_QUOTE_TIME_BUFFER_S - ACROSS_LANDING_WINDOW_S) * 1000;\n\n/**\n * The address a dry quote (pricing only) is asked for when the caller names none. A quote priced with it is never\n * built or signed; the server and a remote client derive the same request from the same parameters with it.\n */\nexport const ACROSS_PLACEHOLDER = \"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045\";\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst ZERO = /^0x0{40}$/;\nconst U256_MAX = (1n << 256n) - 1n;\nconst UINT = /^(?:0|[1-9]\\d{0,77})$/;\n\n/** What the user asked for — the only thing a deposit is compared against. Addresses in any casing. */\nexport interface AcrossRequest {\n /** CAIP-2 of the chain the deposit is sent on. */\n sourceChain: string;\n /** CAIP-2 of the chain the output is paid on. */\n destChain: string;\n /** Input token contract; the zero address is the native coin. */\n sourceToken: string;\n /** Output token contract; the zero address is the native coin. */\n destToken: string;\n /** Exact input, base units. */\n amount: bigint;\n /** The account that signs the deposit: its `depositor` (refunds, and the only key that can sign a speed-up). */\n depositor: string;\n /** Who receives the output. */\n recipient: string;\n /** The caller's own floor on the output, base units. */\n minAmountOut?: bigint;\n /** Fee cap in bps of the input (default {@link ACROSS_DEFAULT_MAX_FEE_BPS}). */\n maxFeeBps?: number;\n /** The clock (ms) deadlines are judged against; defaults to `Date.now()`. */\n nowMs?: number;\n}\n\n/** The deposit transaction under check: what is about to be signed, or what a quote carries. */\nexport interface AcrossDepositTx {\n to?: unknown;\n data?: unknown;\n value?: unknown;\n chainId?: unknown;\n approvalAddress?: unknown;\n}\n\n/** A deposit that passed the checks: the only shape of call this module signs. */\nexport interface AcrossDeposit {\n /** The pinned SpokePool, lowercase. */\n to: string;\n /** The canonical calldata, lowercase. */\n data: Hex;\n /** Wei, decimal: the input amount for the native coin, else \"0\". */\n value: string;\n chainId: number;\n /** ERC-20 input: the spender to approve for exactly the input amount — the pinned SpokePool. */\n approvalAddress?: string;\n}\n\nexport interface VerifiedAcrossDeposit {\n route: AcrossRoute;\n args: AcrossDepositArgs;\n deposit: AcrossDeposit;\n /** input − output, in the input token's base units (both sides have the same decimals). */\n fee: bigint;\n}\n\nconst lower = (s: string): string => s.toLowerCase();\n\n/** A request that passed {@link checkAcrossRequest}: its route, the clock it is judged by, its fee cap. */\nexport interface CheckedAcrossRequest {\n route: AcrossRoute;\n nowS: number;\n maxFeeBps: number;\n}\n\n/** The request's own sanity and its route (pinned chains, same asset); throws {@link AcrossRefusal}. */\nexport function checkAcrossRequest(r: AcrossRequest): CheckedAcrossRequest {\n // A malformed request is the caller's own bug and carries no reason; the zero-address parties and the route are refusals.\n const invalid = (what: string, reason?: Swap2RefusalReason): never => { throw new AcrossRefusal(\"request-invalid\", what, reason); };\n if (r === null || typeof r !== \"object\") invalid(\"no request to check the deposit against\");\n for (const [what, v] of [[\"input token\", r.sourceToken], [\"output token\", r.destToken], [\"depositor\", r.depositor], [\"recipient\", r.recipient]] as const) {\n if (typeof v !== \"string\" || !ADDRESS.test(v)) invalid(`the ${what} is not an address`);\n }\n const route = acrossRouteOf(r.sourceChain, r.sourceToken, r.destChain, r.destToken);\n if (\"code\" in route) throw new AcrossRefusal(route.code, route.detail, \"unsupported_pair\");\n if (ZERO.test(r.depositor)) invalid(\"the depositor is the zero address\", \"recipient_mismatch\");\n if (ZERO.test(r.recipient)) invalid(\"the recipient is the zero address\", \"recipient_mismatch\");\n if (typeof r.amount !== \"bigint\" || r.amount <= 0n || r.amount > U256_MAX) invalid(\"the amount is not a positive integer\");\n if (r.minAmountOut !== undefined && (typeof r.minAmountOut !== \"bigint\" || r.minAmountOut < 0n || r.minAmountOut > U256_MAX)) invalid(\"the output floor is not an unsigned integer\");\n const maxFeeBps = r.maxFeeBps ?? ACROSS_DEFAULT_MAX_FEE_BPS;\n if (!Number.isInteger(maxFeeBps) || maxFeeBps < 0 || maxFeeBps > ACROSS_MAX_FEE_BPS_LIMIT) {\n invalid(`the fee cap must be a whole number of basis points up to ${ACROSS_MAX_FEE_BPS_LIMIT}`, \"policy_refused\");\n }\n const nowMs = r.nowMs ?? Date.now();\n if (!Number.isFinite(nowMs) || nowMs <= 0) invalid(\"the clock is not a time\");\n return {route, nowS: Math.floor(nowMs / 1000), maxFeeBps};\n}\n\n/** Where the deposit goes: the pinned SpokePool of the source chain, and nothing else. Checked before the calldata is read. */\nfunction checkTarget(tx: AcrossDepositTx, route: AcrossRoute): void {\n if (tx === null || typeof tx !== \"object\") throw new AcrossRefusal(\"tx-shape\", \"there is no deposit transaction\", \"policy_refused\");\n const src = route.input.chain;\n 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\");\n if (typeof tx.to !== \"string\" || !ADDRESS.test(tx.to) || lower(tx.to) !== src.spokePool) {\n throw new AcrossRefusal(\"tx-target\", `the deposit calls ${String(tx.to)}, not the ${src.name} SpokePool ${src.spokePool} — periphery, swap and CCTP / OFT routes are not signed by this module`, \"vault_mismatch\");\n }\n}\n\n/**\n * No exclusivity. This module builds every deposit without an exclusive relayer; one named by a quote source would\n * be the only one allowed to fill for its window (a deposit nobody else may fill for up to an hour, or a fee kept for\n * the relayer the source chose), and nothing this module prices calls for one.\n */\nfunction checkExclusivity(a: AcrossDepositArgs): void {\n if (!ZERO.test(a.exclusiveRelayer) || a.exclusivityParameter !== 0) {\n throw new AcrossRefusal(\"tx-exclusivity\", `the deposit names an exclusive relayer or window (${a.exclusiveRelayer}, ${a.exclusivityParameter}) — this module signs plain deposits any relayer may fill`, \"policy_refused\");\n }\n}\n\n/**\n * The deadlines: what the SpokePool accepts, with room for the deposit to land and for a relayer to fill wherever it\n * lands, and no longer a hold on the funds than an Across quote sets.\n */\nfunction checkDeadlines(a: AcrossDepositArgs, nowS: number): void {\n const age = nowS - a.quoteTimestamp;\n 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\");\n if (age > ACROSS_DEPOSIT_QUOTE_TIME_BUFFER_S - ACROSS_LANDING_WINDOW_S) {\n 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\");\n }\n const left = a.fillDeadline - nowS;\n if (left > ACROSS_FILL_DEADLINE_BUFFER_S - ACROSS_CLOCK_SKEW_S) {\n 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\");\n }\n const window = a.fillDeadline - a.quoteTimestamp;\n if (window > ACROSS_MAX_FILL_WINDOW_S) {\n 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 — unfilled, the deposit would hold the funds that long before its refund`, \"policy_refused\");\n }\n if (left < ACROSS_MIN_FILL_WINDOW_S) {\n 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 — the deposit would expire into a refund`, \"quote_expired\");\n }\n // `_depositV3` has no lower bound on the fill deadline: a deposit that waits to be mined lands, expired, as late as\n // its quote time + `depositQuoteTimeBuffer`. The deadline must leave a relayer its window even then.\n if (window < ACROSS_DEPOSIT_QUOTE_TIME_BUFFER_S + ACROSS_MIN_FILL_WINDOW_S) {\n 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\");\n }\n}\n\n/**\n * Check a deposit transaction against the user's request and the pins. Returns the decoded arguments, the route and\n * the deposit as it will be signed; throws {@link AcrossRefusal} otherwise.\n */\nexport function verifyAcrossDeposit(request: AcrossRequest, tx: AcrossDepositTx): VerifiedAcrossDeposit {\n const {route, nowS, maxFeeBps} = checkAcrossRequest(request);\n checkTarget(tx, route);\n const a = decodeAcrossDeposit(tx.data);\n const src = route.input.chain;\n const dst = route.output.chain;\n\n // Who: the deposit is credited (and refunded) to the account that signs, and pays the recipient.\n if (a.depositor !== lower(request.depositor)) {\n throw new AcrossRefusal(\"tx-depositor\", `the deposit is credited to ${a.depositor}, not to the signing account ${lower(request.depositor)} — the depositor is refunded and can redirect the output`, \"recipient_mismatch\");\n }\n if (a.recipient !== lower(request.recipient)) throw new AcrossRefusal(\"tx-recipient\", `the deposit pays ${a.recipient}, not the recipient ${lower(request.recipient)}`, \"recipient_mismatch\");\n if (a.destinationChainId !== BigInt(dst.chainId)) {\n throw new AcrossRefusal(\"tx-destination\", `the deposit is for chain ${a.destinationChainId}, not ${dst.name} (${dst.chainId})`, \"recipient_mismatch\");\n }\n\n // What goes in: exactly the requested amount of the pinned token.\n 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\");\n if (a.inputAmount !== request.amount) throw new AcrossRefusal(\"tx-input-amount\", `the deposit takes ${a.inputAmount}, the request sends ${request.amount}`, \"policy_refused\");\n\n // What comes out: the same asset, at least the floor, and less than went in by a fee relayers can be paid with.\n 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\");\n if (a.outputAmount <= 0n) throw new AcrossRefusal(\"tx-output-amount\", \"the deposit's output is zero\", \"price_check_failed\");\n if (request.minAmountOut !== undefined && a.outputAmount < request.minAmountOut) {\n throw new AcrossRefusal(\"tx-output-amount\", `the deposit pays ${a.outputAmount}, under the caller's floor ${request.minAmountOut}`, \"price_check_failed\");\n }\n if (a.outputAmount > a.inputAmount) {\n throw new AcrossRefusal(\"tx-output-amount\", `the deposit asks relayers for ${a.outputAmount}, more than its ${a.inputAmount} input — nobody fills it, and the funds wait for a refund`, \"price_check_failed\");\n }\n const fee = a.inputAmount - a.outputAmount;\n if (fee === 0n) {\n throw new AcrossRefusal(\"tx-fee\", \"the deposit leaves relayers no fee — nobody fills it, and the funds wait for a refund\", \"price_check_failed\");\n }\n const minPpm = acrossMinFeePpm(route);\n if (fee * 1_000_000n < a.inputAmount * BigInt(minPpm)) {\n 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} — relayers do not fill it, and the funds wait for a refund`, \"price_check_failed\");\n }\n if (fee * 10_000n > a.inputAmount * BigInt(maxFeeBps)) {\n throw new AcrossRefusal(\"tx-fee\", `the deposit leaves ${fee} of ${a.inputAmount} as fees, over the ${maxFeeBps} bps cap`, \"price_check_failed\");\n }\n\n // Nothing runs on arrival.\n if (a.message !== \"0x\") {\n if (a.message.length >= 66 && a.message.slice(0, 66) === ACROSS_V5_MESSAGE_PREFIX) {\n throw new AcrossRefusal(\"tx-message-v5\", \"the deposit carries an Across V5 witness message, consumable only through the V5 Gateway\", \"policy_refused\");\n }\n throw new AcrossRefusal(\"tx-message\", `the deposit carries a ${(a.message.length - 2) / 2}-byte message for the destination — only plain transfers are signed`, \"policy_refused\");\n }\n\n checkExclusivity(a);\n checkDeadlines(a, nowS);\n\n // The money attached: the input itself for the native coin (the SpokePool wraps it), nothing for an ERC-20.\n const value = typeof tx.value === \"string\" && UINT.test(tx.value) ? BigInt(tx.value) : null;\n const wantValue = route.input.native ? a.inputAmount : 0n;\n if (value === null || value !== wantValue) throw new AcrossRefusal(\"tx-value\", `the deposit sends ${String(tx.value)} wei, it must send ${wantValue}`, \"policy_refused\");\n const approval = tx.approvalAddress;\n if (route.input.native) {\n if (approval !== undefined && approval !== \"\") throw new AcrossRefusal(\"tx-approval\", `a native deposit approves nothing, the transaction approves ${String(approval)}`, \"vault_mismatch\");\n } else if (typeof approval !== \"string\" || lower(approval) !== src.spokePool) {\n throw new AcrossRefusal(\"tx-approval\", `the deposit approves ${String(approval)}, it must approve the ${src.name} SpokePool ${src.spokePool}`, \"vault_mismatch\");\n }\n\n return {\n route,\n args: a,\n deposit: {\n to: src.spokePool,\n data: lower(tx.data as string) as Hex,\n value: wantValue.toString(10),\n chainId: src.chainId,\n ...(route.input.native ? {} : {approvalAddress: src.spokePool}),\n },\n fee,\n };\n}\n\n/** The intent id of a deposit: the route and a digest of the exact calldata (`across:<from>:<to>:<16 bytes hex>`). */\nexport function acrossIntentId(sourceChainId: number, destChainId: number, data: Hex): string {\n return `across:${sourceChainId}:${destChainId}:${keccak256(lower(data) as Hex).slice(2, 34)}`;\n}\n\n/** The route an intent id names (a server's `~<tag>` suffix tolerated), or null. */\nexport function parseAcrossIntentId(intentId: string): {sourceChainId: number; destChainId: number; digest: string} | null {\n if (typeof intentId !== \"string\") return null;\n const m = /^across:([1-9]\\d{0,15}):([1-9]\\d{0,15}):([0-9a-f]{32})(?:~[0-9a-f]{32})?$/.exec(intentId);\n if (!m) return null;\n return {sourceChainId: Number(m[1]), destChainId: Number(m[2]), digest: m[3]!};\n}\n\n/**\n * True for typed data an Across speed-up signature would be made over (`UpdateDepositDetails`, or Across's `ACROSS-V2`\n * domain). A wallet can run this on any signing request; nothing this module builds is ever typed data.\n */\nexport function isAcrossSpeedUpTypedData(typedData: unknown): boolean {\n let v: unknown = typedData;\n if (typeof v === \"string\") {\n try { v = JSON.parse(v); } catch { return /UpdateDepositDetails|ACROSS-V2/.test(v as string); }\n }\n if (v === null || typeof v !== \"object\") return false;\n const t = v as {primaryType?: unknown; types?: unknown; domain?: {name?: unknown} | null};\n if (t.primaryType === ACROSS_SPEED_UP_TYPE) return true;\n if (t.types !== null && typeof t.types === \"object\" && Object.prototype.hasOwnProperty.call(t.types, ACROSS_SPEED_UP_TYPE)) return true;\n return t.domain !== null && typeof t.domain === \"object\" && t.domain.name === ACROSS_SPEED_UP_DOMAIN;\n}\n\n/** The one shape a transaction to sign may have: an EVM call — never typed data, a memo or a serialized transaction. */\nexport function checkAcrossTxShape(tx: UnsignedTx): void {\n if (tx.typedData !== undefined) {\n if (isAcrossSpeedUpTypedData(tx.typedData)) throw new AcrossRefusal(\"speed-up\", \"the request is an Across speed-up signature, which can redirect a deposit's output — never signed\", \"policy_refused\");\n throw new AcrossRefusal(\"tx-shape\", \"an Across deposit is one EVM call, not typed data\", \"policy_refused\");\n }\n if (tx.serializedTx !== undefined || tx.memo !== undefined || tx.bodyBoc !== undefined || tx.stateInitBoc !== undefined || tx.orderExtension !== undefined) {\n throw new AcrossRefusal(\"tx-shape\", \"an Across deposit is one EVM call\", \"policy_refused\");\n }\n}\n\n/** A refusal's text for a caller that wants a string (`onRefusal`, remote pins); rethrows anything else. */\nexport function acrossRefusalReason(err: unknown): string {\n if (err instanceof AcrossRefusal) return err.message;\n throw err;\n}\n\n/**\n * The request a `QuoteParams` describes, for the verifier. `placeholder` (a dry quote: pricing only) fills a missing\n * address.\n *\n * The depositor is `sender`, the account that signs — set by the engine on every execution quote. Across refunds the\n * depositor, and the depositor alone can sign a speed-up that a relayer fills to another recipient or for less\n * (SpokePool.sol `fillRelayWithUpdatedDeposit`, an EIP-712 or EIP-1271 signature of `relayData.depositor`): a refund\n * address the caller names is never made the depositor, and one other than the signer is refused. A live request\n * without `sender` is refused; a dry one is priced for `refundAddress` (or the placeholder).\n */\nexport function acrossRequestOf(params: QuoteParams, opts: {placeholder?: string; nowMs?: number; maxFeeBps?: number} = {}): AcrossRequest {\n const invalid = (what: string, reason?: Swap2RefusalReason): never => { throw new AcrossRefusal(\"request-invalid\", what, reason); };\n if (params === null || typeof params !== \"object\") invalid(\"no request\");\n if (params.flex) invalid(\"the amount is part of the deposit (no flexible deposits)\", \"unsupported_pair\");\n if (!acrossChain(params.sourceChain)) throw new AcrossRefusal(\"chain-unsupported\", `source chain ${String(params.sourceChain)} is not a pinned Across chain`, \"unsupported_pair\");\n if (!acrossChain(params.destChain)) throw new AcrossRefusal(\"chain-unsupported\", `destination chain ${String(params.destChain)} is not a pinned Across chain`, \"unsupported_pair\");\n if (params.sourceChain === params.destChain) throw new AcrossRefusal(\"chain-unsupported\", \"same-chain swaps are not served through a SpokePool\", \"unsupported_pair\");\n let sourceToken: string;\n if (typeof params.sourceToken === \"string\" && ADDRESS.test(params.sourceToken)) sourceToken = params.sourceToken;\n else {\n const asset = sourceAssetOf(params);\n if (!asset) invalid(`source token ${String(params.sourceToken)} is not known on ${params.sourceChain}`, \"unsupported_pair\");\n sourceToken = asset!.contract ?? ACROSS_NATIVE;\n if (!ADDRESS.test(sourceToken)) invalid(`source token ${String(params.sourceToken)} has no EVM contract`, \"unsupported_pair\");\n }\n if (typeof params.destToken !== \"string\" || !ADDRESS.test(params.destToken)) invalid(\"the destination token must be an EVM address (zero for the native coin)\", \"unsupported_pair\");\n const route = acrossRouteOf(params.sourceChain, sourceToken, params.destChain, params.destToken);\n if (\"code\" in route) throw new AcrossRefusal(route.code, route.detail, \"unsupported_pair\");\n const unpriced = acrossRouteUnpriced(route);\n if (unpriced) throw new AcrossRefusal(\"route-unpriced\", unpriced, \"unsupported_pair\");\n if (typeof params.amountIn !== \"string\" || !/^[1-9]\\d{0,77}$/.test(params.amountIn)) invalid(\"amount must be a positive base-unit integer\");\n if (params.minAmountOut !== undefined && !UINT.test(params.minAmountOut)) invalid(\"the output floor must be a base-unit integer\");\n const recipient = params.destAddress || opts.placeholder || \"\";\n if (!recipient) invalid(\"a live quote needs a recipient\");\n if (!ADDRESS.test(recipient)) invalid(\"the recipient must be an EVM address\");\n const sender = params.sender || \"\";\n const refund = params.refundAddress || \"\";\n if (sender && !ADDRESS.test(sender)) invalid(\"the signing account (sender) must be an EVM address\");\n if (refund && !ADDRESS.test(refund)) invalid(\"the refund address must be an EVM address\");\n if (sender && refund && lower(sender) !== lower(refund)) {\n 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\");\n }\n const depositor = sender || (opts.placeholder ? refund || opts.placeholder : \"\");\n if (!depositor) invalid(\"a live quote needs the signing account (sender)\");\n if (!ADDRESS.test(depositor)) invalid(\"the depositor must be an EVM address\");\n return {\n sourceChain: params.sourceChain,\n destChain: params.destChain,\n sourceToken,\n destToken: params.destToken,\n amount: BigInt(params.amountIn),\n depositor,\n recipient,\n ...(params.minAmountOut !== undefined ? {minAmountOut: BigInt(params.minAmountOut)} : {}),\n ...(opts.maxFeeBps !== undefined ? {maxFeeBps: opts.maxFeeBps} : {}),\n ...(opts.nowMs !== undefined ? {nowMs: opts.nowMs} : {}),\n };\n}\n\n/**\n * What a quote shows of a deposit's fee: `fees` — exactly one included protocol fee of input − output, in the input\n * token (the zero address for the native coin) — and `feeUsd`, the fee itself for a dollar stablecoin (USDC, USDT, one\n * unit a dollar) and 0 for an asset this module has no price for. The engine's fee caps (`maxProtocolFeeBps`) and the\n * router's scoring read these, so a quote is held to them exactly ({@link checkAcrossQuote}).\n */\nexport function acrossQuoteFeesOf(route: AcrossRoute, fee: bigint): Pick<Quote, \"fees\" | \"feeUsd\"> {\n const usd = route.asset === \"USDC\" || route.asset === \"USDT\";\n return {\n feeUsd: usd ? bigintToUnits(fee, route.input.decimals) : 0,\n 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\"}] : [],\n };\n}\n\n/**\n * A quote of this provider against the request it answers: its transaction passes {@link verifyAcrossDeposit}, its id\n * names that very calldata, and the amounts it shows are the deposit's (`outputAmount` is what the recipient gets —\n * a relayer pays exactly that), its fees too ({@link acrossQuoteFeesOf}: the engine's fee caps read them), and it\n * claims to live no longer than the SpokePool takes its quote time. Throws {@link AcrossRefusal}. Used on the client\n * of a remote provider and again before a build and a signature.\n */\nexport function checkAcrossQuote(request: AcrossRequest, quote: Quote, tx?: AcrossDepositTx & {gasLimit?: unknown}): VerifiedAcrossDeposit {\n if (quote === null || typeof quote !== \"object\" || quote.provider !== \"across\") throw new AcrossRefusal(\"quote-shape\", \"not an Across quote\", \"policy_refused\");\n const t = tx ?? quote.txRequest;\n if (!t) throw new AcrossRefusal(\"quote-shape\", \"the quote has no transaction\", \"policy_refused\");\n if (quote.depositAddress) throw new AcrossRefusal(\"quote-shape\", \"an Across quote pays the SpokePool through its calldata, never a deposit address\", \"vault_mismatch\");\n const extra = quote.txRequest as {serializedTx?: unknown; nativeFee?: unknown} | undefined;\n if (extra?.serializedTx !== undefined || extra?.nativeFee !== undefined) {\n throw new AcrossRefusal(\"quote-shape\", \"an Across deposit carries no extra native fee and no serialized transaction\", \"policy_refused\");\n }\n const v = verifyAcrossDeposit(request, t);\n if (quote.sourceAmount !== v.args.inputAmount.toString(10) || quote.minDestAmount !== v.args.outputAmount.toString(10) || quote.destAmount !== v.args.outputAmount.toString(10)\n || quote.destDecimals !== v.route.output.decimals) {\n throw new AcrossRefusal(\"quote-amounts\", \"the amounts the quote shows are not the deposit's\", \"price_check_failed\");\n }\n // The fee list is what the engine's fee caps add up, and feeUsd what routes are scored by: the deposit's own fee, exactly.\n const shown = acrossQuoteFeesOf(v.route, v.fee);\n const w = shown.fees![0]!;\n const g = Array.isArray(quote.fees) && quote.fees.length === 1 ? quote.fees[0] : undefined;\n 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) {\n 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\");\n }\n // Gas is the one number of the call no argument binds: held to a band, so a backend can neither starve the deposit\n // (a paid revert) nor name an absurd limit. Absent = the wallet estimates.\n const gas = (t as {gasLimit?: unknown}).gasLimit;\n if (gas !== undefined) {\n if (typeof gas !== \"string\" || !/^[1-9]\\d{0,10}$/.test(gas) || BigInt(gas) < ACROSS_GAS_FLOOR || BigInt(gas) > ACROSS_GAS_CAP) {\n throw new AcrossRefusal(\"quote-gas\", `the gas limit ${String(gas).slice(0, 40)} is outside ${ACROSS_GAS_FLOOR}–${ACROSS_GAS_CAP}`, \"policy_refused\");\n }\n }\n const now = request.nowMs ?? Date.now();\n if (typeof quote.validUntilMs !== \"number\" || !Number.isFinite(quote.validUntilMs) || quote.validUntilMs > now + ACROSS_MAX_QUOTE_LIFE_MS) {\n throw new AcrossRefusal(\"quote-expiry\", \"the quote claims to live longer than an Across quote may\", \"policy_refused\");\n }\n // Signed as late as the quote says it may be, the deposit must still land while the SpokePool takes its quote time.\n if (quote.validUntilMs > acrossQuoteTimeLimitMs(v.args.quoteTimestamp)) {\n 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 — signed then, the deposit would revert on it`, \"policy_refused\");\n }\n // A server appends its intent token (`<id>~<tag>`); the id before it must name this deposit.\n const intent = parseAcrossIntentId(quote.intentId);\n const want = acrossIntentId(v.route.input.chain.chainId, v.route.output.chain.chainId, v.deposit.data);\n if (!intent || `across:${intent.sourceChainId}:${intent.destChainId}:${intent.digest}` !== want) {\n throw new AcrossRefusal(\"quote-intent\", \"the quote's id does not name its deposit\", \"policy_refused\");\n }\n return v;\n}\n\n// The reason behind each text the pins return (`acrossPins.reasonOf`), bounded.\nconst pinNotes = refusalNotes();\n/** The refusal's text, its reason noted for `acrossPins.reasonOf`; rethrows anything that is not a refusal. */\nfunction notedReason(err: unknown): string {\n const text = acrossRefusalReason(err);\n const info = refusalOf(err);\n return info ? pinNotes.note(text, info) : text;\n}\n\n/** What the pins hold a remote quote to beyond the user's request: the app's own fee cap. */\nexport interface AcrossPinsOptions {\n /** Fee cap in bps of the input (default {@link ACROSS_DEFAULT_MAX_FEE_BPS}, at most {@link ACROSS_MAX_FEE_BPS_LIMIT}) — the app's, never the server's. */\n maxFeeBps?: number;\n}\n\n/** The request a remote quote is held to: the server's own derivation — a dry quote priced for the placeholder where the caller named no address. */\nexport const acrossPinsRequestOf = (params: QuoteParams, cap: {maxFeeBps?: number} = {}): AcrossRequest => acrossRequestOf(params, params.dry !== false ? {...cap, placeholder: ACROSS_PLACEHOLDER} : cap);\n\nfunction verifyQuoteWith(params: QuoteParams, quote: Quote, cap: {maxFeeBps?: number}): string | null {\n try {\n checkAcrossQuote(acrossPinsRequestOf(params, cap), quote);\n return null;\n } catch (err) {\n return notedReason(err);\n }\n}\n\n/**\n * A remote build against the request the app sent, by the device's clock now: the quote's own deposit, verified again\n * ({@link checkAcrossQuote}). Throws {@link AcrossRefusal}. `acrossPins.verifyBuild` and `acrossRemoteProvider`'s\n * preflight (right before signing) run it.\n */\nexport function acrossCheckBuild(quote: Quote, tx: UnsignedTx, params: QuoteParams | undefined, cap: {maxFeeBps?: number} = {}): VerifiedAcrossDeposit {\n if (!params) throw new AcrossRefusal(\"request-invalid\", \"the request this quote answered is not known on this side — quote again\", \"policy_refused\");\n if (tx.chain !== params.sourceChain) throw new AcrossRefusal(\"tx-chain\", `the build is for ${tx.chain}, not ${params.sourceChain}`, \"vault_mismatch\");\n checkAcrossTxShape(tx);\n return checkAcrossQuote(acrossRequestOf(params, cap), quote, tx);\n}\n\nfunction verifyBuildWith(quote: Quote, tx: UnsignedTx, params: QuoteParams | undefined, cap: {maxFeeBps?: number}): string | null {\n try {\n acrossCheckBuild(quote, tx, params, cap);\n return null;\n } catch (err) {\n return notedReason(err);\n }\n}\n\n/** `RemotePins.verifyQuote` with the default fee cap: the reason a remote Across quote fails against the user's own request, or null. */\nexport function acrossVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n return verifyQuoteWith(params, quote, {});\n}\n\n/** `RemotePins.verifyBuild` with the default fee cap: a remote build must be the quote's own (verified) transaction, and is verified again. */\nexport function acrossVerifyBuild(quote: Quote, tx: UnsignedTx, params?: QuoteParams): string | null {\n return verifyBuildWith(quote, tx, params, {});\n}\n\n/**\n * The app's pins for a remote Across provider (`remoteProvider({name: \"across\", ...acrossPinsWith({maxFeeBps})})`): the\n * only contract a build may call or approve is the chain's SpokePool, and every quote and build is verified on the\n * client against the user's own request and the app's fee cap — a server's own cap (`acrossProvider({maxFeeBps})`) is\n * not known on this side, so the app states the one it holds remote quotes to. `reasonOf` classifies a text\n * `verifyQuote` / `verifyBuild` returned. Throws a plain `Error` for a cap out of range.\n */\nexport function acrossPinsWith(opts: AcrossPinsOptions = {}): RemotePins {\n const maxFeeBps = opts.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 cap = Object.freeze(maxFeeBps !== undefined ? {maxFeeBps} : {});\n return Object.freeze({\n callTargets: (chain: string): readonly string[] => { const c = acrossChain(chain); return c ? [c.spokePool] : []; },\n spenders: (chain: string): readonly string[] => { const c = acrossChain(chain); return c ? [c.spokePool] : []; },\n verifyQuote: (params: QuoteParams, quote: Quote): string | null => verifyQuoteWith(params, quote, cap),\n verifyBuild: (quote: Quote, tx: UnsignedTx, params?: QuoteParams): string | null => verifyBuildWith(quote, tx, params, cap),\n reasonOf: pinNotes.reasonOf,\n });\n}\n\n/** {@link acrossPinsWith} with the default fee cap (10 %): `remoteProvider({name: \"across\", ...acrossPins})`. */\nexport const acrossPins: RemotePins = acrossPinsWith();\n","/**\n * How much a plain SpokePool deposit leaves to relayers — the one number a quote source decides.\n *\n * The risk is two-sided. Asking relayers for too much (`outputAmount` too high) and nobody fills: the funds wait for\n * the fill deadline (two hours) and then Across's refund bundles (hours more). Asking for too little and the user\n * overpays. Across API V5 is the price source, but it prices V5's OWN route, not a plain deposit: an execution step on\n * the origin chain through Across's Gateway that a plain deposit does not have (the user's own wallet pays the\n * deposit's gas), sometimes another rail (USDT Ethereum → Arbitrum went to a 20-minute rail on 2026-11-14), and an\n * auction whose relayers fill large ETH L2 → L2 transfers at ~1 bp, well below what plain deposits are filled at.\n *\n * The rule (study of 2026-11-15: 27 V5 / suggested-fees pairs and 8 272 deposits on Ethereum, Optimism, Base and\n * Arbitrum over 24 h — 1 369 of 1 369 organic plain deposits to Base, Arbitrum and Optimism priced at or above the\n * relayer fee were filled, p50 2 s, p90 13 s):\n *\n * ```\n * F5 = V5 fee.totalFee − Σ V5 gasEstimates[origin, included_in_transfer_fee] (the add-back rounded down)\n * Fneed = /suggested-fees totalRelayFee.total while Across answers it\n * = floor(asset, origin, size) + 1.5 × V5's destination gas otherwise (studied routes only)\n * fee = max(F5, Fneed); outputAmount = input − fee\n * = Fneed, from /suggested-fees only, when V5's fill estimate is over a minute (V5 prices another rail)\n * quoteTimestamp = /suggested-fees `timestamp` (the LP fee was priced there; never ahead of the server's clock), else\n * min(latest Ethereum block time − 60 s, latest origin block time)\n * fillDeadline = quoteTimestamp + 7200; no exclusivity\n * ```\n *\n * `max()` keeps both bounds: never more than V5 charges for the same transfer (net of the step a plain deposit does\n * not have), never less than plain deposits are filled at today. When V5's fill estimate is over a minute its price\n * is another rail's (a CCTP or OFT transfer, 1 216 s for USDT Ethereum → Arbitrum on 2026-11-15, at 12× the relayer\n * fee), not a bound on a plain deposit: the deposit is then priced on Across's relayer fee alone, and refused without it.\n *\n * The device holds whatever a server says to its own checks (`verify.ts`, `remote.ts`): the user's cap, a per-asset\n * fee floor, and — through `acrossRemoteProvider` — Across's keyless relayer fee read on the device itself\n * ({@link acrossCheckRelayerFee}), so a server can neither take a deposit nor get one signed that relayers leave unfilled.\n */\nimport type {AcrossSuggestedFees} from \"./api.js\";\nimport type {AcrossRoute} from \"./config.js\";\nimport {AcrossRefusal} from \"./refusal.js\";\n\n/** The fill deadline after the quote time: what Across's own quotes give (3 923 of 6 982 plain deposits, 2026-11-14). */\nexport const ACROSS_FILL_WINDOW_S = 7_200;\n/** Without `/suggested-fees`, the quote time lags Ethereum's latest block by this much (the LP fee is priced at a HubPool block). */\nexport const ACROSS_QUOTE_TIME_LAG_S = 60;\n\n/**\n * The relayer-fee floor without `/suggested-fees`, in hundredths of a basis point (millionths) of the input, read off 24 h of\n * fills priced by it (2026-11-14): stablecoins 1.00 bp, WBTC 3.10 bps, ETH from Ethereum 1.00 bp (fills seen at\n * 0.74–0.84), ETH from an L2 on a size curve. Plus 1.5 × V5's destination gas.\n */\nexport const ACROSS_FLOOR_CBPS = Object.freeze({stable: 100, wbtc: 310, ethFromEthereum: 100});\n/** ETH from an L2: [size in USD, hundredths of a bp], linear between points — the curve every plain ETH L2 → L2 deposit of $1 000+ paid. */\nexport const ACROSS_ETH_L2_CURVE: readonly (readonly [number, number])[] = Object.freeze([\n [0, 477], [1_000, 515], [2_000, 540], [4_000, 605], [8_000, 715], [16_000, 850], [36_000, 920],\n].map((p) => Object.freeze(p as [number, number])));\n/** Above this size (USD) no plain ETH L2 deposit was seen: refused when the floor is what prices it. */\nexport const ACROSS_ETH_L2_FLOOR_MAX_USD = 36_000;\n/**\n * The chains the floor was derived on: deposits from Ethereum, Optimism, Base and Arbitrum to Optimism, Base and\n * Arbitrum. Without `/suggested-fees` any other route has no relayer price this module can stand behind.\n */\nexport const ACROSS_FLOOR_ORIGINS: readonly number[] = Object.freeze([1, 10, 8453, 42161]);\nexport const ACROSS_FLOOR_DESTINATIONS: readonly number[] = Object.freeze([10, 8453, 42161]);\n\n/** Whether the pinned floor covers a route (its origin and destination are among the studied chains). */\nexport function acrossFloorCovers(route: AcrossRoute): boolean {\n return ACROSS_FLOOR_ORIGINS.includes(route.input.chain.chainId) && ACROSS_FLOOR_DESTINATIONS.includes(route.output.chain.chainId);\n}\n\n/**\n * Over this fill estimate (ms) a V5 quote prices another rail than an Across relayer fill: Across-rail fills were\n * estimated at 1.3–14 s on every recorded cell, the OFT rail for USDT Ethereum → Arbitrum at 1 216 s (2026-11-15).\n */\nexport const ACROSS_V5_OTHER_RAIL_FILL_MS = 60_000;\n/** True when a V5 fill estimate says V5 priced another rail. */\nexport const acrossV5OtherRail = (expectedFillTimeMs: number): boolean => expectedFillTimeMs > ACROSS_V5_OTHER_RAIL_FILL_MS;\n\n/**\n * Why a route is not priced at all, or null. Ethereum as the destination: small plain deposits to Ethereum went\n * unfilled in the study's window (some paying more than filled ones), for reasons the data does not show — kept out\n * until studied rather than priced on a guess.\n */\nexport function acrossRouteUnpriced(route: AcrossRoute): string | null {\n if (route.output.chain.chainId === 1) return \"plain deposits to Ethereum are not priced yet — small ones went unfilled in the 2026-11-14 study for reasons the data does not show\";\n return null;\n}\n\n/** The floor in hundredths of a bp for a route and size (USD), or a refusal text. */\nexport function acrossFloorCbps(route: AcrossRoute, amountUsd: number | undefined): number | string {\n const src = route.input.chain.chainId;\n if (!acrossFloorCovers(route)) {\n return `without Across's relayer fee quote there is no relayer price for ${route.input.chain.name} → ${route.output.chain.name} (the pinned floor covers Ethereum, Optimism, Base and Arbitrum to Optimism, Base and Arbitrum)`;\n }\n if (route.asset === \"USDC\" || route.asset === \"USDT\") return ACROSS_FLOOR_CBPS.stable;\n if (route.asset === \"WBTC\") return ACROSS_FLOOR_CBPS.wbtc;\n if (src === 1) return ACROSS_FLOOR_CBPS.ethFromEthereum;\n if (amountUsd === undefined || !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\";\n 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)`;\n const c = ACROSS_ETH_L2_CURVE;\n for (let i = 1; i < c.length; i++) {\n const [x1, y1] = c[i]!;\n if (amountUsd <= x1) {\n const [x0, y0] = c[i - 1]!;\n return Math.ceil(y0 + ((y1 - y0) * (amountUsd - x0)) / (x1 - x0));\n }\n }\n return c[c.length - 1]![1];\n}\n\n/** `amount × cbps / 1 000 000`, rounded up. */\nexport const acrossCbpsOf = (amount: bigint, cbps: number): bigint => (amount * BigInt(cbps) + 999_999n) / 1_000_000n;\n\n/** The pinned-floor relayer need for a route without `/suggested-fees`: floor + 1.5 × V5's destination gas, rounded up. */\nexport function acrossFloorFee(route: AcrossRoute, amount: bigint, amountUsd: number | undefined, destinationGas: bigint | null): bigint {\n const cbps = acrossFloorCbps(route, amountUsd);\n if (typeof cbps === \"string\") {\n // Too large only where the floor covers the route and the size is what it lacks; elsewhere the relayer price is.\n const tooLarge = acrossFloorCovers(route) && route.asset === \"ETH\" && route.input.chain.chainId !== 1 && amountUsd !== undefined && amountUsd > ACROSS_ETH_L2_FLOOR_MAX_USD;\n throw new AcrossRefusal(\"relayer-price\", cbps, tooLarge ? \"amount_too_large\" : \"upstream_unavailable\");\n }\n 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\");\n return acrossCbpsOf(amount, cbps) + (destinationGas * 3n + 1n) / 2n;\n}\n\n/** The fee of a plain deposit: `max(F5, Fneed)`, with both terms. */\nexport interface AcrossPlainFee {\n fee: bigint;\n /** V5's fee net of its origin execution step. */\n f5: bigint;\n /** What a relayer needs (`/suggested-fees`, or the floor). */\n need: bigint;\n}\n\n/**\n * `max(F5, Fneed)`; `Fneed` alone when V5 priced another rail (`otherRail`: F5 is then that rail's price, kept for\n * display only). Refuses a fee that eats the whole input (`amount_too_small`).\n */\nexport function acrossPlainFee(amount: bigint, v5: {totalFee: bigint; originGas: bigint}, need: bigint, otherRail = false): AcrossPlainFee {\n const f5 = v5.totalFee - (v5.originGas > v5.totalFee ? v5.totalFee : v5.originGas);\n const fee = otherRail || need > f5 ? need : f5;\n if (fee >= amount) throw new AcrossRefusal(\"relayer-price\", `relayers would keep all of the ${amount} sent (fee ${fee})`, \"amount_too_small\");\n return {fee, f5, need};\n}\n\n/**\n * How far under Across's own relayer fee a deposit's fee may sit when the device reads that fee itself, in percent of\n * it: the server's read and the device's are seconds apart, and the same quote moved at most 2.2 % over a minute\n * (five corridors, 2026-11-15).\n */\nexport const ACROSS_RELAYER_FEE_TOLERANCE_PCT = 10;\n\n/**\n * The device's own check of a deposit's fee against Across's keyless relayer fee for it, read on the device\n * (`acrossRemoteProvider`): a fee more than {@link ACROSS_RELAYER_FEE_TOLERANCE_PCT} % under it is refused\n * (`price_check_failed` — relayers would leave the deposit unfilled for its two-hour deadline and the refund after);\n * Across refusing the deposit refuses it with Across's reason. Without an answer only a route the pinned floor covers\n * stands, on the per-asset floor the verifier already held it to; any other route is refused (`upstream_unavailable`).\n * Throws {@link AcrossRefusal} `relayer-price`.\n */\nexport function acrossCheckRelayerFee(route: AcrossRoute, amount: bigint, fee: bigint, answer: AcrossSuggestedFees): void {\n if (answer.kind === \"refused\") throw new AcrossRefusal(\"relayer-price\", `${answer.detail} (read on this device)`, answer.reason);\n if (answer.kind === \"unavailable\") {\n if (acrossFloorCovers(route)) return;\n throw new AcrossRefusal(\"relayer-price\", `Across's relayer fee quote did not answer on this device (${answer.detail.slice(0, 120)}), and ${route.input.chain.name} → ${route.output.chain.name} has no studied floor to stand on`, \"upstream_unavailable\");\n }\n const need = answer.totalRelayFee;\n if (fee * 100n < need * BigInt(100 - ACROSS_RELAYER_FEE_TOLERANCE_PCT)) {\n throw new AcrossRefusal(\"relayer-price\", `the deposit leaves relayers ${fee} of ${amount}, under the ${need} Across's own relayer fee quote names for it (read on this device) — relayers would leave it unfilled, and the funds wait for a refund`, \"price_check_failed\");\n }\n}\n\n/** The deposit's quote time without `/suggested-fees`: `min(Ethereum − 60 s, origin)`, from the chains' latest blocks. */\nexport function acrossQuoteTimeOf(ethereumBlockTime: number, originBlockTime: number): number {\n return Math.min(ethereumBlockTime - ACROSS_QUOTE_TIME_LAG_S, originBlockTime);\n}\n","/**\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","/**\n * Where an Across deposit stands, read from the chains themselves — no Across API.\n *\n * 1. The source receipt: the deposit's `FundsDeposited` event, emitted by the pinned SpokePool of the source chain,\n * carries every field of the relay (V3SpokePoolInterface.sol `FundsDeposited`; `exclusivityDeadline` there is the\n * resolved timestamp, which is what the relay is keyed by). The event taken is the intent's own: the `deposit`\n * calldata its fields make hashes to the intent id's digest ({@link acrossDepositIsIntent}) — another deposit in\n * the same transaction, or another transaction's, is never reported as this one.\n * 2. The relay hash, exactly as the destination SpokePool computes it: `keccak256(abi.encode(relayData, chainId()))`\n * with `relayData` the `V3RelayData` struct (depositor, recipient, exclusiveRelayer, inputToken, outputToken,\n * inputAmount, outputAmount, originChainId, depositId, fillDeadline, exclusivityDeadline, message) and `chainId()`\n * the destination's own `block.chainid` (SpokePool.sol `getV3RelayHash`; no pinned chain overrides it).\n * 3. The destination SpokePool's `fillStatuses(relayHash)`, read at the latest block together with that block's time:\n * 2 is filled; 0 (unfilled) or 1 (slow fill requested) is still open while the block time is at or before the fill\n * deadline, and final after it — every fill path reverts with `ExpiredFillDeadline` once `fillDeadline <\n * block.timestamp`. Such a deposit is reported `expired`, a terminal state: Across refunds it to its depositor on\n * the source chain through its next settlement bundles (hours, not minutes; Across's docs: \"do not tell users to\n * expect immediate refunds\"), and this module does not watch for the refund itself.\n *\n * Display only: nothing is signed on what this reads. A node that does not answer, or a receipt that does not hold\n * exactly the intent's deposit, leaves the status where it was (\"pending\"); a terminal state is reported only from a\n * reverted receipt or a fill status that says so.\n */\nimport {decodeAbiParameters, encodeAbiParameters, keccak256, type Hex} from \"viem\";\nimport type {IntentStatus} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {redactUrls, timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {ACROSS_FILL_STATUSES, ACROSS_FUNDS_DEPOSITED, ACROSS_MAX_EXCLUSIVITY_PERIOD_S, type AcrossChain} from \"./config.js\";\nimport {acrossAddressOf, encodeAcrossDeposit} from \"./deposit.js\";\n\n/** A deposit as its `FundsDeposited` event states it. Parties and tokens are the raw bytes32 words, lowercase. */\nexport interface AcrossDepositEvent {\n originChainId: number;\n destinationChainId: bigint;\n depositId: bigint;\n depositor: Hex;\n recipient: Hex;\n exclusiveRelayer: Hex;\n inputToken: Hex;\n outputToken: Hex;\n inputAmount: bigint;\n outputAmount: bigint;\n quoteTimestamp: number;\n fillDeadline: number;\n /** The resolved exclusivity deadline (0 for none), not the deposit's raw parameter. */\n exclusivityDeadline: number;\n message: Hex;\n}\n\n/** `fillStatuses` values (V3SpokePoolInterface.sol `FillStatus`). */\nexport const ACROSS_FILL_STATUS = Object.freeze({UNFILLED: 0, REQUESTED_SLOW_FILL: 1, FILLED: 2} as const);\n\n/** A relay's state on the destination. `expired`: unfilled past its fill deadline — refunded on the source chain by Across. */\nexport type AcrossFillState = \"unfilled\" | \"slow-fill-requested\" | \"filled\" | \"expired\";\n\nconst EVENT_DATA = [\n {name: \"inputToken\", type: \"bytes32\"},\n {name: \"outputToken\", type: \"bytes32\"},\n {name: \"inputAmount\", type: \"uint256\"},\n {name: \"outputAmount\", type: \"uint256\"},\n {name: \"quoteTimestamp\", type: \"uint32\"},\n {name: \"fillDeadline\", type: \"uint32\"},\n {name: \"exclusivityDeadline\", type: \"uint32\"},\n {name: \"recipient\", type: \"bytes32\"},\n {name: \"exclusiveRelayer\", type: \"bytes32\"},\n {name: \"message\", type: \"bytes\"},\n] as const;\n\nconst RELAY_DATA = {\n type: \"tuple\",\n components: [\n {name: \"depositor\", type: \"bytes32\"},\n {name: \"recipient\", type: \"bytes32\"},\n {name: \"exclusiveRelayer\", type: \"bytes32\"},\n {name: \"inputToken\", type: \"bytes32\"},\n {name: \"outputToken\", type: \"bytes32\"},\n {name: \"inputAmount\", type: \"uint256\"},\n {name: \"outputAmount\", type: \"uint256\"},\n {name: \"originChainId\", type: \"uint256\"},\n {name: \"depositId\", type: \"uint256\"},\n {name: \"fillDeadline\", type: \"uint32\"},\n {name: \"exclusivityDeadline\", type: \"uint32\"},\n {name: \"message\", type: \"bytes\"},\n ],\n} as const;\n\nconst WORD = /^0x[0-9a-fA-F]{64}$/;\nconst HEX = /^0x(?:[0-9a-fA-F]{2})*$/;\nconst DIGEST = /^[0-9a-f]{32}$/;\nconst QUANTITY = /^0x[0-9a-fA-F]{1,16}$/;\nconst lowerHex = (s: string): Hex => s.toLowerCase() as Hex;\n\n/**\n * Every `FundsDeposited` the pinned SpokePool of `source` emitted in a transaction receipt (an `eth_getTransactionReceipt`\n * answer), in log order. Logs of any other contract, and logs that do not decode as the event, are skipped.\n */\nexport function acrossDepositsInReceipt(receipt: unknown, source: AcrossChain): AcrossDepositEvent[] {\n const logs = (receipt as {logs?: unknown} | null)?.logs;\n if (!Array.isArray(logs)) return [];\n const out: AcrossDepositEvent[] = [];\n for (const log of logs as {address?: unknown; topics?: unknown; data?: unknown; removed?: unknown}[]) {\n if (log === null || typeof log !== \"object\" || log.removed === true) continue;\n if (typeof log.address !== \"string\" || log.address.toLowerCase() !== source.spokePool) continue;\n const topics = log.topics;\n if (!Array.isArray(topics) || topics.length !== 4 || !topics.every((t) => typeof t === \"string\" && WORD.test(t))) continue;\n if ((topics[0] as string).toLowerCase() !== ACROSS_FUNDS_DEPOSITED) continue;\n if (typeof log.data !== \"string\" || !HEX.test(log.data)) continue;\n let d: readonly [Hex, Hex, bigint, bigint, number, number, number, Hex, Hex, Hex];\n try {\n d = decodeAbiParameters(EVENT_DATA, log.data as Hex);\n } catch {\n continue;\n }\n out.push({\n originChainId: source.chainId,\n destinationChainId: BigInt(topics[1] as string),\n depositId: BigInt(topics[2] as string),\n depositor: lowerHex(topics[3] as string),\n inputToken: lowerHex(d[0]),\n outputToken: lowerHex(d[1]),\n inputAmount: d[2],\n outputAmount: d[3],\n quoteTimestamp: d[4],\n fillDeadline: d[5],\n exclusivityDeadline: d[6],\n recipient: lowerHex(d[7]),\n exclusiveRelayer: lowerHex(d[8]),\n message: lowerHex(d[9]),\n });\n }\n return out;\n}\n\n/**\n * The `deposit` calldata an event's fields make with this exclusivity parameter — what an intent id's digest is taken\n * over. Null for a deposit whose parties or tokens are not EVM addresses: not one this module builds.\n */\nfunction depositDataOf(e: AcrossDepositEvent, exclusivityParameter: number): Hex | null {\n const depositor = acrossAddressOf(e.depositor);\n const recipient = acrossAddressOf(e.recipient);\n const inputToken = acrossAddressOf(e.inputToken);\n const outputToken = acrossAddressOf(e.outputToken);\n const exclusiveRelayer = acrossAddressOf(e.exclusiveRelayer);\n if (!depositor || !recipient || !inputToken || !outputToken || !exclusiveRelayer) return null;\n try {\n return encodeAcrossDeposit({\n depositor, recipient, inputToken, outputToken, inputAmount: e.inputAmount, outputAmount: e.outputAmount, destinationChainId: e.destinationChainId,\n exclusiveRelayer, quoteTimestamp: e.quoteTimestamp, fillDeadline: e.fillDeadline, exclusivityParameter, message: e.message,\n });\n } catch {\n return null;\n }\n}\n\n/**\n * Whether a deposit event is the one an intent id names: the canonical `deposit` calldata of its fields hashes to the\n * id's digest (`acrossIntentId`), so every field — parties, tokens, amounts, destination, deadlines, message — is the\n * signed one. The event carries the resolved exclusivity deadline, not the parameter: 0 for none, the parameter itself\n * for a timestamp, and for an offset the time of the block the deposit landed in plus the offset (SpokePool.sol\n * `_depositV3`) — so an offset is recognized only with `sourceBlockTime`.\n */\nexport function acrossDepositIsIntent(e: AcrossDepositEvent, digest: string, sourceBlockTime?: number): boolean {\n if (typeof digest !== \"string\" || !DIGEST.test(digest)) return false;\n const d = e.exclusivityDeadline;\n const candidates: number[] = [];\n if (d === 0) candidates.push(0);\n else {\n if (d > ACROSS_MAX_EXCLUSIVITY_PERIOD_S) candidates.push(d);\n if (sourceBlockTime !== undefined && d - sourceBlockTime > 0 && d - sourceBlockTime <= ACROSS_MAX_EXCLUSIVITY_PERIOD_S) candidates.push(d - sourceBlockTime);\n }\n return candidates.some((p) => {\n const data = depositDataOf(e, p);\n return data !== null && keccak256(data).slice(2, 34) === digest;\n });\n}\n\n/** The relay hash of a deposit — the key of `fillStatuses` on its destination chain. */\nexport function acrossRelayHash(e: AcrossDepositEvent): Hex {\n return keccak256(encodeAbiParameters([RELAY_DATA, {type: \"uint256\"}], [{\n depositor: e.depositor,\n recipient: e.recipient,\n exclusiveRelayer: e.exclusiveRelayer,\n inputToken: e.inputToken,\n outputToken: e.outputToken,\n inputAmount: e.inputAmount,\n outputAmount: e.outputAmount,\n originChainId: BigInt(e.originChainId),\n depositId: e.depositId,\n fillDeadline: e.fillDeadline,\n exclusivityDeadline: e.exclusivityDeadline,\n message: e.message,\n }, e.destinationChainId]));\n}\n\n/** Calldata of `fillStatuses(relayHash)`. */\nexport function acrossFillStatusCall(relayHash: Hex): Hex {\n if (!WORD.test(relayHash)) throw new Error(\"across: a relay hash is 32 bytes\");\n return `${ACROSS_FILL_STATUSES}${relayHash.slice(2).toLowerCase()}` as Hex;\n}\n\n/** A `fillStatuses` answer: 0, 1 or 2; null for anything else (another word, another length). */\nexport function parseAcrossFillStatus(answer: unknown): 0 | 1 | 2 | null {\n if (typeof answer !== \"string\" || !/^0x0{63}[0-2]$/i.test(answer)) return null;\n return Number(answer.slice(-1)) as 0 | 1 | 2;\n}\n\n/** A fill status read at a destination block whose time is `blockTime`. */\nexport function acrossFillState(status: 0 | 1 | 2, fillDeadline: number, blockTime: number): AcrossFillState {\n if (status === ACROSS_FILL_STATUS.FILLED) return \"filled\";\n // `fillDeadline < block.timestamp` reverts every fill, slow or fast: at a later block nothing can fill it any more.\n if (blockTime > fillDeadline) return \"expired\";\n return status === ACROSS_FILL_STATUS.REQUESTED_SLOW_FILL ? \"slow-fill-requested\" : \"unfilled\";\n}\n\n/** A JSON-RPC caller: the `result` of `method`, or a throw. */\nexport type AcrossRpc = (method: string, params: readonly unknown[]) => Promise<unknown>;\n\nconst MAX_RPC_BODY = 8 * 1024 * 1024;\n\n/** A minimal JSON-RPC client over `fetch` (12 s per call); its errors never carry the URL (a keyed RPC has its key there). */\nexport function acrossRpc(url: string, fetchImpl?: typeof fetch, timeoutMs = 12_000): AcrossRpc {\n if (typeof url !== \"string\" || !/^https?:\\/\\//.test(url)) throw new Error(\"across: an RPC URL must use http or https\");\n let id = 0;\n return async (method, params) => {\n let text: string;\n try {\n const res = await (fetchImpl ?? fetch)(url, {\n method: \"POST\",\n headers: {\"content-type\": \"application/json\", accept: \"application/json\"},\n body: JSON.stringify({jsonrpc: \"2.0\", id: ++id, method, params}),\n signal: timeoutSignal(timeoutMs),\n });\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n text = await res.text();\n } catch (err) {\n throw new Error(`across: ${method} failed — ${redactUrls(err instanceof Error ? err.message : String(err)).slice(0, 160)}`);\n }\n if (text.length > MAX_RPC_BODY) throw new Error(`across: ${method} answered more than ${MAX_RPC_BODY} bytes`);\n let body: {result?: unknown; error?: {message?: unknown}} | null;\n try {\n body = JSON.parse(text) as typeof body;\n } catch {\n throw new Error(`across: ${method} answered something that is not JSON`);\n }\n if (body === null || typeof body !== \"object\") throw new Error(`across: ${method} answered something that is not JSON-RPC`);\n if (body.error !== undefined) throw new Error(`across: ${method} failed — ${redactUrls(String(body.error?.message ?? \"error\")).slice(0, 160)}`);\n if (!Object.prototype.hasOwnProperty.call(body, \"result\")) throw new Error(`across: ${method} answered no result`);\n return body.result;\n };\n}\n\n/** What {@link trackAcrossDeposit} found: the status, and the facts it rests on when they were read. */\nexport interface AcrossTrack {\n status: IntentStatus;\n deposit?: AcrossDepositEvent;\n relayHash?: Hex;\n fill?: AcrossFillState;\n /** The destination block the fill status was read at. */\n destBlock?: {number: string; timestamp: number};\n}\n\nexport interface AcrossTrackInput {\n sourceTxHash: string;\n /** The intent id's digest of the deposit calldata (`parseAcrossIntentId(id).digest`): the deposit looked for. */\n intentDigest: string;\n source: AcrossChain;\n dest: AcrossChain;\n /** The source chain's RPC; without it nothing can be read (\"pending\"). */\n sourceRpc?: AcrossRpc;\n /** The destination chain's RPC; without it the deposit is seen but its fill is not (\"pending\"). */\n destRpc?: AcrossRpc;\n}\n\n/** The time of a source block, by number; null when the node does not say. */\nasync function blockTimeOf(rpc: AcrossRpc, number: unknown): Promise<number | null> {\n if (typeof number !== \"string\" || !QUANTITY.test(number)) return null;\n try {\n const block = (await rpc(\"eth_getBlockByNumber\", [number, false])) as {number?: unknown; timestamp?: unknown} | null;\n const timestamp = block?.timestamp;\n if (typeof block?.number !== \"string\" || block.number.toLowerCase() !== number.toLowerCase()) return null;\n if (typeof timestamp !== \"string\" || !/^0x[0-9a-fA-F]{1,12}$/.test(timestamp)) return null;\n return parseInt(timestamp, 16);\n } catch {\n return null;\n }\n}\n\n/**\n * The intent's deposit in the transaction `sourceTxHash` from `source` to `dest`, and whether it was filled — read on\n * chain only.\n */\nexport async function trackAcrossDeposit(input: AcrossTrackInput): Promise<AcrossTrack> {\n const {source, dest, sourceRpc, destRpc} = input;\n if (typeof input.sourceTxHash !== \"string\" || !WORD.test(input.sourceTxHash) || !sourceRpc) return {status: {state: \"pending\"}};\n if (typeof input.intentDigest !== \"string\" || !DIGEST.test(input.intentDigest)) return {status: {state: \"pending\"}};\n let receipt: unknown;\n try {\n receipt = await sourceRpc(\"eth_getTransactionReceipt\", [input.sourceTxHash]);\n } catch {\n return {status: {state: \"pending\"}};\n }\n // Not mined yet (or not seen by this node).\n if (receipt === null || receipt === undefined) return {status: {state: \"pending\"}};\n if (typeof receipt !== \"object\") return {status: {state: \"pending\"}};\n const status = (receipt as {status?: unknown}).status;\n // The deposit reverted: nothing left the wallet but the gas.\n if (status === \"0x0\") return {status: {state: \"failed\"}};\n if (status !== \"0x1\") return {status: {state: \"pending\"}};\n // A receipt for another transaction is no answer.\n const txHash = (receipt as {transactionHash?: unknown}).transactionHash;\n if (txHash !== undefined && (typeof txHash !== \"string\" || txHash.toLowerCase() !== input.sourceTxHash.toLowerCase())) return {status: {state: \"pending\"}};\n const onRoute = acrossDepositsInReceipt(receipt, source).filter((d) => d.destinationChainId === BigInt(dest.chainId));\n let mine = onRoute.filter((d) => acrossDepositIsIntent(d, input.intentDigest));\n // An offset exclusivity resolves against the source block's time, read only when an event needs it.\n if (mine.length === 0 && onRoute.some((d) => d.exclusivityDeadline !== 0)) {\n const blockTime = await blockTimeOf(sourceRpc, (receipt as {blockNumber?: unknown}).blockNumber);\n if (blockTime === null) return {status: {state: \"pending\"}};\n mine = onRoute.filter((d) => acrossDepositIsIntent(d, input.intentDigest, blockTime));\n }\n // Not exactly the intent's deposit — a node with partial logs, another transaction's hash, the same call twice:\n // nothing is known about this transfer, which is not a failure.\n if (mine.length !== 1) return {status: {state: \"pending\"}};\n const deposit = mine[0]!;\n const relayHash = acrossRelayHash(deposit);\n const seen: AcrossTrack = {status: {state: \"pending\", depositReceived: true}, deposit, relayHash};\n if (!destRpc) return seen;\n try {\n const block = (await destRpc(\"eth_getBlockByNumber\", [\"latest\", false])) as {number?: unknown; timestamp?: unknown} | null;\n const number = block?.number;\n const timestamp = block?.timestamp;\n 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;\n const blockTime = parseInt(timestamp, 16);\n const fillStatus = parseAcrossFillStatus(await destRpc(\"eth_call\", [{to: dest.spokePool, data: acrossFillStatusCall(relayHash)}, number]));\n if (fillStatus === null) return seen;\n const fill = acrossFillState(fillStatus, deposit.fillDeadline, blockTime);\n const destBlock = {number: number.toLowerCase(), timestamp: blockTime};\n if (fill === \"filled\") return {status: {state: \"completed\", depositReceived: true}, deposit, relayHash, fill, destBlock};\n // Past its fill deadline unfilled: final. Across refunds the depositor on the source chain in the coming hours; the\n // refund is not watched here, so the state is one that ends polling.\n if (fill === \"expired\") return {status: {state: \"expired\", depositReceived: true}, deposit, relayHash, fill, destBlock};\n return {status: {state: \"pending\", depositReceived: true}, deposit, relayHash, fill, destBlock};\n } catch {\n return seen;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAkC;;;ACgElC,IAAM,OAAO,CAAC,SAAiB,SAAS,WAAwB,OAAO,OAAO,EAAC,OAAO,QAAQ,SAAS,QAAQ,UAAU,EAAC,CAAC;AAC3H,IAAM,OAAO,CAAC,SAAiB,SAAS,WAAwB,OAAO,OAAO,EAAC,OAAO,QAAQ,SAAS,QAAQ,UAAU,EAAC,CAAC;AAC3H,IAAM,OAA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OAAwB;AACxD,WAAO,OAAU,cAAc,KAAK;AAAA,EACtC;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,OAAU,SAAS,WAAW,OAAO;AAAA,EAC9C;AACF;","names":["chain","chain","import_errors","chain","import_errors","ZERO","text","ADDRESS","import_viem","import_errors","import_util","ADDRESS","ZERO","U256_MAX","UINT","text","chain","UINT","ADDRESS","U32_MAX","import_viem","import_util","HEX","text","ADDRESS","chain"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import * as _anywalletkit_protocol_swap2_core_types from '@anywalletkit/protocol-swap2-core/types';
|
|
2
|
+
import { SingleProviderSwap2 } from '@anywalletkit/protocol-swap2-core/swap2/single';
|
|
3
|
+
import { Swap2EngineConfig, Swap2Account } from '@anywalletkit/protocol-swap2-core/swap2/base';
|
|
4
|
+
import { AcrossProviderConfig } from './provider.cjs';
|
|
5
|
+
|
|
6
|
+
interface AcrossSwap2Config extends Swap2EngineConfig, AcrossProviderConfig {
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Standalone Across swap2: EVM → EVM through the source chain's SpokePool, every deposit built and verified on the
|
|
10
|
+
* device. Quoting needs the Across API V5 key, so this class quotes only on a server (`apiKey`); an app uses
|
|
11
|
+
* `acrossRemoteProvider` in a router instead.
|
|
12
|
+
*/
|
|
13
|
+
declare class AcrossSwap2Protocol extends SingleProviderSwap2 {
|
|
14
|
+
protected readonly provider: _anywalletkit_protocol_swap2_core_types.CrossChainProvider;
|
|
15
|
+
constructor(account: Swap2Account | undefined, config: AcrossSwap2Config);
|
|
16
|
+
protected chainSupported(caip2: string): boolean;
|
|
17
|
+
protected pairSupported(fromChain: string, toChain: string): boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export { type AcrossSwap2Config, AcrossSwap2Protocol };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import * as _anywalletkit_protocol_swap2_core_types from '@anywalletkit/protocol-swap2-core/types';
|
|
2
|
+
import { SingleProviderSwap2 } from '@anywalletkit/protocol-swap2-core/swap2/single';
|
|
3
|
+
import { Swap2EngineConfig, Swap2Account } from '@anywalletkit/protocol-swap2-core/swap2/base';
|
|
4
|
+
import { AcrossProviderConfig } from './provider.js';
|
|
5
|
+
|
|
6
|
+
interface AcrossSwap2Config extends Swap2EngineConfig, AcrossProviderConfig {
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Standalone Across swap2: EVM → EVM through the source chain's SpokePool, every deposit built and verified on the
|
|
10
|
+
* device. Quoting needs the Across API V5 key, so this class quotes only on a server (`apiKey`); an app uses
|
|
11
|
+
* `acrossRemoteProvider` in a router instead.
|
|
12
|
+
*/
|
|
13
|
+
declare class AcrossSwap2Protocol extends SingleProviderSwap2 {
|
|
14
|
+
protected readonly provider: _anywalletkit_protocol_swap2_core_types.CrossChainProvider;
|
|
15
|
+
constructor(account: Swap2Account | undefined, config: AcrossSwap2Config);
|
|
16
|
+
protected chainSupported(caip2: string): boolean;
|
|
17
|
+
protected pairSupported(fromChain: string, toChain: string): boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export { type AcrossSwap2Config, AcrossSwap2Protocol };
|