@anywalletkit/protocol-swap2-layerswap 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +97 -2
- package/dist/activity.cjs +122 -0
- package/dist/activity.cjs.map +1 -0
- package/dist/activity.d.cts +15 -0
- package/dist/activity.d.ts +15 -0
- package/dist/activity.js +10 -0
- package/dist/activity.js.map +1 -0
- package/dist/chunk-5QTIHCE4.js +99 -0
- package/dist/chunk-5QTIHCE4.js.map +1 -0
- package/dist/chunk-KCAZCR4I.js +27 -0
- package/dist/chunk-KCAZCR4I.js.map +1 -0
- package/dist/chunk-TEL62A5J.js +564 -0
- package/dist/chunk-TEL62A5J.js.map +1 -0
- package/dist/chunk-WEMNS3LY.js +21 -0
- package/dist/chunk-WEMNS3LY.js.map +1 -0
- package/dist/chunk-ZKT24QPJ.js +123 -0
- package/dist/chunk-ZKT24QPJ.js.map +1 -0
- package/dist/chunk-ZTFJO6AI.js +410 -0
- package/dist/chunk-ZTFJO6AI.js.map +1 -0
- package/dist/config.cjs +143 -0
- package/dist/config.cjs.map +1 -0
- package/dist/config.d.cts +74 -0
- package/dist/config.d.ts +74 -0
- package/dist/config.js +31 -0
- package/dist/config.js.map +1 -0
- package/dist/index.cjs +1189 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +84 -0
- package/dist/index.d.ts +84 -0
- package/dist/index.js +126 -0
- package/dist/index.js.map +1 -0
- package/dist/pins.cjs +557 -0
- package/dist/pins.cjs.map +1 -0
- package/dist/pins.d.cts +6 -0
- package/dist/pins.d.ts +6 -0
- package/dist/pins.js +11 -0
- package/dist/pins.js.map +1 -0
- package/dist/protocol.cjs +1052 -0
- package/dist/protocol.cjs.map +1 -0
- package/dist/protocol.d.cts +19 -0
- package/dist/protocol.d.ts +19 -0
- package/dist/protocol.js +11 -0
- package/dist/protocol.js.map +1 -0
- package/dist/provider.cjs +1039 -0
- package/dist/provider.cjs.map +1 -0
- package/dist/provider.d.cts +23 -0
- package/dist/provider.d.ts +23 -0
- package/dist/provider.js +16 -0
- package/dist/provider.js.map +1 -0
- package/dist/verify.cjs +554 -0
- package/dist/verify.cjs.map +1 -0
- package/dist/verify.d.cts +169 -0
- package/dist/verify.d.ts +169 -0
- package/dist/verify.js +46 -0
- package/dist/verify.js.map +1 -0
- package/module.json +64 -0
- package/package.json +100 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/protocol.ts","../src/config.ts","../src/provider.ts","../src/activity.ts","../src/api.ts","../src/verify.ts"],"sourcesContent":["import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {layerswap as layerswapCfg} from \"./config.js\";\nimport {layerswapProvider, type LayerswapProviderConfig} from \"./provider.js\";\n\nexport interface LayerswapSwap2Config extends Swap2EngineConfig, LayerswapProviderConfig {}\n\n/**\n * Standalone Layerswap swap2: from EVM (through the pinned Depository), Solana, TON, Tron and Bitcoin to any chain\n * Layerswap serves; every swap read back and its deposit checked on the device before it is signed.\n */\nexport class LayerswapSwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n constructor(account: Swap2Account | undefined, config: LayerswapSwap2Config) {\n super(account, config);\n this.provider = layerswapProvider(config);\n }\n protected override chainSupported(caip2: string): boolean {\n return layerswapCfg.supportsChain(caip2);\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return layerswapCfg.supports(fromChain, toChain);\n }\n}\n","import {namespace} from \"@anywalletkit/protocol-swap2-core/util\";\n\n/**\n * Layerswap (layerswap.io) — what this module pins and which chains it serves.\n *\n * Layerswap is a solver bridge: the source leg pays Layerswap on the source chain, and Layerswap pays the recipient\n * out of its own liquidity on the destination chain (or chains CCTP / a native rollup bridge / a DEX hop behind it).\n * The recipient, the destination and the minimum live in Layerswap's records under the swap id, not on chain: the\n * module reads the swap back and holds every field to the request before anything is signed (see `verify.ts`).\n */\n\n/** Layerswap's v2 API. One base URL for mainnet and testnet: the API key picks the environment. */\nexport const LAYERSWAP_API = \"https://api.layerswap.io/api/v2\";\n\n/**\n * LayerswapDepository (github.com/layerswap/layerswap-depository, `evm/src/LayerswapDepository.sol`; audited by\n * Hexens, March 2026). It holds nothing: `depositNative(id, receiver)` / `depositERC20(id, token, receiver, amount)`\n * forward the input in the same call to a receiver on the contract's own whitelist and emit\n * `Deposited(id, token, receiver, amount)`, `id` being the swap's sequence number. Deployed at one address; read on\n * 2026-12-01 on every EVM chain Layerswap lists (public RPCs from its `/networks`): runtime code keccak\n * `0xe2c5b091…` on each chain below, owner `0xB6103502673173ab5Df6A57Ac3017Db4e16af399`, not paused, whitelist\n * exactly {@link LAYERSWAP_RECEIVERS}. A second contract of the same code at `0x8f00775A…B038` (Ethereum, Mantle)\n * whitelists its own owner only and is not Layerswap's live one: it is never a target here.\n */\nexport const LAYERSWAP_DEPOSITORY = \"0xe226e4825cb215abafad98fdd400583eab6a594f\";\n\n/**\n * The solver addresses the Depository forwards to (`getWhitelistedAddresses()`, the same two on every chain on\n * 2026-12-01; 0x2fc6…befe is the address Layerswap has paid out of since 2022). A deposit naming any other receiver\n * is refused even if Layerswap's owner key whitelists it later: a new receiver ships in a module release, after it\n * is read on chain. Both are plain accounts (no code).\n */\nexport const LAYERSWAP_RECEIVERS: readonly string[] = Object.freeze([\n \"0x2fc617e933a52713247ce25730f6695920b3befe\",\n \"0x08b00ceee2fb66029b53d76110b19eeaabfd1e65\",\n]);\n\n/** `depositNative(bytes32,address)` and `depositERC20(bytes32,address,address,uint256)`. */\nexport const DEPOSIT_NATIVE_SELECTOR = \"0x80a6de92\";\nexport const DEPOSIT_ERC20_SELECTOR = \"0xf4371f63\";\n\n/**\n * EVM chains a deposit can leave from: the Depository at {@link LAYERSWAP_DEPOSITORY} with the pinned code, owner and\n * whitelist (read 2026-12-01). Layerswap also lists Flare, Cronos, Rootstock, Telos, Fuse, Flow, Citrea and 0G (no\n * Depository there) and Mode (its Depository did not answer the reads): those are destinations only.\n */\nexport const LAYERSWAP_DEPOSITORY_CHAINS: readonly number[] = Object.freeze([\n 1, 10, 56, 100, 130, 137, 143, 146, 169, 196, 204, 252, 324, 360, 480, 988, 999, 1329, 1868, 2020, 2741, 2818, 4217,\n 4326, 4663, 5000, 5042, 8217, 8453, 9745, 13371, 42161, 42220, 42793, 43114, 48900, 57073, 59144, 60808, 80094, 99901,\n 167000, 534352, 747474, 7777777,\n]);\n\n/** Every EVM chain Layerswap listed on 2026-12-01 (`GET /networks`, type `evm`), as a destination. */\nexport const LAYERSWAP_EVM_CHAINS: readonly number[] = Object.freeze([\n ...LAYERSWAP_DEPOSITORY_CHAINS, 14, 25, 30, 40, 122, 747, 4114, 16661, 34443,\n].sort((a, b) => a - b));\n\n/** The non-EVM chains this module serves, by our CAIP-2 id → Layerswap's network name. */\nexport const LAYERSWAP_NON_EVM: Readonly<Record<string, string>> = Object.freeze({\n \"solana:mainnet\": \"SOLANA_MAINNET\",\n \"ton:-239\": \"TON_MAINNET\",\n \"tron:728126428\": \"TRON_MAINNET\",\n \"bitcoin:mainnet\": \"BITCOIN_MAINNET\",\n});\n\n/**\n * How the source leg is funded, per source family:\n * - EVM: the Depository (`use_depository`), pinned above.\n * - Solana: the wallet flow — Layerswap's serialized transfer with the swap's sequence number as a top-level memo.\n * The deposit-address flow costs a sweep (≈ $0.36 on 100 USDC, 2026-12-01).\n * - TON: the wallet flow — a transfer (or jetton transfer) with the swap's comment. TON has no deposit address.\n * - Tron: the wallet flow — a TRC-20 transfer with the memo in `raw_data.data`. The deposit-address flow costs\n * ≈ $4 a swap (2026-12-01).\n * - Bitcoin: a deposit address minted for the swap (`use_deposit_address`): the wallet flow needs an OP_RETURN\n * output the Bitcoin account does not write; the address costs ≈ 0.03 % (2026-12-01).\n */\nexport type LayerswapFunding = \"depository\" | \"wallet\" | \"deposit_address\";\n\nexport function fundingFor(sourceChain: string): LayerswapFunding | null {\n const ns = namespace(sourceChain);\n if (ns === \"eip155\") return LAYERSWAP_DEPOSITORY_CHAINS.includes(evmChainId(sourceChain) ?? -1) ? \"depository\" : null;\n if (ns === \"solana\" || ns === \"ton\" || ns === \"tron\") return sourceChain in LAYERSWAP_NON_EVM ? \"wallet\" : null;\n if (ns === \"bitcoin\") return sourceChain in LAYERSWAP_NON_EVM ? \"deposit_address\" : null;\n return null;\n}\n\n/** `eip155:<id>` → id, else null. */\nexport function evmChainId(caip2: string): number | null {\n const m = /^eip155:([1-9]\\d{0,9})$/.exec(caip2);\n return m ? Number(m[1]) : null;\n}\n\n/**\n * Whether this module names the chain, and how: the numeric chain id for EVM (matched against `chain_id` in\n * Layerswap's network list), the network name otherwise; null for a chain this module does not serve. Requests carry\n * the `name` from Layerswap's list for either.\n */\nexport function layerswapNetwork(caip2: string): string | null {\n const id = evmChainId(caip2);\n if (id !== null) return LAYERSWAP_EVM_CHAINS.includes(id) ? String(id) : null;\n return Object.prototype.hasOwnProperty.call(LAYERSWAP_NON_EVM, caip2) ? LAYERSWAP_NON_EVM[caip2]! : null;\n}\n\n/** Layerswap's network name for a chain as its responses name it (EVM by chain id). */\nexport function sameNetwork(caip2: string, network: {name?: unknown; chain_id?: unknown} | null | undefined): boolean {\n if (!network) return false;\n const id = evmChainId(caip2);\n if (id !== null) return String(network.chain_id ?? \"\") === String(id);\n return network.name === LAYERSWAP_NON_EVM[caip2];\n}\n\nexport const layerswap = {\n supportsChain(chain: string): boolean {\n return layerswapNetwork(chain) !== null;\n },\n /** A route this module can try: a source with a funding method, any served destination, never the same chain. */\n supports(from: string, to: string): boolean {\n return from !== to && fundingFor(from) !== null && layerswapNetwork(to) !== null;\n },\n};\n","import {resolveAsset} from \"@anywalletkit/swap2-assets\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentState, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {refusalOf, type Swap2RefusalInfo} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {describeLayerswapActivity} from \"./activity.js\";\nimport {LAYERSWAP_API, fundingFor, layerswap as cfg, layerswapNetwork, type LayerswapFunding} from \"./config.js\";\nimport {MAX_NETWORKS_BODY, answerRefusal, clip, decimalToUnits, layerswapClient, networkFor, parseNetworks, tokenOn, unitsToDecimal, type LayerswapNetwork} from \"./api.js\";\nimport {LayerswapRefusal, checkBitcoinDeposit, checkEvmDeposit, checkSolanaDeposit, checkSwapRecord, checkTonDeposit, checkTronDeposit, pickAction, type LayerswapRequest, type LayerswapSwapRecord} from \"./verify.js\";\n\n/**\n * Layerswap — a solver bridge. One source transaction funds a swap Layerswap keeps under an id; Layerswap pays the\n * recipient on the destination chain from its own liquidity (or refunds the source address).\n *\n * - Display quote (`dry`) = `GET /quote`: nothing is created upstream.\n * - Execution quote = `POST /swaps`: Layerswap creates the swap and answers its deposit action. The swap record is\n * held to the request (networks, tokens, recipient, sender, amount, funding) and the deposit is checked\n * per chain family (`verify.ts`) before the quote is returned; the swap is read back again before the build and\n * right before the signature.\n * - EVM: `depositNative` / `depositERC20` on the pinned Depository, rebuilt here byte for byte, the receiver one of\n * the pinned solver addresses; an ERC-20 input approves exactly the input to the Depository (the engine's own\n * approval; Layerswap's approval step is never used).\n * - Solana: Layerswap's prepared legacy transaction, read instruction by instruction (one transfer of exactly the\n * input to the deposit address, the swap's memo); TON: a transfer / jetton transfer with the swap's comment; Tron:\n * a TRX / TRC-20 transfer with the memo in `raw_data.data`; Bitcoin: a send to the deposit address minted for the\n * swap.\n * - What no check here can see: where Layerswap pays out is its own record. The read-back holds that record to the\n * request, so a wrong recipient is refused — but an API that answers one record and pays from another is trusted,\n * as with every deposit-address venue.\n * - Status: `GET /swaps/{id}`. Display only, nothing is signed on its word.\n */\n\nconst INTENT_PREFIX = \"layerswap:\";\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\nconst QUOTE_TTL_MS = 60_000;\n/** Solana: the prepared transaction carries a recent blockhash (≈ 60–90 s), so its quote lives shorter. */\nconst SOLANA_QUOTE_TTL_MS = 40_000;\nconst NETWORKS_TTL_MS = 15 * 60_000;\nconst NETWORKS_TIMEOUT_MS = 25_000;\nconst CREATE_TIMEOUT_MS = 25_000;\nconst STATUS_TIMEOUT_MS = 12_000;\nconst MAX_REMEMBERED = 256;\nconst GAS_FLOOR_NATIVE = 120_000n;\nconst GAS_FLOOR_ERC20 = 160_000n;\nconst GAS_CAP = 3_000_000n;\n/** Layerswap reads amounts as JSON doubles: more significant digits than a double keeps would be rounded upstream. */\nconst MAX_SIGNIFICANT_DIGITS = 15;\nlet dryCounter = 0;\n\nexport interface LayerswapProviderConfig {\n enabled?: boolean;\n /** Layerswap's API (default https://api.layerswap.io/api/v2) or the app's own proxy in front of it. */\n baseUrl?: string;\n /**\n * Sent as `X-LS-APIKEY` (Partner Dashboard → app → key; the key picks mainnet or testnet). Read endpoints answer\n * without one; swap creation is attributed to it. Prefer a proxy that adds it — a key shipped in an app is public.\n */\n apiKey?: string;\n /** Injectable for tests and for runtimes that bring their own. */\n fetchImpl?: typeof fetch;\n}\n\n/** Layerswap's swap statuses → swap2 states. */\nexport const LAYERSWAP_STATUS_MAP: Readonly<Record<string, IntentState>> = Object.freeze({\n user_transfer_pending: \"pending\",\n ls_transfer_pending: \"pending\",\n completed: \"completed\",\n failed: \"failed\",\n expired: \"expired\",\n pending_refund: \"refund-pending\",\n refunded: \"refunded\",\n});\n\n/** `avg_completion_time` (.NET TimeSpan: \"00:00:04.78\", \"1.02:03:04\") → whole seconds; null when unreadable. */\nexport function etaSeconds(value: unknown): number | null {\n if (typeof value !== \"string\") return null;\n const m = /^(?:(\\d{1,3})\\.)?(\\d{1,2}):(\\d{2}):(\\d{2})(\\.\\d{1,9})?$/.exec(value.trim());\n if (!m) return null;\n const s = Number(m[1] ?? 0) * 86_400 + Number(m[2]) * 3_600 + Number(m[3]) * 60 + Number(m[4]) + Number(m[5] ?? 0);\n return Math.min(Math.max(1, Math.ceil(s)), 7 * 86_400);\n}\n\n/** Slippage as Layerswap takes it (a fraction), one basis point tighter than asked so its float minimum never lands under ours. */\nexport function slippageText(bps: number): string {\n const tight = Math.max(0, Math.floor(bps) - 1);\n return unitsToDecimal(BigInt(tight), 4);\n}\n\nconst NETWORK_NAME = /^[A-Z][A-Z0-9_]{1,47}$/;\n\ninterface Resolved {\n request: LayerswapRequest;\n /** Layerswap's own network names (`BASE_MAINNET`, `SOLANA_MAINNET`), from its list — what a live create was seen to take. */\n sourceNetwork: string;\n destNetwork: string;\n sourceSymbol: string;\n destSymbol: string;\n destDecimals: number;\n funding: LayerswapFunding;\n}\n\nexport function layerswapProvider(config: LayerswapProviderConfig = {}): CrossChainProvider {\n config = Object.freeze({...config});\n const api = layerswapClient(config, LAYERSWAP_API);\n\n let networksCache: {at: number; list: LayerswapNetwork[]} | null = null;\n async function networks(signal?: AbortSignal): Promise<LayerswapNetwork[]> {\n if (networksCache && Date.now() - networksCache.at < NETWORKS_TTL_MS) return networksCache.list;\n const a = await api.get(\"/networks\", undefined, signal, NETWORKS_TIMEOUT_MS, MAX_NETWORKS_BODY);\n if (!a.ok) throw new LayerswapRefusal(\"networks\", `the network list is unavailable (${answerRefusal(a).text})`, \"upstream_unavailable\");\n const list = parseNetworks(a.body?.data);\n networksCache = {at: Date.now(), list};\n return list;\n }\n\n // The request each live quote was issued for, kept on this side: a build and a signature are checked against what\n // was asked here, not against what the quote object says was asked.\n const issued = new Map<string, LayerswapRequest>();\n // Swaps a deposit was cleared for: one deposit per swap, ever, from this instance.\n const cleared = new Set<string>();\n const remember = <V>(m: Map<string, V>, k: string, 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 string);\n };\n\n async function resolve(params: QuoteParams, live: boolean, signal?: AbortSignal): Promise<Resolved> {\n const funding = fundingFor(params.sourceChain);\n if (!funding || !layerswapNetwork(params.destChain) || params.sourceChain === params.destChain) {\n throw new LayerswapRefusal(\"route\", `does not serve ${params.sourceChain} → ${params.destChain}`, \"unsupported_pair\");\n }\n if (params.flex) throw new LayerswapRefusal(\"route\", \"only an exact input is quoted\", \"unsupported_pair\");\n const source = sourceAssetOf(params);\n if (!source) throw new LayerswapRefusal(\"source-token\", `unknown source token ${clip(params.sourceToken, 60)} on ${params.sourceChain}`, \"unsupported_pair\");\n const listedDest = resolveAsset(params.destChain, params.destToken);\n const destContract = listedDest ? (listedDest.contract ?? null) : (params.destToken === \"\" || /^0x0{40}$/i.test(params.destToken) ? null : params.destToken);\n const list = await networks(signal);\n const srcNet = networkFor(params.sourceChain, list);\n const dstNet = networkFor(params.destChain, list);\n if (!srcNet || !dstNet) throw new LayerswapRefusal(\"route\", `Layerswap does not list ${!srcNet ? params.sourceChain : params.destChain}`, \"unsupported_pair\");\n if (!NETWORK_NAME.test(srcNet.name) || !NETWORK_NAME.test(dstNet.name)) throw new LayerswapRefusal(\"route\", \"Layerswap names the network unreadably\", \"upstream_unavailable\");\n const srcToken = tokenOn(params.sourceChain, srcNet, source.contract ?? null);\n if (!srcToken) throw new LayerswapRefusal(\"source-token\", `Layerswap does not take ${source.symbol} on ${params.sourceChain}`, \"unsupported_pair\");\n if (srcToken.decimals !== source.decimals) throw new LayerswapRefusal(\"source-token\", `Layerswap counts ${source.symbol} in ${srcToken.decimals} decimals, not ${source.decimals}`, \"policy_refused\");\n const dstToken = tokenOn(params.destChain, dstNet, destContract);\n if (!dstToken) throw new LayerswapRefusal(\"destination-token\", `Layerswap does not pay out ${clip(params.destToken || \"the native coin\", 60)} on ${params.destChain}`, \"unsupported_pair\");\n if (listedDest && dstToken.decimals !== listedDest.decimals) throw new LayerswapRefusal(\"destination-token\", `Layerswap counts the output in ${dstToken.decimals} decimals, not ${listedDest.decimals}`, \"policy_refused\");\n if (!/^[1-9]\\d{0,77}$/.test(params.amountIn)) throw new LayerswapRefusal(\"amount\", \"the input amount is not a positive integer\", \"policy_refused\");\n const significant = unitsToDecimal(BigInt(params.amountIn), source.decimals).replace(\".\", \"\").replace(/^0+/, \"\").replace(/0+$/, \"\");\n if (significant.length > MAX_SIGNIFICANT_DIGITS) {\n throw new LayerswapRefusal(\"amount\", `Layerswap takes amounts as a double: at most ${MAX_SIGNIFICANT_DIGITS} significant digits — round the amount`, \"policy_refused\");\n }\n const sender = params.sender ?? params.refundAddress ?? \"\";\n if (live) {\n if (!params.destAddress) throw new LayerswapRefusal(\"request\", \"a swap is never created without the recipient\", \"recipient_mismatch\");\n if (!sender) throw new LayerswapRefusal(\"request\", \"a swap is never created without the sending account\", \"policy_refused\");\n // The refund goes back to the account that funds the deposit, on the source chain, never anywhere else.\n if (params.refundAddress && params.refundAddress !== sender) throw new LayerswapRefusal(\"request\", \"the refund address must be the sending account\", \"policy_refused\");\n }\n return {\n funding,\n sourceNetwork: srcNet.name,\n destNetwork: dstNet.name,\n sourceSymbol: srcToken.symbol,\n destSymbol: dstToken.symbol,\n destDecimals: dstToken.decimals,\n request: {\n sourceChain: params.sourceChain, destChain: params.destChain,\n sourceContract: source.contract ?? null, sourceDecimals: source.decimals, destContract,\n amount: BigInt(params.amountIn), sender, recipient: params.destAddress, funding,\n },\n };\n }\n\n /** `data.quote` of a quote / create answer → the amounts and facts a Quote carries, held to the request's tokens. */\n function readQuote(r: Resolved, quote: unknown): {dest: bigint; min: bigint; feeUsd: number; eta: number | null; path: string} {\n const q = (quote ?? null) as Record<string, unknown> | null;\n if (!q) throw new LayerswapRefusal(\"quote\", \"the answer carries no quote\", \"upstream_unavailable\");\n // The API names an integrator fee as `integrator_fee_splits` (an empty list when none, seen 2026-12-01); the docs'\n // scalar `integrator_fee` is held too.\n const splits = q.integrator_fee_splits;\n const integratorFee = q.integrator_fee;\n if ((Array.isArray(splits) ? splits.length > 0 : splits !== undefined && splits !== null) || (typeof integratorFee === \"number\" && integratorFee > 0)) {\n throw new LayerswapRefusal(\"quote\", \"the quote charges an integrator fee this module did not ask for\", \"policy_refused\");\n }\n if (typeof q.refuel_in_source === \"number\" && q.refuel_in_source > 0) throw new LayerswapRefusal(\"quote\", \"the quote converts part of the input into a gas top-up this module did not ask for\", \"policy_refused\");\n const dest = decimalToUnits(q.receive_amount, r.destDecimals);\n const min = decimalToUnits(q.min_receive_amount, r.destDecimals);\n if (dest === null || min === null || dest <= 0n || min <= 0n || min > dest) throw new LayerswapRefusal(\"quote\", \"the quote's amounts are unreadable\", \"upstream_unavailable\");\n const fee = typeof q.total_fee_in_usd === \"number\" && Number.isFinite(q.total_fee_in_usd) && q.total_fee_in_usd >= 0 ? q.total_fee_in_usd : 0;\n const path = Array.isArray(q.path) ? (q.path as Array<{provider?: unknown}>).map((p) => clip(String(p?.provider ?? \"?\"), 30)).join(\">\") : \"\";\n return {dest, min, feeUsd: fee, eta: etaSeconds(q.avg_completion_time), path};\n }\n\n function routeQuery(r: Resolved, params: QuoteParams): Record<string, string> {\n return {\n source_network: r.sourceNetwork,\n source_token: r.sourceSymbol,\n destination_network: r.destNetwork,\n destination_token: r.destSymbol,\n amount: unitsToDecimal(r.request.amount, r.request.sourceDecimals),\n ...(r.funding === \"depository\" ? {use_depository: \"true\"} : {}),\n ...(r.funding === \"deposit_address\" ? {use_deposit_address: \"true\"} : {}),\n ...(params.slippageBps !== undefined ? {slippage: slippageText(params.slippageBps)} : {}),\n };\n }\n\n /** The deposit of a swap, checked for its family. */\n function checkDeposit(request: LayerswapRequest, swap: LayerswapSwapRecord, actions: unknown) {\n const a = pickAction(actions);\n const ns = request.sourceChain.split(\":\")[0];\n if (ns === \"eip155\") return {kind: \"evm\" as const, evm: checkEvmDeposit(request, swap, a)};\n if (ns === \"solana\") return {kind: \"solana\" as const, solana: checkSolanaDeposit(request, swap, a)};\n if (ns === \"ton\") return {kind: \"memo\" as const, memo: checkTonDeposit(request, swap, a)};\n if (ns === \"tron\") return {kind: \"memo\" as const, memo: checkTronDeposit(request, swap, a)};\n return {kind: \"memo\" as const, memo: checkBitcoinDeposit(request, a)};\n }\n\n function requestOf(quote: Quote): LayerswapRequest {\n const mine = issued.get(quote.intentId);\n if (!mine) throw new LayerswapRefusal(\"request\", \"this quote was not issued by this provider instance — quote again\", \"policy_refused\");\n return mine;\n }\n\n function swapIdOf(intentId: string): string {\n const id = intentId.startsWith(INTENT_PREFIX) ? intentId.slice(INTENT_PREFIX.length) : \"\";\n if (!UUID.test(id)) throw new LayerswapRefusal(\"intent\", \"malformed Layerswap intent id\", \"policy_refused\");\n return id;\n }\n\n /** The swap as Layerswap holds it now, checked against the request; still waiting for this deposit. */\n async function readBack(request: LayerswapRequest, swapId: string): Promise<{record: LayerswapSwapRecord; actions: unknown}> {\n // The record from the swap; the deposit from deposit_actions for this sender — `GET /swaps/{id}` alone lists the\n // Solana deposit as a manual transfer with no transaction, which is built per source address (seen 2026-12-01).\n const [a, d] = await Promise.all([\n api.get(`/swaps/${swapId}`, {exclude_deposit_actions: \"true\"}, undefined, STATUS_TIMEOUT_MS),\n api.get(`/swaps/${swapId}/deposit_actions`, {source_address: request.sender}, undefined, STATUS_TIMEOUT_MS),\n ]);\n for (const r of [a, d]) {\n if (!r.ok) {\n const why = answerRefusal(r);\n throw new LayerswapRefusal(\"read-back\", `the swap could not be read back (${why.text})`, why.info.reason);\n }\n }\n const data = (a.body?.data ?? null) as {swap?: unknown} | null;\n const record = checkSwapRecord(request, data?.swap);\n if (record.id !== swapId) throw new LayerswapRefusal(\"read-back\", \"the read-back answered another swap\", \"policy_refused\");\n if (record.status !== \"user_transfer_pending\") throw new LayerswapRefusal(\"read-back\", `the swap is ${clip(record.status || \"in an unknown state\", 40)}, no longer waiting for a deposit — quote again`, \"quote_expired\");\n return {record, actions: (d.body as {data?: unknown} | null)?.data};\n }\n\n /**\n * The deposit the quote carries, held to the swap as Layerswap holds it NOW (sequence number, deposit target, memo,\n * calldata): at build, and again right before the signature.\n */\n function currentDeposit(quote: Quote, request: LayerswapRequest, now: {record: LayerswapSwapRecord; actions: unknown}): UnsignedTx {\n const {record, actions} = now;\n if (record.sequence.toString(10) !== quote.providerData?.sequence) throw new LayerswapRefusal(\"read-back\", \"the swap's sequence number changed\", \"policy_refused\");\n const tx = quote.txRequest;\n if (request.sourceChain.startsWith(\"eip155:\")) {\n // The Depository call is rebuilt from the read-back; it must be the quoted one.\n const e = checkEvmDeposit(request, record, pickAction(actions));\n if (!tx || tx.to !== e.to || tx.data !== e.data || tx.value !== e.value.toString(10)) throw new LayerswapRefusal(\"build\", \"the swap's deposit changed since the quote — quote again\", \"quote_expired\");\n return {chain: request.sourceChain, to: e.to, value: tx.value!, data: e.data, chainId: e.chainId, ...(tx.gasLimit ? {gasLimit: tx.gasLimit} : {}), ...(e.approvalAddress ? {approvalAddress: e.approvalAddress} : {})};\n }\n if (request.sourceChain.startsWith(\"solana:\")) {\n // The quoted transaction (its blockhash) is the one signed: checked again against the deposit address now.\n if (!tx?.serializedTx) throw new LayerswapRefusal(\"build\", \"the Solana quote carries no transaction\", \"policy_refused\");\n const s = checkSolanaDeposit(request, record, {...pickAction(actions), callData: tx.serializedTx});\n if (s.depositTo !== quote.providerData?.depositTo) throw new LayerswapRefusal(\"build\", \"the swap's deposit address changed since the quote — quote again\", \"quote_expired\");\n return {chain: request.sourceChain, to: \"\", value: s.value.toString(10), serializedTx: s.serializedTx};\n }\n const d = checkDeposit(request, record, actions);\n if (d.kind !== \"memo\" || d.memo.to !== quote.depositAddress || (d.memo.memo ?? null) !== quote.depositMemo) {\n throw new LayerswapRefusal(\"build\", \"the swap's deposit address or memo changed since the quote — quote again\", \"quote_expired\");\n }\n return {chain: request.sourceChain, to: d.memo.to, value: d.memo.value.toString(10), ...(d.memo.memo !== undefined ? {memo: d.memo.memo} : {})};\n }\n\n return {\n name: \"layerswap\",\n describeActivity: describeLayerswapActivity,\n enabled: () => config.enabled ?? true,\n // The Depository call goes out with the account's own gas estimate of exactly that call, dry-run before broadcast.\n ownGasEstimate: true,\n supportsChain: (chain: string) => cfg.supportsChain(chain),\n supportsChainPair: (from: string, to: string) => cfg.supports(from, to),\n supportsRoute: (from: Asset, to: Asset) => cfg.supports(from.chain, to.chain),\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (text: string, info?: Swap2RefusalInfo): null => {\n params.onRefusal?.(text.startsWith(\"layerswap:\") ? text : `layerswap: ${text}`, info);\n return null;\n };\n const live = params.dry === false;\n try {\n const r = await resolve(params, live, signal);\n if (!live) {\n const a = await api.get(\"/quote\", routeQuery(r, params), signal);\n if (!a.ok || !a.body?.data) {\n const why = answerRefusal(a);\n return refuse(`no quote — ${why.text}`, signal?.aborted ? undefined : why.info);\n }\n const q = readQuote(r, (a.body.data as {quote?: unknown}).quote);\n return {\n provider: \"layerswap\",\n intentId: `dry:${Date.now().toString(36)}-${(dryCounter = (dryCounter + 1) % 1_000_000).toString(36)}`,\n depositAddress: \"\",\n depositMemo: null,\n sourceAmount: params.amountIn,\n destAmount: q.dest.toString(10),\n minDestAmount: q.min.toString(10),\n destDecimals: r.destDecimals,\n feeUsd: q.feeUsd,\n etaSeconds: q.eta,\n reliability: 0.95,\n validUntilMs: Date.now() + QUOTE_TTL_MS,\n providerData: {path: q.path, funding: r.funding},\n };\n }\n\n // Execution: create the swap. Amounts go out as exact decimal literals (Layerswap reads JSON numbers).\n const query = routeQuery(r, params);\n const body = JSON.stringify({\n source_network: query.source_network,\n source_token: query.source_token,\n destination_network: query.destination_network,\n destination_token: query.destination_token,\n amount: \"__AMOUNT__\",\n source_address: r.request.sender,\n destination_address: r.request.recipient,\n refund_address: r.request.sender,\n refuel: false,\n ...(r.funding === \"depository\" ? {use_depository: true} : {}),\n ...(r.funding === \"deposit_address\" ? {use_deposit_address: true} : {}),\n ...(query.slippage !== undefined ? {slippage: query.slippage} : {}),\n }).replace('\"__AMOUNT__\"', query.amount!);\n const a = await api.post(\"/swaps\", body, signal, CREATE_TIMEOUT_MS);\n if (!a.ok || !a.body?.data) {\n const why = answerRefusal(a);\n return refuse(`no swap — ${why.text}`, signal?.aborted ? undefined : why.info);\n }\n const data = a.body.data as {swap?: unknown; quote?: unknown; deposit_actions?: unknown};\n const record = checkSwapRecord(r.request, data.swap);\n if (record.status !== \"user_transfer_pending\") return refuse(`the new swap is ${clip(record.status, 40)}, not waiting for a deposit`, {reason: \"upstream_unavailable\"});\n // The swap is priced again at creation: its own quote is the one reviewed.\n const q = readQuote(r, data.quote);\n const deposit = checkDeposit(r.request, record, data.deposit_actions);\n const intentId = `${INTENT_PREFIX}${record.id}`;\n remember(issued, intentId, r.request);\n const ttl = deposit.kind === \"solana\" ? SOLANA_QUOTE_TTL_MS : QUOTE_TTL_MS;\n const common = {\n provider: \"layerswap\",\n intentId,\n sourceAmount: params.amountIn,\n destAmount: q.dest.toString(10),\n minDestAmount: q.min.toString(10),\n destDecimals: r.destDecimals,\n feeUsd: q.feeUsd,\n etaSeconds: q.eta,\n reliability: 0.95,\n validUntilMs: Date.now() + ttl,\n };\n const pd = {swapId: record.id, sequence: record.sequence.toString(10), funding: r.funding, path: q.path, depositTo: deposit.kind === \"evm\" ? deposit.evm.to : deposit.kind === \"solana\" ? deposit.solana.depositTo : deposit.memo.to};\n if (deposit.kind === \"evm\") {\n const e = deposit.evm;\n const floor = e.approvalAddress ? GAS_FLOOR_ERC20 : GAS_FLOOR_NATIVE;\n const doubled = e.gasLimit !== null ? e.gasLimit * 2n : 0n;\n const gas = doubled > GAS_CAP ? GAS_CAP : doubled > floor ? doubled : floor;\n return {\n ...common,\n depositAddress: \"\",\n depositMemo: null,\n txRequest: {\n to: e.to, data: e.data, value: e.value.toString(10), chainId: e.chainId, gasLimit: gas.toString(10),\n ...(e.approvalAddress ? {approvalAddress: e.approvalAddress} : {}),\n },\n providerData: {...pd, receiver: e.receiver},\n };\n }\n if (deposit.kind === \"solana\") {\n return {\n ...common,\n depositAddress: \"\",\n depositMemo: null,\n txRequest: {value: deposit.solana.value.toString(10), serializedTx: deposit.solana.serializedTx},\n providerData: pd,\n };\n }\n return {...common, depositAddress: deposit.memo.to, depositMemo: deposit.memo.memo ?? null, providerData: pd};\n } catch (err) {\n if (err instanceof LayerswapRefusal) return refuse(err.message, refusalOf(err));\n const info = refusalOf(err) ?? (signal?.aborted ? undefined : {reason: \"upstream_unavailable\" as const});\n return refuse(`request failed — ${clip(err instanceof Error ? err.message : String(err))}`, info);\n }\n },\n\n /** The quote's own deposit, after the swap has been read back and its deposit checked once more. */\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const request = requestOf(quote);\n return currentDeposit(quote, request, await readBack(request, swapIdOf(quote.intentId)));\n },\n\n /** Right before the signature: the swap read back once more, and each swap funded once. */\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n const request = requestOf(quote);\n const swapId = swapIdOf(quote.intentId);\n if (tx.chain && tx.chain !== request.sourceChain) throw new LayerswapRefusal(\"preflight\", `the deposit is for ${clip(tx.chain, 40)}, not ${request.sourceChain}`, \"vault_mismatch\");\n if (tx.typedData !== undefined || tx.bodyBoc !== undefined || tx.permit2Transfer !== undefined) throw new LayerswapRefusal(\"preflight\", \"a Layerswap deposit is one transfer or one Depository call\", \"policy_refused\");\n // EVM / Solana: native value only for a native input. TON / Tron / Bitcoin: the transfer amount, native or token.\n const valueLeg = request.sourceChain.startsWith(\"eip155:\") || request.sourceChain.startsWith(\"solana:\");\n const expected = valueLeg ? (request.sourceContract === null ? request.amount : 0n) : request.amount;\n if (!/^\\d{1,78}$/.test(tx.value || \"\") || BigInt(tx.value) !== expected) throw new LayerswapRefusal(\"preflight\", \"the deposit value is not the input\", \"policy_refused\");\n if (cleared.has(swapId)) throw new LayerswapRefusal(\"preflight\", \"this swap was already cleared for a deposit — quote again\", \"policy_refused\");\n // The deposit about to be signed must still be the swap's: target, memo, calldata, transaction.\n const now = currentDeposit(quote, request, await readBack(request, swapId));\n const same = (x: string | undefined, y: string | undefined) => (x ?? \"\").toLowerCase() === (y ?? \"\").toLowerCase();\n if (!same(tx.to, now.to) || tx.value !== now.value || !same(tx.data, now.data) || tx.serializedTx !== now.serializedTx || (tx.memo ?? null) !== (now.memo ?? null) || !same(tx.approvalAddress, now.approvalAddress)) {\n throw new LayerswapRefusal(\"preflight\", \"the transaction about to be signed is not the swap's deposit\", \"policy_refused\");\n }\n cleared.add(swapId);\n if (cleared.size > MAX_REMEMBERED) cleared.delete(cleared.values().next().value as string);\n },\n\n /** Layerswap matches deposits on its own; the hash speeds that up. Best effort. */\n async notifyDeposit(intentId: string, txHash: string): Promise<void> {\n const swapId = swapIdOf(intentId);\n if (typeof txHash !== \"string\" || !/^[\\x21-\\x7e]{8,200}$/.test(txHash)) return;\n const a = await api.post(`/swaps/${swapId}/deposit_speedup`, JSON.stringify({transaction_id: txHash}), undefined, STATUS_TIMEOUT_MS);\n if (!a.ok) {\n const why = answerRefusal(a);\n throw new LayerswapRefusal(\"notify\", `deposit speed-up failed (${why.text})`, why.info.reason);\n }\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n let swapId: string;\n try { swapId = swapIdOf(ref.intentId); } catch { return {state: \"failed\"}; }\n try {\n const a = await api.get(`/swaps/${swapId}`, {exclude_deposit_actions: \"true\"}, undefined, STATUS_TIMEOUT_MS);\n if (!a.ok) return {state: \"pending\"};\n const swap = ((a.body?.data ?? null) as {swap?: Record<string, unknown>} | null)?.swap;\n const status = typeof swap?.status === \"string\" ? swap.status : \"\";\n if (String(swap?.id ?? \"\").toLowerCase() !== swapId) return {state: \"pending\"};\n if (status === \"user_transfer_pending\" && ref.sourceTxHash) {\n // Sent but not matched yet: hand the hash over again (the post-broadcast notification may have failed).\n await this.notifyDeposit?.(ref.intentId, ref.sourceTxHash).catch(() => {});\n }\n const state = Object.prototype.hasOwnProperty.call(LAYERSWAP_STATUS_MAP, status) ? LAYERSWAP_STATUS_MAP[status]! : \"pending\";\n const txs = Array.isArray(swap?.transactions) ? (swap!.transactions as Array<Record<string, unknown>>) : [];\n const output = txs.find((t) => t?.type === \"output\" && typeof t.transaction_hash === \"string\" && /^[\\x21-\\x7e]{8,200}$/.test(t.transaction_hash));\n const received = status !== \"user_transfer_pending\" && status !== \"expired\" && status !== \"\";\n return {state, ...(received ? {depositReceived: true} : {}), ...(state === \"completed\" && output ? {destTxHash: output.transaction_hash as string} : {})};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n","/**\n * Activity recognition for Layerswap on every EVM chain with the pinned Depository: `depositNative` /\n * `depositERC20` on it is our source leg (\"Bridged USDC\").\n *\n * The other legs are not claimed. A Solana / TON / Tron / Bitcoin deposit is a plain transfer to an address Layerswap\n * names per swap, and the payout is an ordinary transfer from a Layerswap solver account: nothing on chain a stranger\n * could not imitate. The swap id the engine journals ties them back to the swap.\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {chainLabel, describeSwapLike, matchesCall} from \"@anywalletkit/protocol-swap2-core/activity\";\nimport {DEPOSIT_ERC20_SELECTOR, DEPOSIT_NATIVE_SELECTOR, LAYERSWAP_DEPOSITORY, fundingFor} from \"./config.js\";\n\nexport const LAYERSWAP_MODULE = \"@anywalletkit/protocol-swap2-layerswap\";\n\nexport function describeLayerswapActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n if (fundingFor(tx.chain) !== \"depository\") return null;\n if (!matchesCall(tx, [LAYERSWAP_DEPOSITORY], [DEPOSIT_NATIVE_SELECTOR, DEPOSIT_ERC20_SELECTOR])) return null;\n return describeSwapLike(tx, ctx, {protocol: LAYERSWAP_MODULE, subtitle: `Layerswap · ${chainLabel(tx.chain)}`, kind: \"bridge\", outVerb: \"Bridged\"});\n}\n","import {anySignal, redactUrls, timeoutSignal, tonRawAddress} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {httpRefusal, type Swap2RefusalInfo, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {LAYERSWAP_NON_EVM, evmChainId} from \"./config.js\";\n\n/**\n * Layerswap's v2 API as this module reads it: JSON envelopes `{data}` / `{error: {code, message}}`, and HTTP 400 with\n * an EMPTY body for a request that fails model binding (a bad enum, wrong casing) — both handled. Amounts in requests\n * and answers are JSON numbers; the exact ones are only `deposit_actions[].amount_in_base_units` (strings), so every\n * amount this module sends is written as an exact decimal literal and every amount it signs is the base-unit string.\n */\n\nconst MAX_BODY = 1024 * 1024;\n/**\n * `GET /networks` alone may be larger: 2.66 MB on 2026-12-01 (63 networks, hundreds of tokens on each big EVM chain since\n * Layerswap added DEX hops). The provider reads it once per 15-minute cache window and keeps only names, chain ids and token symbols, contracts and decimals.\n */\nexport const MAX_NETWORKS_BODY = 8 * 1024 * 1024;\nconst DEFAULT_TIMEOUT_MS = 15_000;\n\n/** Layerswap's error codes (docs.layerswap.io/api/errors, plus the ones seen live 2026-12-01) → why there is no quote. */\nexport const LAYERSWAP_ERROR_REASONS: Readonly<Record<string, Swap2RefusalReason>> = Object.freeze(Object.assign(Object.create(null) as Record<string, Swap2RefusalReason>, {\n ROUTE_NOT_FOUND_ERROR: \"unsupported_pair\",\n VALIDATION_ERROR: \"unsupported_pair\",\n UNSUPPORTED_GASLESS_SOURCE: \"unsupported_pair\",\n LESS_THAN_MIN_ERROR: \"amount_too_small\",\n GREATER_THAN_MAX_ERROR: \"amount_too_large\",\n INVALID_ADDRESS_ERROR: \"recipient_mismatch\",\n UNACTIVATED_ADDRESS_ERROR: \"recipient_mismatch\",\n REFUND_ADDRESS_MISSING: \"policy_refused\",\n DUPLICATE_REFERENCE_ID: \"policy_refused\",\n PRICE_IMPACT_TOO_HIGH: \"price_check_failed\",\n API_KEY_FORBIDDEN: \"key_rejected\",\n UNEXPECTED_ERROR: \"upstream_unavailable\",\n NOT_FOUND: \"upstream_unavailable\",\n}));\n\nexport interface LayerswapAnswer {\n ok: boolean;\n status: number;\n /** The parsed body, or null for an empty / non-JSON one. */\n body: {data?: unknown; error?: {code?: unknown; message?: unknown}} | null;\n retryAfter: string | null;\n}\n\nexport interface LayerswapClientConfig {\n baseUrl?: string;\n apiKey?: string;\n fetchImpl?: typeof fetch;\n}\n\nexport function clip(text: string, max = 240): string {\n const t = redactUrls(text).replace(/[\\u0000-\\u001f\\u007f]/g, \" \").replace(/\\s+/g, \" \").trim();\n return t.length > max ? `${t.slice(0, max)}…` : t;\n}\n\nexport function layerswapClient(config: LayerswapClientConfig, defaultBase: string) {\n const base = (config.baseUrl ?? defaultBase).replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(base)) throw new Error(\"layerswap: baseUrl must use http or https\");\n if (config.apiKey !== undefined && (typeof config.apiKey !== \"string\" || !/^[\\x21-\\x7e]{1,256}$/.test(config.apiKey))) {\n throw new Error(\"layerswap: apiKey must be a printable string\");\n }\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-LS-APIKEY\": config.apiKey} : {}),\n });\n\n async function call(method: \"GET\" | \"POST\", path: string, opts: {query?: Record<string, string>; body?: string; signal?: AbortSignal; timeoutMs?: number; maxBody?: number} = {}): Promise<LayerswapAnswer> {\n const qs = opts.query ? `?${new URLSearchParams(opts.query).toString()}` : \"\";\n const timeout = timeoutSignal(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n const res = await doFetch(`${base}${path}${qs}`, {\n method,\n headers: headers(opts.body !== undefined),\n ...(opts.body !== undefined ? {body: opts.body} : {}),\n signal: opts.signal ? anySignal([opts.signal, timeout]) : timeout,\n });\n const text = await res.text();\n if (text.length > (opts.maxBody ?? MAX_BODY)) throw new Error(\"layerswap: response too large\");\n let body: LayerswapAnswer[\"body\"] = null;\n if (text.trim() !== \"\") {\n try {\n const parsed = JSON.parse(text) as unknown;\n if (parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed)) body = parsed as LayerswapAnswer[\"body\"];\n } catch { body = null; }\n }\n return {ok: res.ok, status: res.status, body, retryAfter: res.headers?.get?.(\"retry-after\") ?? null};\n }\n\n return {\n base,\n get: (path: string, query?: Record<string, string>, signal?: AbortSignal, timeoutMs?: number, maxBody?: number) =>\n call(\"GET\", path, {...(query ? {query} : {}), ...(signal ? {signal} : {}), ...(timeoutMs ? {timeoutMs} : {}), ...(maxBody ? {maxBody} : {})}),\n post: (path: string, body: string, signal?: AbortSignal, timeoutMs?: number) =>\n call(\"POST\", path, {body, ...(signal ? {signal} : {}), ...(timeoutMs ? {timeoutMs} : {})}),\n };\n}\n\nexport type LayerswapClient = ReturnType<typeof layerswapClient>;\n\n/**\n * Why an answer is not a usable one: a 429 with its wait first, then Layerswap's own code, then the status. An empty\n * 400 is a request the API could not bind (a parameter it does not take for this route): `unsupported_pair`.\n */\nexport function answerRefusal(a: LayerswapAnswer): {text: string; info: Swap2RefusalInfo} {\n const code = typeof a.body?.error?.code === \"string\" ? a.body.error.code : \"\";\n const message = typeof a.body?.error?.message === \"string\" ? clip(a.body.error.message) : \"\";\n const byStatus = httpRefusal(a.status, a.retryAfter);\n const text = code ? `${clip(code, 60)}${message ? `: ${message}` : \"\"}` : a.body === null ? `HTTP ${a.status} with no body` : `HTTP ${a.status}`;\n if (byStatus?.reason === \"rate_limited\") return {text, info: byStatus};\n const byCode = code && Object.prototype.hasOwnProperty.call(LAYERSWAP_ERROR_REASONS, code) ? LAYERSWAP_ERROR_REASONS[code]! : undefined;\n if (byCode) return {text, info: byCode === \"upstream_unavailable\" || byCode === \"key_rejected\" ? {reason: byCode, httpStatus: a.status} : {reason: byCode}};\n if (a.status === 400 && a.body === null) return {text, info: {reason: \"unsupported_pair\"}};\n if (byStatus) return {text, info: byStatus};\n return {text, info: a.body?.error ? {reason: \"no_route\"} : {reason: \"upstream_unavailable\", httpStatus: a.status}};\n}\n\n// ── Amounts ─────────────────────────────────────────────────────────────────\n\n/** Base units → an exact decimal literal (\"1.5\", \"0.000001\", \"25\"); never exponent notation. */\nexport function unitsToDecimal(units: bigint, decimals: number): string {\n if (units < 0n) throw new Error(\"layerswap: negative amount\");\n const digits = units.toString(10).padStart(decimals + 1, \"0\");\n const whole = digits.slice(0, digits.length - decimals);\n const frac = decimals > 0 ? digits.slice(digits.length - decimals).replace(/0+$/, \"\") : \"\";\n return frac ? `${whole}.${frac}` : whole;\n}\n\n/**\n * A JSON number from Layerswap (a float) → base units, rounded DOWN, so an amount shown or held as a minimum is never\n * more than Layerswap said. Null for anything that is not a finite, non-negative number.\n */\nexport function decimalToUnits(value: unknown, decimals: number): bigint | null {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0 || value > 1e30) return null;\n let text = String(value);\n if (/e/i.test(text)) text = value.toFixed(Math.min(100, Math.max(decimals, 20)));\n const m = /^(\\d+)(?:\\.(\\d+))?$/.exec(text);\n if (!m) return null;\n const frac = (m[2] ?? \"\").slice(0, decimals).padEnd(decimals, \"0\");\n return BigInt(m[1]! + frac);\n}\n\n/** An exact base-unit string from the API (\"0\", \"1500000\"); null otherwise. */\nexport function baseUnits(value: unknown): bigint | null {\n return typeof value === \"string\" && /^(?:0|[1-9]\\d{0,77})$/.test(value) ? BigInt(value) : null;\n}\n\n// ── Networks and tokens ─────────────────────────────────────────────────────\n\nexport interface LayerswapToken {\n symbol: string;\n contract: string | null;\n decimals: number;\n}\n\nexport interface LayerswapNetwork {\n name: string;\n type: string;\n chainId: string | null;\n tokens: LayerswapToken[];\n}\n\n/** `GET /networks` → the networks this module can name, tokens with a symbol and whole decimals only. */\nexport function parseNetworks(data: unknown): LayerswapNetwork[] {\n if (!Array.isArray(data)) throw new Error(\"layerswap: /networks did not answer a list\");\n const out: LayerswapNetwork[] = [];\n for (const n of data as Array<Record<string, unknown>>) {\n if (!n || typeof n !== \"object\" || typeof n.name !== \"string\" || typeof n.type !== \"string\") continue;\n const tokens: LayerswapToken[] = [];\n for (const t of Array.isArray(n.tokens) ? (n.tokens as Array<Record<string, unknown>>) : []) {\n if (!t || typeof t.symbol !== \"string\" || !/^[\\x21-\\x7e]{1,40}$/.test(t.symbol)) continue;\n if (typeof t.decimals !== \"number\" || !Number.isInteger(t.decimals) || t.decimals < 0 || t.decimals > 36) continue;\n if (t.contract !== null && t.contract !== undefined && typeof t.contract !== \"string\") continue;\n tokens.push({symbol: t.symbol, contract: typeof t.contract === \"string\" && t.contract !== \"\" ? t.contract : null, decimals: t.decimals});\n }\n out.push({name: n.name, type: n.type, chainId: n.chain_id === null || n.chain_id === undefined ? null : String(n.chain_id), tokens});\n }\n return out;\n}\n\n/** The Layerswap network for one of our chains. */\nexport function networkFor(caip2: string, networks: readonly LayerswapNetwork[]): LayerswapNetwork | undefined {\n const id = evmChainId(caip2);\n if (id !== null) return networks.find((n) => n.type === \"evm\" && n.chainId === String(id));\n const name = Object.prototype.hasOwnProperty.call(LAYERSWAP_NON_EVM, caip2) ? LAYERSWAP_NON_EVM[caip2] : undefined;\n return name ? networks.find((n) => n.name === name) : undefined;\n}\n\n/** A token contract in the form two spellings of it compare equal in (EVM lowercase, TON raw), or null for native. */\nexport function tokenKey(caip2: string, contract: string | null | undefined): string | null {\n if (contract === null || contract === undefined || contract === \"\" || /^0x0{40}$/i.test(contract)) return null;\n if (caip2.startsWith(\"eip155:\")) return contract.toLowerCase();\n if (caip2.startsWith(\"ton:\")) return tonRawAddress(contract) ?? `?${contract}`;\n return contract;\n}\n\n/** Our token (its contract, or null for the chain's native coin) on Layerswap's list for that network. */\nexport function tokenOn(caip2: string, network: LayerswapNetwork, contract: string | null): LayerswapToken | undefined {\n const want = tokenKey(caip2, contract);\n return network.tokens.find((t) => tokenKey(caip2, t.contract) === want);\n}\n\n/** An address in the form two spellings of it compare equal in, per chain family. */\nexport function addressKey(caip2: string, address: unknown): string | null {\n if (typeof address !== \"string\" || address.trim() === \"\") return null;\n const a = address.trim();\n if (caip2.startsWith(\"eip155:\")) return /^0x[0-9a-fA-F]{40}$/.test(a) ? a.toLowerCase() : null;\n if (caip2.startsWith(\"ton:\")) return tonRawAddress(a);\n return a;\n}\n","import {decodeFunctionData, encodeFunctionData, pad, toHex} from \"viem\";\nimport {ed25519} from \"@noble/curves/ed25519.js\";\nimport {sha256} from \"@noble/hashes/sha2.js\";\nimport {base64Bytes} from \"@anywalletkit/protocol-swap2-core/util\";\nimport type {Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {withReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {LAYERSWAP_DEPOSITORY, LAYERSWAP_RECEIVERS, evmChainId, sameNetwork, type LayerswapFunding} from \"./config.js\";\nimport {addressKey, baseUnits, tokenKey, unitsToDecimal} from \"./api.js\";\n\n/**\n * Everything a Layerswap answer is held to before a deposit is built or signed. Layerswap's deposit names the swap\n * (its sequence number) and nothing else — not the recipient, not the destination, not the minimum — so the only\n * guard on those is the swap record itself: read back and compared with the request, field by field, before every\n * build. On the source leg the deposit is rebuilt from this side's values wherever the chain allows (EVM: the\n * Depository call byte for byte; Solana: every instruction read), so the answer can only add what is checked here.\n */\n\n/** A refusal this module raises: a named check and the reason class the engine reports. */\nexport class LayerswapRefusal extends Error {\n constructor(readonly check: string, message: string, reason: Swap2RefusalReason) {\n super(`layerswap: ${message}`);\n this.name = \"LayerswapRefusal\";\n withReason(this, reason);\n }\n}\n\nfunction fail(check: string, message: string, reason: Swap2RefusalReason = \"policy_refused\"): never {\n throw new LayerswapRefusal(check, message, reason);\n}\n\n/** What was asked — kept on this side and compared with every answer. */\nexport interface LayerswapRequest {\n sourceChain: string;\n destChain: string;\n /** Source token contract / mint / jetton master; null for the native coin. */\n sourceContract: string | null;\n sourceDecimals: number;\n destContract: string | null;\n amount: bigint;\n /** The account that funds the deposit (and the refund address). */\n sender: string;\n recipient: string;\n funding: LayerswapFunding;\n}\n\n// ── The swap record ─────────────────────────────────────────────────────────\n\nexport interface LayerswapSwapRecord {\n id: string;\n sequence: bigint;\n status: string;\n}\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * `swap` of a create / details answer, held to the request: networks, tokens, recipient, sender, amount,\n * funding flag; its id and sequence number well-formed. The amount is held exactly on the deposit action.\n */\nexport function checkSwapRecord(request: LayerswapRequest, swap: unknown): LayerswapSwapRecord {\n if (swap === null || typeof swap !== \"object\") fail(\"swap-record\", \"the answer carries no swap\", \"upstream_unavailable\");\n const s = swap as Record<string, unknown>;\n const id = typeof s.id === \"string\" ? s.id : \"\";\n if (!UUID.test(id)) fail(\"swap-record\", \"the swap has no id\", \"upstream_unavailable\");\n const seqRaw = (s.metadata as {sequence_number?: unknown} | null | undefined)?.sequence_number;\n if (typeof seqRaw !== \"number\" || !Number.isSafeInteger(seqRaw) || seqRaw <= 0) fail(\"swap-record\", \"the swap has no sequence number\", \"upstream_unavailable\");\n if (!sameNetwork(request.sourceChain, s.source_network as never)) fail(\"swap-source\", `the swap leaves from ${describe(s.source_network)}, not ${request.sourceChain}`, \"vault_mismatch\");\n if (!sameNetwork(request.destChain, s.destination_network as never)) fail(\"swap-destination\", `the swap pays out on ${describe(s.destination_network)}, not ${request.destChain}`, \"vault_mismatch\");\n const srcToken = (s.source_token ?? null) as {contract?: unknown} | null;\n const dstToken = (s.destination_token ?? null) as {contract?: unknown} | null;\n if (!srcToken || tokenKey(request.sourceChain, srcToken.contract as string | null) !== tokenKey(request.sourceChain, request.sourceContract)) {\n fail(\"swap-source-token\", \"the swap takes another source token than the one asked\", \"policy_refused\");\n }\n if (!dstToken || tokenKey(request.destChain, dstToken.contract as string | null) !== tokenKey(request.destChain, request.destContract)) {\n fail(\"swap-destination-token\", \"the swap pays out another token than the one asked\", \"policy_refused\");\n }\n const recipient = addressKey(request.destChain, s.destination_address);\n if (!recipient || recipient !== addressKey(request.destChain, request.recipient)) {\n fail(\"swap-recipient\", \"the swap pays out to another address than the recipient asked\", \"recipient_mismatch\");\n }\n // The record does not echo the source or refund address it was given (seen 2026-12-01); the deposit itself is this\n // account's own transfer or its own signature, checked per family. A record that does name a source address must\n // name this account.\n if (s.source_address !== undefined && s.source_address !== null && addressKey(request.sourceChain, s.source_address) !== addressKey(request.sourceChain, request.sender)) {\n fail(\"swap-sender\", \"the swap is recorded for another source address\", \"policy_refused\");\n }\n if (Array.isArray(s.integrator_fee_splits) ? s.integrator_fee_splits.length > 0 : s.integrator_fee_splits !== undefined && s.integrator_fee_splits !== null) {\n fail(\"swap-fee\", \"the swap carries an integrator fee this module did not ask for\", \"policy_refused\");\n }\n // The amount is held exactly on the deposit; the record's (a JSON double) must still be the input.\n const asked = Number(unitsToDecimal(request.amount, request.sourceDecimals));\n if (typeof s.requested_amount !== \"number\" || !(Math.abs(s.requested_amount - asked) <= Math.abs(asked) * 1e-9)) {\n fail(\"swap-amount\", \"the swap is recorded for another amount than the input\", \"policy_refused\");\n }\n if ((s.use_deposit_address === true) !== (request.funding === \"deposit_address\")) {\n fail(\"swap-funding\", \"the swap was created for another funding method\", \"policy_refused\");\n }\n const status = typeof s.status === \"string\" ? s.status : \"\";\n return {id: id.toLowerCase(), sequence: BigInt(seqRaw as number), status};\n}\n\nfunction describe(network: unknown): string {\n const n = network as {name?: unknown; chain_id?: unknown} | null;\n return clipName(n?.name ?? n?.chain_id ?? \"an unnamed network\");\n}\nfunction clipName(v: unknown): string {\n return String(v).replace(/[^\\x20-\\x7e]/g, \"?\").slice(0, 60);\n}\n\n// ── Deposit actions ─────────────────────────────────────────────────────────\n\nexport interface LayerswapAction {\n type: string;\n step: string;\n toAddress: string;\n amountInBaseUnits: bigint | null;\n callData: string | null;\n gasLimit: bigint | null;\n network: {name?: unknown; chain_id?: unknown} | null;\n tokenContract: string | null;\n}\n\n/**\n * The one action this account must perform. The workflow lists every step with its status; only an\n * `action_required` item carries transaction fields. An approval step Layerswap lists is not used (the engine\n * approves exactly the input to the pinned Depository); a signing step (gasless, Permit2) is never taken.\n */\nexport function pickAction(actions: unknown): LayerswapAction {\n if (!Array.isArray(actions) || actions.length === 0 || actions.length > 8) fail(\"actions\", \"the swap has no deposit action\", \"upstream_unavailable\");\n const steps = (actions as Array<Record<string, unknown>>).filter((a) => a && typeof a === \"object\" && !/approve/i.test(String(a.step ?? \"\")));\n const open = (want: (status: unknown) => boolean) => steps.filter((a) => want(a.status));\n // The step this account must take: the one action_required; else (an approval step listed as the required one) the\n // pending deposit — the engine approves the Depository itself. Never a completed or failed step.\n let usable = open((st) => st === undefined || st === null || st === \"action_required\");\n if (usable.length === 0) usable = open((st) => st === \"pending\");\n if (usable.length !== 1) fail(\"actions\", usable.length === 0 ? \"the swap asks for no deposit this account can make\" : \"the swap asks for more than one deposit transaction\", \"unsupported_pair\");\n const a = usable[0]!;\n const type = typeof a.type === \"string\" ? a.type : \"\";\n if (type !== \"transfer\" && type !== \"manual_transfer\") fail(\"actions\", `the swap asks for a \"${clipName(type)}\" action, only a transfer is made`, \"unsupported_pair\");\n if (a.typed_data !== undefined && a.typed_data !== null) fail(\"actions\", \"the deposit action carries typed data to sign\", \"policy_refused\");\n if (typeof a.to_address !== \"string\" || a.to_address.trim() === \"\") fail(\"actions\", \"the deposit action names no address\", \"upstream_unavailable\");\n const gas = typeof a.gas_limit === \"string\" && /^[1-9]\\d{0,9}$/.test(a.gas_limit) ? BigInt(a.gas_limit) : null;\n const token = a.token as {contract?: unknown} | null | undefined;\n return {\n type,\n step: typeof a.step === \"string\" ? a.step : \"\",\n toAddress: (a.to_address as string).trim(),\n amountInBaseUnits: baseUnits(a.amount_in_base_units),\n callData: typeof a.call_data === \"string\" && a.call_data !== \"\" ? a.call_data : null,\n gasLimit: gas,\n network: (a.network ?? null) as LayerswapAction[\"network\"],\n tokenContract: typeof token?.contract === \"string\" && token.contract !== \"\" ? token.contract : null,\n };\n}\n\n/** What every family checks first: the action's network and token are the request's. */\nfunction commonAction(request: LayerswapRequest, a: LayerswapAction): void {\n if (!sameNetwork(request.sourceChain, a.network)) fail(\"action-network\", `the deposit is on ${describe(a.network)}, not ${request.sourceChain}`, \"vault_mismatch\");\n if (tokenKey(request.sourceChain, a.tokenContract) !== tokenKey(request.sourceChain, request.sourceContract)) {\n fail(\"action-token\", \"the deposit moves another token than the swap's input\", \"policy_refused\");\n }\n}\n\n// ── EVM: the pinned Depository ──────────────────────────────────────────────\n\nexport const DEPOSITORY_ABI = [\n {type: \"function\", name: \"depositNative\", stateMutability: \"payable\", inputs: [{name: \"id\", type: \"bytes32\"}, {name: \"receiver\", type: \"address\"}], outputs: []},\n {type: \"function\", name: \"depositERC20\", stateMutability: \"nonpayable\", inputs: [{name: \"id\", type: \"bytes32\"}, {name: \"token\", type: \"address\"}, {name: \"receiver\", type: \"address\"}, {name: \"amount\", type: \"uint256\"}], outputs: []},\n] as const;\n\nexport interface EvmDeposit {\n to: string;\n data: `0x${string}`;\n value: bigint;\n chainId: number;\n /** ERC-20 input: the spender to approve for exactly the input — the Depository. */\n approvalAddress?: string;\n receiver: string;\n gasLimit: bigint | null;\n}\n\n/** The swap id as the Depository carries it: the sequence number, big-endian in 32 bytes. */\nexport function depositId(sequence: bigint): `0x${string}` {\n return pad(toHex(sequence), {size: 32});\n}\n\n/**\n * The Depository call, rebuilt here from the request, the swap's sequence number and a pinned receiver, and required\n * to equal Layerswap's byte for byte; the target and the approval spender are the pinned Depository.\n */\nexport function checkEvmDeposit(request: LayerswapRequest, swap: LayerswapSwapRecord, a: LayerswapAction): EvmDeposit {\n commonAction(request, a);\n const chainId = evmChainId(request.sourceChain);\n if (chainId === null) fail(\"evm-chain\", `${request.sourceChain} is not an EVM chain`, \"vault_mismatch\");\n if (a.type !== \"transfer\") fail(\"evm-action\", \"an EVM deposit must be the Depository call\", \"unsupported_pair\");\n if (a.toAddress.toLowerCase() !== LAYERSWAP_DEPOSITORY) fail(\"evm-target\", `the deposit calls ${clipName(a.toAddress)}, not the pinned Depository`, \"policy_refused\");\n const data = a.callData;\n if (!data || !/^0x[0-9a-fA-F]+$/.test(data)) fail(\"evm-calldata\", \"the deposit carries no calldata\", \"upstream_unavailable\");\n let decoded: {functionName: string; args: readonly unknown[]};\n try {\n decoded = decodeFunctionData({abi: DEPOSITORY_ABI, data: data as `0x${string}`}) as never;\n } catch {\n return fail(\"evm-calldata\", \"the deposit is not a Depository deposit call\", \"policy_refused\");\n }\n const receiver = String(decoded.args[decoded.functionName === \"depositNative\" ? 1 : 2] ?? \"\").toLowerCase();\n if (!LAYERSWAP_RECEIVERS.includes(receiver)) fail(\"evm-receiver\", `the deposit forwards to ${clipName(receiver)}, not a pinned Layerswap receiver`, \"policy_refused\");\n const id = depositId(swap.sequence);\n const native = request.sourceContract === null;\n const expected = native\n ? encodeFunctionData({abi: DEPOSITORY_ABI, functionName: \"depositNative\", args: [id, receiver as `0x${string}`]})\n : encodeFunctionData({abi: DEPOSITORY_ABI, functionName: \"depositERC20\", args: [id, request.sourceContract as `0x${string}`, receiver as `0x${string}`, request.amount]});\n if (data.toLowerCase() !== expected.toLowerCase()) {\n fail(\"evm-calldata\", native ? \"the deposit is not depositNative for this swap\" : \"the deposit is not depositERC20 of exactly the input for this swap\", \"policy_refused\");\n }\n const value = a.amountInBaseUnits ?? 0n;\n if (native ? value !== request.amount : value !== 0n) fail(\"evm-value\", native ? `the deposit sends ${value}, not the input ${request.amount}` : \"an ERC-20 deposit must not attach native value\", \"policy_refused\");\n return {\n to: LAYERSWAP_DEPOSITORY,\n data: expected,\n value: native ? request.amount : 0n,\n chainId: chainId!,\n ...(native ? {} : {approvalAddress: LAYERSWAP_DEPOSITORY}),\n receiver,\n gasLimit: a.gasLimit,\n };\n}\n\n// ── TON: transfer / jetton transfer with the swap's comment ────────────────\n\nexport interface MemoDeposit {\n to: string;\n value: bigint;\n memo?: string;\n}\n\nexport function checkTonDeposit(request: LayerswapRequest, swap: LayerswapSwapRecord, a: LayerswapAction): MemoDeposit {\n commonAction(request, a);\n if (a.type !== \"transfer\") fail(\"ton-action\", \"a TON deposit must be a transfer with the swap's comment\", \"unsupported_pair\");\n let payload: {amount?: unknown; asset?: unknown; comment?: unknown};\n try {\n payload = JSON.parse(a.callData ?? \"\") as typeof payload;\n } catch {\n return fail(\"ton-payload\", \"the TON deposit carries no comment payload\", \"upstream_unavailable\");\n }\n const comment = typeof payload?.comment === \"string\" ? payload.comment : \"\";\n // The comment is how Layerswap's shared address tells deposits apart: it must name THIS swap (its sequence number).\n if (comment !== swap.sequence.toString(10)) fail(\"ton-comment\", \"the TON deposit comment does not name this swap\", \"policy_refused\");\n if (request.sourceContract === null) {\n if (a.amountInBaseUnits !== request.amount) fail(\"ton-amount\", `the deposit sends ${a.amountInBaseUnits ?? \"nothing\"}, not the input ${request.amount}`, \"policy_refused\");\n } else if (baseUnits(payload.amount) !== request.amount) {\n fail(\"ton-amount\", \"the jetton transfer amount is not the input\", \"policy_refused\");\n }\n if (!addressKey(request.sourceChain, a.toAddress)) fail(\"ton-target\", \"the TON deposit address is not a TON address\", \"upstream_unavailable\");\n return {to: a.toAddress, value: request.amount, memo: comment};\n}\n\n// ── Tron: TRC-20 / TRX transfer with the memo in raw_data.data ─────────────\n\nconst TRON_ADDRESS = /^T[1-9A-HJ-NP-Za-km-z]{33}$/;\n\nexport function checkTronDeposit(request: LayerswapRequest, swap: LayerswapSwapRecord, a: LayerswapAction): MemoDeposit {\n commonAction(request, a);\n if (a.type !== \"transfer\") fail(\"tron-action\", \"a Tron deposit must be a transfer with the swap's memo\", \"unsupported_pair\");\n if (!TRON_ADDRESS.test(a.toAddress)) fail(\"tron-target\", \"the Tron deposit address is not a Tron address\", \"upstream_unavailable\");\n const memo = a.callData ?? \"\";\n if (memo !== swap.sequence.toString(10)) fail(\"tron-memo\", \"the Tron deposit memo does not name this swap\", \"policy_refused\");\n // The action's base-unit amount is the transfer's: the token amount for TRC-20, the TRX value otherwise.\n if (a.amountInBaseUnits !== request.amount) fail(\"tron-amount\", `the deposit sends ${a.amountInBaseUnits ?? \"nothing\"}, not the input ${request.amount}`, \"policy_refused\");\n return {to: a.toAddress, value: request.amount, memo};\n}\n\n// ── Bitcoin: a deposit address minted for the swap ─────────────────────────\n\nconst BTC_ADDRESS = /^(?:bc1[02-9ac-hj-np-z]{11,87}|[13][1-9A-HJ-NP-Za-km-z]{25,34})$/;\n\nexport function checkBitcoinDeposit(request: LayerswapRequest, a: LayerswapAction): MemoDeposit {\n commonAction(request, a);\n if (a.type !== \"manual_transfer\") fail(\"btc-action\", \"a Bitcoin deposit must go to the swap's deposit address\", \"unsupported_pair\");\n if (a.callData !== null) fail(\"btc-action\", \"the Bitcoin deposit asks for a memo output, which this account does not write\", \"unsupported_pair\");\n if (!BTC_ADDRESS.test(a.toAddress)) fail(\"btc-target\", \"the deposit address is not a Bitcoin mainnet address\", \"upstream_unavailable\");\n if (a.amountInBaseUnits !== request.amount) fail(\"btc-amount\", `the deposit asks for ${a.amountInBaseUnits ?? \"nothing\"} sat, not the input ${request.amount}`, \"policy_refused\");\n return {to: a.toAddress, value: request.amount};\n}\n\n// ── Solana: Layerswap's serialized legacy transfer, read instruction by instruction ──\n\nconst B58 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\nexport function base58Decode(text: string): Uint8Array | null {\n if (!/^[1-9A-HJ-NP-Za-km-z]{1,64}$/.test(text)) return null;\n let n = 0n;\n for (const ch of text) n = n * 58n + BigInt(B58.indexOf(ch));\n const bytes: number[] = [];\n while (n > 0n) { bytes.unshift(Number(n & 0xffn)); n >>= 8n; }\n for (const ch of text) { if (ch !== \"1\") break; bytes.unshift(0); }\n return Uint8Array.from(bytes);\n}\n\nexport function base58Encode(bytes: Uint8Array): string {\n let n = 0n;\n for (const b of bytes) n = (n << 8n) | BigInt(b);\n let out = \"\";\n while (n > 0n) { out = B58[Number(n % 58n)] + out; n /= 58n; }\n for (const b of bytes) { if (b !== 0) break; out = `1${out}`; }\n return out;\n}\n\n/** Compute a deposit may ask for: a transfer, a memo and one account creation run far below this. */\nexport const SOLANA_MAX_COMPUTE_UNITS = 400_000;\n/** Priority fee cap, micro-lamports per compute unit: 400 000 × 5 000 000 = 0.002 SOL at most. */\nexport const SOLANA_MAX_MICROLAMPORTS = 5_000_000n;\n\nexport const SOLANA_PROGRAMS = Object.freeze({\n system: \"11111111111111111111111111111111\",\n token: \"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA\",\n token2022: \"TokenzQdBNbLqP5VEhdkAS6EPFLC1PazqiGFRk8ZVvo\",\n ata: \"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL\",\n computeBudget: \"ComputeBudget111111111111111111111111111111\",\n memoV1: \"Memo1UhkJRfHyvLMcVucJwxXeuD728EqVDDwQDxFMNo\",\n memoV2: \"MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr\",\n});\n/** The same message behind one empty signature slot (count 1, 64 zero bytes), as base64 wire. */\nexport function withSignatureSlot(bytes: Uint8Array, messageOffset: number): string {\n const message = bytes.subarray(messageOffset);\n const out = new Uint8Array(1 + 64 + message.length);\n out[0] = 1;\n out.set(message, 65);\n return base64Encode(out);\n}\n\nconst B64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n/** Standard base64 with padding, without Buffer or btoa (Hermes). */\nexport function base64Encode(bytes: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < bytes.length; i += 3) {\n const b0 = bytes[i]!, b1 = bytes[i + 1], b2 = bytes[i + 2];\n const n = (b0 << 16) | ((b1 ?? 0) << 8) | (b2 ?? 0);\n out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + (b1 === undefined ? \"=\" : B64[(n >> 6) & 63]!) + (b2 === undefined ? \"=\" : B64[n & 63]!);\n }\n return out;\n}\n\n/** Listed (as an account, never called) by the associated-token-account Create instruction Layerswap builds. */\nexport const SOLANA_RENT_SYSVAR = \"SysvarRent111111111111111111111111111111111\";\n\ninterface LegacyInstruction {program: string; accounts: string[]; data: Uint8Array}\nexport interface LegacyMessage {\n numSignatures: number;\n requiredSignatures: number;\n /** Where the message starts: after the signature count and the signature slots. */\n messageOffset: number;\n keys: string[];\n instructions: LegacyInstruction[];\n}\n\n/** A Solana wire transaction with a LEGACY message (what Layerswap returns), parsed; null for anything else. */\nexport function parseLegacyTransaction(bytes: Uint8Array): LegacyMessage | null {\n let o = 0;\n const u8 = (): number => { if (o >= bytes.length) throw new Error(\"short\"); return bytes[o++]!; };\n const cu16 = (): number => { let v = 0; for (let s = 0; s < 21; s += 7) { const b = u8(); v |= (b & 0x7f) << s; if (!(b & 0x80)) return v; } throw new Error(\"bad length\"); };\n const take = (n: number): Uint8Array => { if (n < 0 || o + n > bytes.length) throw new Error(\"short\"); const out = bytes.subarray(o, o + n); o += n; return out; };\n try {\n const numSignatures = cu16();\n if (numSignatures > 8) return null;\n take(64 * numSignatures);\n const messageOffset = o;\n const first = u8();\n if (first & 0x80) return null; // a versioned (v0) message\n const requiredSignatures = first;\n u8(); u8();\n const numKeys = cu16();\n if (numKeys === 0 || numKeys > 64) return null;\n const keys: string[] = [];\n for (let i = 0; i < numKeys; i++) keys.push(base58Encode(take(32)));\n take(32); // recent blockhash\n const numIx = cu16();\n if (numIx > 16) return null;\n const instructions: LegacyInstruction[] = [];\n for (let i = 0; i < numIx; i++) {\n const p = u8();\n const na = cu16();\n const idx = Array.from(take(na));\n const data = take(cu16());\n if (p >= keys.length || idx.some((k) => k >= keys.length)) return null;\n instructions.push({program: keys[p]!, accounts: idx.map((k) => keys[k]!), data: Uint8Array.from(data)});\n }\n if (o !== bytes.length) return null;\n return {numSignatures, requiredSignatures, messageOffset, keys, instructions};\n } catch {\n return null;\n }\n}\n\n/** The associated token account of `owner` for `mint` under `tokenProgram` (the PDA, first off-curve bump). */\nexport function associatedTokenAccount(owner: string, mint: string, tokenProgram: string): string | null {\n const o = base58Decode(owner), m = base58Decode(mint), t = base58Decode(tokenProgram), ata = base58Decode(SOLANA_PROGRAMS.ata);\n if (!o || !m || !t || !ata || o.length !== 32 || m.length !== 32 || t.length !== 32) return null;\n const marker = new TextEncoder().encode(\"ProgramDerivedAddress\");\n for (let bump = 255; bump >= 0; bump--) {\n const h = sha256(Uint8Array.from([...o, ...t, ...m, bump, ...ata, ...marker]));\n let onCurve = true;\n try { ed25519.Point.fromBytes(h); } catch { onCurve = false; }\n if (!onCurve) return base58Encode(h);\n }\n return null;\n}\n\nconst u64le = (d: Uint8Array, at: number): bigint => {\n let v = 0n;\n for (let i = 7; i >= 0; i--) v = (v << 8n) | BigInt(d[at + i]!);\n return v;\n};\n\nexport interface SolanaDeposit {\n serializedTx: string;\n /** The deposit address the transfer pays (its owner, for a token transfer). */\n depositTo: string;\n /** The SOL the transaction may move besides fees: the input for a SOL source, nothing for a token. */\n value: bigint;\n}\n\n/**\n * Layerswap's Solana deposit, read instruction by instruction: a legacy message this account alone signs; only the\n * system, token, associated-token, compute-budget and memo programs; exactly one top-level memo, the swap's sequence\n * number; exactly one transfer of exactly the input, from this account, to the deposit address (SOL) or its\n * associated token account (SPL, `transferChecked` with the source mint and decimals); an account creation only for\n * that associated token account. The wallet then simulates it and holds the balances to the input.\n */\nexport function checkSolanaDeposit(request: LayerswapRequest, swap: LayerswapSwapRecord, a: LayerswapAction): SolanaDeposit {\n commonAction(request, a);\n if (a.type !== \"transfer\") fail(\"solana-action\", \"a Solana deposit must be the prepared transfer\", \"unsupported_pair\");\n const bytes = a.callData ? base64Bytes(a.callData) : null;\n const tx = bytes ? parseLegacyTransaction(bytes) : null;\n if (!tx) fail(\"solana-tx\", \"the Solana deposit is not a legacy transaction\", \"policy_refused\");\n const t = tx!;\n if (t.requiredSignatures !== 1 || t.keys[0] !== request.sender) fail(\"solana-signer\", \"the Solana deposit is not signed by this account alone\", \"policy_refused\");\n // Layerswap sends the message with no signature slots (seen 2026-12-01); the wallet's decoder wants one per required\n // signer. Only an empty or a single slot is taken; the message bytes are passed on unchanged either way.\n if (t.numSignatures !== 0 && t.numSignatures !== 1) fail(\"solana-signer\", \"the Solana deposit carries signature slots for other signers\", \"policy_refused\");\n const allowed = new Set(Object.values(SOLANA_PROGRAMS));\n const foreign = t.instructions.find((ix) => !allowed.has(ix.program as never));\n if (foreign) fail(\"solana-program\", `the Solana deposit calls ${clipName(foreign.program)}`, \"policy_refused\");\n const memos = t.instructions.filter((ix) => ix.program === SOLANA_PROGRAMS.memoV1 || ix.program === SOLANA_PROGRAMS.memoV2);\n const want = new TextEncoder().encode(swap.sequence.toString(10));\n const memo = memos[0]?.data;\n if (memos.length !== 1 || !memo || memo.length !== want.length || memo.some((b, i) => b !== want[i])) {\n fail(\"solana-memo\", \"the Solana deposit does not carry exactly this swap's memo\", \"policy_refused\");\n }\n const native = request.sourceContract === null;\n let transfers = 0;\n let limits = 0, prices = 0, creates = 0;\n let createdUnder: string | null = null, transferredUnder: string | null = null;\n for (const ix of t.instructions) {\n if (ix.program === SOLANA_PROGRAMS.memoV1 || ix.program === SOLANA_PROGRAMS.memoV2) continue;\n if (ix.program === SOLANA_PROGRAMS.computeBudget) {\n // Only SetComputeUnitLimit (2, u32) and SetComputeUnitPrice (3, u64 micro-lamports), once each and bounded: the\n // API knows the sender, so an unbounded price would be a fee drain the balance guard does not count.\n if (ix.data.length === 5 && ix.data[0] === 2) {\n const units = ix.data[1]! | (ix.data[2]! << 8) | (ix.data[3]! << 16) | (ix.data[4]! * 2 ** 24);\n if (++limits > 1 || units > SOLANA_MAX_COMPUTE_UNITS) fail(\"solana-compute\", \"the Solana deposit sets a compute limit above a transfer's\", \"policy_refused\");\n } else if (ix.data.length === 9 && ix.data[0] === 3) {\n if (++prices > 1 || u64le(ix.data, 1) > SOLANA_MAX_MICROLAMPORTS) fail(\"solana-compute\", \"the Solana deposit sets a priority fee above the cap\", \"policy_refused\");\n } else {\n fail(\"solana-compute\", \"the Solana deposit sets an unexpected compute-budget instruction\", \"policy_refused\");\n }\n continue;\n }\n if (ix.program === SOLANA_PROGRAMS.system) {\n // SystemProgram::Transfer (2): [from, to], lamports u64.\n if (!native || ix.data.length !== 12 || ix.data[0] !== 2 || ix.data[1] !== 0 || ix.data[2] !== 0 || ix.data[3] !== 0) fail(\"solana-system\", \"the Solana deposit runs an unexpected system instruction\", \"policy_refused\");\n if (ix.accounts[0] !== request.sender || ix.accounts[1] !== a.toAddress) fail(\"solana-transfer\", \"the SOL transfer is not from this account to the deposit address\", \"policy_refused\");\n if (u64le(ix.data, 4) !== request.amount) fail(\"solana-amount\", \"the SOL transfer is not exactly the input\", \"policy_refused\");\n transfers++;\n continue;\n }\n if (ix.program === SOLANA_PROGRAMS.ata) {\n // CreateIdempotent (1) / Create (0) of an associated token account for the source mint, paid by this account:\n // this account's own (what Layerswap's message does, seen 2026-12-01) or the deposit address's.\n if (native || !(ix.data.length === 0 || (ix.data.length === 1 && (ix.data[0] === 0 || ix.data[0] === 1)))) fail(\"solana-ata\", \"the Solana deposit runs an unexpected account instruction\", \"policy_refused\");\n // Accounts: [payer, associated account, owner, mint, system program, token program(, rent sysvar)] — once,\n // under the token program the transfer runs (checked below), never another program that would own the rent.\n const program = ix.accounts[5];\n if (++creates > 1 || (ix.accounts.length !== 6 && !(ix.accounts.length === 7 && ix.accounts[6] === SOLANA_RENT_SYSVAR)) || ix.accounts[4] !== SOLANA_PROGRAMS.system || (program !== SOLANA_PROGRAMS.token && program !== SOLANA_PROGRAMS.token2022)) {\n fail(\"solana-ata\", \"the Solana deposit runs an unexpected account instruction\", \"policy_refused\");\n }\n const owner = ix.accounts[2];\n const created = owner === request.sender || owner === a.toAddress ? associatedTokenAccount(owner, request.sourceContract!, program!) : null;\n if (ix.accounts[0] !== request.sender || ix.accounts[3] !== request.sourceContract || !created || ix.accounts[1] !== created) {\n fail(\"solana-ata\", \"the Solana deposit creates an account that is neither this account's nor the deposit address's\", \"policy_refused\");\n }\n createdUnder = program!;\n continue;\n }\n // Token / Token-2022: Transfer (3) [source, destination, owner] amount u64, or TransferChecked (12)\n // [source, mint, destination, owner] amount u64 + decimals u8. Source and destination are the associated token\n // accounts of this account and of the deposit address for the source mint, so the mint is fixed either way.\n if (native) fail(\"solana-token\", \"a SOL deposit runs a token instruction\", \"policy_refused\");\n const checked = ix.data.length === 10 && ix.data[0] === 12;\n const plain = ix.data.length === 9 && ix.data[0] === 3;\n if (!checked && !plain) fail(\"solana-token\", \"the Solana deposit runs an unexpected token instruction\", \"policy_refused\");\n const [src, dst, owner] = checked ? [ix.accounts[0], ix.accounts[2], ix.accounts[3]] : [ix.accounts[0], ix.accounts[1], ix.accounts[2]];\n if (checked && (ix.accounts[1] !== request.sourceContract || ix.data[9] !== request.sourceDecimals)) fail(\"solana-token\", \"the token transfer is not of the source mint\", \"policy_refused\");\n if (owner !== request.sender) fail(\"solana-token\", \"the token transfer is not authorized by this account\", \"policy_refused\");\n if (u64le(ix.data, 1) !== request.amount) fail(\"solana-amount\", \"the token transfer is not exactly the input\", \"policy_refused\");\n const own = associatedTokenAccount(request.sender, request.sourceContract!, ix.program);\n if (!own || src !== own) fail(\"solana-token\", \"the token transfer does not spend this account's own token account\", \"policy_refused\");\n const theirs = associatedTokenAccount(a.toAddress, request.sourceContract!, ix.program);\n if (!theirs || dst !== theirs) fail(\"solana-transfer\", \"the token transfer does not pay the deposit address's token account\", \"policy_refused\");\n transferredUnder = ix.program;\n transfers++;\n }\n if (transfers !== 1) fail(\"solana-transfer\", \"the Solana deposit does not make exactly one transfer\", \"policy_refused\");\n if (createdUnder !== null && createdUnder !== transferredUnder) fail(\"solana-ata\", \"the Solana deposit creates the account under another token program than the transfer's\", \"policy_refused\");\n return {serializedTx: t.numSignatures === 1 ? a.callData! : withSignatureSlot(bytes!, t.messageOffset), depositTo: a.toAddress, value: native ? request.amount : 0n};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAkC;;;ACAlC,kBAAwB;AAYjB,IAAM,gBAAgB;AAYtB,IAAM,uBAAuB;AAQ7B,IAAM,sBAAyC,OAAO,OAAO;AAAA,EAClE;AAAA,EACA;AACF,CAAC;AAGM,IAAM,0BAA0B;AAChC,IAAM,yBAAyB;AAO/B,IAA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AE1D,gBAAM,KAAK,gBAAgB,IAAI,UAAU,IAAI,YAAY,EAAE,MAAM,MAAM;AAAA,UAAC,CAAC;AAAA,QAC3E;AACA,cAAM,QAAQ,OAAO,UAAU,eAAe,KAAK,sBAAsB,MAAM,IAAI,qBAAqB,MAAM,IAAK;AACnH,cAAM,MAAM,MAAM,QAAQ,MAAM,YAAY,IAAK,KAAM,eAAkD,CAAC;AAC1G,cAAM,SAAS,IAAI,KAAK,CAAC,MAAM,GAAG,SAAS,YAAY,OAAO,EAAE,qBAAqB,YAAY,uBAAuB,KAAK,EAAE,gBAAgB,CAAC;AAChJ,cAAM,WAAW,WAAW,2BAA2B,WAAW,aAAa,WAAW;AAC1F,eAAO,EAAC,OAAO,GAAI,WAAW,EAAC,iBAAiB,KAAI,IAAI,CAAC,GAAI,GAAI,UAAU,eAAe,SAAS,EAAC,YAAY,OAAO,iBAA0B,IAAI,CAAC,EAAE;AAAA,MAC1J,QAAQ;AACN,eAAO,EAAC,OAAO,UAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;;;AF9bO,IAAM,yBAAN,cAAqC,kCAAoB;AAAA,EAC3C;AAAA,EACnB,YAAY,SAAmC,QAA8B;AAC3E,UAAM,SAAS,MAAM;AACrB,SAAK,WAAW,kBAAkB,MAAM;AAAA,EAC1C;AAAA,EACmB,eAAe,OAAwB;AACxD,WAAO,UAAa,cAAc,KAAK;AAAA,EACzC;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,UAAa,SAAS,WAAW,OAAO;AAAA,EACjD;AACF;","names":["import_util","import_errors","import_util","import_util","import_errors","a","owner","UUID","a","q"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import * as _anywalletkit_protocol_swap2_core_types from '@anywalletkit/protocol-swap2-core/types';
|
|
2
|
+
import { SingleProviderSwap2 } from '@anywalletkit/protocol-swap2-core/swap2/single';
|
|
3
|
+
import { Swap2EngineConfig, Swap2Account } from '@anywalletkit/protocol-swap2-core/swap2/base';
|
|
4
|
+
import { LayerswapProviderConfig } from './provider.cjs';
|
|
5
|
+
|
|
6
|
+
interface LayerswapSwap2Config extends Swap2EngineConfig, LayerswapProviderConfig {
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Standalone Layerswap swap2: from EVM (through the pinned Depository), Solana, TON, Tron and Bitcoin to any chain
|
|
10
|
+
* Layerswap serves; every swap read back and its deposit checked on the device before it is signed.
|
|
11
|
+
*/
|
|
12
|
+
declare class LayerswapSwap2Protocol extends SingleProviderSwap2 {
|
|
13
|
+
protected readonly provider: _anywalletkit_protocol_swap2_core_types.CrossChainProvider;
|
|
14
|
+
constructor(account: Swap2Account | undefined, config: LayerswapSwap2Config);
|
|
15
|
+
protected chainSupported(caip2: string): boolean;
|
|
16
|
+
protected pairSupported(fromChain: string, toChain: string): boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export { type LayerswapSwap2Config, LayerswapSwap2Protocol };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import * as _anywalletkit_protocol_swap2_core_types from '@anywalletkit/protocol-swap2-core/types';
|
|
2
|
+
import { SingleProviderSwap2 } from '@anywalletkit/protocol-swap2-core/swap2/single';
|
|
3
|
+
import { Swap2EngineConfig, Swap2Account } from '@anywalletkit/protocol-swap2-core/swap2/base';
|
|
4
|
+
import { LayerswapProviderConfig } from './provider.js';
|
|
5
|
+
|
|
6
|
+
interface LayerswapSwap2Config extends Swap2EngineConfig, LayerswapProviderConfig {
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Standalone Layerswap swap2: from EVM (through the pinned Depository), Solana, TON, Tron and Bitcoin to any chain
|
|
10
|
+
* Layerswap serves; every swap read back and its deposit checked on the device before it is signed.
|
|
11
|
+
*/
|
|
12
|
+
declare class LayerswapSwap2Protocol extends SingleProviderSwap2 {
|
|
13
|
+
protected readonly provider: _anywalletkit_protocol_swap2_core_types.CrossChainProvider;
|
|
14
|
+
constructor(account: Swap2Account | undefined, config: LayerswapSwap2Config);
|
|
15
|
+
protected chainSupported(caip2: string): boolean;
|
|
16
|
+
protected pairSupported(fromChain: string, toChain: string): boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export { type LayerswapSwap2Config, LayerswapSwap2Protocol };
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import {
|
|
2
|
+
LayerswapSwap2Protocol
|
|
3
|
+
} from "./chunk-KCAZCR4I.js";
|
|
4
|
+
import "./chunk-ZTFJO6AI.js";
|
|
5
|
+
import "./chunk-TEL62A5J.js";
|
|
6
|
+
import "./chunk-WEMNS3LY.js";
|
|
7
|
+
import "./chunk-ZKT24QPJ.js";
|
|
8
|
+
export {
|
|
9
|
+
LayerswapSwap2Protocol
|
|
10
|
+
};
|
|
11
|
+
//# sourceMappingURL=protocol.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|