@anywalletkit/protocol-swap2-relay 0.1.1 → 0.1.3
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/README.md +1 -1
- package/dist/{chunk-WRIKAUWI.js → chunk-C3I2XYSW.js} +92 -84
- package/dist/chunk-C3I2XYSW.js.map +1 -0
- package/dist/{chunk-CCMNAZZB.js → chunk-JTPYU26F.js} +72 -29
- package/dist/chunk-JTPYU26F.js.map +1 -0
- package/dist/{chunk-UVHDMGM5.js → chunk-MDXHT7HY.js} +5 -3
- package/dist/chunk-MDXHT7HY.js.map +1 -0
- package/dist/{chunk-7LPLU3MB.js → chunk-TBFD7BPZ.js} +2 -2
- package/dist/index.cjs +163 -110
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +4 -4
- package/dist/order.cjs +4 -2
- package/dist/order.cjs.map +1 -1
- package/dist/order.d.cts +9 -1
- package/dist/order.d.ts +9 -1
- package/dist/order.js +1 -1
- package/dist/protocol.cjs +163 -110
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.js +4 -4
- package/dist/provider.cjs +163 -110
- package/dist/provider.cjs.map +1 -1
- package/dist/provider.js +3 -3
- package/dist/verify.cjs +94 -84
- package/dist/verify.cjs.map +1 -1
- package/dist/verify.d.cts +2 -1
- package/dist/verify.d.ts +2 -1
- package/dist/verify.js +2 -2
- package/package.json +6 -6
- package/dist/chunk-CCMNAZZB.js.map +0 -1
- package/dist/chunk-UVHDMGM5.js.map +0 -1
- package/dist/chunk-WRIKAUWI.js.map +0 -1
- /package/dist/{chunk-7LPLU3MB.js.map → chunk-TBFD7BPZ.js.map} +0 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/order.ts","../src/verify.ts","../src/cleared.ts","../src/provider.ts","../src/activity.ts","../src/protocol.ts"],"sourcesContent":["export * from \"./config.js\";\nexport * from \"./order.js\";\nexport * from \"./verify.js\";\nexport * from \"./provider.js\";\nexport {RelaySwap2Protocol, type RelaySwap2Config} from \"./protocol.js\";\nexport {RelaySwap2Protocol as default} from \"./protocol.js\";\nexport * from \"./activity.js\";\n","// Relay (relay.link) — the pins this module signs against. Nothing here is read from the API at run time: the API (or\n// an app's own proxy in front of it) is untrusted, and a deposit is signed only for a depository, a chain mapping and\n// a solver signer written in this file.\n//\n// Sources, all read on 2026-11-10:\n// - `GET https://api.relay.link/chains` — per chain: `id`, `protocol.v2.chainId` (the chain's name inside an order,\n// which is NOT always `name`: BNB Chain is \"bnb\" in orders and \"bsc\" as `name`, World Chain \"worldchain\" /\n// \"world-chain\"), `protocol.v2.depository`, `solverAddresses`.\n// - On chain, over the SDK's public RPCs, for every row below: the depository has code, `allocator()` =\n// {@link RELAY_ALLOCATOR}, `owner()` = {@link RELAY_OWNER}, its EIP-712 domain reports the row's chain id, and the\n// bytecode carries the three deposit selectors. The runtime code is the same 8 628 bytes everywhere apart from the\n// immutables (the Mantle / Linea deployment is a second build, 8 777 bytes, at its own address).\n// - The contract: github.com/relayprotocol/relay-depository, packages/ethereum-vm/src/RelayDepository.sol.\n// - The order: github.com/relayprotocol/relay-protocol-sdk, src/order/index.ts (types and hashing), and Relay's own\n// \"input validation\" page (docs.relay.link), which names the solver below and tells integrators to take the\n// depository from `/chains` rather than from a quote.\n//\n// Only chains the SDK ships are listed, plus Elysium (99901), whose catalog entry is added separately. Relay also\n// serves chains the SDK does not carry; the SDK's Flare (14) and Sei (1329) are not on Relay.\n\nexport interface RelayChain {\n caip2: string;\n chainId: number;\n /** The chain's name inside a Relay order (`/chains[].protocol.v2.chainId`). */\n slug: string;\n name: string;\n /** RelayDepository on that chain: the only contract a deposit calls and the only spender an approval names. */\n depository: string;\n}\n\nconst DEPOSITORY = \"0x4cd00e387622c35bddb9b4c962c136462338bc31\";\n/** Mantle and Linea run a second deployment. */\nconst DEPOSITORY_B = \"0x59916da825d2d2ec1bf878d71c88826f6633ecca\";\n\nconst c = (chainId: number, slug: string, name: string, depository: string = DEPOSITORY): RelayChain =>\n Object.freeze({caip2: `eip155:${chainId}`, chainId, slug, name, depository});\n\n/** CAIP-2 → the chain as Relay knows it. A null-prototype map: `RELAY_CHAINS[\"constructor\"]` is undefined. */\nexport const RELAY_CHAINS: Readonly<Record<string, RelayChain>> = Object.freeze(Object.assign(Object.create(null) as Record<string, RelayChain>, Object.fromEntries([\n c(1, \"ethereum\", \"Ethereum\"),\n c(10, \"optimism\", \"OP Mainnet\"),\n c(56, \"bnb\", \"BNB Chain\"),\n c(100, \"gnosis\", \"Gnosis\"),\n c(130, \"unichain\", \"Unichain\"),\n c(137, \"polygon\", \"Polygon\"),\n c(143, \"monad\", \"Monad\"),\n c(146, \"sonic\", \"Sonic\"),\n c(196, \"xlayer\", \"X Layer\"),\n c(324, \"zksync\", \"zkSync Era\"),\n c(480, \"worldchain\", \"World Chain\"),\n c(999, \"hyperevm\", \"HyperEVM\"),\n c(2818, \"morph\", \"Morph\"),\n c(4326, \"megaeth\", \"MegaETH\"),\n c(4663, \"robinhood\", \"Robinhood Chain\"),\n c(5000, \"mantle\", \"Mantle\", DEPOSITORY_B),\n c(5042, \"arc\", \"Arc\"),\n c(8453, \"base\", \"Base\"),\n c(9745, \"plasma\", \"Plasma\"),\n c(42161, \"arbitrum\", \"Arbitrum\"),\n c(42220, \"celo\", \"Celo\"),\n c(43114, \"avalanche\", \"Avalanche\"),\n c(57073, \"ink\", \"Ink\"),\n c(59144, \"linea\", \"Linea\", DEPOSITORY_B),\n c(80094, \"berachain\", \"Berachain\"),\n c(98866, \"plume\", \"Plume\"),\n c(99901, \"elysium\", \"Elysium\"),\n c(534352, \"scroll\", \"Scroll\"),\n c(747474, \"katana\", \"Katana\"),\n].map((x) => [x.caip2, x]))));\n\n/** The chain for a CAIP-2 id, or undefined — own keys only. */\nexport function relayChain(caip2: string): RelayChain | undefined {\n return typeof caip2 === \"string\" && Object.prototype.hasOwnProperty.call(RELAY_CHAINS, caip2) ? RELAY_CHAINS[caip2] : undefined;\n}\n\n/**\n * The solver whose signature makes an order worth depositing for: `order.solver` on `order.solverChainId`, the signer of\n * `orderSignature`. One pair today (every order seen, Relay's validation page, first in `/chains[].solverAddresses`).\n * An order naming any other solver, or this address on another solver chain, is refused.\n */\nexport const RELAY_SOLVERS: readonly {readonly chainId: string; readonly address: string}[] = Object.freeze([\n Object.freeze({chainId: \"base\", address: \"0xf70da97812cb96acdf810712aa562db8dfa3dbef\"}),\n]);\n\n/** `allocator()` of every pinned depository (the key that authorises withdrawals from it) — a watched fact, not used in checks. */\nexport const RELAY_ALLOCATOR = \"0x63c1d3e9c646184529c5694630a01c00df171b56\";\n/** `owner()` of every pinned depository — a watched fact, not used in checks. */\nexport const RELAY_OWNER = \"0xf61a305199fa1135d76ffab3752d42f55cbd775a\";\n\n/** Relay's API. An app may point the provider at its own proxy instead (`baseUrl`); either is untrusted. */\nexport const RELAY_API = \"https://api.relay.link\";\n\n/** The native coin in a Relay order and in the API: twenty zero bytes. */\nexport const RELAY_NATIVE = \"0x0000000000000000000000000000000000000000\";\n\n/** `depositNative(address depositor, bytes32 id)` payable. */\nexport const RELAY_DEPOSIT_NATIVE = \"0x49290c1c\";\n/** `depositErc20(address depositor, address token, uint256 amount, bytes32 id)`. */\nexport const RELAY_DEPOSIT_ERC20 = \"0xe8017952\";\n/**\n * `depositErc20(address depositor, address token, bytes32 id)` — deposits the caller's WHOLE allowance. Never built and\n * always refused: the amount is not in the calldata.\n */\nexport const RELAY_DEPOSIT_ERC20_ALLOWANCE = \"0x5a1ee3ac\";\n\n/** The only order version this module reads. */\nexport const RELAY_ORDER_VERSION = \"v1\";\n\n/**\n * How long Relay gives an order: the output deadline and every refund deadline are the quote time + 7 days (every\n * order seen, 2026-11-02 … 2026-11-10). The verifier holds a deadline to this lifetime, which is also what makes an\n * old order stale: one issued more than {@link RELAY_MAX_ORDER_AGE_S} ago is refused even when everything else fits.\n */\nexport const RELAY_ORDER_LIFETIME_S = 604_800;\n/** An order older than this is refused (the quote itself lives for `quoteTtlMs`, 60 s by default, 5 min at most). */\nexport const RELAY_MAX_ORDER_AGE_S = 600;\n/** Tolerated clock difference between the device and Relay, forwards. */\nexport const RELAY_CLOCK_SKEW_S = 300;\n\nexport const relay = {\n supportsChain(chain: string): boolean {\n return relayChain(chain) !== undefined;\n },\n /** Two different pinned EVM chains. */\n supports(from: string, to: string): boolean {\n return from !== to && relayChain(from) !== undefined && relayChain(to) !== undefined;\n },\n};\n","/**\n * A Relay order, read strictly, hashed and attributed here.\n *\n * - The order id is the EIP-712 `hashStruct` of the order under {@link RELAY_ORDER_TYPES} (no domain separator), as\n * github.com/relayprotocol/relay-protocol-sdk (src/order/index.ts) computes it. Chain ids are STRINGS (Relay's own\n * chain names), addresses and currencies are `bytes` (20 raw bytes on an EVM chain).\n * - `orderSignature` is the solver's EIP-191 `personal_sign` over the 32 raw bytes of that id.\n *\n * The id a deposit names is a commitment to everything in the order — recipient, chain, token, minimum, refunds — so\n * recomputing it from the order the API hands over, and reading that same parsed order, is what binds the deposit\n * to terms the device has seen.\n */\nimport {secp256k1} from \"@noble/curves/secp256k1.js\";\nimport {hashMessage, hashStruct, hexToBytes, keccak256, type Hex} from \"viem\";\n\n/** Why an order, a quote or a deposit was refused. One code per check; the message says what was found. */\nexport type RelayRefusalCode =\n | \"request-invalid\"\n | \"chain-unsupported\"\n | \"protocol-data-missing\"\n | \"hub-type\"\n | \"order-malformed\"\n | \"order-version\"\n | \"order-inputs\"\n | \"order-payments\"\n | \"order-calls\"\n | \"order-fees\"\n | \"solver-not-pinned\"\n | \"input-chain\"\n | \"input-currency\"\n | \"input-amount\"\n | \"input-weight\"\n | \"output-chain\"\n | \"output-recipient\"\n | \"output-currency\"\n | \"output-minimum\"\n | \"output-expected\"\n | \"output-deadline\"\n | \"refund-missing\"\n | \"refund-chain\"\n | \"refund-recipient\"\n | \"refund-currency\"\n | \"refund-deadline\"\n | \"order-id-mismatch\"\n | \"signature-invalid\"\n | \"payment-details\"\n | \"tx-chain\"\n | \"tx-target\"\n | \"tx-selector\"\n | \"tx-calldata\"\n | \"tx-depositor\"\n | \"tx-token\"\n | \"tx-amount\"\n | \"tx-id\"\n | \"tx-value\"\n | \"order-reused\"\n | \"app-fee\"\n | \"gas-topup\"\n | \"quote-gas\"\n | \"quote-expiry\"\n | \"quote-steps\"\n | \"quote-amounts\"\n | \"quote-approval\"\n | \"quote-shape\";\n\nexport class RelayRefusal extends Error {\n readonly code: RelayRefusalCode;\n constructor(code: RelayRefusalCode, detail: string) {\n super(`relay: ${detail} [${code}]`);\n this.name = \"RelayRefusal\";\n this.code = code;\n }\n}\n\nexport const RELAY_ORDER_TYPES = {\n Order: [\n {name: \"version\", type: \"string\"},\n {name: \"solverChainId\", type: \"string\"},\n {name: \"solver\", type: \"address\"},\n {name: \"salt\", type: \"uint256\"},\n {name: \"inputs\", type: \"Input[]\"},\n {name: \"output\", type: \"Output\"},\n {name: \"fees\", type: \"Fee[]\"},\n ],\n Input: [\n {name: \"payment\", type: \"InputPayment\"},\n {name: \"refunds\", type: \"InputRefund[]\"},\n ],\n InputPayment: [\n {name: \"chainId\", type: \"string\"},\n {name: \"currency\", type: \"bytes\"},\n {name: \"amount\", type: \"uint256\"},\n {name: \"weight\", type: \"uint256\"},\n ],\n InputRefund: [\n {name: \"chainId\", type: \"string\"},\n {name: \"recipient\", type: \"bytes\"},\n {name: \"currency\", type: \"bytes\"},\n {name: \"minimumAmount\", type: \"uint256\"},\n {name: \"deadline\", type: \"uint32\"},\n {name: \"extraData\", type: \"bytes\"},\n ],\n Output: [\n {name: \"chainId\", type: \"string\"},\n {name: \"payments\", type: \"OutputPayment[]\"},\n {name: \"deadline\", type: \"uint32\"},\n {name: \"calls\", type: \"bytes[]\"},\n {name: \"extraData\", type: \"bytes\"},\n ],\n OutputPayment: [\n {name: \"recipient\", type: \"bytes\"},\n {name: \"currency\", type: \"bytes\"},\n {name: \"minimumAmount\", type: \"uint256\"},\n {name: \"expectedAmount\", type: \"uint256\"},\n ],\n Fee: [\n {name: \"recipientChainId\", type: \"string\"},\n {name: \"recipient\", type: \"bytes\"},\n {name: \"currencyChainId\", type: \"string\"},\n {name: \"currency\", type: \"bytes\"},\n {name: \"amount\", type: \"uint256\"},\n ],\n} as const;\n\nexport interface RelayInputRefund {chainId: string; recipient: Hex; currency: Hex; minimumAmount: bigint; deadline: number; extraData: Hex}\nexport interface RelayInput {payment: {chainId: string; currency: Hex; amount: bigint; weight: bigint}; refunds: RelayInputRefund[]}\nexport interface RelayOutputPayment {recipient: Hex; currency: Hex; minimumAmount: bigint; expectedAmount: bigint}\nexport interface RelayFee {recipientChainId: string; recipient: Hex; currencyChainId: string; currency: Hex; amount: bigint}\n/** An order after {@link parseRelayOrder}: hex lowercased, integers exact. Every field below is hashed into the id. */\nexport interface RelayOrder {\n version: string;\n solverChainId: string;\n solver: Hex;\n salt: bigint;\n inputs: RelayInput[];\n output: {chainId: string; payments: RelayOutputPayment[]; deadline: number; calls: Hex[]; extraData: Hex};\n fees: RelayFee[];\n}\n\nconst MAX_LIST = 8;\nconst MAX_BYTES_HEX = 2 + 2 * 1024;\nconst MAX_TEXT = 64;\nconst U256_MAX = (1n << 256n) - 1n;\n\nconst bad = (what: string): never => { throw new RelayRefusal(\"order-malformed\", `the order's ${what}`); };\n\nfunction rec(v: unknown, what: string): Record<string, unknown> {\n if (v === null || typeof v !== \"object\" || Array.isArray(v)) bad(`${what} is not an object`);\n return v as Record<string, unknown>;\n}\nfunction list(v: unknown, what: string): unknown[] {\n if (!Array.isArray(v)) bad(`${what} is not a list`);\n if ((v as unknown[]).length > MAX_LIST) bad(`${what} has more than ${MAX_LIST} entries`);\n return v as unknown[];\n}\n/** Own property only: a field missing from the JSON is never read off a prototype. */\nfunction own(o: Record<string, unknown>, key: string): unknown {\n return Object.prototype.hasOwnProperty.call(o, key) ? o[key] : undefined;\n}\nfunction text(v: unknown, what: string): string {\n if (typeof v !== \"string\" || v.length === 0 || v.length > MAX_TEXT) bad(`${what} is not a short string`);\n return v as string;\n}\n/** `bytes`: 0x-hex of whole bytes, lowercased. */\nfunction bytes(v: unknown, what: string): Hex {\n if (typeof v !== \"string\" || v.length > MAX_BYTES_HEX || !/^0x(?:[0-9a-fA-F]{2})*$/.test(v)) bad(`${what} is not hex bytes`);\n return (v as string).toLowerCase() as Hex;\n}\n/** `uint256`: a decimal string, a 0x-hex string (Relay writes the salt that way) or a safe non-negative integer. */\nfunction uint(v: unknown, what: string, max: bigint = U256_MAX): bigint {\n let n: bigint | null = null;\n if (typeof v === \"string\" && (/^(?:0|[1-9]\\d{0,77})$/.test(v) || /^0x[0-9a-fA-F]{1,64}$/.test(v))) n = BigInt(v);\n else if (typeof v === \"number\" && Number.isSafeInteger(v) && v >= 0) n = BigInt(v);\n if (n === null || n > max) bad(`${what} is not an unsigned integer in range`);\n return n as bigint;\n}\nfunction uint32(v: unknown, what: string): number {\n // Below 2^32, so the conversion is exact.\n return parseInt(uint(v, what, 0xffff_ffffn).toString(10), 10);\n}\nfunction address(v: unknown, what: string): Hex {\n if (typeof v !== \"string\" || !/^0x[0-9a-fA-F]{40}$/.test(v)) bad(`${what} is not an address`);\n return (v as string).toLowerCase() as Hex;\n}\n\n/**\n * Read an order as the API gives it (`protocol.v2.orderData`, already JSON-parsed) into the one typed form the id,\n * the signature and every check are computed from. Anything that is not exactly the documented shape is refused\n * (`order-malformed`); keys the type does not have are ignored — they are outside the hash, and nothing reads them.\n */\nexport function parseRelayOrder(raw: unknown): RelayOrder {\n const o = rec(raw, \"body\");\n const output = rec(own(o, \"output\"), \"output\");\n return {\n version: text(own(o, \"version\"), \"version\"),\n solverChainId: text(own(o, \"solverChainId\"), \"solver chain\"),\n solver: address(own(o, \"solver\"), \"solver\"),\n salt: uint(own(o, \"salt\"), \"salt\"),\n inputs: list(own(o, \"inputs\"), \"inputs\").map((x, i) => {\n const input = rec(x, `input ${i}`);\n const p = rec(own(input, \"payment\"), `input ${i} payment`);\n return {\n payment: {\n chainId: text(own(p, \"chainId\"), `input ${i} chain`),\n currency: bytes(own(p, \"currency\"), `input ${i} currency`),\n amount: uint(own(p, \"amount\"), `input ${i} amount`),\n weight: uint(own(p, \"weight\"), `input ${i} weight`),\n },\n refunds: list(own(input, \"refunds\"), `input ${i} refunds`).map((y, j) => {\n const r = rec(y, `refund ${j}`);\n return {\n chainId: text(own(r, \"chainId\"), `refund ${j} chain`),\n recipient: bytes(own(r, \"recipient\"), `refund ${j} recipient`),\n currency: bytes(own(r, \"currency\"), `refund ${j} currency`),\n minimumAmount: uint(own(r, \"minimumAmount\"), `refund ${j} minimum`),\n deadline: uint32(own(r, \"deadline\"), `refund ${j} deadline`),\n extraData: bytes(own(r, \"extraData\"), `refund ${j} extra data`),\n };\n }),\n };\n }),\n output: {\n chainId: text(own(output, \"chainId\"), \"output chain\"),\n payments: list(own(output, \"payments\"), \"output payments\").map((x, i) => {\n const p = rec(x, `output payment ${i}`);\n return {\n recipient: bytes(own(p, \"recipient\"), `output payment ${i} recipient`),\n currency: bytes(own(p, \"currency\"), `output payment ${i} currency`),\n minimumAmount: uint(own(p, \"minimumAmount\"), `output payment ${i} minimum`),\n expectedAmount: uint(own(p, \"expectedAmount\"), `output payment ${i} expected amount`),\n };\n }),\n deadline: uint32(own(output, \"deadline\"), \"output deadline\"),\n calls: list(own(output, \"calls\"), \"output calls\").map((x, i) => bytes(x, `output call ${i}`)),\n extraData: bytes(own(output, \"extraData\"), \"output extra data\"),\n },\n fees: list(own(o, \"fees\"), \"fees\").map((x, i) => {\n const f = rec(x, `fee ${i}`);\n return {\n recipientChainId: text(own(f, \"recipientChainId\"), `fee ${i} recipient chain`),\n recipient: bytes(own(f, \"recipient\"), `fee ${i} recipient`),\n currencyChainId: text(own(f, \"currencyChainId\"), `fee ${i} currency chain`),\n currency: bytes(own(f, \"currency\"), `fee ${i} currency`),\n amount: uint(own(f, \"amount\"), `fee ${i} amount`),\n };\n }),\n };\n}\n\n/** The order id: `hashStruct(Order)`, no domain. */\nexport function relayOrderId(order: RelayOrder): Hex {\n return hashStruct({types: RELAY_ORDER_TYPES, primaryType: \"Order\", data: order as never});\n}\n\n/**\n * The address whose `personal_sign` over the id's 32 bytes this signature is (lowercase), or null when it is not a\n * 65-byte secp256k1 signature that recovers at all. Synchronous on purpose: the same check runs wherever the order\n * is read, with nothing left for a later asynchronous step.\n */\nexport function relayOrderSigner(id: Hex, signature: unknown): Hex | null {\n if (typeof signature !== \"string\" || !/^0x[0-9a-fA-F]{130}$/.test(signature)) return null;\n const sig = hexToBytes(signature as Hex);\n const v = sig[64]!;\n const recovery = v === 27 || v === 28 ? v - 27 : v === 0 || v === 1 ? v : -1;\n if (recovery < 0) return null;\n try {\n const recoverable = new Uint8Array(65);\n recoverable[0] = recovery;\n recoverable.set(sig.subarray(0, 64), 1);\n const digest = hexToBytes(hashMessage({raw: id}));\n const key = secp256k1.recoverPublicKey(recoverable, digest, {prehash: false});\n // The recovery must also verify: a malformed (r, s) never passes as a signer.\n if (!secp256k1.verify(sig.subarray(0, 64), digest, key, {prehash: false})) return null;\n const uncompressed = secp256k1.Point.fromBytes(key).toBytes(false);\n return `0x${keccak256(uncompressed.subarray(1)).slice(-40)}`.toLowerCase() as Hex;\n } catch {\n return null;\n }\n}\n","/**\n * The device-side check of a Relay order and of the deposit that funds it.\n *\n * A Relay deposit is `depositNative(depositor, id)` / `depositErc20(depositor, token, amount, id)` on the chain's\n * RelayDepository: the calldata names no recipient, no destination and no minimum — only `id`, the hash of an order\n * that lives off chain. Signing such a deposit is safe exactly when the device holds the order behind the id and that\n * order says what the user asked for. {@link verifyRelayOrder} establishes that, from nothing but the user's own\n * request, the pins in `config.ts`, and the bytes the API (or an app's proxy — equally untrusted) returned:\n *\n * 1. the order is the documented shape, one input, one output payment, no destination calls, no order-level fees;\n * 2. its content is the request: recipient, destination chain and token, a minimum no lower than the caller's, a\n * deadline one order lifetime away, the input chain / token / amount, refunds only to the user;\n * 3. its solver is the pinned one and the solver signed this very id;\n * 4. the id recomputed here (EIP-712 `hashStruct`) is the id in the calldata;\n * 5. the transaction is a known deposit call on the pinned depository, depositing exactly the order's input from the\n * user's own address — and is byte-for-byte the call this module would build itself.\n *\n * Every refusal is a {@link RelayRefusal} with its own code. Nothing here is asynchronous and nothing reads the\n * network, so the same function runs at quote time, again right before signing, and on the client of a remote\n * provider (`relayPins.verifyQuote`).\n */\nimport {encodeFunctionData, parseAbi, type Hex} from \"viem\";\nimport type {Quote, QuoteParams, RemotePins, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {\n RELAY_CLOCK_SKEW_S, RELAY_DEPOSIT_ERC20, RELAY_DEPOSIT_ERC20_ALLOWANCE, RELAY_DEPOSIT_NATIVE, RELAY_MAX_ORDER_AGE_S,\n RELAY_NATIVE, RELAY_ORDER_LIFETIME_S, RELAY_ORDER_VERSION, RELAY_SOLVERS, relayChain, type RelayChain,\n} from \"./config.js\";\nimport {RelayRefusal, parseRelayOrder, relayOrderId, relayOrderSigner, type RelayOrder} from \"./order.js\";\n\nconst DEPOSITORY_ABI = parseAbi([\n \"function depositNative(address depositor, bytes32 id) payable\",\n \"function depositErc20(address depositor, address token, uint256 amount, bytes32 id)\",\n]);\n\n/** Widest slippage a request may ask for. */\nexport const RELAY_MAX_SLIPPAGE_BPS = 5_000;\n/**\n * The slippage this module asks Relay for, and holds the order to, when the caller names none (Relay's own default\n * on 2026-11-10). Without it the answering side would choose how far the minimum may sit under the expected amount.\n */\nexport const RELAY_DEFAULT_SLIPPAGE_BPS = 200;\n\n/** A direct deposit used ~33k (native) and ~76k (ERC-20) gas in Relay's own estimates (2026-11-10). */\nexport const RELAY_GAS_FLOOR_NATIVE = 90_000n;\nexport const RELAY_GAS_FLOOR_ERC20 = 180_000n;\n/** Chains that meter gas differently (Mantle, zkSync) estimate far higher; an estimate is taken up to this. */\nexport const RELAY_GAS_CAP = 60_000_000n;\n/** The longest a quote may claim to live: the provider's own upper bound plus the tolerated clock difference. */\nexport const RELAY_MAX_QUOTE_LIFE_MS = 300_000 + RELAY_CLOCK_SKEW_S * 1000;\n\nexport {relayClearOrder} from \"./cleared.js\";\nimport {relayClearOrder} from \"./cleared.js\";\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst U256_MAX = (1n << 256n) - 1n;\n\n/** What the user asked for — the only thing an order is compared against. Addresses in any casing. */\nexport interface RelayRequest {\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: the `depositor` argument and the origin-chain refund recipient. */\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 /** The slippage the caller asked for: the order's minimum may sit at most this far under its expected amount. */\n slippageBps?: number;\n /** The clock (ms) deadlines are judged against; defaults to `Date.now()`. */\n nowMs?: number;\n}\n\n/** `protocol.v2` of a quote response, as received. */\nexport interface RelayProtocolData {\n orderId?: unknown;\n hubType?: unknown;\n orderData?: unknown;\n orderSignature?: unknown;\n paymentDetails?: unknown;\n}\n\n/** The deposit transaction under check: what the API proposed, or what is about to be signed. */\nexport interface RelayDepositTx {\n to?: unknown;\n data?: unknown;\n value?: unknown;\n chainId?: unknown;\n}\n\n/** A deposit this module built: the only bytes a Relay quote ever carries. */\nexport interface RelayDeposit {\n to: string;\n data: Hex;\n /** Wei, decimal. */\n value: string;\n chainId: number;\n /** ERC-20 input: the spender to approve for exactly the input amount — the pinned depository. */\n approvalAddress?: string;\n}\n\nexport interface VerifiedRelayOrder {\n order: RelayOrder;\n /** The order id, recomputed. */\n id: Hex;\n /** The deposit built here from the pins and the order. */\n deposit: RelayDeposit;\n /** `expectedAmount` of the single output payment. */\n expectedAmount: bigint;\n /** `minimumAmount` of the single output payment: the least the solver may pay for the order to count as filled. */\n minimumAmount: bigint;\n source: RelayChain;\n dest: RelayChain;\n}\n\nconst lower = (s: string): string => s.toLowerCase();\nconst isNative = (token: string): boolean => lower(token) === RELAY_NATIVE;\n\n/** The deposit call for an order: built from pinned and verified values only. */\nexport function buildRelayDeposit(source: RelayChain, depositor: string, token: string, amount: bigint, id: Hex): RelayDeposit {\n if (!ADDRESS.test(depositor) || /^0x0{40}$/.test(depositor)) throw new RelayRefusal(\"request-invalid\", \"the depositor is not an address\");\n if (!ADDRESS.test(token)) throw new RelayRefusal(\"request-invalid\", \"the input token is not an address\");\n if (amount <= 0n || amount > U256_MAX) throw new RelayRefusal(\"request-invalid\", \"the amount is not a positive integer\");\n if (!/^0x[0-9a-f]{64}$/.test(id)) throw new RelayRefusal(\"order-id-mismatch\", \"the order id is not 32 bytes\");\n if (isNative(token)) {\n return {\n to: source.depository,\n data: encodeFunctionData({abi: DEPOSITORY_ABI, functionName: \"depositNative\", args: [lower(depositor) as Hex, id]}),\n value: amount.toString(10),\n chainId: source.chainId,\n };\n }\n return {\n to: source.depository,\n data: encodeFunctionData({abi: DEPOSITORY_ABI, functionName: \"depositErc20\", args: [lower(depositor) as Hex, lower(token) as Hex, amount, id]}),\n value: \"0\",\n chainId: source.chainId,\n approvalAddress: source.depository,\n };\n}\n\nfunction checkRequest(r: RelayRequest): {source: RelayChain; dest: RelayChain; nowS: number} {\n const invalid = (what: string): never => { throw new RelayRefusal(\"request-invalid\", what); };\n if (r === null || typeof r !== \"object\") invalid(\"no request to check the order against\");\n const source = relayChain(r.sourceChain);\n const dest = relayChain(r.destChain);\n if (!source) throw new RelayRefusal(\"chain-unsupported\", `source chain ${String(r.sourceChain)} is not a pinned Relay chain`);\n if (!dest) throw new RelayRefusal(\"chain-unsupported\", `destination chain ${String(r.destChain)} is not a pinned Relay chain`);\n if (source === dest) throw new RelayRefusal(\"chain-unsupported\", \"source and destination are the same chain\");\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 if (/^0x0{40}$/.test(r.depositor)) invalid(\"the depositor is the zero address\");\n if (/^0x0{40}$/.test(r.recipient)) invalid(\"the recipient is the zero address\");\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)) invalid(\"the output floor is not an unsigned integer\");\n if (r.slippageBps !== undefined && (!Number.isInteger(r.slippageBps) || r.slippageBps < 0 || r.slippageBps > RELAY_MAX_SLIPPAGE_BPS)) {\n invalid(`slippage must be a whole number of basis points up to ${RELAY_MAX_SLIPPAGE_BPS}`);\n }\n const nowMs = r.nowMs ?? Date.now();\n if (!Number.isFinite(nowMs) || nowMs <= 0) invalid(\"the clock is not a time\");\n return {source, dest, nowS: Math.floor(nowMs / 1000)};\n}\n\n/** Twenty raw bytes equal to an address. `bytes` fields are lowercased by the parser. */\nconst isAddr = (bytes: Hex, addr: string): boolean => bytes.length === 42 && bytes === lower(addr);\n\nfunction checkDeadline(code: \"output-deadline\" | \"refund-deadline\", what: string, deadline: number, nowS: number): void {\n const left = deadline - nowS;\n if (left > RELAY_ORDER_LIFETIME_S + RELAY_CLOCK_SKEW_S) {\n throw new RelayRefusal(code, `${what} is ${left} s away, past the ${RELAY_ORDER_LIFETIME_S} s an order lives`);\n }\n if (left < RELAY_ORDER_LIFETIME_S - RELAY_MAX_ORDER_AGE_S) {\n throw new RelayRefusal(code, `${what} is ${left} s away: the order is older than ${RELAY_MAX_ORDER_AGE_S} s or already past it`);\n }\n}\n\n/** A 32-byte calldata word that is a left-padded address. */\nfunction wordAddress(word: string): string | null {\n return /^0{24}/.test(word) ? `0x${word.slice(24)}` : null;\n}\n\n/** Where the deposit goes: the pinned depository of the source chain, and nothing else. Checked before the order is read. */\nfunction checkDepositTarget(tx: RelayDepositTx, source: RelayChain): void {\n if (tx === null || typeof tx !== \"object\") throw new RelayRefusal(\"tx-calldata\", \"there is no deposit transaction\");\n if (tx.chainId !== source.chainId) {\n throw new RelayRefusal(\"tx-chain\", `the deposit is for chain ${String(tx.chainId)}, not ${source.chainId}`);\n }\n if (typeof tx.to !== \"string\" || !ADDRESS.test(tx.to) || lower(tx.to) !== source.depository) {\n throw new RelayRefusal(\"tx-target\", `the deposit calls ${String(tx.to)}, not the ${source.name} depository ${source.depository} — routes that first swap on the source chain go through a router and are not signed by this module`);\n }\n}\n\nfunction checkDepositTx(tx: RelayDepositTx, source: RelayChain, request: RelayRequest, order: RelayOrder, id: Hex): void {\n checkDepositTarget(tx, source);\n if (typeof tx.data !== \"string\" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(tx.data) || tx.data.length < 10) {\n throw new RelayRefusal(\"tx-calldata\", \"the deposit has no calldata\");\n }\n const data = lower(tx.data);\n const selector = data.slice(0, 10);\n const input = order.inputs[0]!.payment;\n const native = isNative(input.currency);\n if (selector === RELAY_DEPOSIT_ERC20_ALLOWANCE) {\n throw new RelayRefusal(\"tx-selector\", \"the deposit uses depositErc20 without an amount, which takes the whole allowance\");\n }\n if (selector !== RELAY_DEPOSIT_NATIVE && selector !== RELAY_DEPOSIT_ERC20) {\n throw new RelayRefusal(\"tx-selector\", `the deposit calls ${selector}, not a known deposit function`);\n }\n if ((selector === RELAY_DEPOSIT_NATIVE) !== native) {\n throw new RelayRefusal(\"tx-selector\", `the deposit calls ${native ? \"depositErc20\" : \"depositNative\"} for an order whose input is ${native ? \"the native coin\" : \"a token\"}`);\n }\n const words = native ? 2 : 4;\n if (data.length !== 10 + 64 * words) {\n throw new RelayRefusal(\"tx-calldata\", `the deposit calldata is ${(data.length - 2) / 2} bytes, not ${4 + 32 * words}`);\n }\n const word = (i: number): string => data.slice(10 + 64 * i, 74 + 64 * i);\n const depositor = wordAddress(word(0));\n if (depositor === null) throw new RelayRefusal(\"tx-calldata\", \"the depositor argument is not a padded address\");\n if (depositor !== lower(request.depositor)) {\n throw new RelayRefusal(\"tx-depositor\", `the deposit is credited to ${depositor}, not to the sender ${lower(request.depositor)}`);\n }\n if (!native) {\n const token = wordAddress(word(1));\n if (token === null) throw new RelayRefusal(\"tx-calldata\", \"the token argument is not a padded address\");\n if (token !== input.currency) throw new RelayRefusal(\"tx-token\", `the deposit moves ${token}, the order's input is ${input.currency}`);\n const amount = BigInt(`0x${word(2)}`);\n if (amount !== input.amount) throw new RelayRefusal(\"tx-amount\", `the deposit moves ${amount}, the order's input is ${input.amount}`);\n }\n const txId = `0x${word(native ? 1 : 3)}`;\n if (txId !== id) throw new RelayRefusal(\"tx-id\", `the deposit names order ${txId}, the order received hashes to ${id}`);\n const value = typeof tx.value === \"string\" && /^(?:0|[1-9]\\d{0,77})$/.test(tx.value) ? BigInt(tx.value) : null;\n const wantValue = native ? input.amount : 0n;\n if (value === null || value !== wantValue) {\n throw new RelayRefusal(\"tx-value\", `the deposit sends ${String(tx.value)} wei, it must send ${wantValue}`);\n }\n}\n\n/**\n * Check an order against the user's request and — when given — a deposit transaction against the order. Returns the\n * parsed order, its id and the deposit this module builds for it; throws {@link RelayRefusal} otherwise.\n *\n * `deposit` is what the API proposed (at quote time) or what is about to be signed (before signing). Without it the\n * order alone is checked and the caller uses the returned `deposit`.\n */\nexport function verifyRelayOrder(request: RelayRequest, protocol: RelayProtocolData | null | undefined, deposit?: RelayDepositTx): VerifiedRelayOrder {\n const {source, dest, nowS} = checkRequest(request);\n // A deposit that does not call the pinned depository is refused for that, whatever order comes with it.\n if (deposit !== undefined) checkDepositTarget(deposit, source);\n\n // The envelope.\n if (protocol === null || typeof protocol !== \"object\") {\n throw new RelayRefusal(\"protocol-data-missing\", \"the quote carries no order (protocol.v2) — nothing to check the deposit against\");\n }\n if (protocol.orderData === undefined || protocol.orderData === null) {\n throw new RelayRefusal(\"protocol-data-missing\", \"the quote carries no order data — nothing to check the deposit against\");\n }\n if (protocol.hubType !== \"onchain\") {\n throw new RelayRefusal(\"hub-type\", `the order settles through a \"${String(protocol.hubType)}\" hub, only \"onchain\" is read`);\n }\n const order = parseRelayOrder(protocol.orderData);\n\n // The shape.\n if (order.version !== RELAY_ORDER_VERSION) throw new RelayRefusal(\"order-version\", `order version \"${order.version}\" is not ${RELAY_ORDER_VERSION}`);\n if (order.inputs.length !== 1) throw new RelayRefusal(\"order-inputs\", `the order has ${order.inputs.length} inputs, exactly one is signed for`);\n if (order.output.payments.length !== 1) throw new RelayRefusal(\"order-payments\", `the order pays ${order.output.payments.length} outputs, exactly one is accepted`);\n if (order.output.calls.length !== 0) throw new RelayRefusal(\"order-calls\", \"the order runs calls on the destination — only plain payments are accepted\");\n if (order.fees.length !== 0) throw new RelayRefusal(\"order-fees\", \"the order carries order-level fees, which this module does not show and does not accept\");\n const input = order.inputs[0]!;\n const pay = order.output.payments[0]!;\n if (input.payment.weight === 0n) throw new RelayRefusal(\"input-weight\", \"the order's input has zero weight\");\n\n // The solver.\n if (!RELAY_SOLVERS.some((s) => s.address === order.solver && s.chainId === order.solverChainId)) {\n throw new RelayRefusal(\"solver-not-pinned\", `solver ${order.solver} on \"${order.solverChainId}\" is not a pinned Relay solver`);\n }\n\n // The output: who is paid, where, in what, and at least how much.\n if (order.output.chainId !== dest.slug) throw new RelayRefusal(\"output-chain\", `the order pays on \"${order.output.chainId}\", the request is for ${dest.name} (\"${dest.slug}\")`);\n if (!isAddr(pay.recipient, request.recipient)) throw new RelayRefusal(\"output-recipient\", `the order pays ${pay.recipient}, not the recipient ${lower(request.recipient)}`);\n if (!isAddr(pay.currency, request.destToken)) throw new RelayRefusal(\"output-currency\", `the order pays in ${pay.currency}, the request is for ${lower(request.destToken)}`);\n if (pay.minimumAmount <= 0n) throw new RelayRefusal(\"output-minimum\", \"the order's minimum output is zero\");\n if (request.minAmountOut !== undefined && pay.minimumAmount < request.minAmountOut) {\n throw new RelayRefusal(\"output-minimum\", `the order's minimum output ${pay.minimumAmount} is under the caller's floor ${request.minAmountOut}`);\n }\n if (pay.expectedAmount < pay.minimumAmount) throw new RelayRefusal(\"output-expected\", `the order expects ${pay.expectedAmount}, less than its own minimum ${pay.minimumAmount}`);\n const slippage = BigInt(request.slippageBps ?? RELAY_DEFAULT_SLIPPAGE_BPS);\n const floor = (pay.expectedAmount * (10_000n - slippage)) / 10_000n;\n if (pay.minimumAmount < floor) {\n throw new RelayRefusal(\"output-minimum\", `the order's minimum output ${pay.minimumAmount} is more than ${slippage} bps under its expected ${pay.expectedAmount}`);\n }\n checkDeadline(\"output-deadline\", \"the output deadline\", order.output.deadline, nowS);\n\n // The input: exactly what is sent.\n if (input.payment.chainId !== source.slug) throw new RelayRefusal(\"input-chain\", `the order is funded on \"${input.payment.chainId}\", the request sends on ${source.name} (\"${source.slug}\")`);\n if (!isAddr(input.payment.currency, request.sourceToken)) throw new RelayRefusal(\"input-currency\", `the order is funded in ${input.payment.currency}, the request sends ${lower(request.sourceToken)}`);\n if (input.payment.amount !== request.amount) throw new RelayRefusal(\"input-amount\", `the order is funded with ${input.payment.amount}, the request sends ${request.amount}`);\n\n // Refunds: on the source chain back to the sender in the token sent; on the destination to the recipient or the\n // sender; nowhere else. An unfilled order must have a way back on the source chain.\n let originRefund = false;\n for (const refund of input.refunds) {\n if (refund.chainId === source.slug) {\n if (!isAddr(refund.recipient, request.depositor)) throw new RelayRefusal(\"refund-recipient\", `a source-chain refund goes to ${refund.recipient}, not the sender ${lower(request.depositor)}`);\n if (refund.currency !== input.payment.currency) throw new RelayRefusal(\"refund-currency\", `a source-chain refund is in ${refund.currency}, not the token sent`);\n originRefund = true;\n } else if (refund.chainId === dest.slug) {\n if (!isAddr(refund.recipient, request.recipient) && !isAddr(refund.recipient, request.depositor)) {\n throw new RelayRefusal(\"refund-recipient\", `a destination-chain refund goes to ${refund.recipient}, neither the recipient nor the sender`);\n }\n if (refund.currency.length !== 42) throw new RelayRefusal(\"refund-currency\", \"a destination-chain refund names no token\");\n } else {\n throw new RelayRefusal(\"refund-chain\", `a refund is payable on \"${refund.chainId}\", neither the source nor the destination chain`);\n }\n checkDeadline(\"refund-deadline\", \"a refund deadline\", refund.deadline, nowS);\n }\n if (!originRefund) throw new RelayRefusal(\"refund-missing\", \"the order has no refund to the sender on the source chain\");\n\n // The id and who signed it.\n const id = relayOrderId(order);\n if (typeof protocol.orderId !== \"string\" || lower(protocol.orderId) !== id) {\n throw new RelayRefusal(\"order-id-mismatch\", `the quote names order ${String(protocol.orderId)}, the order data hashes to ${id}`);\n }\n const signer = relayOrderSigner(id, protocol.orderSignature);\n if (signer === null || signer !== order.solver) {\n throw new RelayRefusal(\"signature-invalid\", signer === null ? \"the order signature is not a valid signature\" : `the order is signed by ${signer}, not by its solver ${order.solver}`);\n }\n\n // What the API says the payment is: it must describe the same deposit.\n const pd = protocol.paymentDetails as {chainId?: unknown; depository?: unknown; currency?: unknown; amount?: unknown} | null | undefined;\n if (pd === null || typeof pd !== \"object\") throw new RelayRefusal(\"payment-details\", \"the quote has no payment details\");\n if (pd.chainId !== source.slug || typeof pd.depository !== \"string\" || lower(pd.depository) !== source.depository\n || typeof pd.currency !== \"string\" || lower(pd.currency) !== input.payment.currency\n || typeof pd.amount !== \"string\" || pd.amount !== input.payment.amount.toString(10)) {\n throw new RelayRefusal(\"payment-details\", \"the quote's payment details do not describe the order's input on the pinned depository\");\n }\n\n const built = buildRelayDeposit(source, request.depositor, input.payment.currency, input.payment.amount, id);\n if (deposit !== undefined) {\n checkDepositTx(deposit, source, request, order, id);\n // Whatever the field checks above let through, the bytes signed are the bytes built here.\n if (lower(deposit.data as string) !== built.data || lower(deposit.to as string) !== built.to || deposit.value !== built.value) {\n throw new RelayRefusal(\"tx-calldata\", \"the deposit is not the call this module builds for the order\");\n }\n }\n return {order, id, deposit: built, expectedAmount: pay.expectedAmount, minimumAmount: pay.minimumAmount, source, dest};\n}\n\n/** A refusal's text for a caller that wants a string (`onRefusal`, remote pins); rethrows anything else. */\nexport function relayRefusalReason(err: unknown): string {\n if (err instanceof RelayRefusal) return err.message;\n throw err;\n}\n\n/**\n * The request a `QuoteParams` describes, for the verifier. `dry` fills a missing address with `placeholder` (pricing\n * only). The sender is `refundAddress` — the engine sets it to the account that signs.\n */\nexport function relayRequestOf(params: QuoteParams, opts: {placeholder?: string; nowMs?: number} = {}): RelayRequest {\n const invalid = (what: string): never => { throw new RelayRefusal(\"request-invalid\", what); };\n if (params.flex) invalid(\"the amount is sealed into the order (no flexible deposits)\");\n if (!relayChain(params.sourceChain)) throw new RelayRefusal(\"chain-unsupported\", `source chain ${params.sourceChain} is not a pinned Relay chain`);\n if (!relayChain(params.destChain)) throw new RelayRefusal(\"chain-unsupported\", `destination chain ${params.destChain} is not a pinned Relay chain`);\n if (params.sourceChain === params.destChain) throw new RelayRefusal(\"chain-unsupported\", \"same-chain swaps are not served through the depository\");\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}`);\n sourceToken = asset!.contract ?? RELAY_NATIVE;\n if (!ADDRESS.test(sourceToken)) invalid(`source token ${String(params.sourceToken)} has no EVM contract`);\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)\");\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 && !/^(?:0|[1-9]\\d{0,77})$/.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 depositor = params.refundAddress || opts.placeholder || \"\";\n if (!depositor) invalid(\"a live quote needs the sender's address (refundAddress)\");\n if (!ADDRESS.test(depositor)) invalid(\"the sender's address 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 ...(params.slippageBps !== undefined ? {slippageBps: params.slippageBps} : {}),\n ...(opts.nowMs !== undefined ? {nowMs: opts.nowMs} : {}),\n };\n}\n\n/** The order a quote of this provider carries (`providerData`), back in the form the verifier reads. */\nexport function relayProtocolOf(quote: Quote): RelayProtocolData | null {\n const pd = quote.providerData;\n if (!pd || typeof pd.orderData !== \"string\") return null;\n let orderData: unknown;\n let paymentDetails: unknown;\n try {\n orderData = JSON.parse(pd.orderData);\n paymentDetails = typeof pd.paymentDetails === \"string\" ? JSON.parse(pd.paymentDetails) : undefined;\n } catch {\n return null;\n }\n return {orderId: pd.orderId, hubType: pd.hubType, orderData, orderSignature: pd.orderSignature, paymentDetails};\n}\n\n/**\n * A quote of this provider against the request it answers: the order it carries is verified, its transaction is\n * that order's deposit, its approval names the pinned depository, and the amounts it shows are the order's. Throws\n * {@link RelayRefusal}. Used on the client of a remote provider and again before signing.\n */\nexport function checkRelayQuote(request: RelayRequest, quote: Quote, tx?: RelayDepositTx & {approvalAddress?: unknown}): VerifiedRelayOrder {\n if (quote === null || typeof quote !== \"object\" || quote.provider !== \"relay\") throw new RelayRefusal(\"quote-shape\", \"not a Relay quote\");\n const t = tx ?? quote.txRequest;\n if (!t) throw new RelayRefusal(\"quote-shape\", \"the quote has no transaction\");\n if (quote.depositAddress) throw new RelayRefusal(\"quote-shape\", \"a Relay quote pays the depository through its calldata, never a deposit address\");\n if ((quote.txRequest as {serializedTx?: unknown; nativeFee?: unknown} | undefined)?.serializedTx !== undefined || (quote.txRequest as {nativeFee?: unknown} | undefined)?.nativeFee !== undefined) {\n throw new RelayRefusal(\"quote-shape\", \"a Relay deposit carries no extra native fee and no serialized transaction\");\n }\n const v = verifyRelayOrder(request, relayProtocolOf(quote), t);\n const approval = (t as {approvalAddress?: unknown}).approvalAddress;\n if (v.deposit.approvalAddress === undefined ? approval !== undefined && approval !== \"\" : typeof approval !== \"string\" || lower(approval) !== v.deposit.approvalAddress) {\n throw new RelayRefusal(\"quote-approval\", `the quote approves ${String(approval)}, the order needs ${v.deposit.approvalAddress ?? \"no approval\"}`);\n }\n if (quote.sourceAmount !== request.amount.toString(10) || quote.minDestAmount !== v.minimumAmount.toString(10) || quote.destAmount !== v.expectedAmount.toString(10)) {\n throw new RelayRefusal(\"quote-amounts\", \"the amounts the quote shows are not the order's\");\n }\n // Gas is the one number of the call that no order binds: held to the band this module itself would set, so a\n // backend can neither starve the deposit (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 const floor = v.deposit.approvalAddress === undefined ? RELAY_GAS_FLOOR_NATIVE : RELAY_GAS_FLOOR_ERC20;\n if (typeof gas !== \"string\" || !/^[1-9]\\d{0,10}$/.test(gas) || BigInt(gas) < floor || BigInt(gas) > RELAY_GAS_CAP) {\n throw new RelayRefusal(\"quote-gas\", `the gas limit ${String(gas).slice(0, 40)} is outside ${floor}–${RELAY_GAS_CAP}`);\n }\n }\n const now = request.nowMs ?? Date.now();\n if (typeof quote.validUntilMs !== \"number\" || !Number.isFinite(quote.validUntilMs) || quote.validUntilMs > now + RELAY_MAX_QUOTE_LIFE_MS) {\n throw new RelayRefusal(\"quote-expiry\", \"the quote claims to live longer than a Relay quote may\");\n }\n if (typeof quote.intentId !== \"string\" || quote.intentId !== `relay:${String(quote.providerData?.requestId)}` || !/^relay:0x[0-9a-f]{64}$/.test(quote.intentId)) {\n throw new RelayRefusal(\"quote-shape\", \"the quote's id is not its Relay request id\");\n }\n return v;\n}\n\n/** `RemotePins.verifyQuote`: the reason a remote Relay quote fails against the user's own request, or null. */\nexport function relayVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n try {\n checkRelayQuote(relayRequestOf(params), quote);\n return null;\n } catch (err) {\n return relayRefusalReason(err);\n }\n}\n\n/** `RemotePins.verifyBuild`: a remote build must be the quote's own (verified) transaction, and is verified again. */\nexport function relayVerifyBuild(quote: Quote, tx: UnsignedTx, params?: QuoteParams): string | null {\n try {\n if (!params) throw new RelayRefusal(\"request-invalid\", \"the request this quote answered is not known on this side — quote again\");\n if (tx.chain !== params.sourceChain) throw new RelayRefusal(\"tx-chain\", `the build is for ${tx.chain}, not ${params.sourceChain}`);\n if (tx.serializedTx !== undefined || tx.memo !== undefined || tx.typedData !== undefined || tx.bodyBoc !== undefined) {\n throw new RelayRefusal(\"quote-shape\", \"a Relay deposit is one EVM call\");\n }\n const v = checkRelayQuote(relayRequestOf(params), quote, tx);\n // The remote path has no client-side step after this one: an order is built for once.\n relayClearOrder(v.id, \"build\");\n return null;\n } catch (err) {\n return relayRefusalReason(err);\n }\n}\n\n/**\n * The app's pins for a remote Relay provider (`remoteProvider({name: \"relay\", ...relayPins})`): the only contract a\n * build may call or approve is the chain's depository, and every quote and build is verified on the client against\n * the user's own request.\n */\nexport const relayPins: RemotePins = Object.freeze({\n callTargets: (chain: string): readonly string[] => { const c = relayChain(chain); return c ? [c.depository] : []; },\n spenders: (chain: string): readonly string[] => { const c = relayChain(chain); return c ? [c.depository] : []; },\n verifyQuote: relayVerifyQuote,\n verifyBuild: relayVerifyBuild,\n});\n","/**\n * One deposit per order: the ids already cleared, for the whole JS realm — every provider instance and every remote\n * stub share it, so a second instance cannot be handed the order the first one already signed for.\n */\nimport {RELAY_CLOCK_SKEW_S, RELAY_MAX_ORDER_AGE_S} from \"./config.js\";\nimport {RelayRefusal} from \"./order.js\";\n\n// Order ids already cleared, per stage, for the whole JS realm (every provider instance and every remote stub): the\n// same order is never built or signed for twice while it could still pass the age check. An entry outlives the\n// order's own acceptance window (age + skew), after which the order is stale anyway.\nconst CLEARED_TTL_MS = (RELAY_MAX_ORDER_AGE_S + 2 * RELAY_CLOCK_SKEW_S) * 1000;\nconst CLEARED_MAX = 4096;\nconst clearedOrders = new Map<string, number>();\n\n/**\n * Record that `id` is being used at `stage` (\"build\" on the client of a remote provider, \"sign\" right before a\n * signature); throws `order-reused` when it already was. Fail-closed when the record is full of live entries.\n */\nexport function relayClearOrder(id: string, stage: \"build\" | \"sign\", nowMs: number = Date.now()): void {\n const key = `${stage}:${id.toLowerCase()}`;\n const until = clearedOrders.get(key);\n if (until !== undefined && until > nowMs) throw new RelayRefusal(\"order-reused\", `order ${id} was already cleared for a deposit — quote again`);\n if (clearedOrders.size >= CLEARED_MAX) {\n for (const [k, t] of clearedOrders) if (t <= nowMs) clearedOrders.delete(k);\n if (clearedOrders.size >= CLEARED_MAX) throw new RelayRefusal(\"order-reused\", \"too many deposits cleared in the last minutes — try again later\");\n }\n clearedOrders.set(key, nowMs + CLEARED_TTL_MS);\n}\n\n/** Tests only; the package index leaves it out. */\nexport function forgetClearedOrders(): void {\n clearedOrders.clear();\n}\n","import {anySignal, redactUrls, timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentState, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {describeRelayActivity} from \"./activity.js\";\nimport {RELAY_API, relay as relayCfg, relayChain} from \"./config.js\";\nimport {RelayRefusal} from \"./order.js\";\nimport {RELAY_DEFAULT_SLIPPAGE_BPS, RELAY_GAS_CAP as GAS_CAP, RELAY_GAS_FLOOR_ERC20 as GAS_FLOOR_ERC20, RELAY_GAS_FLOOR_NATIVE as GAS_FLOOR_NATIVE, checkRelayQuote, relayClearOrder, relayRequestOf, verifyRelayOrder, type RelayRequest} from \"./verify.js\";\n\n/**\n * Relay (relay.link) — a solver network. ONE source transaction: a deposit into the chain's RelayDepository that names\n * an order by its hash; Relay's solver then pays the recipient on the destination chain, or the deposit is refunded.\n *\n * - Quote = `POST /quote/v2` with `includeProtocolData: true`, which returns the order itself next to the deposit.\n * The answer is only an input to `verify.ts`: the order is parsed, hashed and attributed on the device, compared\n * with the request, and the deposit this module builds from its own pins must be byte-for-byte the one offered.\n * What a quote carries afterwards is that own-built call; the amounts it shows are the order's (`expectedAmount`\n * as the estimate, `minimumAmount` as the enforced minimum).\n * - The API's `approve` step is never used: an ERC-20 input sets `approvalAddress` to the pinned depository and the\n * engine approves exactly the input amount.\n * - `baseUrl` may be the app's own proxy that adds the API key. It cannot get a deposit signed for another\n * recipient, chain, token, minimum or refund address than the request's. It CAN make the quote worse: the solver\n * signs whatever request reaches Relay, so a proxy that adds an app fee or a gas top-up gets a genuine order with\n * a lower expected amount. The response's own account of such extras is refused (`app-fee`, `gas-topup`), but a\n * proxy can strip that too — the amounts shown are always the order's, and what bounds the price is the caller's\n * `minAmountOut` or the other quotes of the router, not this module.\n * - Routes Relay serves by first swapping on the source chain call a router, not the depository, and are refused\n * by name (`tx-target`); so are non-EVM chains and any chain without a pin.\n * - Status: `GET /intents/status/v3?requestId=` — display only, nothing is signed on its word.\n */\n\nconst EVM_PLACEHOLDER = \"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045\";\nconst DEFAULT_QUOTE_TTL_MS = 60_000;\nconst QUOTE_TIMEOUT_MS = 20_000;\nconst STATUS_TIMEOUT_MS = 12_000;\nconst INTENT_PREFIX = \"relay:\";\nconst REQUEST_ID = /^0x[0-9a-f]{64}$/;\nconst MAX_BODY = 512 * 1024;\nconst MAX_REMEMBERED = 256;\n\nexport interface RelayProviderConfig {\n enabled?: boolean;\n /**\n * Relay's API (default https://api.relay.link) or the app's own proxy in front of it. Untrusted either way:\n * every answer is verified on the device.\n */\n baseUrl?: string;\n /** Sent as `x-api-key` when set. Prefer a proxy that adds it — a key shipped in an app is public. */\n apiKey?: string;\n /** Local lifetime of a quote (default 60 s, at most 5 min). The order itself is refused once older than 10 min. */\n quoteTtlMs?: number;\n /** Injectable for tests and for runtimes that bring their own. */\n fetchImpl?: typeof fetch;\n /**\n * Where cleared order ids are also kept, so that \"one deposit per order\" survives an app restart (the built-in\n * record lives in memory). `has` is asked and `add` awaited right before a signature; either throwing refuses.\n */\n clearedStore?: RelayClearedStore;\n}\n\n/** A durable record of order ids a deposit was cleared for. `expiresAtMs` is when an entry may be dropped. */\nexport interface RelayClearedStore {\n has(orderId: string): boolean | Promise<boolean>;\n add(orderId: string, expiresAtMs: number): void | Promise<void>;\n}\n\ninterface RelayStep {id?: unknown; requestId?: unknown; items?: unknown}\ninterface RelayQuoteBody {\n steps?: unknown;\n fees?: {relayer?: {currency?: {address?: unknown}; amount?: unknown; amountUsd?: unknown}; app?: {amount?: unknown}};\n details?: {timeEstimate?: unknown; currencyGasTopup?: {amount?: unknown}};\n protocol?: {v2?: unknown};\n message?: unknown;\n errorCode?: unknown;\n}\n\n/** Relay's request states → swap2 states. `failure` is read together with `refundFailReason` (see `trackIntent`). */\nexport const RELAY_STATUS_MAP: Readonly<Record<string, IntentState>> = Object.freeze({\n waiting: \"pending\", depositing: \"pending\", pending: \"pending\", submitted: \"pending\", delayed: \"pending\", unknown: \"pending\",\n success: \"completed\", refund: \"refunded\", refunded: \"refunded\", failure: \"refund-pending\",\n});\n\nfunction clip(text: string, max = 240): string {\n const t = redactUrls(text).replace(/\\s+/g, \" \").trim();\n return t.length > max ? `${t.slice(0, max)}…` : t;\n}\n\n/** The single deposit step of a quote response; an `approve` step is ignored, anything else refuses the quote. */\nfunction depositStep(body: RelayQuoteBody): {requestId: string; tx: {to?: unknown; data?: unknown; value?: unknown; chainId?: unknown; gas?: unknown}} {\n const steps = body.steps;\n if (!Array.isArray(steps) || steps.length === 0 || steps.length > 8) throw new RelayRefusal(\"quote-steps\", \"the quote has no steps\");\n let found: RelayStep | null = null;\n for (const s of steps as RelayStep[]) {\n if (s === null || typeof s !== \"object\") throw new RelayRefusal(\"quote-steps\", \"the quote has a malformed step\");\n if (s.id === \"approve\") continue; // never used: the approval is built here, for the exact amount, to the pinned depository\n if (s.id !== \"deposit\") throw new RelayRefusal(\"quote-steps\", `the quote needs a \"${clip(String(s.id), 40)}\" step, only a single deposit is signed`);\n if (found) throw new RelayRefusal(\"quote-steps\", \"the quote has more than one deposit step\");\n found = s;\n }\n if (!found) throw new RelayRefusal(\"quote-steps\", \"the quote has no deposit step\");\n const items = found.items;\n if (!Array.isArray(items) || items.length !== 1) throw new RelayRefusal(\"quote-steps\", \"the deposit step is not a single transaction\");\n const data = (items[0] as {data?: unknown} | null)?.data;\n if (data === null || typeof data !== \"object\") throw new RelayRefusal(\"quote-steps\", \"the deposit step has no transaction\");\n const requestId = typeof found.requestId === \"string\" ? found.requestId.toLowerCase() : \"\";\n if (!REQUEST_ID.test(requestId)) throw new RelayRefusal(\"quote-steps\", \"the quote has no request id to track the deposit by\");\n return {requestId, tx: data as never};\n}\n\nexport function relayProvider(config: RelayProviderConfig = {}): CrossChainProvider {\n config = Object.freeze({...config});\n const base = (config.baseUrl ?? RELAY_API).replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(base)) throw new Error(\"relay: baseUrl must use http or https\");\n const quoteTtlMs = config.quoteTtlMs ?? DEFAULT_QUOTE_TTL_MS;\n if (!Number.isInteger(quoteTtlMs) || quoteTtlMs <= 0 || quoteTtlMs > 300_000) throw new Error(\"relay: quoteTtlMs must be an integer between 1 and 300000\");\n if (config.apiKey !== undefined && (typeof config.apiKey !== \"string\" || !/^[\\x21-\\x7e]{1,256}$/.test(config.apiKey))) throw new Error(\"relay: apiKey must be a printable string\");\n const doFetch: typeof fetch = (input, init) => (config.fetchImpl ?? fetch)(input, init);\n const headers = (json: boolean): Record<string, string> => ({\n accept: \"application/json\",\n ...(json ? {\"content-type\": \"application/json\"} : {}),\n ...(config.apiKey ? {\"x-api-key\": config.apiKey} : {}),\n });\n\n // The request each live quote answered, kept on this side: a deposit is checked against what was asked here, not\n // against what the quote object says was asked.\n const issued = new Map<string, RelayRequest>();\n const remember = <K, V>(m: Map<K, V>, k: K, v: V): void => {\n m.delete(k);\n m.set(k, v);\n if (m.size > MAX_REMEMBERED) m.delete(m.keys().next().value as K);\n };\n\n /** The request a quote is checked against before a build or a signature. */\n function requestOf(quote: Quote): RelayRequest {\n const pd = quote.providerData ?? {};\n const sealed: RelayRequest = {\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 ...(/^\\d{1,5}$/.test(pd.slippageBps ?? \"\") ? {slippageBps: Number(pd.slippageBps)} : {}),\n };\n // The pricing placeholder is never a party to a deposit, whatever flags the quote object carries.\n if (sealed.depositor.toLowerCase() === EVM_PLACEHOLDER.toLowerCase() || sealed.recipient.toLowerCase() === EVM_PLACEHOLDER.toLowerCase()) {\n throw new RelayRefusal(\"request-invalid\", \"a quote priced without the real addresses is never built or signed — quote again with them\");\n }\n const mine = issued.get(quote.intentId);\n if (!mine) return sealed;\n const same = mine.sourceChain === sealed.sourceChain && mine.destChain === sealed.destChain && mine.amount === sealed.amount\n && mine.sourceToken.toLowerCase() === sealed.sourceToken.toLowerCase() && mine.destToken.toLowerCase() === sealed.destToken.toLowerCase()\n && mine.depositor.toLowerCase() === sealed.depositor.toLowerCase() && mine.recipient.toLowerCase() === sealed.recipient.toLowerCase();\n if (!same) throw new RelayRefusal(\"request-invalid\", \"the quote no longer says what was asked when it was issued — quote again\");\n return mine;\n }\n\n async function readJson(res: Response): Promise<unknown> {\n const text = await res.text();\n if (text.length > MAX_BODY) throw new Error(\"relay: response too large\");\n return JSON.parse(text) as unknown;\n }\n\n return {\n name: \"relay\",\n describeActivity: describeRelayActivity,\n enabled: () => config.enabled ?? true,\n supportsChain: (chain: string) => relayCfg.supportsChain(chain),\n supportsChainPair: (from: string, to: string) => relayCfg.supports(from, to),\n supportsRoute: (from: Asset, to: Asset) => relayCfg.supports(from.chain, to.chain),\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (reason: string) => { params.onRefusal?.(reason); return null; };\n const dry = params.dry !== false;\n // Only a quote priced with the placeholder is unbuildable; one asked with real addresses is a real order.\n const placeholder = dry && (!params.destAddress || !params.refundAddress);\n let request: RelayRequest;\n try {\n // The placeholder prices a dry quote; a live one without addresses is refused.\n request = relayRequestOf(params, dry ? {placeholder: EVM_PLACEHOLDER} : {});\n } catch (err) {\n if (err instanceof RelayRefusal) return refuse(err.message);\n throw err;\n }\n const src = relayChain(request.sourceChain)!;\n const dst = relayChain(request.destChain)!;\n let body: RelayQuoteBody;\n try {\n const res = await doFetch(`${base}/quote/v2`, {\n method: \"POST\",\n headers: headers(true),\n body: JSON.stringify({\n user: request.depositor,\n recipient: request.recipient,\n refundTo: request.depositor,\n originChainId: src.chainId,\n destinationChainId: dst.chainId,\n originCurrency: request.sourceToken.toLowerCase(),\n destinationCurrency: request.destToken.toLowerCase(),\n amount: request.amount.toString(10),\n tradeType: \"EXACT_INPUT\",\n includeProtocolData: true,\n // Always named: Relay's \"auto\" would leave the distance between expected and minimum to the answering side.\n slippageTolerance: String(request.slippageBps ?? RELAY_DEFAULT_SLIPPAGE_BPS),\n }),\n signal: signal ? anySignal([signal, timeoutSignal(QUOTE_TIMEOUT_MS)]) : timeoutSignal(QUOTE_TIMEOUT_MS),\n });\n let parsed: unknown;\n try { parsed = await readJson(res); } catch { parsed = null; }\n if (!res.ok) {\n const e = (parsed ?? {}) as RelayQuoteBody;\n const why = typeof e.message === \"string\" ? clip(e.message) : `HTTP ${res.status}`;\n return refuse(`relay: no quote — ${typeof e.errorCode === \"string\" ? `${clip(e.errorCode, 60)}: ` : \"\"}${why}`);\n }\n if (parsed === null || typeof parsed !== \"object\") return refuse(\"relay: the quote response is not JSON\");\n body = parsed as RelayQuoteBody;\n } catch (err) {\n return refuse(`relay: quote request failed — ${clip(err instanceof Error ? err.message : String(err))}`);\n }\n\n try {\n const step = depositStep(body);\n const proto = (body.protocol?.v2 ?? null) as Record<string, unknown> | null;\n const v = verifyRelayOrder(request, proto, step.tx);\n // Extras this module never asks for. Each lowers the output inside a genuine order; the response's own account\n // of them is only a hint (an answering side that adds one can also hide it), so this refuses the honest case.\n const extra = (x: unknown): boolean => x !== undefined && x !== null && x !== \"0\" && x !== 0;\n if (extra(body.fees?.app?.amount)) throw new RelayRefusal(\"app-fee\", \"the quote charges an app fee this module did not ask for\");\n if (extra(body.details?.currencyGasTopup?.amount)) throw new RelayRefusal(\"gas-topup\", \"the quote converts part of the output into a gas top-up this module did not ask for\");\n const native = v.deposit.approvalAddress === undefined;\n const floor = native ? GAS_FLOOR_NATIVE : GAS_FLOOR_ERC20;\n const apiGas = typeof step.tx.gas === \"string\" && /^[1-9]\\d{0,9}$/.test(step.tx.gas) ? BigInt(step.tx.gas) * 2n : 0n;\n const gasLimit = apiGas > GAS_CAP ? GAS_CAP : apiGas > floor ? apiGas : floor;\n\n // Fees are Relay's own account of the quote: shown, never used in a check. They are already inside the output.\n const relayer = body.fees?.relayer;\n const usd = typeof relayer?.amountUsd === \"string\" && /^\\d{1,12}(?:\\.\\d{1,18})?$/.test(relayer.amountUsd) ? parseFloat(relayer.amountUsd) : 0;\n const feeToken = relayer?.currency?.address;\n const fees = typeof relayer?.amount === \"string\" && /^[1-9]\\d{0,77}$/.test(relayer.amount) && typeof feeToken === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(feeToken)\n ? [{type: \"protocol\" as const, amount: relayer.amount, token: feeToken.toLowerCase(), included: true, description: \"Relay fee\"}]\n : [];\n const eta = body.details?.timeEstimate;\n const etaSeconds = typeof eta === \"number\" && Number.isFinite(eta) && eta > 0 ? Math.min(Math.ceil(eta), 86_400) : 60;\n\n const intentId = `${INTENT_PREFIX}${step.requestId}`;\n if (!placeholder) remember(issued, intentId, request);\n return {\n provider: \"relay\",\n intentId,\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 gasLimit: gasLimit.toString(10),\n ...(v.deposit.approvalAddress ? {approvalAddress: v.deposit.approvalAddress} : {}),\n },\n sourceAmount: request.amount.toString(10),\n destAmount: v.expectedAmount.toString(10),\n minDestAmount: v.minimumAmount.toString(10),\n feeUsd: usd,\n fees,\n etaSeconds,\n reliability: 0.97,\n validUntilMs: Date.now() + quoteTtlMs,\n providerData: {\n requestId: step.requestId,\n orderId: v.id,\n hubType: \"onchain\",\n // The order as received, re-read by the same parser before a build and before a signature.\n orderData: JSON.stringify(proto!.orderData),\n orderSignature: String(proto!.orderSignature).toLowerCase(),\n paymentDetails: JSON.stringify(proto!.paymentDetails),\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 ...(request.minAmountOut !== undefined ? {minAmountOut: request.minAmountOut.toString(10)} : {}),\n ...(request.slippageBps !== undefined ? {slippageBps: String(request.slippageBps)} : {}),\n ...(placeholder ? {placeholder: \"1\"} : {}),\n },\n };\n } catch (err) {\n if (err instanceof RelayRefusal) return refuse(err.message);\n return refuse(`relay: unreadable quote — ${clip(err instanceof Error ? err.message : String(err))}`);\n }\n },\n\n /** The quote's own transaction — after the order it carries has been verified once more. */\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n if (!tx || !quote.intentId.startsWith(INTENT_PREFIX)) throw new Error(\"swap2: Relay quote has no transaction request\");\n if (quote.providerData?.placeholder === \"1\") throw new RelayRefusal(\"request-invalid\", \"a quote priced without the real addresses is never built — quote again with them\");\n const request = requestOf(quote);\n const v = checkRelayQuote(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 /**\n * Right before signing: the whole verification again, against the request this instance issued the quote for\n * and the exact transaction about to be signed — and each order is cleared for one deposit only.\n */\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n if (quote.providerData?.placeholder === \"1\") throw new RelayRefusal(\"request-invalid\", \"a quote priced without the real addresses is never signed\");\n const request = requestOf(quote);\n if (tx.chain !== request.sourceChain) throw new RelayRefusal(\"tx-chain\", `the deposit is for ${tx.chain}, not ${request.sourceChain}`);\n if (tx.serializedTx !== undefined || tx.memo !== undefined || tx.typedData !== undefined || tx.bodyBoc !== undefined) {\n throw new RelayRefusal(\"quote-shape\", \"a Relay deposit is one EVM call\");\n }\n const v = checkRelayQuote(request, quote, tx);\n const store = config.clearedStore;\n if (store && await store.has(v.id)) throw new RelayRefusal(\"order-reused\", `order ${v.id} was already cleared for a deposit — quote again`);\n relayClearOrder(v.id, \"sign\");\n // Kept until the order's own deadline: a deposit for it is never signed twice, restart or not.\n if (store) await store.add(v.id, v.order.output.deadline * 1000);\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n if (typeof ref.intentId !== \"string\" || !ref.intentId.startsWith(INTENT_PREFIX)) return {state: \"failed\"};\n const requestId = ref.intentId.slice(INTENT_PREFIX.length);\n if (!REQUEST_ID.test(requestId)) return {state: \"failed\"};\n // Nothing was sent yet: Relay answers \"waiting\" for a request it has seen no deposit for.\n if (!ref.sourceTxHash) return {state: \"pending\"};\n try {\n const res = await doFetch(`${base}/intents/status/v3?requestId=${requestId}`, {headers: headers(false), signal: timeoutSignal(STATUS_TIMEOUT_MS)});\n if (!res.ok) return {state: \"pending\"};\n const s = (await readJson(res)) as {status?: unknown; txHashes?: unknown; refundFailReason?: unknown} | null;\n const status = typeof s?.status === \"string\" ? s.status.toLowerCase() : \"\";\n const state = Object.prototype.hasOwnProperty.call(RELAY_STATUS_MAP, status) ? RELAY_STATUS_MAP[status]! : \"pending\";\n const seen = status !== \"waiting\" && status !== \"unknown\" && status !== \"\";\n if (state === \"completed\") {\n const hashes = Array.isArray(s?.txHashes) ? s.txHashes.filter((h): h is string => typeof h === \"string\" && /^0x[0-9a-fA-F]{64}$/.test(h)) : [];\n const dest = hashes[hashes.length - 1] ?? ref.destTxHash ?? undefined;\n return {state, depositReceived: true, ...(dest ? {destTxHash: dest} : {})};\n }\n if (status === \"failure\") {\n // A failed fill is refunded by Relay on its own. Only when the refund itself failed is there nothing\n // more coming without Relay's support.\n const why = typeof s?.refundFailReason === \"string\" ? s.refundFailReason.trim() : \"\";\n return {state: why !== \"\" && why.toUpperCase() !== \"N/A\" ? \"failed\" : \"refund-pending\", depositReceived: true};\n }\n return {state, ...(seen ? {depositReceived: true} : {})};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n","/**\n * Activity recognition for Relay on every pinned chain: `depositNative` / `depositErc20` on the chain's\n * RelayDepository is our source leg (\"Bridged ETH\").\n *\n * The destination leg is not claimed. A fill is sent by one of Relay's many relayer keys as an ordinary transfer (or\n * through a router for a destination swap) and names neither the order nor Relay on chain, so there is nothing to\n * recognise it by that a stranger could not imitate; it 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 {RELAY_DEPOSIT_ERC20, RELAY_DEPOSIT_ERC20_ALLOWANCE, RELAY_DEPOSIT_NATIVE, relayChain} from \"./config.js\";\n\nexport const RELAY_MODULE = \"@anywalletkit/protocol-swap2-relay\";\n\nexport function describeRelayActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n const chain = relayChain(tx.chain);\n if (!chain) return null;\n // All three deposit functions are read here (history is not ours alone); only two are ever built or signed.\n if (!matchesCall(tx, [chain.depository], [RELAY_DEPOSIT_NATIVE, RELAY_DEPOSIT_ERC20, RELAY_DEPOSIT_ERC20_ALLOWANCE])) return null;\n return describeSwapLike(tx, ctx, {protocol: RELAY_MODULE, subtitle: `Relay · ${chainLabel(tx.chain)}`, kind: \"bridge\", outVerb: \"Bridged\"});\n}\n","import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {relay as relayCfg} from \"./config.js\";\nimport {relayProvider, type RelayProviderConfig} from \"./provider.js\";\n\nexport interface RelaySwap2Config extends Swap2EngineConfig, RelayProviderConfig {}\n\n/** Standalone Relay swap2: EVM → EVM through Relay's depository, every order verified on the device before a deposit is signed. */\nexport class RelaySwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n constructor(account: Swap2Account | undefined, config: RelaySwap2Config) {\n super(account, config);\n this.provider = relayProvider(config);\n }\n protected override chainSupported(caip2: string): boolean {\n return relayCfg.supportsChain(caip2);\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return relayCfg.supports(fromChain, toChain);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8BA,IAAM,aAAa;AAEnB,IAAM,eAAe;AAErB,IAAM,IAAI,CAAC,SAAiB,MAAc,MAAc,aAAqB,eAC3E,OAAO,OAAO,EAAC,OAA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AM,SAAS,MAAM;AACrB,SAAK,WAAW,cAAc,MAAM;AAAA,EACtC;AAAA,EACmB,eAAe,OAAwB;AACxD,WAAO,MAAS,cAAc,KAAK;AAAA,EACrC;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,MAAS,SAAS,WAAW,OAAO;AAAA,EAC7C;AACF;","names":["import_viem","U256_MAX","bytes","c","import_util","text"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/order.ts","../src/verify.ts","../src/cleared.ts","../src/provider.ts","../src/activity.ts","../src/protocol.ts"],"sourcesContent":["export * from \"./config.js\";\nexport * from \"./order.js\";\nexport * from \"./verify.js\";\nexport * from \"./provider.js\";\nexport {RelaySwap2Protocol, type RelaySwap2Config} from \"./protocol.js\";\nexport {RelaySwap2Protocol as default} from \"./protocol.js\";\nexport * from \"./activity.js\";\n","// Relay (relay.link) — the pins this module signs against. Nothing here is read from the API at run time: the API (or\n// an app's own proxy in front of it) is untrusted, and a deposit is signed only for a depository, a chain mapping and\n// a solver signer written in this file.\n//\n// Sources, all read on 2026-11-10:\n// - `GET https://api.relay.link/chains` — per chain: `id`, `protocol.v2.chainId` (the chain's name inside an order,\n// which is NOT always `name`: BNB Chain is \"bnb\" in orders and \"bsc\" as `name`, World Chain \"worldchain\" /\n// \"world-chain\"), `protocol.v2.depository`, `solverAddresses`.\n// - On chain, over the SDK's public RPCs, for every row below: the depository has code, `allocator()` =\n// {@link RELAY_ALLOCATOR}, `owner()` = {@link RELAY_OWNER}, its EIP-712 domain reports the row's chain id, and the\n// bytecode carries the three deposit selectors. The runtime code is the same 8 628 bytes everywhere apart from the\n// immutables (the Mantle / Linea deployment is a second build, 8 777 bytes, at its own address).\n// - The contract: github.com/relayprotocol/relay-depository, packages/ethereum-vm/src/RelayDepository.sol.\n// - The order: github.com/relayprotocol/relay-protocol-sdk, src/order/index.ts (types and hashing), and Relay's own\n// \"input validation\" page (docs.relay.link), which names the solver below and tells integrators to take the\n// depository from `/chains` rather than from a quote.\n//\n// Only chains the SDK ships are listed, plus Elysium (99901), whose catalog entry is added separately. Relay also\n// serves chains the SDK does not carry; the SDK's Flare (14) and Sei (1329) are not on Relay.\n\nexport interface RelayChain {\n caip2: string;\n chainId: number;\n /** The chain's name inside a Relay order (`/chains[].protocol.v2.chainId`). */\n slug: string;\n name: string;\n /** RelayDepository on that chain: the only contract a deposit calls and the only spender an approval names. */\n depository: string;\n}\n\nconst DEPOSITORY = \"0x4cd00e387622c35bddb9b4c962c136462338bc31\";\n/** Mantle and Linea run a second deployment. */\nconst DEPOSITORY_B = \"0x59916da825d2d2ec1bf878d71c88826f6633ecca\";\n\nconst c = (chainId: number, slug: string, name: string, depository: string = DEPOSITORY): RelayChain =>\n Object.freeze({caip2: `eip155:${chainId}`, chainId, slug, name, depository});\n\n/** CAIP-2 → the chain as Relay knows it. A null-prototype map: `RELAY_CHAINS[\"constructor\"]` is undefined. */\nexport const RELAY_CHAINS: Readonly<Record<string, RelayChain>> = Object.freeze(Object.assign(Object.create(null) as Record<string, RelayChain>, Object.fromEntries([\n c(1, \"ethereum\", \"Ethereum\"),\n c(10, \"optimism\", \"OP Mainnet\"),\n c(56, \"bnb\", \"BNB Chain\"),\n c(100, \"gnosis\", \"Gnosis\"),\n c(130, \"unichain\", \"Unichain\"),\n c(137, \"polygon\", \"Polygon\"),\n c(143, \"monad\", \"Monad\"),\n c(146, \"sonic\", \"Sonic\"),\n c(196, \"xlayer\", \"X Layer\"),\n c(324, \"zksync\", \"zkSync Era\"),\n c(480, \"worldchain\", \"World Chain\"),\n c(999, \"hyperevm\", \"HyperEVM\"),\n c(2818, \"morph\", \"Morph\"),\n c(4326, \"megaeth\", \"MegaETH\"),\n c(4663, \"robinhood\", \"Robinhood Chain\"),\n c(5000, \"mantle\", \"Mantle\", DEPOSITORY_B),\n c(5042, \"arc\", \"Arc\"),\n c(8453, \"base\", \"Base\"),\n c(9745, \"plasma\", \"Plasma\"),\n c(42161, \"arbitrum\", \"Arbitrum\"),\n c(42220, \"celo\", \"Celo\"),\n c(43114, \"avalanche\", \"Avalanche\"),\n c(57073, \"ink\", \"Ink\"),\n c(59144, \"linea\", \"Linea\", DEPOSITORY_B),\n c(80094, \"berachain\", \"Berachain\"),\n c(98866, \"plume\", \"Plume\"),\n c(99901, \"elysium\", \"Elysium\"),\n c(534352, \"scroll\", \"Scroll\"),\n c(747474, \"katana\", \"Katana\"),\n].map((x) => [x.caip2, x]))));\n\n/** The chain for a CAIP-2 id, or undefined — own keys only. */\nexport function relayChain(caip2: string): RelayChain | undefined {\n return typeof caip2 === \"string\" && Object.prototype.hasOwnProperty.call(RELAY_CHAINS, caip2) ? RELAY_CHAINS[caip2] : undefined;\n}\n\n/**\n * The solver whose signature makes an order worth depositing for: `order.solver` on `order.solverChainId`, the signer of\n * `orderSignature`. One pair today (every order seen, Relay's validation page, first in `/chains[].solverAddresses`).\n * An order naming any other solver, or this address on another solver chain, is refused.\n */\nexport const RELAY_SOLVERS: readonly {readonly chainId: string; readonly address: string}[] = Object.freeze([\n Object.freeze({chainId: \"base\", address: \"0xf70da97812cb96acdf810712aa562db8dfa3dbef\"}),\n]);\n\n/** `allocator()` of every pinned depository (the key that authorises withdrawals from it) — a watched fact, not used in checks. */\nexport const RELAY_ALLOCATOR = \"0x63c1d3e9c646184529c5694630a01c00df171b56\";\n/** `owner()` of every pinned depository — a watched fact, not used in checks. */\nexport const RELAY_OWNER = \"0xf61a305199fa1135d76ffab3752d42f55cbd775a\";\n\n/** Relay's API. An app may point the provider at its own proxy instead (`baseUrl`); either is untrusted. */\nexport const RELAY_API = \"https://api.relay.link\";\n\n/** The native coin in a Relay order and in the API: twenty zero bytes. */\nexport const RELAY_NATIVE = \"0x0000000000000000000000000000000000000000\";\n\n/** `depositNative(address depositor, bytes32 id)` payable. */\nexport const RELAY_DEPOSIT_NATIVE = \"0x49290c1c\";\n/** `depositErc20(address depositor, address token, uint256 amount, bytes32 id)`. */\nexport const RELAY_DEPOSIT_ERC20 = \"0xe8017952\";\n/**\n * `depositErc20(address depositor, address token, bytes32 id)` — deposits the caller's WHOLE allowance. Never built and\n * always refused: the amount is not in the calldata.\n */\nexport const RELAY_DEPOSIT_ERC20_ALLOWANCE = \"0x5a1ee3ac\";\n\n/** The only order version this module reads. */\nexport const RELAY_ORDER_VERSION = \"v1\";\n\n/**\n * How long Relay gives an order: the output deadline and every refund deadline are the quote time + 7 days (every\n * order seen, 2026-11-02 … 2026-11-10). The verifier holds a deadline to this lifetime, which is also what makes an\n * old order stale: one issued more than {@link RELAY_MAX_ORDER_AGE_S} ago is refused even when everything else fits.\n */\nexport const RELAY_ORDER_LIFETIME_S = 604_800;\n/** An order older than this is refused (the quote itself lives for `quoteTtlMs`, 60 s by default, 5 min at most). */\nexport const RELAY_MAX_ORDER_AGE_S = 600;\n/** Tolerated clock difference between the device and Relay, forwards. */\nexport const RELAY_CLOCK_SKEW_S = 300;\n\nexport const relay = {\n supportsChain(chain: string): boolean {\n return relayChain(chain) !== undefined;\n },\n /** Two different pinned EVM chains. */\n supports(from: string, to: string): boolean {\n return from !== to && relayChain(from) !== undefined && relayChain(to) !== undefined;\n },\n};\n","/**\n * A Relay order, read strictly, hashed and attributed here.\n *\n * - The order id is the EIP-712 `hashStruct` of the order under {@link RELAY_ORDER_TYPES} (no domain separator), as\n * github.com/relayprotocol/relay-protocol-sdk (src/order/index.ts) computes it. Chain ids are STRINGS (Relay's own\n * chain names), addresses and currencies are `bytes` (20 raw bytes on an EVM chain).\n * - `orderSignature` is the solver's EIP-191 `personal_sign` over the 32 raw bytes of that id.\n *\n * The id a deposit names is a commitment to everything in the order — recipient, chain, token, minimum, refunds — so\n * recomputing it from the order the API hands over, and reading that same parsed order, is what binds the deposit\n * to terms the device has seen.\n */\nimport {secp256k1} from \"@noble/curves/secp256k1.js\";\nimport {withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {hashMessage, hashStruct, hexToBytes, keccak256, type Hex} from \"viem\";\n\n/** Why an order, a quote or a deposit was refused. One code per check; the message says what was found. */\nexport type RelayRefusalCode =\n | \"request-invalid\"\n | \"chain-unsupported\"\n | \"protocol-data-missing\"\n | \"hub-type\"\n | \"order-malformed\"\n | \"order-version\"\n | \"order-inputs\"\n | \"order-payments\"\n | \"order-calls\"\n | \"order-fees\"\n | \"solver-not-pinned\"\n | \"input-chain\"\n | \"input-currency\"\n | \"input-amount\"\n | \"input-weight\"\n | \"output-chain\"\n | \"output-recipient\"\n | \"output-currency\"\n | \"output-minimum\"\n | \"output-expected\"\n | \"output-deadline\"\n | \"refund-missing\"\n | \"refund-chain\"\n | \"refund-recipient\"\n | \"refund-currency\"\n | \"refund-deadline\"\n | \"order-id-mismatch\"\n | \"signature-invalid\"\n | \"payment-details\"\n | \"tx-chain\"\n | \"tx-target\"\n | \"tx-selector\"\n | \"tx-calldata\"\n | \"tx-depositor\"\n | \"tx-token\"\n | \"tx-amount\"\n | \"tx-id\"\n | \"tx-value\"\n | \"order-reused\"\n | \"app-fee\"\n | \"gas-topup\"\n | \"quote-gas\"\n | \"quote-expiry\"\n | \"quote-steps\"\n | \"quote-amounts\"\n | \"quote-approval\"\n | \"quote-shape\";\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 * (an order deadline too far ahead is `policy_refused`, one already used up is `quote_expired`); a malformed request\n * from the caller (a programming error) carries none.\n */\nexport class RelayRefusal extends Error {\n readonly code: RelayRefusalCode;\n declare readonly reason?: Swap2RefusalReason;\n constructor(code: RelayRefusalCode, detail: string, reason?: Swap2RefusalReason) {\n super(`relay: ${detail} [${code}]`);\n this.name = \"RelayRefusal\";\n this.code = code;\n if (reason !== undefined) withReason(this, reason);\n }\n}\n\nexport const RELAY_ORDER_TYPES = {\n Order: [\n {name: \"version\", type: \"string\"},\n {name: \"solverChainId\", type: \"string\"},\n {name: \"solver\", type: \"address\"},\n {name: \"salt\", type: \"uint256\"},\n {name: \"inputs\", type: \"Input[]\"},\n {name: \"output\", type: \"Output\"},\n {name: \"fees\", type: \"Fee[]\"},\n ],\n Input: [\n {name: \"payment\", type: \"InputPayment\"},\n {name: \"refunds\", type: \"InputRefund[]\"},\n ],\n InputPayment: [\n {name: \"chainId\", type: \"string\"},\n {name: \"currency\", type: \"bytes\"},\n {name: \"amount\", type: \"uint256\"},\n {name: \"weight\", type: \"uint256\"},\n ],\n InputRefund: [\n {name: \"chainId\", type: \"string\"},\n {name: \"recipient\", type: \"bytes\"},\n {name: \"currency\", type: \"bytes\"},\n {name: \"minimumAmount\", type: \"uint256\"},\n {name: \"deadline\", type: \"uint32\"},\n {name: \"extraData\", type: \"bytes\"},\n ],\n Output: [\n {name: \"chainId\", type: \"string\"},\n {name: \"payments\", type: \"OutputPayment[]\"},\n {name: \"deadline\", type: \"uint32\"},\n {name: \"calls\", type: \"bytes[]\"},\n {name: \"extraData\", type: \"bytes\"},\n ],\n OutputPayment: [\n {name: \"recipient\", type: \"bytes\"},\n {name: \"currency\", type: \"bytes\"},\n {name: \"minimumAmount\", type: \"uint256\"},\n {name: \"expectedAmount\", type: \"uint256\"},\n ],\n Fee: [\n {name: \"recipientChainId\", type: \"string\"},\n {name: \"recipient\", type: \"bytes\"},\n {name: \"currencyChainId\", type: \"string\"},\n {name: \"currency\", type: \"bytes\"},\n {name: \"amount\", type: \"uint256\"},\n ],\n} as const;\n\nexport interface RelayInputRefund {chainId: string; recipient: Hex; currency: Hex; minimumAmount: bigint; deadline: number; extraData: Hex}\nexport interface RelayInput {payment: {chainId: string; currency: Hex; amount: bigint; weight: bigint}; refunds: RelayInputRefund[]}\nexport interface RelayOutputPayment {recipient: Hex; currency: Hex; minimumAmount: bigint; expectedAmount: bigint}\nexport interface RelayFee {recipientChainId: string; recipient: Hex; currencyChainId: string; currency: Hex; amount: bigint}\n/** An order after {@link parseRelayOrder}: hex lowercased, integers exact. Every field below is hashed into the id. */\nexport interface RelayOrder {\n version: string;\n solverChainId: string;\n solver: Hex;\n salt: bigint;\n inputs: RelayInput[];\n output: {chainId: string; payments: RelayOutputPayment[]; deadline: number; calls: Hex[]; extraData: Hex};\n fees: RelayFee[];\n}\n\nconst MAX_LIST = 8;\nconst MAX_BYTES_HEX = 2 + 2 * 1024;\nconst MAX_TEXT = 64;\nconst U256_MAX = (1n << 256n) - 1n;\n\n// The answer is not the documented shape.\nconst bad = (what: string): never => { throw new RelayRefusal(\"order-malformed\", `the order's ${what}`, \"upstream_unavailable\"); };\n\nfunction rec(v: unknown, what: string): Record<string, unknown> {\n if (v === null || typeof v !== \"object\" || Array.isArray(v)) bad(`${what} is not an object`);\n return v as Record<string, unknown>;\n}\nfunction list(v: unknown, what: string): unknown[] {\n if (!Array.isArray(v)) bad(`${what} is not a list`);\n if ((v as unknown[]).length > MAX_LIST) bad(`${what} has more than ${MAX_LIST} entries`);\n return v as unknown[];\n}\n/** Own property only: a field missing from the JSON is never read off a prototype. */\nfunction own(o: Record<string, unknown>, key: string): unknown {\n return Object.prototype.hasOwnProperty.call(o, key) ? o[key] : undefined;\n}\nfunction text(v: unknown, what: string): string {\n if (typeof v !== \"string\" || v.length === 0 || v.length > MAX_TEXT) bad(`${what} is not a short string`);\n return v as string;\n}\n/** `bytes`: 0x-hex of whole bytes, lowercased. */\nfunction bytes(v: unknown, what: string): Hex {\n if (typeof v !== \"string\" || v.length > MAX_BYTES_HEX || !/^0x(?:[0-9a-fA-F]{2})*$/.test(v)) bad(`${what} is not hex bytes`);\n return (v as string).toLowerCase() as Hex;\n}\n/** `uint256`: a decimal string, a 0x-hex string (Relay writes the salt that way) or a safe non-negative integer. */\nfunction uint(v: unknown, what: string, max: bigint = U256_MAX): bigint {\n let n: bigint | null = null;\n if (typeof v === \"string\" && (/^(?:0|[1-9]\\d{0,77})$/.test(v) || /^0x[0-9a-fA-F]{1,64}$/.test(v))) n = BigInt(v);\n else if (typeof v === \"number\" && Number.isSafeInteger(v) && v >= 0) n = BigInt(v);\n if (n === null || n > max) bad(`${what} is not an unsigned integer in range`);\n return n as bigint;\n}\nfunction uint32(v: unknown, what: string): number {\n // Below 2^32, so the conversion is exact.\n return parseInt(uint(v, what, 0xffff_ffffn).toString(10), 10);\n}\nfunction address(v: unknown, what: string): Hex {\n if (typeof v !== \"string\" || !/^0x[0-9a-fA-F]{40}$/.test(v)) bad(`${what} is not an address`);\n return (v as string).toLowerCase() as Hex;\n}\n\n/**\n * Read an order as the API gives it (`protocol.v2.orderData`, already JSON-parsed) into the one typed form the id,\n * the signature and every check are computed from. Anything that is not exactly the documented shape is refused\n * (`order-malformed`); keys the type does not have are ignored — they are outside the hash, and nothing reads them.\n */\nexport function parseRelayOrder(raw: unknown): RelayOrder {\n const o = rec(raw, \"body\");\n const output = rec(own(o, \"output\"), \"output\");\n return {\n version: text(own(o, \"version\"), \"version\"),\n solverChainId: text(own(o, \"solverChainId\"), \"solver chain\"),\n solver: address(own(o, \"solver\"), \"solver\"),\n salt: uint(own(o, \"salt\"), \"salt\"),\n inputs: list(own(o, \"inputs\"), \"inputs\").map((x, i) => {\n const input = rec(x, `input ${i}`);\n const p = rec(own(input, \"payment\"), `input ${i} payment`);\n return {\n payment: {\n chainId: text(own(p, \"chainId\"), `input ${i} chain`),\n currency: bytes(own(p, \"currency\"), `input ${i} currency`),\n amount: uint(own(p, \"amount\"), `input ${i} amount`),\n weight: uint(own(p, \"weight\"), `input ${i} weight`),\n },\n refunds: list(own(input, \"refunds\"), `input ${i} refunds`).map((y, j) => {\n const r = rec(y, `refund ${j}`);\n return {\n chainId: text(own(r, \"chainId\"), `refund ${j} chain`),\n recipient: bytes(own(r, \"recipient\"), `refund ${j} recipient`),\n currency: bytes(own(r, \"currency\"), `refund ${j} currency`),\n minimumAmount: uint(own(r, \"minimumAmount\"), `refund ${j} minimum`),\n deadline: uint32(own(r, \"deadline\"), `refund ${j} deadline`),\n extraData: bytes(own(r, \"extraData\"), `refund ${j} extra data`),\n };\n }),\n };\n }),\n output: {\n chainId: text(own(output, \"chainId\"), \"output chain\"),\n payments: list(own(output, \"payments\"), \"output payments\").map((x, i) => {\n const p = rec(x, `output payment ${i}`);\n return {\n recipient: bytes(own(p, \"recipient\"), `output payment ${i} recipient`),\n currency: bytes(own(p, \"currency\"), `output payment ${i} currency`),\n minimumAmount: uint(own(p, \"minimumAmount\"), `output payment ${i} minimum`),\n expectedAmount: uint(own(p, \"expectedAmount\"), `output payment ${i} expected amount`),\n };\n }),\n deadline: uint32(own(output, \"deadline\"), \"output deadline\"),\n calls: list(own(output, \"calls\"), \"output calls\").map((x, i) => bytes(x, `output call ${i}`)),\n extraData: bytes(own(output, \"extraData\"), \"output extra data\"),\n },\n fees: list(own(o, \"fees\"), \"fees\").map((x, i) => {\n const f = rec(x, `fee ${i}`);\n return {\n recipientChainId: text(own(f, \"recipientChainId\"), `fee ${i} recipient chain`),\n recipient: bytes(own(f, \"recipient\"), `fee ${i} recipient`),\n currencyChainId: text(own(f, \"currencyChainId\"), `fee ${i} currency chain`),\n currency: bytes(own(f, \"currency\"), `fee ${i} currency`),\n amount: uint(own(f, \"amount\"), `fee ${i} amount`),\n };\n }),\n };\n}\n\n/** The order id: `hashStruct(Order)`, no domain. */\nexport function relayOrderId(order: RelayOrder): Hex {\n return hashStruct({types: RELAY_ORDER_TYPES, primaryType: \"Order\", data: order as never});\n}\n\n/**\n * The address whose `personal_sign` over the id's 32 bytes this signature is (lowercase), or null when it is not a\n * 65-byte secp256k1 signature that recovers at all. Synchronous on purpose: the same check runs wherever the order\n * is read, with nothing left for a later asynchronous step.\n */\nexport function relayOrderSigner(id: Hex, signature: unknown): Hex | null {\n if (typeof signature !== \"string\" || !/^0x[0-9a-fA-F]{130}$/.test(signature)) return null;\n const sig = hexToBytes(signature as Hex);\n const v = sig[64]!;\n const recovery = v === 27 || v === 28 ? v - 27 : v === 0 || v === 1 ? v : -1;\n if (recovery < 0) return null;\n try {\n const recoverable = new Uint8Array(65);\n recoverable[0] = recovery;\n recoverable.set(sig.subarray(0, 64), 1);\n const digest = hexToBytes(hashMessage({raw: id}));\n const key = secp256k1.recoverPublicKey(recoverable, digest, {prehash: false});\n // The recovery must also verify: a malformed (r, s) never passes as a signer.\n if (!secp256k1.verify(sig.subarray(0, 64), digest, key, {prehash: false})) return null;\n const uncompressed = secp256k1.Point.fromBytes(key).toBytes(false);\n return `0x${keccak256(uncompressed.subarray(1)).slice(-40)}`.toLowerCase() as Hex;\n } catch {\n return null;\n }\n}\n","/**\n * The device-side check of a Relay order and of the deposit that funds it.\n *\n * A Relay deposit is `depositNative(depositor, id)` / `depositErc20(depositor, token, amount, id)` on the chain's\n * RelayDepository: the calldata names no recipient, no destination and no minimum — only `id`, the hash of an order\n * that lives off chain. Signing such a deposit is safe exactly when the device holds the order behind the id and that\n * order says what the user asked for. {@link verifyRelayOrder} establishes that, from nothing but the user's own\n * request, the pins in `config.ts`, and the bytes the API (or an app's proxy — equally untrusted) returned:\n *\n * 1. the order is the documented shape, one input, one output payment, no destination calls, no order-level fees;\n * 2. its content is the request: recipient, destination chain and token, a minimum no lower than the caller's, a\n * deadline one order lifetime away, the input chain / token / amount, refunds only to the user;\n * 3. its solver is the pinned one and the solver signed this very id;\n * 4. the id recomputed here (EIP-712 `hashStruct`) is the id in the calldata;\n * 5. the transaction is a known deposit call on the pinned depository, depositing exactly the order's input from the\n * user's own address — and is byte-for-byte the call this module would build itself.\n *\n * Every refusal is a {@link RelayRefusal} with its own code. Nothing here is asynchronous and nothing reads the\n * network, so the same function runs at quote time, again right before signing, and on the client of a remote\n * provider (`relayPins.verifyQuote`).\n */\nimport {encodeFunctionData, parseAbi, type Hex} from \"viem\";\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 RELAY_CLOCK_SKEW_S, RELAY_DEPOSIT_ERC20, RELAY_DEPOSIT_ERC20_ALLOWANCE, RELAY_DEPOSIT_NATIVE, RELAY_MAX_ORDER_AGE_S,\n RELAY_NATIVE, RELAY_ORDER_LIFETIME_S, RELAY_ORDER_VERSION, RELAY_SOLVERS, relayChain, type RelayChain,\n} from \"./config.js\";\nimport {RelayRefusal, parseRelayOrder, relayOrderId, relayOrderSigner, type RelayOrder} from \"./order.js\";\n\nconst DEPOSITORY_ABI = parseAbi([\n \"function depositNative(address depositor, bytes32 id) payable\",\n \"function depositErc20(address depositor, address token, uint256 amount, bytes32 id)\",\n]);\n\n/** Widest slippage a request may ask for. */\nexport const RELAY_MAX_SLIPPAGE_BPS = 5_000;\n/**\n * The slippage this module asks Relay for, and holds the order to, when the caller names none (Relay's own default\n * on 2026-11-10). Without it the answering side would choose how far the minimum may sit under the expected amount.\n */\nexport const RELAY_DEFAULT_SLIPPAGE_BPS = 200;\n\n/** A direct deposit used ~33k (native) and ~76k (ERC-20) gas in Relay's own estimates (2026-11-10). */\nexport const RELAY_GAS_FLOOR_NATIVE = 90_000n;\nexport const RELAY_GAS_FLOOR_ERC20 = 180_000n;\n/** Chains that meter gas differently (Mantle, zkSync) estimate far higher; an estimate is taken up to this. */\nexport const RELAY_GAS_CAP = 60_000_000n;\n/** The longest a quote may claim to live: the provider's own upper bound plus the tolerated clock difference. */\nexport const RELAY_MAX_QUOTE_LIFE_MS = 300_000 + RELAY_CLOCK_SKEW_S * 1000;\n\nexport {relayClearOrder} from \"./cleared.js\";\nimport {relayClearOrder} from \"./cleared.js\";\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst U256_MAX = (1n << 256n) - 1n;\n\n/** What the user asked for — the only thing an order is compared against. Addresses in any casing. */\nexport interface RelayRequest {\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: the `depositor` argument and the origin-chain refund recipient. */\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 /** The slippage the caller asked for: the order's minimum may sit at most this far under its expected amount. */\n slippageBps?: number;\n /** The clock (ms) deadlines are judged against; defaults to `Date.now()`. */\n nowMs?: number;\n}\n\n/** `protocol.v2` of a quote response, as received. */\nexport interface RelayProtocolData {\n orderId?: unknown;\n hubType?: unknown;\n orderData?: unknown;\n orderSignature?: unknown;\n paymentDetails?: unknown;\n}\n\n/** The deposit transaction under check: what the API proposed, or what is about to be signed. */\nexport interface RelayDepositTx {\n to?: unknown;\n data?: unknown;\n value?: unknown;\n chainId?: unknown;\n}\n\n/** A deposit this module built: the only bytes a Relay quote ever carries. */\nexport interface RelayDeposit {\n to: string;\n data: Hex;\n /** Wei, decimal. */\n value: string;\n chainId: number;\n /** ERC-20 input: the spender to approve for exactly the input amount — the pinned depository. */\n approvalAddress?: string;\n}\n\nexport interface VerifiedRelayOrder {\n order: RelayOrder;\n /** The order id, recomputed. */\n id: Hex;\n /** The deposit built here from the pins and the order. */\n deposit: RelayDeposit;\n /** `expectedAmount` of the single output payment. */\n expectedAmount: bigint;\n /** `minimumAmount` of the single output payment: the least the solver may pay for the order to count as filled. */\n minimumAmount: bigint;\n source: RelayChain;\n dest: RelayChain;\n}\n\nconst lower = (s: string): string => s.toLowerCase();\nconst isNative = (token: string): boolean => lower(token) === RELAY_NATIVE;\n\n/** The deposit call for an order: built from pinned and verified values only. */\nexport function buildRelayDeposit(source: RelayChain, depositor: string, token: string, amount: bigint, id: Hex): RelayDeposit {\n if (!ADDRESS.test(depositor) || /^0x0{40}$/.test(depositor)) throw new RelayRefusal(\"request-invalid\", \"the depositor is not an address\");\n if (!ADDRESS.test(token)) throw new RelayRefusal(\"request-invalid\", \"the input token is not an address\");\n if (amount <= 0n || amount > U256_MAX) throw new RelayRefusal(\"request-invalid\", \"the amount is not a positive integer\");\n if (!/^0x[0-9a-f]{64}$/.test(id)) throw new RelayRefusal(\"order-id-mismatch\", \"the order id is not 32 bytes\");\n if (isNative(token)) {\n return {\n to: source.depository,\n data: encodeFunctionData({abi: DEPOSITORY_ABI, functionName: \"depositNative\", args: [lower(depositor) as Hex, id]}),\n value: amount.toString(10),\n chainId: source.chainId,\n };\n }\n return {\n to: source.depository,\n data: encodeFunctionData({abi: DEPOSITORY_ABI, functionName: \"depositErc20\", args: [lower(depositor) as Hex, lower(token) as Hex, amount, id]}),\n value: \"0\",\n chainId: source.chainId,\n approvalAddress: source.depository,\n };\n}\n\nfunction checkRequest(r: RelayRequest): {source: RelayChain; dest: RelayChain; nowS: number} {\n // A malformed request is the caller's own bug and carries no reason; the zero-address parties and the slippage cap\n // are refusals.\n const invalid = (what: string, reason?: Swap2RefusalReason): never => { throw new RelayRefusal(\"request-invalid\", what, reason); };\n if (r === null || typeof r !== \"object\") invalid(\"no request to check the order against\");\n const source = relayChain(r.sourceChain);\n const dest = relayChain(r.destChain);\n if (!source) throw new RelayRefusal(\"chain-unsupported\", `source chain ${String(r.sourceChain)} is not a pinned Relay chain`, \"unsupported_pair\");\n if (!dest) throw new RelayRefusal(\"chain-unsupported\", `destination chain ${String(r.destChain)} is not a pinned Relay chain`, \"unsupported_pair\");\n if (source === dest) throw new RelayRefusal(\"chain-unsupported\", \"source and destination are the same chain\", \"unsupported_pair\");\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 if (/^0x0{40}$/.test(r.depositor)) invalid(\"the depositor is the zero address\", \"recipient_mismatch\");\n if (/^0x0{40}$/.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)) invalid(\"the output floor is not an unsigned integer\");\n if (r.slippageBps !== undefined && (!Number.isInteger(r.slippageBps) || r.slippageBps < 0 || r.slippageBps > RELAY_MAX_SLIPPAGE_BPS)) {\n invalid(`slippage must be a whole number of basis points up to ${RELAY_MAX_SLIPPAGE_BPS}`, \"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 {source, dest, nowS: Math.floor(nowMs / 1000)};\n}\n\n/** Twenty raw bytes equal to an address. `bytes` fields are lowercased by the parser. */\nconst isAddr = (bytes: Hex, addr: string): boolean => bytes.length === 42 && bytes === lower(addr);\n\nfunction checkDeadline(code: \"output-deadline\" | \"refund-deadline\", what: string, deadline: number, nowS: number): void {\n const left = deadline - nowS;\n if (left > RELAY_ORDER_LIFETIME_S + RELAY_CLOCK_SKEW_S) {\n throw new RelayRefusal(code, `${what} is ${left} s away, past the ${RELAY_ORDER_LIFETIME_S} s an order lives`, \"policy_refused\");\n }\n if (left < RELAY_ORDER_LIFETIME_S - RELAY_MAX_ORDER_AGE_S) {\n throw new RelayRefusal(code, `${what} is ${left} s away: the order is older than ${RELAY_MAX_ORDER_AGE_S} s or already past it`, \"quote_expired\");\n }\n}\n\n/** A 32-byte calldata word that is a left-padded address. */\nfunction wordAddress(word: string): string | null {\n return /^0{24}/.test(word) ? `0x${word.slice(24)}` : null;\n}\n\n/** Where the deposit goes: the pinned depository of the source chain, and nothing else. Checked before the order is read. */\nfunction checkDepositTarget(tx: RelayDepositTx, source: RelayChain): void {\n if (tx === null || typeof tx !== \"object\") throw new RelayRefusal(\"tx-calldata\", \"there is no deposit transaction\", \"policy_refused\");\n if (tx.chainId !== source.chainId) {\n throw new RelayRefusal(\"tx-chain\", `the deposit is for chain ${String(tx.chainId)}, not ${source.chainId}`, \"vault_mismatch\");\n }\n if (typeof tx.to !== \"string\" || !ADDRESS.test(tx.to) || lower(tx.to) !== source.depository) {\n throw new RelayRefusal(\"tx-target\", `the deposit calls ${String(tx.to)}, not the ${source.name} depository ${source.depository} — routes that first swap on the source chain go through a router and are not signed by this module`, \"vault_mismatch\");\n }\n}\n\nfunction checkDepositTx(tx: RelayDepositTx, source: RelayChain, request: RelayRequest, order: RelayOrder, id: Hex): void {\n checkDepositTarget(tx, source);\n if (typeof tx.data !== \"string\" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(tx.data) || tx.data.length < 10) {\n throw new RelayRefusal(\"tx-calldata\", \"the deposit has no calldata\", \"policy_refused\");\n }\n const data = lower(tx.data);\n const selector = data.slice(0, 10);\n const input = order.inputs[0]!.payment;\n const native = isNative(input.currency);\n if (selector === RELAY_DEPOSIT_ERC20_ALLOWANCE) {\n throw new RelayRefusal(\"tx-selector\", \"the deposit uses depositErc20 without an amount, which takes the whole allowance\", \"policy_refused\");\n }\n if (selector !== RELAY_DEPOSIT_NATIVE && selector !== RELAY_DEPOSIT_ERC20) {\n throw new RelayRefusal(\"tx-selector\", `the deposit calls ${selector}, not a known deposit function`, \"policy_refused\");\n }\n if ((selector === RELAY_DEPOSIT_NATIVE) !== native) {\n throw new RelayRefusal(\"tx-selector\", `the deposit calls ${native ? \"depositErc20\" : \"depositNative\"} for an order whose input is ${native ? \"the native coin\" : \"a token\"}`, \"policy_refused\");\n }\n const words = native ? 2 : 4;\n if (data.length !== 10 + 64 * words) {\n throw new RelayRefusal(\"tx-calldata\", `the deposit calldata is ${(data.length - 2) / 2} bytes, not ${4 + 32 * words}`, \"policy_refused\");\n }\n const word = (i: number): string => data.slice(10 + 64 * i, 74 + 64 * i);\n const depositor = wordAddress(word(0));\n if (depositor === null) throw new RelayRefusal(\"tx-calldata\", \"the depositor argument is not a padded address\", \"policy_refused\");\n if (depositor !== lower(request.depositor)) {\n throw new RelayRefusal(\"tx-depositor\", `the deposit is credited to ${depositor}, not to the sender ${lower(request.depositor)}`, \"recipient_mismatch\");\n }\n if (!native) {\n const token = wordAddress(word(1));\n if (token === null) throw new RelayRefusal(\"tx-calldata\", \"the token argument is not a padded address\", \"policy_refused\");\n if (token !== input.currency) throw new RelayRefusal(\"tx-token\", `the deposit moves ${token}, the order's input is ${input.currency}`, \"policy_refused\");\n const amount = BigInt(`0x${word(2)}`);\n if (amount !== input.amount) throw new RelayRefusal(\"tx-amount\", `the deposit moves ${amount}, the order's input is ${input.amount}`, \"policy_refused\");\n }\n const txId = `0x${word(native ? 1 : 3)}`;\n if (txId !== id) throw new RelayRefusal(\"tx-id\", `the deposit names order ${txId}, the order received hashes to ${id}`, \"recipient_unverifiable\");\n const value = typeof tx.value === \"string\" && /^(?:0|[1-9]\\d{0,77})$/.test(tx.value) ? BigInt(tx.value) : null;\n const wantValue = native ? input.amount : 0n;\n if (value === null || value !== wantValue) {\n throw new RelayRefusal(\"tx-value\", `the deposit sends ${String(tx.value)} wei, it must send ${wantValue}`, \"policy_refused\");\n }\n}\n\n/**\n * Check an order against the user's request and — when given — a deposit transaction against the order. Returns the\n * parsed order, its id and the deposit this module builds for it; throws {@link RelayRefusal} otherwise.\n *\n * `deposit` is what the API proposed (at quote time) or what is about to be signed (before signing). Without it the\n * order alone is checked and the caller uses the returned `deposit`.\n */\nexport function verifyRelayOrder(request: RelayRequest, protocol: RelayProtocolData | null | undefined, deposit?: RelayDepositTx): VerifiedRelayOrder {\n const {source, dest, nowS} = checkRequest(request);\n // A deposit that does not call the pinned depository is refused for that, whatever order comes with it.\n if (deposit !== undefined) checkDepositTarget(deposit, source);\n\n // The envelope.\n if (protocol === null || typeof protocol !== \"object\") {\n throw new RelayRefusal(\"protocol-data-missing\", \"the quote carries no order (protocol.v2) — nothing to check the deposit against\", \"upstream_unavailable\");\n }\n if (protocol.orderData === undefined || protocol.orderData === null) {\n throw new RelayRefusal(\"protocol-data-missing\", \"the quote carries no order data — nothing to check the deposit against\", \"upstream_unavailable\");\n }\n if (protocol.hubType !== \"onchain\") {\n throw new RelayRefusal(\"hub-type\", `the order settles through a \"${String(protocol.hubType)}\" hub, only \"onchain\" is read`, \"unsupported_pair\");\n }\n const order = parseRelayOrder(protocol.orderData);\n\n // The shape.\n if (order.version !== RELAY_ORDER_VERSION) throw new RelayRefusal(\"order-version\", `order version \"${order.version}\" is not ${RELAY_ORDER_VERSION}`, \"upstream_unavailable\");\n if (order.inputs.length !== 1) throw new RelayRefusal(\"order-inputs\", `the order has ${order.inputs.length} inputs, exactly one is signed for`, \"policy_refused\");\n if (order.output.payments.length !== 1) throw new RelayRefusal(\"order-payments\", `the order pays ${order.output.payments.length} outputs, exactly one is accepted`, \"policy_refused\");\n if (order.output.calls.length !== 0) throw new RelayRefusal(\"order-calls\", \"the order runs calls on the destination — only plain payments are accepted\", \"policy_refused\");\n if (order.fees.length !== 0) throw new RelayRefusal(\"order-fees\", \"the order carries order-level fees, which this module does not show and does not accept\", \"policy_refused\");\n const input = order.inputs[0]!;\n const pay = order.output.payments[0]!;\n if (input.payment.weight === 0n) throw new RelayRefusal(\"input-weight\", \"the order's input has zero weight\", \"policy_refused\");\n\n // The solver.\n if (!RELAY_SOLVERS.some((s) => s.address === order.solver && s.chainId === order.solverChainId)) {\n throw new RelayRefusal(\"solver-not-pinned\", `solver ${order.solver} on \"${order.solverChainId}\" is not a pinned Relay solver`, \"recipient_unverifiable\");\n }\n\n // The output: who is paid, where, in what, and at least how much.\n if (order.output.chainId !== dest.slug) throw new RelayRefusal(\"output-chain\", `the order pays on \"${order.output.chainId}\", the request is for ${dest.name} (\"${dest.slug}\")`, \"recipient_mismatch\");\n if (!isAddr(pay.recipient, request.recipient)) throw new RelayRefusal(\"output-recipient\", `the order pays ${pay.recipient}, not the recipient ${lower(request.recipient)}`, \"recipient_mismatch\");\n if (!isAddr(pay.currency, request.destToken)) throw new RelayRefusal(\"output-currency\", `the order pays in ${pay.currency}, the request is for ${lower(request.destToken)}`, \"price_check_failed\");\n if (pay.minimumAmount <= 0n) throw new RelayRefusal(\"output-minimum\", \"the order's minimum output is zero\", \"price_check_failed\");\n if (request.minAmountOut !== undefined && pay.minimumAmount < request.minAmountOut) {\n throw new RelayRefusal(\"output-minimum\", `the order's minimum output ${pay.minimumAmount} is under the caller's floor ${request.minAmountOut}`, \"price_check_failed\");\n }\n if (pay.expectedAmount < pay.minimumAmount) throw new RelayRefusal(\"output-expected\", `the order expects ${pay.expectedAmount}, less than its own minimum ${pay.minimumAmount}`, \"price_check_failed\");\n const slippage = BigInt(request.slippageBps ?? RELAY_DEFAULT_SLIPPAGE_BPS);\n const floor = (pay.expectedAmount * (10_000n - slippage)) / 10_000n;\n if (pay.minimumAmount < floor) {\n throw new RelayRefusal(\"output-minimum\", `the order's minimum output ${pay.minimumAmount} is more than ${slippage} bps under its expected ${pay.expectedAmount}`, \"price_check_failed\");\n }\n checkDeadline(\"output-deadline\", \"the output deadline\", order.output.deadline, nowS);\n\n // The input: exactly what is sent.\n if (input.payment.chainId !== source.slug) throw new RelayRefusal(\"input-chain\", `the order is funded on \"${input.payment.chainId}\", the request sends on ${source.name} (\"${source.slug}\")`, \"policy_refused\");\n if (!isAddr(input.payment.currency, request.sourceToken)) throw new RelayRefusal(\"input-currency\", `the order is funded in ${input.payment.currency}, the request sends ${lower(request.sourceToken)}`, \"policy_refused\");\n if (input.payment.amount !== request.amount) throw new RelayRefusal(\"input-amount\", `the order is funded with ${input.payment.amount}, the request sends ${request.amount}`, \"policy_refused\");\n\n // Refunds: on the source chain back to the sender in the token sent; on the destination to the recipient or the\n // sender; nowhere else. An unfilled order must have a way back on the source chain.\n let originRefund = false;\n for (const refund of input.refunds) {\n if (refund.chainId === source.slug) {\n if (!isAddr(refund.recipient, request.depositor)) throw new RelayRefusal(\"refund-recipient\", `a source-chain refund goes to ${refund.recipient}, not the sender ${lower(request.depositor)}`, \"recipient_mismatch\");\n if (refund.currency !== input.payment.currency) throw new RelayRefusal(\"refund-currency\", `a source-chain refund is in ${refund.currency}, not the token sent`, \"policy_refused\");\n originRefund = true;\n } else if (refund.chainId === dest.slug) {\n if (!isAddr(refund.recipient, request.recipient) && !isAddr(refund.recipient, request.depositor)) {\n throw new RelayRefusal(\"refund-recipient\", `a destination-chain refund goes to ${refund.recipient}, neither the recipient nor the sender`, \"recipient_mismatch\");\n }\n if (refund.currency.length !== 42) throw new RelayRefusal(\"refund-currency\", \"a destination-chain refund names no token\", \"policy_refused\");\n } else {\n throw new RelayRefusal(\"refund-chain\", `a refund is payable on \"${refund.chainId}\", neither the source nor the destination chain`, \"recipient_mismatch\");\n }\n checkDeadline(\"refund-deadline\", \"a refund deadline\", refund.deadline, nowS);\n }\n if (!originRefund) throw new RelayRefusal(\"refund-missing\", \"the order has no refund to the sender on the source chain\", \"policy_refused\");\n\n // The id and who signed it.\n const id = relayOrderId(order);\n if (typeof protocol.orderId !== \"string\" || lower(protocol.orderId) !== id) {\n throw new RelayRefusal(\"order-id-mismatch\", `the quote names order ${String(protocol.orderId)}, the order data hashes to ${id}`, \"recipient_unverifiable\");\n }\n const signer = relayOrderSigner(id, protocol.orderSignature);\n if (signer === null || signer !== order.solver) {\n throw new RelayRefusal(\"signature-invalid\", signer === null ? \"the order signature is not a valid signature\" : `the order is signed by ${signer}, not by its solver ${order.solver}`, \"recipient_unverifiable\");\n }\n\n // What the API says the payment is: it must describe the same deposit.\n const pd = protocol.paymentDetails as {chainId?: unknown; depository?: unknown; currency?: unknown; amount?: unknown} | null | undefined;\n if (pd === null || typeof pd !== \"object\") throw new RelayRefusal(\"payment-details\", \"the quote has no payment details\", \"upstream_unavailable\");\n if (pd.chainId !== source.slug || typeof pd.depository !== \"string\" || lower(pd.depository) !== source.depository\n || typeof pd.currency !== \"string\" || lower(pd.currency) !== input.payment.currency\n || typeof pd.amount !== \"string\" || pd.amount !== input.payment.amount.toString(10)) {\n throw new RelayRefusal(\"payment-details\", \"the quote's payment details do not describe the order's input on the pinned depository\", \"vault_mismatch\");\n }\n\n const built = buildRelayDeposit(source, request.depositor, input.payment.currency, input.payment.amount, id);\n if (deposit !== undefined) {\n checkDepositTx(deposit, source, request, order, id);\n // Whatever the field checks above let through, the bytes signed are the bytes built here.\n if (lower(deposit.data as string) !== built.data || lower(deposit.to as string) !== built.to || deposit.value !== built.value) {\n throw new RelayRefusal(\"tx-calldata\", \"the deposit is not the call this module builds for the order\", \"policy_refused\");\n }\n }\n return {order, id, deposit: built, expectedAmount: pay.expectedAmount, minimumAmount: pay.minimumAmount, source, dest};\n}\n\n/** A refusal's text for a caller that wants a string (`onRefusal`, remote pins); rethrows anything else. */\nexport function relayRefusalReason(err: unknown): string {\n if (err instanceof RelayRefusal) return err.message;\n throw err;\n}\n\n/**\n * The request a `QuoteParams` describes, for the verifier. `dry` fills a missing address with `placeholder` (pricing\n * only). The sender is `refundAddress` — the engine sets it to the account that signs.\n */\nexport function relayRequestOf(params: QuoteParams, opts: {placeholder?: string; nowMs?: number} = {}): RelayRequest {\n const invalid = (what: string, reason?: Swap2RefusalReason): never => { throw new RelayRefusal(\"request-invalid\", what, reason); };\n if (params.flex) invalid(\"the amount is sealed into the order (no flexible deposits)\", \"unsupported_pair\");\n if (!relayChain(params.sourceChain)) throw new RelayRefusal(\"chain-unsupported\", `source chain ${params.sourceChain} is not a pinned Relay chain`, \"unsupported_pair\");\n if (!relayChain(params.destChain)) throw new RelayRefusal(\"chain-unsupported\", `destination chain ${params.destChain} is not a pinned Relay chain`, \"unsupported_pair\");\n if (params.sourceChain === params.destChain) throw new RelayRefusal(\"chain-unsupported\", \"same-chain swaps are not served through the depository\", \"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 ?? RELAY_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 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 && !/^(?:0|[1-9]\\d{0,77})$/.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 depositor = params.refundAddress || opts.placeholder || \"\";\n if (!depositor) invalid(\"a live quote needs the sender's address (refundAddress)\");\n if (!ADDRESS.test(depositor)) invalid(\"the sender's address 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 ...(params.slippageBps !== undefined ? {slippageBps: params.slippageBps} : {}),\n ...(opts.nowMs !== undefined ? {nowMs: opts.nowMs} : {}),\n };\n}\n\n/** The order a quote of this provider carries (`providerData`), back in the form the verifier reads. */\nexport function relayProtocolOf(quote: Quote): RelayProtocolData | null {\n const pd = quote.providerData;\n if (!pd || typeof pd.orderData !== \"string\") return null;\n let orderData: unknown;\n let paymentDetails: unknown;\n try {\n orderData = JSON.parse(pd.orderData);\n paymentDetails = typeof pd.paymentDetails === \"string\" ? JSON.parse(pd.paymentDetails) : undefined;\n } catch {\n return null;\n }\n return {orderId: pd.orderId, hubType: pd.hubType, orderData, orderSignature: pd.orderSignature, paymentDetails};\n}\n\n/**\n * A quote of this provider against the request it answers: the order it carries is verified, its transaction is\n * that order's deposit, its approval names the pinned depository, and the amounts it shows are the order's. Throws\n * {@link RelayRefusal}. Used on the client of a remote provider and again before signing.\n */\nexport function checkRelayQuote(request: RelayRequest, quote: Quote, tx?: RelayDepositTx & {approvalAddress?: unknown}): VerifiedRelayOrder {\n if (quote === null || typeof quote !== \"object\" || quote.provider !== \"relay\") throw new RelayRefusal(\"quote-shape\", \"not a Relay quote\", \"policy_refused\");\n const t = tx ?? quote.txRequest;\n if (!t) throw new RelayRefusal(\"quote-shape\", \"the quote has no transaction\", \"policy_refused\");\n if (quote.depositAddress) throw new RelayRefusal(\"quote-shape\", \"a Relay quote pays the depository through its calldata, never a deposit address\", \"vault_mismatch\");\n if ((quote.txRequest as {serializedTx?: unknown; nativeFee?: unknown} | undefined)?.serializedTx !== undefined || (quote.txRequest as {nativeFee?: unknown} | undefined)?.nativeFee !== undefined) {\n throw new RelayRefusal(\"quote-shape\", \"a Relay deposit carries no extra native fee and no serialized transaction\", \"policy_refused\");\n }\n const v = verifyRelayOrder(request, relayProtocolOf(quote), t);\n const approval = (t as {approvalAddress?: unknown}).approvalAddress;\n if (v.deposit.approvalAddress === undefined ? approval !== undefined && approval !== \"\" : typeof approval !== \"string\" || lower(approval) !== v.deposit.approvalAddress) {\n throw new RelayRefusal(\"quote-approval\", `the quote approves ${String(approval)}, the order needs ${v.deposit.approvalAddress ?? \"no approval\"}`, \"vault_mismatch\");\n }\n if (quote.sourceAmount !== request.amount.toString(10) || quote.minDestAmount !== v.minimumAmount.toString(10) || quote.destAmount !== v.expectedAmount.toString(10)) {\n throw new RelayRefusal(\"quote-amounts\", \"the amounts the quote shows are not the order's\", \"price_check_failed\");\n }\n // Gas is the one number of the call that no order binds: held to the band this module itself would set, so a\n // backend can neither starve the deposit (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 const floor = v.deposit.approvalAddress === undefined ? RELAY_GAS_FLOOR_NATIVE : RELAY_GAS_FLOOR_ERC20;\n if (typeof gas !== \"string\" || !/^[1-9]\\d{0,10}$/.test(gas) || BigInt(gas) < floor || BigInt(gas) > RELAY_GAS_CAP) {\n throw new RelayRefusal(\"quote-gas\", `the gas limit ${String(gas).slice(0, 40)} is outside ${floor}–${RELAY_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 + RELAY_MAX_QUOTE_LIFE_MS) {\n throw new RelayRefusal(\"quote-expiry\", \"the quote claims to live longer than a Relay quote may\", \"policy_refused\");\n }\n if (typeof quote.intentId !== \"string\" || quote.intentId !== `relay:${String(quote.providerData?.requestId)}` || !/^relay:0x[0-9a-f]{64}$/.test(quote.intentId)) {\n throw new RelayRefusal(\"quote-shape\", \"the quote's id is not its Relay request id\", \"policy_refused\");\n }\n return v;\n}\n\n// The reason behind each text the pins return (`relayPins.reasonOf`), bounded.\nconst pinNotes = refusalNotes();\n/** The refusal's text, its reason noted for `relayPins.reasonOf`; rethrows anything that is not a refusal. */\nfunction notedReason(err: unknown): string {\n const text = relayRefusalReason(err);\n const info = refusalOf(err);\n return info ? pinNotes.note(text, info) : text;\n}\n\n/** `RemotePins.verifyQuote`: the reason a remote Relay quote fails against the user's own request, or null. */\nexport function relayVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n try {\n checkRelayQuote(relayRequestOf(params), quote);\n return null;\n } catch (err) {\n return notedReason(err);\n }\n}\n\n/** `RemotePins.verifyBuild`: a remote build must be the quote's own (verified) transaction, and is verified again. */\nexport function relayVerifyBuild(quote: Quote, tx: UnsignedTx, params?: QuoteParams): string | null {\n try {\n if (!params) throw new RelayRefusal(\"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 RelayRefusal(\"tx-chain\", `the build is for ${tx.chain}, not ${params.sourceChain}`, \"vault_mismatch\");\n if (tx.serializedTx !== undefined || tx.memo !== undefined || tx.typedData !== undefined || tx.bodyBoc !== undefined) {\n throw new RelayRefusal(\"quote-shape\", \"a Relay deposit is one EVM call\", \"policy_refused\");\n }\n const v = checkRelayQuote(relayRequestOf(params), quote, tx);\n // The remote path has no client-side step after this one: an order is built for once.\n relayClearOrder(v.id, \"build\");\n return null;\n } catch (err) {\n return notedReason(err);\n }\n}\n\n/**\n * The app's pins for a remote Relay provider (`remoteProvider({name: \"relay\", ...relayPins})`): the only contract a\n * build may call or approve is the chain's depository, and every quote and build is verified on the client against\n * the user's own request. `reasonOf` classifies a text `verifyQuote` / `verifyBuild` returned.\n */\nexport const relayPins: RemotePins = Object.freeze({\n callTargets: (chain: string): readonly string[] => { const c = relayChain(chain); return c ? [c.depository] : []; },\n spenders: (chain: string): readonly string[] => { const c = relayChain(chain); return c ? [c.depository] : []; },\n verifyQuote: relayVerifyQuote,\n verifyBuild: relayVerifyBuild,\n reasonOf: pinNotes.reasonOf,\n});\n","/**\n * One deposit per order: the ids already cleared, for the whole JS realm — every provider instance and every remote\n * stub share it, so a second instance cannot be handed the order the first one already signed for.\n */\nimport {RELAY_CLOCK_SKEW_S, RELAY_MAX_ORDER_AGE_S} from \"./config.js\";\nimport {RelayRefusal} from \"./order.js\";\n\n// Order ids already cleared, per stage, for the whole JS realm (every provider instance and every remote stub): the\n// same order is never built or signed for twice while it could still pass the age check. An entry outlives the\n// order's own acceptance window (age + skew), after which the order is stale anyway.\nconst CLEARED_TTL_MS = (RELAY_MAX_ORDER_AGE_S + 2 * RELAY_CLOCK_SKEW_S) * 1000;\nconst CLEARED_MAX = 4096;\nconst clearedOrders = new Map<string, number>();\n\n/**\n * Record that `id` is being used at `stage` (\"build\" on the client of a remote provider, \"sign\" right before a\n * signature); throws `order-reused` when it already was. Fail-closed when the record is full of live entries.\n */\nexport function relayClearOrder(id: string, stage: \"build\" | \"sign\", nowMs: number = Date.now()): void {\n const key = `${stage}:${id.toLowerCase()}`;\n const until = clearedOrders.get(key);\n if (until !== undefined && until > nowMs) throw new RelayRefusal(\"order-reused\", `order ${id} was already cleared for a deposit — quote again`, \"policy_refused\");\n if (clearedOrders.size >= CLEARED_MAX) {\n for (const [k, t] of clearedOrders) if (t <= nowMs) clearedOrders.delete(k);\n if (clearedOrders.size >= CLEARED_MAX) throw new RelayRefusal(\"order-reused\", \"too many deposits cleared in the last minutes — try again later\", \"policy_refused\");\n }\n clearedOrders.set(key, nowMs + CLEARED_TTL_MS);\n}\n\n/** Tests only; the package index leaves it out. */\nexport function forgetClearedOrders(): void {\n clearedOrders.clear();\n}\n","import {anySignal, redactUrls, timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentState, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {httpRefusal, refusal, refusalOf, type Swap2RefusalInfo, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {describeRelayActivity} from \"./activity.js\";\nimport {RELAY_API, relay as relayCfg, relayChain} from \"./config.js\";\nimport {RelayRefusal} from \"./order.js\";\nimport {RELAY_DEFAULT_SLIPPAGE_BPS, RELAY_GAS_CAP as GAS_CAP, RELAY_GAS_FLOOR_ERC20 as GAS_FLOOR_ERC20, RELAY_GAS_FLOOR_NATIVE as GAS_FLOOR_NATIVE, checkRelayQuote, relayClearOrder, relayRequestOf, verifyRelayOrder, type RelayRequest} from \"./verify.js\";\n\n/**\n * Relay (relay.link) — a solver network. ONE source transaction: a deposit into the chain's RelayDepository that names\n * an order by its hash; Relay's solver then pays the recipient on the destination chain, or the deposit is refunded.\n *\n * - Quote = `POST /quote/v2` with `includeProtocolData: true`, which returns the order itself next to the deposit.\n * The answer is only an input to `verify.ts`: the order is parsed, hashed and attributed on the device, compared\n * with the request, and the deposit this module builds from its own pins must be byte-for-byte the one offered.\n * What a quote carries afterwards is that own-built call; the amounts it shows are the order's (`expectedAmount`\n * as the estimate, `minimumAmount` as the enforced minimum).\n * - The API's `approve` step is never used: an ERC-20 input sets `approvalAddress` to the pinned depository and the\n * engine approves exactly the input amount.\n * - `baseUrl` may be the app's own proxy that adds the API key. It cannot get a deposit signed for another\n * recipient, chain, token, minimum or refund address than the request's. It CAN make the quote worse: the solver\n * signs whatever request reaches Relay, so a proxy that adds an app fee or a gas top-up gets a genuine order with\n * a lower expected amount. The response's own account of such extras is refused (`app-fee`, `gas-topup`), but a\n * proxy can strip that too — the amounts shown are always the order's, and what bounds the price is the caller's\n * `minAmountOut` or the other quotes of the router, not this module.\n * - Routes Relay serves by first swapping on the source chain call a router, not the depository, and are refused\n * by name (`tx-target`); so are non-EVM chains and any chain without a pin.\n * - Status: `GET /intents/status/v3?requestId=` — display only, nothing is signed on its word.\n */\n\nconst EVM_PLACEHOLDER = \"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045\";\nconst DEFAULT_QUOTE_TTL_MS = 60_000;\nconst QUOTE_TIMEOUT_MS = 20_000;\nconst STATUS_TIMEOUT_MS = 12_000;\nconst INTENT_PREFIX = \"relay:\";\nconst REQUEST_ID = /^0x[0-9a-f]{64}$/;\nconst MAX_BODY = 512 * 1024;\nconst MAX_REMEMBERED = 256;\n\nexport interface RelayProviderConfig {\n enabled?: boolean;\n /**\n * Relay's API (default https://api.relay.link) or the app's own proxy in front of it. Untrusted either way:\n * every answer is verified on the device.\n */\n baseUrl?: string;\n /** Sent as `x-api-key` when set. Prefer a proxy that adds it — a key shipped in an app is public. */\n apiKey?: string;\n /** Local lifetime of a quote (default 60 s, at most 5 min). The order itself is refused once older than 10 min. */\n quoteTtlMs?: number;\n /** Injectable for tests and for runtimes that bring their own. */\n fetchImpl?: typeof fetch;\n /**\n * Where cleared order ids are also kept, so that \"one deposit per order\" survives an app restart (the built-in\n * record lives in memory). `has` is asked and `add` awaited right before a signature; either throwing refuses.\n */\n clearedStore?: RelayClearedStore;\n}\n\n/** A durable record of order ids a deposit was cleared for. `expiresAtMs` is when an entry may be dropped. */\nexport interface RelayClearedStore {\n has(orderId: string): boolean | Promise<boolean>;\n add(orderId: string, expiresAtMs: number): void | Promise<void>;\n}\n\ninterface RelayStep {id?: unknown; requestId?: unknown; items?: unknown}\ninterface RelayQuoteBody {\n steps?: unknown;\n fees?: {relayer?: {currency?: {address?: unknown}; amount?: unknown; amountUsd?: unknown}; app?: {amount?: unknown}};\n details?: {timeEstimate?: unknown; currencyGasTopup?: {amount?: unknown}};\n protocol?: {v2?: unknown};\n message?: unknown;\n errorCode?: unknown;\n}\n\n/** Relay's request states → swap2 states. `failure` is read together with `refundFailReason` (see `trackIntent`). */\nexport const RELAY_STATUS_MAP: Readonly<Record<string, IntentState>> = Object.freeze({\n waiting: \"pending\", depositing: \"pending\", pending: \"pending\", submitted: \"pending\", delayed: \"pending\", unknown: \"pending\",\n success: \"completed\", refund: \"refunded\", refunded: \"refunded\", failure: \"refund-pending\",\n});\n\n/**\n * Relay's error codes that say why there is no quote (`errorCode` of a non-2xx answer, as docs.relay.link lists them\n * under \"handling errors\"). They win over the HTTP status except a 429, which keeps its Retry-After; a code not\n * listed here is read from the status, and failing that a JSON refusal is `no_route`.\n */\nconst RELAY_ERROR_REASONS: Readonly<Record<string, Swap2RefusalReason>> = Object.freeze(Object.assign(Object.create(null) as Record<string, Swap2RefusalReason>, {\n AMOUNT_TOO_LOW: \"amount_too_small\",\n AMOUNT_TOO_HIGH: \"amount_too_large\",\n INSUFFICIENT_LIQUIDITY: \"insufficient_liquidity\",\n NO_QUOTES: \"no_route\",\n NO_SWAP_ROUTES_FOUND: \"no_route\",\n NO_INTERNAL_SWAP_ROUTES_FOUND: \"no_route\",\n // Relay's own failures: a third-party pricing failure, and the transient codes it says to retry with backoff.\n SWAP_QUOTE_FAILED: \"upstream_unavailable\",\n REQUEST_TIMED_OUT: \"upstream_unavailable\",\n RPC_HTTP_ERROR: \"upstream_unavailable\",\n PRICE_FETCH_FAILED: \"upstream_unavailable\",\n SERVICE_UNAVAILABLE: \"upstream_unavailable\",\n // The recipient resolves to a token contract, which cannot receive.\n INVALID_RECIPIENT: \"recipient_mismatch\",\n UNSUPPORTED_CHAIN: \"unsupported_pair\",\n UNSUPPORTED_CURRENCY: \"unsupported_pair\",\n UNSUPPORTED_ROUTE: \"unsupported_pair\",\n UNSUPPORTED_EXECUTION_TYPE: \"unsupported_pair\",\n INVALID_INPUT_CURRENCY: \"unsupported_pair\",\n INVALID_OUTPUT_CURRENCY: \"unsupported_pair\",\n CHAIN_DISABLED: \"chain_halted\",\n ROUTE_TEMPORARILY_RESTRICTED: \"chain_halted\",\n SWAP_IMPACT_TOO_HIGH: \"price_check_failed\",\n UNAUTHORIZED: \"key_rejected\",\n UNAUTHORIZED_QUOTE: \"key_rejected\",\n FORBIDDEN: \"key_rejected\",\n}));\n\n/**\n * Why a non-2xx quote answer refused: a 429 first (its wait), then Relay's own code, then the status, then the body's\n * shape. `aborted`: the caller's own signal fired, so a body that could not be read is not Relay's failure.\n */\nfunction quoteHttpRefusal(res: Response, parsed: unknown, aborted: boolean): Swap2RefusalInfo | undefined {\n const code = (parsed as RelayQuoteBody | null)?.errorCode;\n const byCode = typeof code === \"string\" && Object.prototype.hasOwnProperty.call(RELAY_ERROR_REASONS, code) ? RELAY_ERROR_REASONS[code] : undefined;\n const byStatus = httpRefusal(res.status, res.headers?.get?.(\"retry-after\"));\n if (byStatus?.reason === \"rate_limited\") return byStatus;\n if (byCode) {\n if (byStatus?.reason === byCode) return byStatus;\n // The reasons that carry the status keep it whatever the status was.\n return byCode === \"upstream_unavailable\" || byCode === \"key_rejected\" ? {reason: byCode, httpStatus: res.status} : {reason: byCode};\n }\n if (byStatus) return byStatus;\n // A JSON refusal Relay did not name is a quote it does not have; anything else is an answer of another shape.\n if (parsed !== null && typeof parsed === \"object\") return {reason: \"no_route\"};\n return aborted ? undefined : {reason: \"upstream_unavailable\", httpStatus: res.status};\n}\n\nfunction clip(text: string, max = 240): string {\n const t = redactUrls(text).replace(/\\s+/g, \" \").trim();\n return t.length > max ? `${t.slice(0, max)}…` : t;\n}\n\n/** The single deposit step of a quote response; an `approve` step is ignored, anything else refuses the quote. */\nfunction depositStep(body: RelayQuoteBody): {requestId: string; tx: {to?: unknown; data?: unknown; value?: unknown; chainId?: unknown; gas?: unknown}} {\n const steps = body.steps;\n if (!Array.isArray(steps) || steps.length === 0 || steps.length > 8) throw new RelayRefusal(\"quote-steps\", \"the quote has no steps\", \"upstream_unavailable\");\n let found: RelayStep | null = null;\n for (const s of steps as RelayStep[]) {\n if (s === null || typeof s !== \"object\") throw new RelayRefusal(\"quote-steps\", \"the quote has a malformed step\", \"upstream_unavailable\");\n if (s.id === \"approve\") continue; // never used: the approval is built here, for the exact amount, to the pinned depository\n if (s.id !== \"deposit\") throw new RelayRefusal(\"quote-steps\", `the quote needs a \"${clip(String(s.id), 40)}\" step, only a single deposit is signed`, \"unsupported_pair\");\n if (found) throw new RelayRefusal(\"quote-steps\", \"the quote has more than one deposit step\", \"unsupported_pair\");\n found = s;\n }\n if (!found) throw new RelayRefusal(\"quote-steps\", \"the quote has no deposit step\", \"upstream_unavailable\");\n const items = found.items;\n if (!Array.isArray(items) || items.length !== 1) throw new RelayRefusal(\"quote-steps\", \"the deposit step is not a single transaction\", \"unsupported_pair\");\n const data = (items[0] as {data?: unknown} | null)?.data;\n if (data === null || typeof data !== \"object\") throw new RelayRefusal(\"quote-steps\", \"the deposit step has no transaction\", \"upstream_unavailable\");\n const requestId = typeof found.requestId === \"string\" ? found.requestId.toLowerCase() : \"\";\n if (!REQUEST_ID.test(requestId)) throw new RelayRefusal(\"quote-steps\", \"the quote has no request id to track the deposit by\", \"upstream_unavailable\");\n return {requestId, tx: data as never};\n}\n\nexport function relayProvider(config: RelayProviderConfig = {}): CrossChainProvider {\n config = Object.freeze({...config});\n const base = (config.baseUrl ?? RELAY_API).replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(base)) throw new Error(\"relay: baseUrl must use http or https\");\n const quoteTtlMs = config.quoteTtlMs ?? DEFAULT_QUOTE_TTL_MS;\n if (!Number.isInteger(quoteTtlMs) || quoteTtlMs <= 0 || quoteTtlMs > 300_000) throw new Error(\"relay: quoteTtlMs must be an integer between 1 and 300000\");\n if (config.apiKey !== undefined && (typeof config.apiKey !== \"string\" || !/^[\\x21-\\x7e]{1,256}$/.test(config.apiKey))) throw new Error(\"relay: apiKey must be a printable string\");\n const doFetch: typeof fetch = (input, init) => (config.fetchImpl ?? fetch)(input, init);\n const headers = (json: boolean): Record<string, string> => ({\n accept: \"application/json\",\n ...(json ? {\"content-type\": \"application/json\"} : {}),\n ...(config.apiKey ? {\"x-api-key\": config.apiKey} : {}),\n });\n\n // The request each live quote answered, kept on this side: a deposit is checked against what was asked here, not\n // against what the quote object says was asked.\n const issued = new Map<string, RelayRequest>();\n const remember = <K, V>(m: Map<K, V>, k: K, v: V): void => {\n m.delete(k);\n m.set(k, v);\n if (m.size > MAX_REMEMBERED) m.delete(m.keys().next().value as K);\n };\n\n /** The request a quote is checked against before a build or a signature. */\n function requestOf(quote: Quote): RelayRequest {\n const pd = quote.providerData ?? {};\n const sealed: RelayRequest = {\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 ...(/^\\d{1,5}$/.test(pd.slippageBps ?? \"\") ? {slippageBps: Number(pd.slippageBps)} : {}),\n };\n // The pricing placeholder is never a party to a deposit, whatever flags the quote object carries.\n if (sealed.depositor.toLowerCase() === EVM_PLACEHOLDER.toLowerCase() || sealed.recipient.toLowerCase() === EVM_PLACEHOLDER.toLowerCase()) {\n throw new RelayRefusal(\"request-invalid\", \"a quote priced without the real addresses is never built or signed — quote again with them\", \"policy_refused\");\n }\n const mine = issued.get(quote.intentId);\n if (!mine) return sealed;\n const same = mine.sourceChain === sealed.sourceChain && mine.destChain === sealed.destChain && mine.amount === sealed.amount\n && mine.sourceToken.toLowerCase() === sealed.sourceToken.toLowerCase() && mine.destToken.toLowerCase() === sealed.destToken.toLowerCase()\n && mine.depositor.toLowerCase() === sealed.depositor.toLowerCase() && mine.recipient.toLowerCase() === sealed.recipient.toLowerCase();\n if (!same) throw new RelayRefusal(\"request-invalid\", \"the quote no longer says what was asked when it was issued — quote again\", \"policy_refused\");\n return mine;\n }\n\n async function readJson(res: Response): Promise<unknown> {\n const text = await res.text();\n if (text.length > MAX_BODY) throw new Error(\"relay: response too large\");\n return JSON.parse(text) as unknown;\n }\n\n return {\n name: \"relay\",\n describeActivity: describeRelayActivity,\n enabled: () => config.enabled ?? true,\n supportsChain: (chain: string) => relayCfg.supportsChain(chain),\n supportsChainPair: (from: string, to: string) => relayCfg.supports(from, to),\n supportsRoute: (from: Asset, to: Asset) => relayCfg.supports(from.chain, to.chain),\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 // Only a quote priced with the placeholder is unbuildable; one asked with real addresses is a real order.\n const placeholder = dry && (!params.destAddress || !params.refundAddress);\n let request: RelayRequest;\n try {\n // The placeholder prices a dry quote; a live one without addresses is refused.\n request = relayRequestOf(params, dry ? {placeholder: EVM_PLACEHOLDER} : {});\n } catch (err) {\n if (err instanceof RelayRefusal) return refuse(err.message, refusalOf(err));\n throw err;\n }\n const src = relayChain(request.sourceChain)!;\n const dst = relayChain(request.destChain)!;\n let body: RelayQuoteBody;\n try {\n const res = await doFetch(`${base}/quote/v2`, {\n method: \"POST\",\n headers: headers(true),\n body: JSON.stringify({\n user: request.depositor,\n recipient: request.recipient,\n refundTo: request.depositor,\n originChainId: src.chainId,\n destinationChainId: dst.chainId,\n originCurrency: request.sourceToken.toLowerCase(),\n destinationCurrency: request.destToken.toLowerCase(),\n amount: request.amount.toString(10),\n tradeType: \"EXACT_INPUT\",\n includeProtocolData: true,\n // Always named: Relay's \"auto\" would leave the distance between expected and minimum to the answering side.\n slippageTolerance: String(request.slippageBps ?? RELAY_DEFAULT_SLIPPAGE_BPS),\n }),\n signal: signal ? anySignal([signal, timeoutSignal(QUOTE_TIMEOUT_MS)]) : timeoutSignal(QUOTE_TIMEOUT_MS),\n });\n let parsed: unknown;\n try { parsed = await readJson(res); } catch { parsed = null; }\n if (!res.ok) {\n const e = (parsed ?? {}) as RelayQuoteBody;\n const why = typeof e.message === \"string\" ? clip(e.message) : `HTTP ${res.status}`;\n return refuse(`relay: no quote — ${typeof e.errorCode === \"string\" ? `${clip(e.errorCode, 60)}: ` : \"\"}${why}`, quoteHttpRefusal(res, parsed, signal?.aborted === true));\n }\n // A body cut off by the caller's own abort is not Relay's failure.\n if (parsed === null || typeof parsed !== \"object\") return refuse(\"relay: the quote response is not JSON\", signal?.aborted ? undefined : {reason: \"upstream_unavailable\"});\n body = parsed as RelayQuoteBody;\n } catch (err) {\n // The network, or this module's own timeout; the caller's own abort is not Relay's failure.\n const info = refusalOf(err) ?? (signal?.aborted ? undefined : {reason: \"upstream_unavailable\" as const});\n return refuse(`relay: quote request failed — ${clip(err instanceof Error ? err.message : String(err))}`, info);\n }\n\n try {\n const step = depositStep(body);\n const proto = (body.protocol?.v2 ?? null) as Record<string, unknown> | null;\n const v = verifyRelayOrder(request, proto, step.tx);\n // Extras this module never asks for. Each lowers the output inside a genuine order; the response's own account\n // of them is only a hint (an answering side that adds one can also hide it), so this refuses the honest case.\n const extra = (x: unknown): boolean => x !== undefined && x !== null && x !== \"0\" && x !== 0;\n if (extra(body.fees?.app?.amount)) throw new RelayRefusal(\"app-fee\", \"the quote charges an app fee this module did not ask for\", \"policy_refused\");\n if (extra(body.details?.currencyGasTopup?.amount)) throw new RelayRefusal(\"gas-topup\", \"the quote converts part of the output into a gas top-up this module did not ask for\", \"policy_refused\");\n const native = v.deposit.approvalAddress === undefined;\n const floor = native ? GAS_FLOOR_NATIVE : GAS_FLOOR_ERC20;\n const apiGas = typeof step.tx.gas === \"string\" && /^[1-9]\\d{0,9}$/.test(step.tx.gas) ? BigInt(step.tx.gas) * 2n : 0n;\n const gasLimit = apiGas > GAS_CAP ? GAS_CAP : apiGas > floor ? apiGas : floor;\n\n // Fees are Relay's own account of the quote: shown, never used in a check. They are already inside the output.\n const relayer = body.fees?.relayer;\n const usd = typeof relayer?.amountUsd === \"string\" && /^\\d{1,12}(?:\\.\\d{1,18})?$/.test(relayer.amountUsd) ? parseFloat(relayer.amountUsd) : 0;\n const feeToken = relayer?.currency?.address;\n const fees = typeof relayer?.amount === \"string\" && /^[1-9]\\d{0,77}$/.test(relayer.amount) && typeof feeToken === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(feeToken)\n ? [{type: \"protocol\" as const, amount: relayer.amount, token: feeToken.toLowerCase(), included: true, description: \"Relay fee\"}]\n : [];\n const eta = body.details?.timeEstimate;\n const etaSeconds = typeof eta === \"number\" && Number.isFinite(eta) && eta > 0 ? Math.min(Math.ceil(eta), 86_400) : 60;\n\n const intentId = `${INTENT_PREFIX}${step.requestId}`;\n if (!placeholder) remember(issued, intentId, request);\n return {\n provider: \"relay\",\n intentId,\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 gasLimit: gasLimit.toString(10),\n ...(v.deposit.approvalAddress ? {approvalAddress: v.deposit.approvalAddress} : {}),\n },\n sourceAmount: request.amount.toString(10),\n destAmount: v.expectedAmount.toString(10),\n minDestAmount: v.minimumAmount.toString(10),\n feeUsd: usd,\n fees,\n etaSeconds,\n reliability: 0.97,\n validUntilMs: Date.now() + quoteTtlMs,\n providerData: {\n requestId: step.requestId,\n orderId: v.id,\n hubType: \"onchain\",\n // The order as received, re-read by the same parser before a build and before a signature.\n orderData: JSON.stringify(proto!.orderData),\n orderSignature: String(proto!.orderSignature).toLowerCase(),\n paymentDetails: JSON.stringify(proto!.paymentDetails),\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 ...(request.minAmountOut !== undefined ? {minAmountOut: request.minAmountOut.toString(10)} : {}),\n ...(request.slippageBps !== undefined ? {slippageBps: String(request.slippageBps)} : {}),\n ...(placeholder ? {placeholder: \"1\"} : {}),\n },\n };\n } catch (err) {\n if (err instanceof RelayRefusal) return refuse(err.message, refusalOf(err));\n return refuse(`relay: unreadable quote — ${clip(err instanceof Error ? err.message : String(err))}`, refusalOf(err) ?? {reason: \"upstream_unavailable\"});\n }\n },\n\n /** The quote's own transaction — after the order it carries has been verified once more. */\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n if (!tx || !quote.intentId.startsWith(INTENT_PREFIX)) throw refusal(\"policy_refused\", \"swap2: Relay quote has no transaction request\");\n if (quote.providerData?.placeholder === \"1\") throw new RelayRefusal(\"request-invalid\", \"a quote priced without the real addresses is never built — quote again with them\", \"policy_refused\");\n const request = requestOf(quote);\n const v = checkRelayQuote(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 /**\n * Right before signing: the whole verification again, against the request this instance issued the quote for\n * and the exact transaction about to be signed — and each order is cleared for one deposit only.\n */\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n if (quote.providerData?.placeholder === \"1\") throw new RelayRefusal(\"request-invalid\", \"a quote priced without the real addresses is never signed\", \"policy_refused\");\n const request = requestOf(quote);\n if (tx.chain !== request.sourceChain) throw new RelayRefusal(\"tx-chain\", `the deposit is for ${tx.chain}, not ${request.sourceChain}`, \"vault_mismatch\");\n if (tx.serializedTx !== undefined || tx.memo !== undefined || tx.typedData !== undefined || tx.bodyBoc !== undefined) {\n throw new RelayRefusal(\"quote-shape\", \"a Relay deposit is one EVM call\", \"policy_refused\");\n }\n const v = checkRelayQuote(request, quote, tx);\n const store = config.clearedStore;\n if (store && await store.has(v.id)) throw new RelayRefusal(\"order-reused\", `order ${v.id} was already cleared for a deposit — quote again`, \"policy_refused\");\n relayClearOrder(v.id, \"sign\");\n // Kept until the order's own deadline: a deposit for it is never signed twice, restart or not.\n if (store) await store.add(v.id, v.order.output.deadline * 1000);\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n if (typeof ref.intentId !== \"string\" || !ref.intentId.startsWith(INTENT_PREFIX)) return {state: \"failed\"};\n const requestId = ref.intentId.slice(INTENT_PREFIX.length);\n if (!REQUEST_ID.test(requestId)) return {state: \"failed\"};\n // Nothing was sent yet: Relay answers \"waiting\" for a request it has seen no deposit for.\n if (!ref.sourceTxHash) return {state: \"pending\"};\n try {\n const res = await doFetch(`${base}/intents/status/v3?requestId=${requestId}`, {headers: headers(false), signal: timeoutSignal(STATUS_TIMEOUT_MS)});\n if (!res.ok) return {state: \"pending\"};\n const s = (await readJson(res)) as {status?: unknown; txHashes?: unknown; refundFailReason?: unknown} | null;\n const status = typeof s?.status === \"string\" ? s.status.toLowerCase() : \"\";\n const state = Object.prototype.hasOwnProperty.call(RELAY_STATUS_MAP, status) ? RELAY_STATUS_MAP[status]! : \"pending\";\n const seen = status !== \"waiting\" && status !== \"unknown\" && status !== \"\";\n if (state === \"completed\") {\n const hashes = Array.isArray(s?.txHashes) ? s.txHashes.filter((h): h is string => typeof h === \"string\" && /^0x[0-9a-fA-F]{64}$/.test(h)) : [];\n const dest = hashes[hashes.length - 1] ?? ref.destTxHash ?? undefined;\n return {state, depositReceived: true, ...(dest ? {destTxHash: dest} : {})};\n }\n if (status === \"failure\") {\n // A failed fill is refunded by Relay on its own. Only when the refund itself failed is there nothing\n // more coming without Relay's support.\n const why = typeof s?.refundFailReason === \"string\" ? s.refundFailReason.trim() : \"\";\n return {state: why !== \"\" && why.toUpperCase() !== \"N/A\" ? \"failed\" : \"refund-pending\", depositReceived: true};\n }\n return {state, ...(seen ? {depositReceived: true} : {})};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n","/**\n * Activity recognition for Relay on every pinned chain: `depositNative` / `depositErc20` on the chain's\n * RelayDepository is our source leg (\"Bridged ETH\").\n *\n * The destination leg is not claimed. A fill is sent by one of Relay's many relayer keys as an ordinary transfer (or\n * through a router for a destination swap) and names neither the order nor Relay on chain, so there is nothing to\n * recognise it by that a stranger could not imitate; it 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 {RELAY_DEPOSIT_ERC20, RELAY_DEPOSIT_ERC20_ALLOWANCE, RELAY_DEPOSIT_NATIVE, relayChain} from \"./config.js\";\n\nexport const RELAY_MODULE = \"@anywalletkit/protocol-swap2-relay\";\n\nexport function describeRelayActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n const chain = relayChain(tx.chain);\n if (!chain) return null;\n // All three deposit functions are read here (history is not ours alone); only two are ever built or signed.\n if (!matchesCall(tx, [chain.depository], [RELAY_DEPOSIT_NATIVE, RELAY_DEPOSIT_ERC20, RELAY_DEPOSIT_ERC20_ALLOWANCE])) return null;\n return describeSwapLike(tx, ctx, {protocol: RELAY_MODULE, subtitle: `Relay · ${chainLabel(tx.chain)}`, kind: \"bridge\", outVerb: \"Bridged\"});\n}\n","import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {relay as relayCfg} from \"./config.js\";\nimport {relayProvider, type RelayProviderConfig} from \"./provider.js\";\n\nexport interface RelaySwap2Config extends Swap2EngineConfig, RelayProviderConfig {}\n\n/** Standalone Relay swap2: EVM → EVM through Relay's depository, every order verified on the device before a deposit is signed. */\nexport class RelaySwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n constructor(account: Swap2Account | undefined, config: RelaySwap2Config) {\n super(account, config);\n this.provider = relayProvider(config);\n }\n protected override chainSupported(caip2: string): boolean {\n return relayCfg.supportsChain(caip2);\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return relayCfg.supports(fromChain, toChain);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8BA,IAAM,aAAa;AAEnB,IAAM,eAAe;AAErB,IAAM,IAAI,CAAC,SAAiB,MAAc,MAAc,aAAqB,eAC3E,OAAO,OAAO,EAAC,OAAO,UAAU,OAAO,IAAI,SAAS,MAAM,MAAM,WAAU,CAAC;AAGtE,IAAM,eAAqD,OAAO,OAAO,OAAO,OAAO,uBAAO,OAAO,IAAI,GAAiC,OAAO,YAAY;AAAA,EAClK,EAAE,GAAG,YAAY,UAAU;AAAA,EAC3B,EAAE,IAAI,YAAY,YAAY;AAAA,EAC9B,EAAE,IAAI,OAAO,WAAW;AAAA,EACxB,EAAE,KAAK,UAAU,QAAQ;AAAA,EACzB,EAAE,KAAK,YAAY,UAAU;AAAA,EAC7B,EAAE,KAAK,WAAW,SAAS;AAAA,EAC3B,EAAE,KAAK,SAAS,OAAO;AAAA,EACvB,EAAE,KAAK,SAAS,OAAO;AAAA,EACvB,EAAE,KAAK,UAAU,SAAS;AAA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,MAAM,IAAI,iBAAiB,MAAM,IAAK;AAC3G,cAAM,OAAO,WAAW,aAAa,WAAW,aAAa,WAAW;AACxE,YAAI,UAAU,aAAa;AACzB,gBAAM,SAAS,MAAM,QAAQ,GAAG,QAAQ,IAAI,EAAE,SAAS,OAAO,CAAC,MAAmB,OAAO,MAAM,YAAY,sBAAsB,KAAK,CAAC,CAAC,IAAI,CAAC;AAC7I,gBAAM,OAAO,OAAO,OAAO,SAAS,CAAC,KAAK,IAAI,cAAc;AAC5D,iBAAO,EAAC,OAAO,iBAAiB,MAAM,GAAI,OAAO,EAAC,YAAY,KAAI,IAAI,CAAC,EAAE;AAAA,QAC3E;AACA,YAAI,WAAW,WAAW;AAGxB,gBAAM,MAAM,OAAO,GAAG,qBAAqB,WAAW,EAAE,iBAAiB,KAAK,IAAI;AAClF,iBAAO,EAAC,OAAO,QAAQ,MAAM,IAAI,YAAY,MAAM,QAAQ,WAAW,kBAAkB,iBAAiB,KAAI;AAAA,QAC/G;AACA,eAAO,EAAC,OAAO,GAAI,OAAO,EAAC,iBAAiB,KAAI,IAAI,CAAC,EAAE;AAAA,MACzD,QAAQ;AACN,eAAO,EAAC,OAAO,UAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;;;AE9ZA,oBAAkC;AAQ3B,IAAM,qBAAN,cAAiC,kCAAoB;AAAA,EACvC;AAAA,EACnB,YAAY,SAAmC,QAA0B;AACvE,UAAM,SAAS,MAAM;AACrB,SAAK,WAAW,cAAc,MAAM;AAAA,EACtC;AAAA,EACmB,eAAe,OAAwB;AACxD,WAAO,MAAS,cAAc,KAAK;AAAA,EACrC;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,MAAS,SAAS,WAAW,OAAO;AAAA,EAC7C;AACF;","names":["import_viem","import_errors","U256_MAX","bytes","text","c","import_util","import_errors","text"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -4,6 +4,7 @@ export { RELAY_DEFAULT_SLIPPAGE_BPS, RELAY_GAS_CAP, RELAY_GAS_FLOOR_ERC20, RELAY
|
|
|
4
4
|
export { RELAY_STATUS_MAP, RelayClearedStore, RelayProviderConfig, relayProvider } from './provider.cjs';
|
|
5
5
|
export { RelaySwap2Config, RelaySwap2Protocol, RelaySwap2Protocol as default } from './protocol.cjs';
|
|
6
6
|
export { RELAY_MODULE, describeRelayActivity } from './activity.cjs';
|
|
7
|
+
import '@anywalletkit/protocol-swap2-core/errors';
|
|
7
8
|
import 'viem';
|
|
8
9
|
import '@anywalletkit/protocol-swap2-core/types';
|
|
9
10
|
import '@anywalletkit/protocol-swap2-core/swap2/single';
|
package/dist/index.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ export { RELAY_DEFAULT_SLIPPAGE_BPS, RELAY_GAS_CAP, RELAY_GAS_FLOOR_ERC20, RELAY
|
|
|
4
4
|
export { RELAY_STATUS_MAP, RelayClearedStore, RelayProviderConfig, relayProvider } from './provider.js';
|
|
5
5
|
export { RelaySwap2Config, RelaySwap2Protocol, RelaySwap2Protocol as default } from './protocol.js';
|
|
6
6
|
export { RELAY_MODULE, describeRelayActivity } from './activity.js';
|
|
7
|
+
import '@anywalletkit/protocol-swap2-core/errors';
|
|
7
8
|
import 'viem';
|
|
8
9
|
import '@anywalletkit/protocol-swap2-core/types';
|
|
9
10
|
import '@anywalletkit/protocol-swap2-core/swap2/single';
|