@anywalletkit/protocol-swap2-omniston 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/validators/index.ts","../src/validators/evm-output.ts","../src/validators/evm-input.ts","../src/validators/ton.ts","../src/validators/settlement.ts"],"sourcesContent":["export * from \"./evm-output.js\";\nexport * from \"./evm-input.js\";\nexport * from \"./ton.js\";\nexport * from \"./settlement.js\";\n","import {\n decodeAbiParameters,\n decodeFunctionData,\n decodeFunctionResult,\n encodeFunctionData,\n getAddress,\n isAddress,\n keccak256,\n stringToHex,\n type Hex,\n} from \"viem\";\nimport { bigintToNumber } from '@anywalletkit/core'\n\nconst ESCROW_FACTORY_ABI = [\n {\n type: \"function\",\n name: \"createDstEscrow\",\n stateMutability: \"payable\",\n inputs: [\n {\n name: \"dstImmutables\",\n type: \"tuple\",\n components: [\n {name: \"orderHash\", type: \"bytes32\"},\n {name: \"hashlock\", type: \"bytes32\"},\n {name: \"maker\", type: \"uint256\"},\n {name: \"taker\", type: \"uint256\"},\n {name: \"token\", type: \"uint256\"},\n {name: \"amount\", type: \"uint256\"},\n {name: \"safetyDeposit\", type: \"uint256\"},\n {name: \"timelocks\", type: \"uint256\"},\n {name: \"parameters\", type: \"bytes\"},\n ],\n },\n {name: \"srcCancellationTimestamp\", type: \"uint256\"},\n ],\n outputs: [],\n },\n {\n type: \"function\",\n name: \"addressOfEscrowDst\",\n stateMutability: \"view\",\n inputs: [\n {\n name: \"immutables\",\n type: \"tuple\",\n components: [\n {name: \"orderHash\", type: \"bytes32\"},\n {name: \"hashlock\", type: \"bytes32\"},\n {name: \"maker\", type: \"uint256\"},\n {name: \"taker\", type: \"uint256\"},\n {name: \"token\", type: \"uint256\"},\n {name: \"amount\", type: \"uint256\"},\n {name: \"safetyDeposit\", type: \"uint256\"},\n {name: \"timelocks\", type: \"uint256\"},\n {name: \"parameters\", type: \"bytes\"},\n ],\n },\n ],\n outputs: [{name: \"escrow\", type: \"address\"}],\n },\n] as const;\n\nconst FACTORY_ABI = [{\n type: \"function\", name: \"FACTORY\", stateMutability: \"view\", inputs: [], outputs: [{type: \"address\"}],\n}] as const;\nconst BALANCE_OF_ABI = [{\n type: \"function\", name: \"balanceOf\", stateMutability: \"view\", inputs: [{name: \"account\", type: \"address\"}], outputs: [{type: \"uint256\"}],\n}] as const;\n\n// Address is a uint256 user-defined value type in the 1inch factory ABI.\nconst DST_ESCROW_CREATED_TOPIC = keccak256(stringToHex(\"DstEscrowCreated(address,bytes32,uint256)\"));\nconst UINT32_MASK = (1n << 32n) - 1n;\nconst DEPLOYED_AT_OFFSET = 224n;\nconst DEPLOYED_AT_MASK = UINT32_MASK << DEPLOYED_AT_OFFSET;\nconst ADDRESS_MASK = (1n << 160n) - 1n;\n\n/** Destination timelock stages (seconds after deploy, words 4–6): dst\n * withdrawal, dst public withdrawal, dst cancellation. Every Omniston\n * destination escrow sampled on Base, Arbitrum, BNB and Polygon (39/39,\n * 2026-10-22) carries 1/120/180 — the dst half of `SRC_STAGES` in\n * evm-input.ts and of `POSITION_STAGES` in ton.ts. Words 0–3 (source stages)\n * differ by source chain (0/0/0/0 for TON-source, 1/120/240/300 for\n * EVM-source) and are not this escrow's to enforce. */\nconst DST_STAGES = [1n, 120n, 180n] as const;\nconst DST_STAGE_WORD = 4;\nconst DST_CANCELLATION_STAGE = 2;\n/** Disclosure is refused this close to the destination cancellation stage: past\n * it the resolver can cancel this escrow and still withdraw the source leg\n * with the disclosed secret. Same margin as evm-input.ts and ton.ts. */\nconst DISCLOSURE_MARGIN_SECONDS = 45n;\n/** `immutables.parameters` of the Omniston EscrowDst: abi(uint256 protocolFee,\n * uint256 integratorFee, uint256 protocolFeeRecipient, uint256\n * integratorFeeRecipient) — paid out of `amount` on withdrawal. */\nconst FEE_PARAMETERS = [{type: \"uint256\"}, {type: \"uint256\"}, {type: \"uint256\"}, {type: \"uint256\"}] as const;\nconst FEE_PARAMETERS_HEX_LENGTH = 2 + 128 * 2;\n\n/** Public fallback endpoints only; deployments pass their own via `rpcUrls`. */\nconst DEFAULT_RPC_URLS: Readonly<Record<string, readonly string[]>> = {\n \"eip155:1\": [\"https://ethereum-rpc.publicnode.com\"],\n \"eip155:56\": [\"https://bsc-rpc.publicnode.com\"],\n \"eip155:137\": [\"https://polygon-bor-rpc.publicnode.com\"],\n \"eip155:4663\": [\"https://rpc.mainnet.chain.robinhood.com\"],\n \"eip155:8453\": [\"https://base-rpc.publicnode.com\"],\n \"eip155:42161\": [\"https://arbitrum-one-rpc.publicnode.com\"],\n \"eip155:43114\": [\"https://avalanche-c-chain-rpc.publicnode.com\"],\n \"eip155:196\": [\"https://rpc.xlayer.tech\"],\n \"eip155:999\": [\"https://rpc.hyperliquid.xyz/evm\"],\n \"eip155:9745\": [\"https://rpc.plasma.to\"],\n};\n\n/** How far back (blocks) a factory event is searched, per chain — shared with the EVM input validator. */\nexport const OMNISTON_EVM_LOOKBACK_BLOCKS: Readonly<Record<string, bigint>> = {\n \"eip155:1\": 3_000n,\n \"eip155:56\": 40_000n,\n \"eip155:137\": 20_000n,\n \"eip155:4663\": 100_000n,\n \"eip155:8453\": 20_000n,\n \"eip155:42161\": 100_000n,\n \"eip155:43114\": 20_000n,\n // ~1 s blocks (measured 2026-10-20): ~11 h, past the 6 h quote horizon.\n \"eip155:196\": 40_000n,\n \"eip155:999\": 40_000n,\n \"eip155:9745\": 40_000n,\n};\n\n/** Confirmations before a factory event counts as final, per chain. */\nexport const OMNISTON_EVM_MIN_CONFIRMATIONS: Readonly<Record<string, bigint>> = {\n \"eip155:1\": 2n,\n \"eip155:56\": 5n,\n \"eip155:137\": 20n,\n \"eip155:4663\": 20n,\n \"eip155:8453\": 20n,\n \"eip155:42161\": 20n,\n \"eip155:43114\": 5n,\n \"eip155:196\": 20n, // sequencer rollup\n \"eip155:999\": 5n, // HyperBFT, fast finality\n \"eip155:9745\": 5n, // PlasmaBFT, fast finality\n};\n\nexport type OmnistonRpcRequest = (chain: string, method: string, params: unknown[]) => Promise<unknown>;\n/** CAIP-2 chain → JSON-RPC URLs, tried in order before the public fallbacks. */\nexport type OmnistonRpcUrls = Readonly<Record<string, readonly string[]>>;\ntype RpcRequest = OmnistonRpcRequest;\n\nexport interface EvmOutputValidationInput {\n chain: string;\n positionAddress: string;\n factoryAddress: string;\n quoteTimestamp: number;\n executionIndex: number;\n recipientAddress: string;\n outputTokenAddress: string;\n inputUnits: string;\n outputUnits: string;\n resolverSendsUnits: string;\n srcHtlcSecurityDepositUnits: string;\n dstSecurityDepositUnits: string;\n protocolFeeUnits: string;\n integratorFeeUnits: string;\n integratorAddress?: string;\n /** The quote's `settlementData.protocolFeeRecipientAddress` (destination\n * chain): the only address the escrow may pay a non-zero protocol fee to. */\n protocolFeeRecipientAddress?: string;\n secretHash: Uint8Array;\n}\n\n/** Diagnostics hook: every refusal names its check and the numbers it compared (never a secret). */\nexport type OmnistonEvmOutputRefusal = (reason: string, details?: Record<string, unknown>) => void;\n\ninterface RpcLog {\n data: Hex;\n transactionHash: Hex;\n blockNumber: Hex;\n}\n\ninterface RpcTransaction {\n to: string;\n input: Hex;\n value: Hex;\n}\n\nfunction quantity(value: bigint): Hex {\n return `0x${value.toString(16)}`;\n}\n\nfunction uintAddress(value: bigint): string {\n return getAddress(`0x${(value & ADDRESS_MASK).toString(16).padStart(40, \"0\")}`);\n}\n\nfunction bytesHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction stage(timelocks: bigint, index: number): bigint {\n return (timelocks >> BigInt(index * 32)) & UINT32_MASK;\n}\n\n/** Fee split of a destination escrow, or null when `parameters` is not the 4-word layout. */\nfunction decodeFeeParameters(parameters: Hex): {protocolFee: bigint; integratorFee: bigint; protocolFeeRecipient: bigint; integratorFeeRecipient: bigint} | null {\n if (parameters.length !== FEE_PARAMETERS_HEX_LENGTH) return null;\n try {\n const [protocolFee, integratorFee, protocolFeeRecipient, integratorFeeRecipient] = decodeAbiParameters(FEE_PARAMETERS, parameters);\n return {protocolFee, integratorFee, protocolFeeRecipient, integratorFeeRecipient};\n } catch {\n return null;\n }\n}\n\n/** JSON-RPC over the caller's endpoints (`rpcUrls`) with public failover (reads only). */\nexport async function omnistonEvmRpcRequest(chain: string, method: string, params: unknown[], rpcUrls?: OmnistonRpcUrls): Promise<unknown> {\n const urls = [...(rpcUrls?.[chain] ?? []), ...(DEFAULT_RPC_URLS[chain] ?? [])].filter((url): url is string => !!url);\n if (!urls.length) throw new Error(`omniston: no RPC configured for ${chain}`);\n let lastError: unknown;\n for (const url of urls) {\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\"content-type\": \"application/json\"},\n body: JSON.stringify({jsonrpc: \"2.0\", id: 1, method, params}),\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n const body = await response.json() as {result?: unknown; error?: unknown};\n if (body.error !== undefined || body.result === undefined) throw new Error(\"invalid JSON-RPC response\");\n return body.result;\n } catch (error) {\n lastError = error;\n }\n }\n throw lastError instanceof Error ? lastError : new Error(`omniston: RPC failed for ${chain}`);\n}\n\nasync function ethCall(request: RpcRequest, chain: string, to: string, data: Hex): Promise<Hex> {\n return await request(chain, \"eth_call\", [{to, data}, \"latest\"]) as Hex;\n}\n\n/**\n * Builds the mandatory disclosure verifier for TON-source Omniston orders.\n * The feed supplies an address only; this routine proves the actual finalized\n * factory transaction and deterministic escrow before the secret can leave.\n */\n\n/**\n * Find the escrow immutables inside a resolver's calldata.\n *\n * The tuple is ABI-encoded wherever it is passed, so anchoring on the 32-byte\n * hashlock (word 1 of the tuple) yields the static words at fixed offsets and\n * the `parameters` bytes through the tuple's own offset word. What is found\n * here is only a CANDIDATE: the caller proves it by deriving the escrow address\n * from it through the trusted factory (CREATE2 over the immutables), so a\n * decoy tuple planted in the calldata cannot pass.\n */\nfunction locateImmutables(input: Hex, secretHash: Hex): {\n orderHash: Hex;\n hashlock: Hex;\n maker: bigint;\n taker: bigint;\n token: bigint;\n amount: bigint;\n safetyDeposit: bigint;\n timelocks: bigint;\n parameters: Hex;\n} | null {\n const data = input.slice(2).toLowerCase();\n const needle = secretHash.slice(2).toLowerCase();\n const at = data.indexOf(needle);\n // Must be word-aligned, preceded by orderHash and followed by seven words.\n if (at < 72 || (at - 8) % 64 !== 0 || data.length < at + 64 * 8) return null;\n const start = at - 64;\n const word = (i: number): bigint => BigInt(`0x${data.slice(at + 64 * i, at + 64 * (i + 1))}`);\n try {\n const offset = word(7);\n if (offset % 32n !== 0n || offset < 288n || offset > 4096n) return null;\n const lengthAt = start + bigintToNumber(offset) * 2; // offset ≤ 4096, checked above\n if (data.length < lengthAt + 64) return null;\n const length = BigInt(`0x${data.slice(lengthAt, lengthAt + 64)}`);\n if (length > 1024n || data.length < lengthAt + 64 + bigintToNumber(length) * 2) return null;\n return {\n orderHash: `0x${data.slice(start, at)}`,\n hashlock: `0x${needle}`,\n maker: word(1), taker: word(2), token: word(3), amount: word(4), safetyDeposit: word(5), timelocks: word(6),\n parameters: `0x${data.slice(lengthAt + 64, lengthAt + 64 + bigintToNumber(length) * 2)}`,\n };\n } catch {\n return null;\n }\n}\n\nexport function createOmnistonEvmOutputValidator(options: {request?: RpcRequest; rpcUrls?: OmnistonRpcUrls; now?: () => number; onRefusal?: OmnistonEvmOutputRefusal} = {}) {\n const refuse = (reason: string, details?: Record<string, unknown>): false => {\n try { options.onRefusal?.(reason, details); } catch { /* diagnostics never break validation */ }\n return false;\n };\n const request: RpcRequest = options.request ?? ((chain, method, params) => omnistonEvmRpcRequest(chain, method, params, options.rpcUrls));\n const now = options.now ?? Date.now;\n return async (input: EvmOutputValidationInput): Promise<boolean> => {\n try {\n if (\n !OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain] || input.executionIndex !== 0 ||\n !isAddress(input.positionAddress) || !isAddress(input.factoryAddress) ||\n !isAddress(input.recipientAddress) || !isAddress(input.outputTokenAddress) ||\n !Number.isInteger(input.quoteTimestamp) || input.quoteTimestamp * 1000 > now() + 120_000 ||\n now() - input.quoteTimestamp * 1000 > 6 * 60 * 60 * 1000\n ) return refuse(\"input-shape\");\n\n const position = getAddress(input.positionAddress);\n const factory = getAddress(input.factoryAddress);\n const recipient = getAddress(input.recipientAddress);\n const token = getAddress(input.outputTokenAddress);\n const secretHash = bytesHex(input.secretHash);\n const outputUnits = BigInt(input.outputUnits);\n const resolverSendsUnits = BigInt(input.resolverSendsUnits);\n const protocolFeeUnits = BigInt(input.protocolFeeUnits);\n const integratorFeeUnits = BigInt(input.integratorFeeUnits);\n const dstDeposit = BigInt(input.dstSecurityDepositUnits);\n if (\n BigInt(input.inputUnits) <= 0n || outputUnits <= 0n || dstDeposit <= 0n ||\n resolverSendsUnits !== outputUnits + protocolFeeUnits + integratorFeeUnits ||\n input.secretHash.length !== 32\n ) return refuse(\"quote-amounts\", {outputUnits: String(outputUnits), resolverSendsUnits: String(resolverSendsUnits), protocolFeeUnits: String(protocolFeeUnits), integratorFeeUnits: String(integratorFeeUnits)});\n if (protocolFeeUnits < 0n || integratorFeeUnits < 0n) return refuse(\"quote-amounts\", {protocolFeeUnits: String(protocolFeeUnits), integratorFeeUnits: String(integratorFeeUnits)});\n // The recipients a non-zero fee may go to come from the quote, never from\n // the escrow: a missing quote field is a refusal, not a skipped check.\n if (protocolFeeUnits > 0n && (!input.protocolFeeRecipientAddress || !isAddress(input.protocolFeeRecipientAddress))) {\n return refuse(\"quote-missing-protocol-fee-recipient\", {protocolFeeUnits: String(protocolFeeUnits)});\n }\n if (integratorFeeUnits > 0n && (!input.integratorAddress || !isAddress(input.integratorAddress))) {\n return refuse(\"quote-missing-integrator-address\", {integratorFeeUnits: String(integratorFeeUnits)});\n }\n\n const latest = BigInt(await request(input.chain, \"eth_blockNumber\", []) as string);\n const minConfirmations = OMNISTON_EVM_MIN_CONFIRMATIONS[input.chain] ?? 20n;\n const newestFinal = latest >= minConfirmations ? latest - minConfirmations : 0n;\n const oldest = newestFinal > OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain]!\n ? newestFinal - OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain]!\n : 0n;\n let matchingLog: RpcLog | undefined;\n for (let to = newestFinal; to >= oldest && !matchingLog;) {\n const from = to - oldest > 4_999n ? to - 4_999n : oldest;\n const logs = await request(input.chain, \"eth_getLogs\", [{\n address: factory,\n topics: [DST_ESCROW_CREATED_TOPIC],\n fromBlock: quantity(from),\n toBlock: quantity(to),\n }]) as RpcLog[];\n matchingLog = logs.find((log) => {\n try {\n const [escrow, hashlock] = decodeAbiParameters(\n [{type: \"address\"}, {type: \"bytes32\"}, {type: \"uint256\"}],\n log.data,\n );\n return getAddress(escrow) === position && hashlock.toLowerCase() === secretHash.toLowerCase();\n } catch {\n return false;\n }\n });\n if (from === oldest) break;\n to = from - 1n;\n }\n if (!matchingLog) return refuse(\"no-escrow-event\", {factory, lookback: String(OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain])});\n\n const [transaction, receipt, block, code] = await Promise.all([\n request(input.chain, \"eth_getTransactionByHash\", [matchingLog.transactionHash]) as Promise<RpcTransaction | null>,\n request(input.chain, \"eth_getTransactionReceipt\", [matchingLog.transactionHash]) as Promise<{status: Hex; blockNumber: Hex} | null>,\n request(input.chain, \"eth_getBlockByNumber\", [matchingLog.blockNumber, false]) as Promise<{timestamp: Hex} | null>,\n request(input.chain, \"eth_getCode\", [position, \"latest\"]) as Promise<Hex>,\n ]);\n if (\n !transaction || !receipt || !block || !code || code === \"0x\" || receipt.status !== \"0x1\" ||\n BigInt(receipt.blockNumber) !== BigInt(matchingLog.blockNumber) ||\n latest - BigInt(receipt.blockNumber) < minConfirmations ||\n BigInt(block.timestamp) + 120n < BigInt(input.quoteTimestamp)\n ) return refuse(\"receipt-or-confirmations\", {receiptStatus: receipt?.status, receiptBlock: receipt?.blockNumber, logBlock: matchingLog.blockNumber, latest: String(latest), minConfirmations: String(minConfirmations), codeLength: code ? code.length : 0, blockTimestamp: block?.timestamp});\n\n // Resolvers deploy the destination escrow through their OWN contract, not\n // by calling the factory directly: the observed transaction targets the\n // resolver, carries its private selector and sends no value, while the\n // factory only emits the event. Reconstructing `createDstEscrow` from that\n // calldata therefore never matches, which silently blocked every\n // disclosure. What the trader actually needs is provable without it: an\n // escrow the TRUSTED factory announced for THIS hashlock, deployed, and\n // already holding the promised output.\n //\n // The immutables still ride through that calldata as a contiguous ABI\n // tuple, so when the hashlock can be located we verify the fields that\n // decide who gets paid, and a contradiction is fatal. When the wrapper\n // hides them, the on-chain evidence below still has to hold.\n // Fail closed: the immutables decide who gets paid, so they must be\n // found AND proven to be this escrow's — the factory derives the escrow\n // address from them (deployedAt is stamped with the deployment block's\n // timestamp before the CREATE2 salt is taken). Seen live on Base\n // 2026-10-20 for every Omniston destination escrow.\n const immutables = locateImmutables(transaction.input, secretHash);\n if (!immutables) return refuse(\"immutables-not-found\", {transaction: matchingLog.transactionHash});\n const stamped = {...immutables, timelocks: (immutables.timelocks & ~DEPLOYED_AT_MASK) | (BigInt(block.timestamp) << DEPLOYED_AT_OFFSET)};\n const derived = decodeFunctionResult({\n abi: ESCROW_FACTORY_ABI,\n functionName: \"addressOfEscrowDst\",\n data: await ethCall(request, input.chain, factory, encodeFunctionData({abi: ESCROW_FACTORY_ABI, functionName: \"addressOfEscrowDst\", args: [stamped]})),\n });\n if (getAddress(derived) !== position) return refuse(\"derived-address\", {derived, position});\n if (!(\n uintAddress(immutables.maker) === recipient &&\n uintAddress(immutables.token) === token &&\n immutables.amount === resolverSendsUnits &&\n immutables.safetyDeposit === dstDeposit\n )) return refuse(\"escrow-terms\", {maker: uintAddress(immutables.maker), recipient, token: uintAddress(immutables.token), expectedToken: token, amount: String(immutables.amount), resolverSendsUnits: String(resolverSendsUnits), safetyDeposit: String(immutables.safetyDeposit), dstDeposit: String(dstDeposit)});\n\n // The fee split is paid OUT of `amount` on withdrawal (scan F12): the\n // amounts must be exactly the quoted fees, a non-zero fee may only go to\n // the quote's recipient, and what is left must be the quoted output.\n const fees = decodeFeeParameters(immutables.parameters);\n if (!fees || fees.protocolFeeRecipient > ADDRESS_MASK || fees.integratorFeeRecipient > ADDRESS_MASK) {\n return refuse(\"fee-parameters-shape\", {parametersLength: (immutables.parameters.length - 2) / 2});\n }\n if (fees.protocolFee !== protocolFeeUnits || fees.integratorFee !== integratorFeeUnits || immutables.amount - fees.protocolFee - fees.integratorFee !== outputUnits) {\n return refuse(\"fee-amounts\", {protocolFee: String(fees.protocolFee), protocolFeeUnits: String(protocolFeeUnits), integratorFee: String(fees.integratorFee), integratorFeeUnits: String(integratorFeeUnits), amount: String(immutables.amount), outputUnits: String(outputUnits)});\n }\n if (fees.protocolFee > 0n && uintAddress(fees.protocolFeeRecipient) !== getAddress(input.protocolFeeRecipientAddress!)) {\n return refuse(\"protocol-fee-recipient\", {escrow: uintAddress(fees.protocolFeeRecipient), quote: getAddress(input.protocolFeeRecipientAddress!)});\n }\n // A zero integrator fee pays nothing, whatever recipient word it carries\n // (live escrows often name one with integratorFee = 0).\n if (fees.integratorFee > 0n && uintAddress(fees.integratorFeeRecipient) !== getAddress(input.integratorAddress!)) {\n return refuse(\"integrator-fee-recipient\", {escrow: uintAddress(fees.integratorFeeRecipient), quote: getAddress(input.integratorAddress!)});\n }\n\n // Destination stages pinned to the audited profile (withdrawal opens\n // before cancellation), and the secret only leaves while there is still\n // time for the maker's withdrawal to land before cancellation opens.\n // deployedAt is the deployment block's timestamp (the factory stamps it).\n if (DST_STAGES.some((expected, index) => stage(immutables.timelocks, DST_STAGE_WORD + index) !== expected)) {\n return refuse(\"dst-timelocks\", {stages: DST_STAGES.map((_, index) => String(stage(immutables.timelocks, DST_STAGE_WORD + index)))});\n }\n const deployedAt = BigInt(block.timestamp);\n const nowSeconds = BigInt(Math.floor(now() / 1000));\n if (nowSeconds + DISCLOSURE_MARGIN_SECONDS >= deployedAt + DST_STAGES[DST_CANCELLATION_STAGE]) {\n return refuse(\"dst-cancellation-window\", {now: String(nowSeconds), deployedAt: String(deployedAt), cancellationAt: String(deployedAt + DST_STAGES[DST_CANCELLATION_STAGE]), marginSeconds: String(DISCLOSURE_MARGIN_SECONDS)});\n }\n\n const [reportedFactory, tokenBalance, nativeBalance] = await Promise.all([\n ethCall(request, input.chain, position, encodeFunctionData({abi: FACTORY_ABI, functionName: \"FACTORY\"}))\n .then((data) => decodeFunctionResult({abi: FACTORY_ABI, functionName: \"FACTORY\", data})),\n ethCall(request, input.chain, token, encodeFunctionData({abi: BALANCE_OF_ABI, functionName: \"balanceOf\", args: [position]}))\n .then((data) => decodeFunctionResult({abi: BALANCE_OF_ABI, functionName: \"balanceOf\", data})),\n request(input.chain, \"eth_getBalance\", [position, \"latest\"]) as Promise<Hex>,\n ]);\n // The escrow points back at the trusted factory, holds the output the\n // resolver promised, and carries its own safety deposit — none of which a\n // resolver can fake by merely reporting a phase.\n const ok = getAddress(reportedFactory) === factory &&\n tokenBalance >= resolverSendsUnits &&\n BigInt(nativeBalance) >= dstDeposit;\n return ok || refuse(\"escrow-state\", {reportedFactory, factory, tokenBalance: String(tokenBalance), resolverSendsUnits: String(resolverSendsUnits), nativeBalance: String(BigInt(nativeBalance)), dstDeposit: String(dstDeposit)});\n } catch (error) {\n return refuse(\"error\", {message: error instanceof Error ? error.message : String(error)});\n }\n };\n}\n\nconst TRANSFER_TOPIC = keccak256(stringToHex(\"Transfer(address,address,uint256)\"));\nconst topicAddress = (address: string): Hex => `0x${getAddress(address).slice(2).toLowerCase().padStart(64, \"0\")}`;\n\n/**\n * Finds an Omniston EVM delivery: the ERC-20 `Transfer` from the destination\n * escrow to the recipient of at least `minUnits`, within the chain's lookback\n * window. Feeds `omnistonProvider({locateEvmDelivery})` so a completed order\n * reports the transaction that actually paid the recipient.\n */\nexport function createOmnistonEvmDeliveryLocator(options: {request?: RpcRequest; rpcUrls?: OmnistonRpcUrls} = {}) {\n const request: RpcRequest = options.request ?? ((chain, method, params) => omnistonEvmRpcRequest(chain, method, params, options.rpcUrls));\n return async (input: {chain: string; positionAddress: string; recipientAddress: string; tokenAddress: string; minUnits: string}): Promise<string | null> => {\n try {\n const lookback = OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain];\n if (!lookback || !isAddress(input.positionAddress) || !isAddress(input.recipientAddress) || !isAddress(input.tokenAddress)) return null;\n const min = BigInt(input.minUnits);\n const latest = BigInt(await request(input.chain, \"eth_blockNumber\", []) as string);\n const oldest = latest > lookback ? latest - lookback : 0n;\n for (let to = latest; to >= oldest;) {\n const from = to - oldest > 4_999n ? to - 4_999n : oldest;\n const logs = await request(input.chain, \"eth_getLogs\", [{\n address: getAddress(input.tokenAddress),\n topics: [TRANSFER_TOPIC, topicAddress(input.positionAddress), topicAddress(input.recipientAddress)],\n fromBlock: quantity(from),\n toBlock: quantity(to),\n }]) as (RpcLog & {address: string})[];\n const hit = [...logs].reverse().find((log) => {\n try {\n return getAddress(log.address) === getAddress(input.tokenAddress) && BigInt(log.data) >= min;\n } catch {\n return false;\n }\n });\n if (hit) return hit.transactionHash;\n if (from === oldest) break;\n to = from - 1n;\n }\n return null;\n } catch {\n return null;\n }\n };\n}\n","import {\n decodeEventLog,\n decodeFunctionResult,\n encodeFunctionData,\n getAddress,\n isAddress,\n keccak256,\n stringToHex,\n type Hex,\n} from \"viem\";\nimport {\n OMNISTON_EVM_LOOKBACK_BLOCKS,\n OMNISTON_EVM_MIN_CONFIRMATIONS,\n omnistonEvmRpcRequest,\n type OmnistonRpcRequest,\n type OmnistonRpcUrls,\n} from \"./evm-output.js\";\n\n/**\n * EVM→TON: proves the trader's SOURCE position before the HTLC secret is\n * disclosed. The Omniston escrow factory (a 1inch cross-chain-swap fork with a\n * `parameters` tail on both immutables structs) emits `SrcEscrowCreated` from\n * the order's post-interaction once the resolver filled the signed order and\n * the maker's tokens plus the resolver's safety deposit sit in the\n * deterministic escrow. Everything below is read from the trusted factory and\n * the escrow itself; the Omniston tracking feed only supplied the address.\n */\n\nconst IMMUTABLES = [\n {name: \"orderHash\", type: \"bytes32\"},\n {name: \"hashlock\", type: \"bytes32\"},\n {name: \"maker\", type: \"uint256\"},\n {name: \"taker\", type: \"uint256\"},\n {name: \"token\", type: \"uint256\"},\n {name: \"amount\", type: \"uint256\"},\n {name: \"safetyDeposit\", type: \"uint256\"},\n {name: \"timelocks\", type: \"uint256\"},\n {name: \"parameters\", type: \"bytes\"},\n] as const;\nconst DST_COMPLEMENT = [\n {name: \"maker\", type: \"uint256\"},\n {name: \"amount\", type: \"uint256\"},\n {name: \"token\", type: \"uint256\"},\n {name: \"safetyDeposit\", type: \"uint256\"},\n {name: \"chainId\", type: \"uint256\"},\n {name: \"parameters\", type: \"bytes\"},\n] as const;\nconst FACTORY_ABI = [\n {\n type: \"event\",\n name: \"SrcEscrowCreated\",\n inputs: [\n {name: \"srcImmutables\", type: \"tuple\", components: IMMUTABLES, indexed: false},\n {name: \"dstImmutablesComplement\", type: \"tuple\", components: DST_COMPLEMENT, indexed: false},\n ],\n },\n {\n type: \"function\",\n name: \"addressOfEscrowSrc\",\n stateMutability: \"view\",\n inputs: [{name: \"immutables\", type: \"tuple\", components: IMMUTABLES}],\n outputs: [{name: \"escrow\", type: \"address\"}],\n },\n {type: \"function\", name: \"FACTORY\", stateMutability: \"view\", inputs: [], outputs: [{type: \"address\"}]},\n {type: \"function\", name: \"balanceOf\", stateMutability: \"view\", inputs: [{name: \"account\", type: \"address\"}], outputs: [{type: \"uint256\"}]},\n] as const;\n\n/** keccak256 of the event signature with the structs expanded (live Base 2026-10-16: 0x1140dcf8…). */\nexport const SRC_ESCROW_CREATED_TOPIC = keccak256(stringToHex(\n \"SrcEscrowCreated((bytes32,bytes32,uint256,uint256,uint256,uint256,uint256,uint256,bytes),(uint256,uint256,uint256,uint256,uint256,bytes))\",\n));\n\n/** Timelock stages (seconds after deploy) of the audited v1beta8 profile:\n * src withdrawal, src public withdrawal, src cancellation, src public\n * cancellation, dst withdrawal, dst public withdrawal, dst cancellation. */\nconst SRC_STAGES = [1n, 120n, 240n, 300n, 1n, 120n, 180n] as const;\nconst SRC_CANCELLATION_STAGE = 2;\n/** Disclosure is refused this close to the source cancellation stage: the\n * resolver could otherwise withdraw the input while the TON position (which\n * cancels 60 s earlier) can no longer be completed. */\nconst DISCLOSURE_MARGIN_SECONDS = 45n;\nconst UINT32_MASK = (1n << 32n) - 1n;\nconst ADDRESS_MASK = (1n << 160n) - 1n;\n\nexport interface EvmInputValidationInput {\n chain: string;\n positionAddress: string;\n factoryAddress: string;\n orderProtocolAddress: string;\n ownerAddress: string;\n resolverAddress: string;\n inputTokenAddress: string;\n inputUnits: string;\n resolverSendsUnits: string;\n srcHtlcSecurityDepositUnits: string;\n quoteTimestamp: number;\n secretHash: Uint8Array;\n /** EVM destination only: the destination complement must name this chain, token and deposit. */\n destinationChainId?: number;\n destinationTokenAddress?: string;\n dstSecurityDepositUnits?: string;\n}\n\ninterface RpcLog {\n address: string;\n data: Hex;\n topics: Hex[];\n transactionHash: Hex;\n blockNumber: Hex;\n}\n\nfunction quantity(value: bigint): Hex {\n return `0x${value.toString(16)}`;\n}\n\nfunction uintAddress(value: bigint): string {\n return getAddress(`0x${(value & ADDRESS_MASK).toString(16).padStart(40, \"0\")}`);\n}\n\nfunction bytesHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction stage(timelocks: bigint, index: number): bigint {\n return (timelocks >> BigInt(index * 32)) & UINT32_MASK;\n}\n\nasync function ethCall(request: OmnistonRpcRequest, chain: string, to: string, data: Hex): Promise<Hex> {\n return await request(chain, \"eth_call\", [{to, data}, \"latest\"]) as Hex;\n}\n\n/** Diagnostics hook: every refusal names its check and the numbers it compared (never a secret). */\nexport type OmnistonValidatorRefusal = (reason: string, details?: Record<string, unknown>) => void;\n\nexport function createOmnistonEvmInputValidator(options: {request?: OmnistonRpcRequest; rpcUrls?: OmnistonRpcUrls; now?: () => number; onRefusal?: OmnistonValidatorRefusal} = {}) {\n const refuse = (reason: string, details?: Record<string, unknown>): false => {\n try { options.onRefusal?.(reason, details); } catch { /* diagnostics never break validation */ }\n return false;\n };\n const request: OmnistonRpcRequest = options.request ?? ((chain, method, params) => omnistonEvmRpcRequest(chain, method, params, options.rpcUrls));\n const now = options.now ?? Date.now;\n return async (input: EvmInputValidationInput): Promise<boolean> => {\n try {\n if (\n !OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain] ||\n !isAddress(input.positionAddress) || !isAddress(input.factoryAddress) || !isAddress(input.orderProtocolAddress) ||\n !isAddress(input.ownerAddress) || !isAddress(input.resolverAddress) || !isAddress(input.inputTokenAddress) ||\n !Number.isInteger(input.quoteTimestamp) || input.quoteTimestamp * 1000 > now() + 120_000 ||\n now() - input.quoteTimestamp * 1000 > 6 * 60 * 60 * 1000 || input.secretHash.length !== 32\n ) return refuse(\"input-shape\");\n const position = getAddress(input.positionAddress);\n const factory = getAddress(input.factoryAddress);\n const owner = getAddress(input.ownerAddress);\n const resolver = getAddress(input.resolverAddress);\n const token = getAddress(input.inputTokenAddress);\n const secretHash = bytesHex(input.secretHash).toLowerCase();\n const inputUnits = BigInt(input.inputUnits);\n const resolverSendsUnits = BigInt(input.resolverSendsUnits);\n const safetyDeposit = BigInt(input.srcHtlcSecurityDepositUnits);\n if (inputUnits <= 0n || resolverSendsUnits <= 0n || safetyDeposit <= 0n) return refuse(\"non-positive-amounts\");\n\n const latest = BigInt(await request(input.chain, \"eth_blockNumber\", []) as string);\n const minConfirmations = OMNISTON_EVM_MIN_CONFIRMATIONS[input.chain] ?? 20n;\n const newestFinal = latest >= minConfirmations ? latest - minConfirmations : 0n;\n const lookback = OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain]!;\n const oldest = newestFinal > lookback ? newestFinal - lookback : 0n;\n let match: {log: RpcLog; immutables: {\n orderHash: Hex; hashlock: Hex; maker: bigint; taker: bigint; token: bigint; amount: bigint; safetyDeposit: bigint; timelocks: bigint; parameters: Hex;\n }; complement: {maker: bigint; amount: bigint; token: bigint; safetyDeposit: bigint; chainId: bigint; parameters: Hex}} | undefined;\n for (let to = newestFinal; to >= oldest && !match;) {\n const from = to - oldest > 4_999n ? to - 4_999n : oldest;\n const logs = await request(input.chain, \"eth_getLogs\", [{\n address: factory,\n topics: [SRC_ESCROW_CREATED_TOPIC],\n fromBlock: quantity(from),\n toBlock: quantity(to),\n }]) as RpcLog[];\n for (const log of logs) {\n if (getAddress(log.address) !== factory) continue;\n try {\n const decoded = decodeEventLog({abi: FACTORY_ABI, eventName: \"SrcEscrowCreated\", data: log.data, topics: log.topics as [Hex, ...Hex[]]});\n if (decoded.args.srcImmutables.hashlock.toLowerCase() === secretHash) {\n match = {log, immutables: decoded.args.srcImmutables, complement: decoded.args.dstImmutablesComplement};\n break;\n }\n } catch {\n /* a foreign log shape is not ours */\n }\n }\n if (from === oldest) break;\n to = from - 1n;\n }\n if (!match) return refuse(\"no-fill-event\", {factory, lookback: String(OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain])});\n const {immutables, complement, log} = match;\n const deployedAt = stage(immutables.timelocks, 7);\n // What the resolver filled must be exactly what the wallet signed: the\n // trader's full input, for this resolver, with the quoted deposit and\n // the pinned timelocks; the complement binds the TON output amount.\n if (\n uintAddress(immutables.maker) !== owner || uintAddress(immutables.taker) !== resolver ||\n uintAddress(immutables.token) !== token || immutables.amount !== inputUnits ||\n immutables.safetyDeposit !== safetyDeposit || immutables.parameters !== \"0x\" ||\n SRC_STAGES.some((expected, index) => stage(immutables.timelocks, index) !== expected) ||\n deployedAt < BigInt(input.quoteTimestamp) - 120n || deployedAt > BigInt(input.quoteTimestamp) + 900n ||\n // EVM destination: the complement is the destination escrow's amount, enforced by its CREATE2\n // derivation — exact. TON destination: Omniston records a larger figure here (live 2026-10-20,\n // both orders: 1.089 × resolverSendsUnits — 4 485 039 for 4 118 665, 791 340 for 726 690); the\n // delivered amount is proven on the TON position itself (validateTonOutputPosition), so this\n // only has to be no smaller than the promise. Strict equality blocked every EVM → TON disclosure.\n (input.destinationChainId !== undefined ? complement.amount !== resolverSendsUnits : complement.amount < resolverSendsUnits)\n ) return refuse(\"refused\");\n // EVM destination: the complement the factory recorded must point at the\n // quoted chain, token and destination deposit (TON keeps its own terms).\n if (input.destinationChainId !== undefined && (\n complement.chainId !== BigInt(input.destinationChainId) ||\n !input.destinationTokenAddress || !isAddress(input.destinationTokenAddress) ||\n uintAddress(complement.token) !== getAddress(input.destinationTokenAddress) ||\n complement.safetyDeposit !== BigInt(input.dstSecurityDepositUnits ?? \"-1\")\n )) return refuse(\"complement-destination\");\n\n // The escrow address is a function of the immutables (CREATE2 through\n // the factory): the feed's address must be that function's value.\n const derived = decodeFunctionResult({\n abi: FACTORY_ABI,\n functionName: \"addressOfEscrowSrc\",\n data: await ethCall(request, input.chain, factory, encodeFunctionData({abi: FACTORY_ABI, functionName: \"addressOfEscrowSrc\", args: [immutables]})),\n });\n if (getAddress(derived) !== position) return refuse(\"derived-address\", {derived, position});\n\n const [receipt, block, code] = await Promise.all([\n request(input.chain, \"eth_getTransactionReceipt\", [log.transactionHash]) as Promise<{status: Hex; blockNumber: Hex} | null>,\n request(input.chain, \"eth_getBlockByNumber\", [log.blockNumber, false]) as Promise<{timestamp: Hex} | null>,\n request(input.chain, \"eth_getCode\", [position, \"latest\"]) as Promise<Hex>,\n ]);\n if (\n !receipt || !block || !code || code === \"0x\" || receipt.status !== \"0x1\" ||\n BigInt(receipt.blockNumber) !== BigInt(log.blockNumber) ||\n latest - BigInt(receipt.blockNumber) < minConfirmations ||\n BigInt(block.timestamp) !== deployedAt\n ) return refuse(\"receipt-or-confirmations\", {receiptStatus: receipt?.status, receiptBlock: receipt?.blockNumber, logBlock: log.blockNumber, latest: String(latest), minConfirmations: String(minConfirmations), codeLength: code ? code.length : 0, blockTimestamp: block?.timestamp, deployedAt: String(deployedAt)});\n // Still early enough to complete: the resolver must not be able to\n // cancel the source leg (and keep the TON side) once the secret is out.\n const nowSeconds = BigInt(Math.floor(now() / 1000));\n if (nowSeconds + DISCLOSURE_MARGIN_SECONDS >= deployedAt + SRC_STAGES[SRC_CANCELLATION_STAGE]) return refuse(\"receipt-or-confirmations\", {receiptStatus: receipt?.status, receiptBlock: receipt?.blockNumber, logBlock: log.blockNumber, latest: String(latest), minConfirmations: String(minConfirmations), codeLength: code ? code.length : 0, blockTimestamp: block?.timestamp, deployedAt: String(deployedAt)});\n\n const [reportedFactory, tokenBalance, nativeBalance] = await Promise.all([\n ethCall(request, input.chain, position, encodeFunctionData({abi: FACTORY_ABI, functionName: \"FACTORY\"}))\n .then((data) => decodeFunctionResult({abi: FACTORY_ABI, functionName: \"FACTORY\", data})),\n ethCall(request, input.chain, token, encodeFunctionData({abi: FACTORY_ABI, functionName: \"balanceOf\", args: [position]}))\n .then((data) => decodeFunctionResult({abi: FACTORY_ABI, functionName: \"balanceOf\", data})),\n request(input.chain, \"eth_getBalance\", [position, \"latest\"]) as Promise<Hex>,\n ]);\n const ok = getAddress(reportedFactory) === factory && tokenBalance >= inputUnits && BigInt(nativeBalance) >= safetyDeposit;\n return ok || refuse(\"escrow-state\", {reportedFactory, factory, tokenBalance: String(tokenBalance), inputUnits: String(inputUnits), nativeBalance: String(BigInt(nativeBalance)), safetyDeposit: String(safetyDeposit)});\n } catch (error) {\n return refuse(\"error\", {message: error instanceof Error ? error.message : String(error)});\n }\n };\n}\n","import \"../buffer-global.js\";\nimport {Buffer} from \"buffer\";\nimport {Address, Cell} from \"@ton/core\";\nimport type {OmnistonProviderOptions} from \"../provider.js\";\nimport type {TonSwapLeg} from \"../ton-swap.js\";\nimport {bigintToNumber} from \"@anywalletkit/core\";\n\nconst JETTON_TRANSFER_OP = 0x0f8a7ea5;\nconst ESCROW_CREATE_OP = 0xc0a5f0d9;\nconst ESCROW_CONFIG_OP = 0xf2c6fa63;\nconst ESCROW_EXECUTION_KECCAK_OP = 0xc8d4b428;\nconst MAX_FORWARD_NANO = 2_000_000_000n;\n\n/** Audited from the active mainnet Escrow builder on 2026-08-13. These are\n * immutable TVM code cells, not resolver-controlled addresses. A contract\n * upgrade must deliberately update these hashes after reviewing its schema.\n *\n * `authorityKeys` is the optional 256-bit public key in the escrow config: the\n * escrow code checks `CHKSIGNU` against it for its signature-gated operations\n * (disassembly of code 9e77cb9e…, 2026-10-11). It has been the same key since\n * the August audit, so it stays pinned. */\nexport const DEFAULT_OMNISTON_TON_CODE_HASHES = {\n escrow: [\"9e77cb9e8fd7406d4e85e5f57378eb51e51b862424cf988306c783d50ade697a\"],\n execution: [\"f6edbc76e6fbcd6bac573cb942401a3d9198ee9605f9403b0f5c8081259210e5\"],\n authorityKeys: [\"ed210da12aa96ea42de4f2f61dc172bbaa3da86051a1b2a6f342f69a777d2770\"],\n /** EVM→TON output position: the contract the factory deploys for the\n * resolver's jetton lock (observed on every resolver-created position,\n * 2026-10-15/16), and the escrow code cell it carries in its state. */\n position: [\"e4d5115a321ade7b827e38fb522c20d2f2cd46e4c6b0b5f7dd8b6b096792d77b\"],\n outputEscrow: [\"d30423575384773abaad8d3c6f763898afa3d57a5693005904b7c61e95cee630\"],\n} as const;\n\n/** The factory's message that installs a position's state (op of the deploy\n * message every resolver-created output position received, 2026-10-15). */\nconst POSITION_DEPLOY_OP = \"0xf240cd30\";\n/** Position timelocks after deploy: withdrawal, public withdrawal, cancellation\n * (the EVM extension's dst timelocks 1/120/180; the position stores absolute\n * timestamps = deploy time + stage, with the first one rounded 1 s later). */\nconst POSITION_STAGES = {publicWithdrawalAfterWithdrawal: 119n, cancellationAfterWithdrawal: 179n};\n/** Disclosure is refused this close to the position's cancellation boundary:\n * after it the resolver can take the jettons back while it already holds the\n * secret for the EVM source escrow. */\nconst OUTPUT_DISCLOSURE_MARGIN_SECONDS = 45;\n\n/** Upper bound on the exclusivity window the escrow config may carry. It is\n * how long the trader's input stays locked when no resolver reserves the\n * position (SDK: \"at the end of this period trader's position becomes\n * available for manual withdrawal\"); the live value is 300 s. */\nexport const MAX_OMNISTON_EXCLUSIVITY_SECONDS = 3_600;\n\n// `exclusivityTimeout` optional: the parked web path still runs a module build\n// that predates it (validatePayload refuses when it is absent).\ntype PayloadInput = Omit<Parameters<NonNullable<OmnistonProviderOptions[\"validateTonEscrowPayload\"]>>[0], \"exclusivityTimeout\"> & {\n exclusivityTimeout?: number;\n};\n\n/** Code interfaces (tonapi's by-code-hash labels) a same-chain swap message\n * may pay into. The resolver picks the pool/vault per route, so the check is\n * \"a STON.fi or DeDust contract by code\", not a fixed address list — seen\n * live: native GRAM → DeDust CPMM v2 pool, jettons → STON.fi router v2. */\nexport const DEFAULT_OMNISTON_TON_SWAP_INTERFACES = [\n \"stonfi_router\",\n \"stonfi_router_v2\",\n \"stonfi_pool\",\n \"stonfi_pool_v2\",\n \"dedust_vault\",\n \"dedust_v2_cpmm\",\n \"dedust_pool\",\n] as const;\n\n/** Proxy-TON (pTON) jetton masters STON.fi routes native TON through. A\n * native-input swap pays the ROUTER'S pTON wallet — a plain `jetton_wallet`\n * to tonapi, no DEX code interface — so such a target is accepted only when\n * its jetton master is pTON AND its owner carries a DEX router interface.\n * Seen live 2026-09-05: GRAM → USDT on StonFiV2 targeted the router's pTON\n * v2 wallet and the code-interface check alone refused it. */\nexport const DEFAULT_OMNISTON_TON_PROXY_TON_MASTERS = [\n \"EQCM3B12QK1e4yZSf8GtBRT0aLMNyEsBc_DhVfRRtOEffLez\", // pTON v1\n \"EQBnGWMCf3-FZZq1W4IWcWiGAc3PHuZ0_H-7sad2oY00o83S\", // pTON v2\n] as const;\n\nexport interface OmnistonTonValidationOptions {\n fetch?: typeof fetch;\n /** Diagnostics hook: every refusal of validateTonOutputPosition names its check (never a secret). */\n onRefusal?: (reason: string, details?: Record<string, unknown>) => void;\n tonApiUrl?: string;\n tonApiKey?: string;\n /** Code interfaces accepted as swap targets (default: the STON.fi / DeDust set above). */\n swapTargetInterfaces?: readonly string[];\n /** Proxy-TON masters whose router-owned wallets may receive native input (default: pTON v1/v2). */\n proxyTonMasters?: readonly string[];\n escrowCodeHashes?: readonly string[];\n executionCodeHashes?: readonly string[];\n /** Pinned escrow authority public keys (hex, 32 bytes). */\n authorityKeys?: readonly string[];\n /** EVM→TON output position code hashes (default: the observed factory position). */\n positionCodeHashes?: readonly string[];\n /** Escrow code cells an output position may carry (default: the observed one). */\n outputEscrowCodeHashes?: readonly string[];\n now?: () => number;\n}\n\nexport type TonOutputPositionInput = Parameters<NonNullable<OmnistonProviderOptions[\"validateTonOutputPosition\"]>>[0];\n\nfunction cellFromApi(value: string): Cell {\n const roots = Cell.fromBoc(Buffer.from(value, /^b5ee9c/i.test(value) ? \"hex\" : \"base64\"));\n if (roots.length !== 1) throw new Error(\"omniston TON validator: account cell must have one root\");\n return roots[0]!;\n}\n\n/**\n * EVM→TON output position, as the factory writes it (decoded from live\n * resolver-created positions, 2026-10-15/16 — every field is checked in its\n * slot, nothing is located by search):\n *\n * ```text\n * data: phase:uint8 quoteId:bits256 factory:MsgAddressStd\n * jettonWallet:MsgAddressStd (the factory's wallet of the output\n * jetton — custody stays there) flags:bits5\n * ref0: owner:MsgAddressStd (resolver) jettonMaster:MsgAddressStd bits6\n * ref0: fee profile (constant, not security-relevant)\n * ref1: jettonWallet, gas, owner\n * ref1: hashlock:bits256 amount:Coins withdrawalAt:uint64\n * publicWithdrawalAt:uint64 cancellationAt:uint64\n * ref0: recipient:MsgAddressStd resolver:MsgAddressStd deposit:Coins\n * ref1: authority:(Maybe bits256) recipient:MsgAddressStd\n * ref2: escrow code cell\n * ```\n */\nlet lastStateRefusal: string | null = null;\nfunction validateOutputPositionState(\n data: Cell,\n input: TonOutputPositionInput,\n expected: {jettonWallet: string; trusted: {outputEscrow: ReadonlySet<string>; authorityKeys: ReadonlySet<string>}; nowSeconds: number},\n): {withdrawalAt: bigint} | null {\n if (!/^[0-9a-fA-F]{48,64}$/.test(input.quoteId) || input.secretHash.length !== 32) { lastStateRefusal = \"state#1: if (!/^[0-9a-fA-F]{48,64}$/.test(input.quoteId) || input.secretHash.length !== 32) return null;\"; return null; }\n if (!/^\\d+$/.test(input.resolverSendsUnits) || !/^\\d+$/.test(input.outputUnits) || !/^\\d+$/.test(input.dstSecurityDepositUnits)) { lastStateRefusal = \"state#2: if (!/^\\\\d+$/.test(input.resolverSendsUnits) || !/^\\\\d+$/.test(input.outputUnits) || !/^\\\\d+$/.test(inp\"; return null; }\n if (data.refs.length !== 3) { lastStateRefusal = \"state#3: if (data.refs.length !== 3) return null;\"; return null; }\n const root = data.beginParse();\n root.loadUint(8); // phase — not trusted for custody; the factory deploy + timelocks are\n if (!sameHex(root.loadBuffer(32), input.quoteId.padStart(64, \"0\"))) { lastStateRefusal = \"state#4: if (!sameHex(root.loadBuffer(32), input.quoteId.padStart(64, \\\"0\\\"))) return null;\"; return null; }\n if (!sameAddress(root.loadAddressAny(), input.protocolAddress)) { lastStateRefusal = \"state#5: if (!sameAddress(root.loadAddressAny(), input.protocolAddress)) return null;\"; return null; }\n if (!sameAddress(root.loadAddressAny(), expected.jettonWallet)) { lastStateRefusal = \"state#6: if (!sameAddress(root.loadAddressAny(), expected.jettonWallet)) return null;\"; return null; }\n // Root tail: 5 bits once the position is settled or rolled back (tag 2 / 3 — the shape the\n // fixtures were cut from), 29 bits while it is live and awaiting completion (tag 1, live\n // 2026-10-20 on every Base → TON position; the 24 extra bits are not fund-critical — every\n // binding field is checked in the refs below). Any other width is a foreign layout.\n if ((root.remainingBits !== 5 && root.remainingBits !== 29) || root.remainingRefs !== 3) { lastStateRefusal = `state#7: root tail ${root.remainingBits} bits / ${root.remainingRefs} refs`; return null; }\n\n const parties = data.refs[0]!;\n if (parties.refs.length !== 2) { lastStateRefusal = \"state#8: if (parties.refs.length !== 2) return null;\"; return null; }\n const partySlice = parties.beginParse();\n if (!(partySlice.loadAddressAny() instanceof Address)) { lastStateRefusal = \"state#9: if (!(partySlice.loadAddressAny() instanceof Address)) return null; // owner (resolver) — any\"; return null; } // owner (resolver) — any\n if (!sameAddress(partySlice.loadAddressAny(), input.outputJettonMasterAddress)) { lastStateRefusal = \"state#10: if (!sameAddress(partySlice.loadAddressAny(), input.outputJettonMasterAddress)) return null;\"; return null; }\n if (partySlice.remainingBits !== 6) { lastStateRefusal = \"state#11: if (partySlice.remainingBits !== 6) return null;\"; return null; }\n\n const lock = data.refs[1]!;\n if (lock.refs.length !== 2) { lastStateRefusal = \"state#12: if (lock.refs.length !== 2) return null;\"; return null; }\n const lockSlice = lock.beginParse();\n if (!Buffer.from(lockSlice.loadBuffer(32)).equals(Buffer.from(input.secretHash))) { lastStateRefusal = \"state#13: if (!Buffer.from(lockSlice.loadBuffer(32)).equals(Buffer.from(input.secretHash))) return null;\"; return null; }\n if (lockSlice.loadCoins() < BigInt(input.resolverSendsUnits)) { lastStateRefusal = \"state#14: if (lockSlice.loadCoins() < BigInt(input.resolverSendsUnits)) return null;\"; return null; }\n const withdrawalAt = lockSlice.loadUintBig(64);\n const publicWithdrawalAt = lockSlice.loadUintBig(64);\n const cancellationAt = lockSlice.loadUintBig(64);\n if (lockSlice.remainingBits !== 0) { lastStateRefusal = \"state#15: if (lockSlice.remainingBits !== 0) return null; // its two refs are the terms and authority cells be\"; return null; } // its two refs are the terms and authority cells below\n if (publicWithdrawalAt - withdrawalAt !== POSITION_STAGES.publicWithdrawalAfterWithdrawal) { lastStateRefusal = \"state#16: if (publicWithdrawalAt - withdrawalAt !== POSITION_STAGES.publicWithdrawalAfterWithdrawal) return nu\"; return null; }\n if (cancellationAt - withdrawalAt !== POSITION_STAGES.cancellationAfterWithdrawal) { lastStateRefusal = \"state#17: if (cancellationAt - withdrawalAt !== POSITION_STAGES.cancellationAfterWithdrawal) return null;\"; return null; }\n // Deployed after the quote (resolvers lock within minutes of the fill) and\n // still far enough from cancellation to be completed.\n if (withdrawalAt < BigInt(input.quoteTimestamp) - 120n || withdrawalAt > BigInt(input.quoteTimestamp) + 900n) { lastStateRefusal = \"state#18: if (withdrawalAt < BigInt(input.quoteTimestamp) - 120n || withdrawalAt > BigInt(input.quoteTimestamp\"; return null; }\n if (BigInt(expected.nowSeconds + OUTPUT_DISCLOSURE_MARGIN_SECONDS) >= cancellationAt) { lastStateRefusal = \"state#19: if (BigInt(expected.nowSeconds + OUTPUT_DISCLOSURE_MARGIN_SECONDS) >= cancellationAt) return null;\"; return null; }\n\n const terms = lock.refs[0]!.beginParse();\n if (!sameAddress(terms.loadAddressAny(), input.recipientAddress)) { lastStateRefusal = \"state#20: if (!sameAddress(terms.loadAddressAny(), input.recipientAddress)) return null;\"; return null; }\n if (!(terms.loadAddressAny() instanceof Address)) { lastStateRefusal = \"state#21: if (!(terms.loadAddressAny() instanceof Address)) return null; // resolver — any\"; return null; } // resolver — any\n if (terms.loadCoins() !== BigInt(input.dstSecurityDepositUnits) || !exactCellEnd(terms)) { lastStateRefusal = \"state#22: if (terms.loadCoins() !== BigInt(input.dstSecurityDepositUnits) || !exactCellEnd(terms)) return null\"; return null; }\n\n const authority = lock.refs[1]!.beginParse();\n if (!authority.loadBit() || !expected.trusted.authorityKeys.has(Buffer.from(authority.loadBuffer(32)).toString(\"hex\"))) { lastStateRefusal = \"state#23: if (!authority.loadBit() || !expected.trusted.authorityKeys.has(Buffer.from(authority.loadBuffer(32)\"; return null; }\n // Authority address: the trader's TON address on TON-source positions; `addr_none` on EVM-source\n // positions (live 2026-10-20, every Base → TON order) — the payout target is bound in the terms cell\n // above, and the pinned authority key is what the public path checks. Anything else is foreign.\n const authorityAddress = authority.loadAddressAny();\n if ((authorityAddress !== null && !sameAddress(authorityAddress, input.recipientAddress)) || !exactCellEnd(authority)) { lastStateRefusal = \"state#24: if ((authorityAddress !== null && !sameAddress(authorityAddress, input.recipientAddress)) || !exactC\"; return null; }\n\n if (!expected.trusted.outputEscrow.has(data.refs[2]!.hash().toString(\"hex\"))) { lastStateRefusal = \"state#25: if (!expected.trusted.outputEscrow.has(data.refs[2]!.hash().toString(\\\"hex\\\"))) return null;\"; return null; }\n return {withdrawalAt};\n}\n\nfunction oneRoot(hex: string, label: string): Cell {\n if (!/^(?:[0-9a-fA-F]{2})+$/.test(hex)) throw new Error(`omniston TON validator: malformed ${label} hex`);\n const roots = Cell.fromBoc(Buffer.from(hex, \"hex\"));\n if (roots.length !== 1) throw new Error(`omniston TON validator: ${label} must have one root`);\n return roots[0]!;\n}\n\nfunction sameAddress(actual: unknown, expected: string): boolean {\n try {\n return actual instanceof Address && actual.equals(Address.parse(expected));\n } catch {\n return false;\n }\n}\n\nfunction sameHex(actual: Uint8Array, expected: string): boolean {\n const clean = expected.replace(/^0x/, \"\").toLowerCase();\n return clean.length === actual.length * 2 && Buffer.from(actual).toString(\"hex\") === clean;\n}\n\nfunction exactCellEnd(slice: {remainingBits: number; remainingRefs: number}): boolean {\n return slice.remainingBits === 0 && slice.remainingRefs === 0;\n}\n\nfunction destinationChainId(chain: string): bigint | null {\n const ids: Record<string, bigint> = {\n ethereum: 1n,\n bnb: 56n,\n polygon: 137n,\n robinhood: 4663n,\n base: 8453n,\n arbitrum: 42161n,\n avalanche: 43114n,\n xlayer: 196n,\n hyperevm: 999n,\n plasma: 9745n,\n };\n return ids[chain] ?? null;\n}\n\nfunction validatePayload(input: PayloadInput, trusted: {\n escrow: ReadonlySet<string>;\n execution: ReadonlySet<string>;\n authorityKeys: ReadonlySet<string>;\n}): boolean {\n // Read structurally so this stays type-compatible with module builds that\n // predate the field; absent → refused below.\n const exclusivityTimeout = (input as {exclusivityTimeout?: unknown}).exclusivityTimeout;\n if (\n typeof exclusivityTimeout !== \"number\" || !Number.isSafeInteger(exclusivityTimeout) ||\n exclusivityTimeout < 1 || exclusivityTimeout > MAX_OMNISTON_EXCLUSIVITY_SECONDS\n ) return false;\n if (\n !/^\\d+$/.test(input.inputUnits) || !/^\\d+$/.test(input.resolverSendsUnits) ||\n !/^\\d+$/.test(input.srcHtlcSecurityDepositUnits) || !/^[0-9a-fA-F]{48,64}$/.test(input.quoteId) ||\n input.secretHashes.length !== 1 || input.secretHashes[0]?.length !== 32 ||\n input.hashingFunction !== \"HASHING_FUNCTION_KECCAK256\"\n ) return false;\n\n const payload = oneRoot(input.payloadBocHex, \"payload\");\n const outer = payload.beginParse();\n if (outer.loadUint(32) !== JETTON_TRANSFER_OP) return false;\n outer.loadUintBig(64); // query id is intentionally wallet/resolver-selected\n if (outer.loadCoins() !== BigInt(input.inputUnits)) return false;\n if (!sameAddress(outer.loadAddressAny(), input.protocolAddress)) return false;\n if (!sameAddress(outer.loadAddressAny(), input.ownerAddress)) return false;\n if (outer.loadMaybeRef() !== null) return false;\n const forwardNano = outer.loadCoins();\n if (forwardNano <= 0n || forwardNano > MAX_FORWARD_NANO || !outer.loadBit()) return false;\n if (outer.remainingBits !== 0 || outer.remainingRefs !== 1) return false;\n const embeddedForward = outer.loadRef();\n const forward = oneRoot(input.forwardPayloadBocHex, \"forward payload\");\n if (!embeddedForward.hash().equals(forward.hash())) return false;\n\n const root = forward.beginParse();\n if (root.loadUint(32) !== ESCROW_CREATE_OP || !sameHex(root.loadBuffer(32), input.quoteId.padStart(64, \"0\"))) return false;\n if (root.loadBit() || !sameAddress(root.loadAddressAny(), input.ownerAddress)) return false;\n const escrowForwardNano = root.loadCoins();\n if (escrowForwardNano <= 0n || escrowForwardNano > MAX_FORWARD_NANO || root.loadBit()) return false;\n if (root.remainingBits !== 0 || root.remainingRefs !== 4) return false;\n const [config, escrowCode, auxiliary, flags] = [root.loadRef(), root.loadRef(), root.loadRef(), root.loadRef()];\n if (!trusted.escrow.has(escrowCode.hash().toString(\"hex\"))) return false;\n\n // Escrow config, as the escrow code's deploy handler parses it (disassembly\n // of 9e77cb9e…, 2026-10-11):\n // op:uint32 resolver:MsgAddressStd authority:(Maybe uint256)\n // exclusivity:uint64 postExclusivity:uint64 state:^Cell\n // destination:(Maybe ^Cell) parts:uint16\n // On deploy the escrow stores now+exclusivity and now+exclusivity+postExclusivity\n // as its phase boundaries. Every field is checked in its slot; nothing is\n // compared as an opaque blob, so a protocol-side timing change shows up as a\n // named field instead of a silent refusal.\n const configSlice = config.beginParse();\n if (configSlice.loadUint(32) !== ESCROW_CONFIG_OP || !sameAddress(configSlice.loadAddressAny(), input.initialResolverAddress)) return false;\n if (!configSlice.loadBit() || !trusted.authorityKeys.has(Buffer.from(configSlice.loadBuffer(32)).toString(\"hex\"))) return false;\n // Bound to the quote the user accepted: the resolver cannot lengthen the\n // window the trader's funds are locked for without a reservation.\n if (configSlice.loadUintBig(64) !== BigInt(exclusivityTimeout)) return false;\n // A non-zero window after exclusivity is the Dutch-auction phase (\"Dutch\n // auction starts if specified by escrow condition\"); its price curve is not\n // part of the trader quote, so only the no-auction profile is accepted.\n if (configSlice.loadUintBig(64) !== 0n) return false;\n if (configSlice.remainingRefs !== 2) return false;\n const state = configSlice.loadRef();\n if (!configSlice.loadBit()) return false; // destination is mandatory\n const destination = configSlice.loadRef();\n // 0 = single full fill, which is what the one-hash execution below commits to.\n if (configSlice.loadUint(16) !== 0 || !exactCellEnd(configSlice)) return false;\n if (state.bits.length !== 0 || state.refs.length !== 2) return false;\n if (!trusted.execution.has(state.refs[0]!.hash().toString(\"hex\"))) return false;\n\n const execution = state.refs[1]!.beginParse();\n if (\n execution.loadUint(32) !== ESCROW_EXECUTION_KECCAK_OP ||\n !Buffer.from(execution.loadBuffer(32)).equals(Buffer.from(input.secretHashes[0]!)) ||\n !sameAddress(execution.loadAddressAny(), input.initialResolverAddress)\n ) return false;\n // Current audited escrow policy: one execution, then 120/240/300-second\n // exclusivity, cancellation and refund boundaries.\n if ([1n, 120n, 240n, 300n].some((expected) => execution.loadUintBig(64) !== expected)) return false;\n if (execution.remainingBits !== 0 || execution.remainingRefs !== 1) return false;\n const ownerData = execution.loadRef().beginParse();\n if (!sameAddress(ownerData.loadAddressAny(), input.ownerAddress) || ownerData.loadBit()) return false;\n if (ownerData.loadCoins() !== BigInt(input.srcHtlcSecurityDepositUnits) || !exactCellEnd(ownerData)) return false;\n\n const destinationSlice = destination.beginParse();\n const chainId = destinationChainId(input.destinationChain);\n if (chainId === null || destinationSlice.loadUintBig(64) !== chainId) return false;\n if (!sameHex(destinationSlice.loadBuffer(20), input.outputTokenAddress)) return false;\n if (!sameHex(destinationSlice.loadBuffer(20), input.destinationAddress)) return false;\n if (destinationSlice.loadCoins() !== BigInt(input.resolverSendsUnits) || !exactCellEnd(destinationSlice)) return false;\n\n // These cells contain optional escrow bookkeeping. Their exact shapes and\n // reference counts are part of the reviewed ABI; fund destinations above\n // are never located by byte search.\n if (auxiliary.bits.length !== 537 || auxiliary.refs.length !== 1) return false;\n if (flags.bits.length !== 98 || flags.refs.length !== 0) return false;\n return true;\n}\n\nexport function createOmnistonTonValidators(options: OmnistonTonValidationOptions = {}): Required<Pick<\n OmnistonProviderOptions,\n \"validateTonJettonWallet\" | \"validateTonSwapTarget\" | \"validateTonOutputPosition\" | \"validateTonSwapLeg\"\n>> & {validateTonEscrowPayload: (input: PayloadInput) => boolean | Promise<boolean>} {\n const now = options.now ?? Date.now;\n const swapInterfaces = new Set(options.swapTargetInterfaces ?? DEFAULT_OMNISTON_TON_SWAP_INTERFACES);\n const proxyTonMasters = new Set(\n (options.proxyTonMasters ?? DEFAULT_OMNISTON_TON_PROXY_TON_MASTERS).map((value) => Address.parse(value).toRawString()),\n );\n const request = options.fetch ?? fetch;\n const base = (options.tonApiUrl ?? \"https://tonapi.io\").replace(/\\/$/, \"\");\n const headers = options.tonApiKey ? {Authorization: `Bearer ${options.tonApiKey}`} : undefined;\n const get = (path: string) => request(`${base}${path}`, {...(headers ? {headers} : {}), signal: AbortSignal.timeout(5_000)});\n /** Same, retrying tonapi's rate limit (keyless: ~1 rps) — the swap-leg\n * checks run a few reads back to back right after the target checks. */\n const getRetry = async (path: string): Promise<Response> => {\n for (let attempt = 0; ; attempt++) {\n const response = await get(path);\n if (response.status !== 429 || attempt >= 3) return response;\n await new Promise((resolve) => setTimeout(resolve, 1_100 * (attempt + 1)));\n }\n };\n /** A get-method's stack (tonapi), or null when the call failed. */\n const runGet = async (address: string, method: string, args: readonly string[] = []): Promise<{type: string; cell?: string}[] | null> => {\n const query = args.length ? `?${args.map((arg) => `args=${encodeURIComponent(arg)}`).join(\"&\")}` : \"\";\n const response = await getRetry(`/v2/blockchain/accounts/${encodeURIComponent(address)}/methods/${method}${query}`);\n if (!response.ok) return null;\n const body = await response.json() as {success?: boolean; exit_code?: number; stack?: {type: string; cell?: string}[]};\n return body.success === true && (body.exit_code ?? 0) === 0 && Array.isArray(body.stack) ? body.stack : null;\n };\n const stackCell = (entry: {type: string; cell?: string} | undefined): Cell | null =>\n entry && (entry.type === \"cell\" || entry.type === \"slice\") && entry.cell ? cellFromApi(entry.cell) : null;\n /** The jetton wallet a master derives for an owner — computed by the master, not looked up. */\n const derivedWallet = async (master: string, owner: string): Promise<Address | null> => {\n const cell = stackCell((await runGet(master, \"get_wallet_address\", [Address.parse(owner).toRawString()]))?.[0]);\n return cell ? cell.beginParse().loadAddress() : null;\n };\n /** get_wallet_data of a jetton wallet: owner + master, read from the wallet itself. */\n const walletData = async (wallet: string): Promise<{owner: Address; master: Address} | null> => {\n const stack = await runGet(wallet, \"get_wallet_data\");\n const owner = stackCell(stack?.[1]);\n const master = stackCell(stack?.[2]);\n return owner && master ? {owner: owner.beginParse().loadAddress(), master: master.beginParse().loadAddress()} : null;\n };\n const accountHas = async (address: string, iface: string): Promise<boolean> => {\n const response = await getRetry(`/v2/accounts/${encodeURIComponent(address)}`);\n if (!response.ok) return false;\n const body = await response.json() as {address?: string; interfaces?: string[]; is_wallet?: boolean};\n return !!body.address && sameAddress(Address.parse(body.address), address) && body.is_wallet !== true && (body.interfaces ?? []).includes(iface);\n };\n /** Unordered pair equality of jetton masters (null = native GRAM). */\n const samePair = (pool: readonly (string | null)[], leg: readonly (string | null)[]): boolean => {\n const key = (value: string | null) => value === null ? \"native\" : Address.parse(value).toRawString();\n const a = pool.map(key).sort();\n const b = leg.map(key).sort();\n return a.length === 2 && a[0] === b[0] && a[1] === b[1] && a[0] !== a[1];\n };\n /** tonapi's view of a contract: null when unreachable or not the address asked for. */\n const readAccount = async (address: string): Promise<{interfaces: string[]; isWallet: boolean} | null> => {\n const response = await get(`/v2/accounts/${encodeURIComponent(address)}`);\n if (!response.ok) return null;\n const body = await response.json() as {address?: string; interfaces?: string[]; is_wallet?: boolean};\n if (!body.address || !sameAddress(Address.parse(body.address), address)) return null;\n return {interfaces: body.interfaces ?? [], isWallet: body.is_wallet === true};\n };\n const isDexContract = (account: {interfaces: string[]; isWallet: boolean}): boolean =>\n !account.isWallet && account.interfaces.some((name) => swapInterfaces.has(name));\n const trusted = {\n escrow: new Set((options.escrowCodeHashes ?? DEFAULT_OMNISTON_TON_CODE_HASHES.escrow).map((value) => value.toLowerCase())),\n execution: new Set((options.executionCodeHashes ?? DEFAULT_OMNISTON_TON_CODE_HASHES.execution).map((value) => value.toLowerCase())),\n authorityKeys: new Set((options.authorityKeys ?? DEFAULT_OMNISTON_TON_CODE_HASHES.authorityKeys).map((value) => value.toLowerCase())),\n position: new Set((options.positionCodeHashes ?? DEFAULT_OMNISTON_TON_CODE_HASHES.position).map((value) => value.toLowerCase())),\n outputEscrow: new Set((options.outputEscrowCodeHashes ?? DEFAULT_OMNISTON_TON_CODE_HASHES.outputEscrow).map((value) => value.toLowerCase())),\n };\n /** The factory's jetton wallet for a master, from the indexer — the same\n * lookup the TON-source path uses for the trader's wallet. */\n const jettonWalletOf = async (ownerAddress: string, jettonMasterAddress: string): Promise<string | null> => {\n const response = await get(`/v2/accounts/${encodeURIComponent(ownerAddress)}/jettons/${encodeURIComponent(jettonMasterAddress)}`);\n if (!response.ok) return null;\n const body = await response.json() as {wallet_address?: {address?: string}; jetton?: {address?: string}};\n const wallet = body.wallet_address?.address;\n if (!wallet || (body.jetton?.address !== undefined && !sameAddress(Address.parse(body.jetton.address), jettonMasterAddress))) return null;\n return Address.parse(wallet).toString();\n };\n\n return {\n async validateTonJettonWallet({ownerAddress, jettonMasterAddress, walletAddress}) {\n try {\n const url = `${base}/v2/accounts/${encodeURIComponent(ownerAddress)}/jettons/${encodeURIComponent(jettonMasterAddress)}`;\n const response = await request(url, {\n ...(headers ? {headers} : {}),\n signal: AbortSignal.timeout(5_000),\n });\n if (!response.ok) return false;\n const body = await response.json() as {\n wallet_address?: {address?: string};\n jetton?: {address?: string};\n };\n if (!sameAddress(body.wallet_address?.address ? Address.parse(body.wallet_address.address) : null, walletAddress)) return false;\n return body.jetton?.address === undefined || sameAddress(Address.parse(body.jetton.address), jettonMasterAddress);\n } catch {\n return false;\n }\n },\n validateTonEscrowPayload(input: PayloadInput) {\n try {\n return validatePayload(input, trusted);\n } catch {\n return false;\n }\n },\n /**\n * EVM→TON: the position the tracking feed named must be (1) an active\n * contract with the pinned position code, (2) carrying state that binds\n * this quote, hashlock, recipient, output jetton, amount, deposit and the\n * pinned timelocks — still inside the completion window — with jetton\n * custody at the factory's own wallet, and (3) deployed by the trusted\n * factory itself (its deploy message is only sent after the factory's\n * jetton wallet notified it of the resolver's transfer). Nothing here\n * trusts the feed beyond the address it suggested.\n */\n async validateTonOutputPosition(input) {\n const refuse = (reason: string, details?: Record<string, unknown>): false => { try { options.onRefusal?.(reason, details); } catch { /* diagnostics never break validation */ } return false; };\n lastStateRefusal = null;\n try {\n Address.parse(input.positionAddress);\n Address.parse(input.recipientAddress);\n const nowSeconds = Math.floor(now() / 1000);\n if (!Number.isInteger(input.quoteTimestamp) || input.quoteTimestamp > nowSeconds + 120 || nowSeconds - input.quoteTimestamp > 6 * 60 * 60) return refuse(\"quote-age\");\n const accountResponse = await get(`/v2/blockchain/accounts/${encodeURIComponent(input.positionAddress)}`);\n if (!accountResponse.ok) return refuse(\"account-fetch\", {status: accountResponse.status});\n const account = await accountResponse.json() as {address?: string; status?: string; code?: string; data?: string};\n if (!account.address || !sameAddress(Address.parse(account.address), input.positionAddress) || account.status !== \"active\" || !account.code || !account.data) return refuse(\"account-state\", {status: account.status, hasCode: !!account.code, hasData: !!account.data});\n if (!trusted.position.has(cellFromApi(account.code).hash().toString(\"hex\"))) return refuse(\"position-code-hash\", {hash: cellFromApi(account.code).hash().toString(\"hex\")});\n const jettonWallet = await jettonWalletOf(input.protocolAddress, input.outputJettonMasterAddress);\n if (!jettonWallet) return refuse(\"jetton-wallet\");\n const state = validateOutputPositionState(cellFromApi(account.data), input, {jettonWallet, trusted, nowSeconds});\n if (!state) return refuse(\"state\", {check: lastStateRefusal});\n const txResponse = await get(`/v2/blockchain/accounts/${encodeURIComponent(input.positionAddress)}/transactions?limit=25`);\n if (!txResponse.ok) return refuse(\"transactions-fetch\", {status: txResponse.status});\n const body = await txResponse.json() as {transactions?: {success?: boolean; aborted?: boolean; utime?: number; in_msg?: {source?: {address?: string}; op_code?: string}}[]};\n const deployedByFactory = (body.transactions ?? []).some((tx) =>\n tx.success === true && tx.aborted !== true && tx.in_msg?.op_code?.toLowerCase() === POSITION_DEPLOY_OP &&\n !!tx.in_msg.source?.address && sameAddress(Address.parse(tx.in_msg.source.address), input.protocolAddress) &&\n typeof tx.utime === \"number\" && Math.abs(bigintToNumber(BigInt(state.withdrawalAt)) - 1 - tx.utime) <= 5);\n return deployedByFactory || refuse(\"deploy-transaction\", {transactions: (body.transactions ?? []).length});\n } catch (error) {\n return refuse(\"error\", {message: error instanceof Error ? error.message : String(error)});\n }\n },\n /**\n * Scan F11: one chain fact a decoded TON swap body depends on.\n * - STON.fi hop: the router carries the STON.fi router interface of its\n * version; for native input the pTON wallet the message pays is a\n * proxy-TON wallet OWNED BY that router; the hop's ask wallet is the\n * router's own wallet of the hop's output (of a proxy-TON master for\n * native output), as the output's master derives it.\n * - DeDust pool: the pool carries the DeDust pool interface of its version\n * and trades exactly the hop's pair.\n */\n async validateTonSwapLeg(leg: TonSwapLeg) {\n try {\n if (leg.kind === \"stonfi-router\") {\n let router = leg.router ? Address.parse(leg.router) : null;\n if (leg.proxyTonWallet) {\n const data = await walletData(leg.proxyTonWallet);\n if (!data || !proxyTonMasters.has(data.master.toRawString())) return false;\n if (router && !router.equals(data.owner)) return false;\n router = data.owner;\n }\n if (!router) return false;\n if (!await accountHas(router.toString(), leg.version === 1 ? \"stonfi_router\" : \"stonfi_router_v2\")) return false;\n const masters = leg.outputJetton ? [leg.outputJetton] : [...proxyTonMasters];\n for (const master of masters) {\n const wallet = await derivedWallet(master, router.toString());\n if (wallet && wallet.equals(Address.parse(leg.askWallet))) return true;\n }\n return false;\n }\n if (leg.version === 1) {\n if (!await accountHas(leg.pool, \"dedust_pool\")) return false;\n const stack = await runGet(leg.pool, \"get_assets\");\n const assets = [stackCell(stack?.[0]), stackCell(stack?.[1])].map((cell) => {\n if (!cell) return undefined;\n const slice = cell.beginParse();\n const tag = slice.loadUint(4);\n if (tag === 0) return null;\n if (tag !== 1) return undefined;\n return new Address(slice.loadInt(8), slice.loadBuffer(32)).toString();\n });\n if (assets.some((asset) => asset === undefined)) return false;\n return samePair(assets as (string | null)[], [leg.inputJetton, leg.outputJetton]);\n }\n if (!await accountHas(leg.pool, \"dedust_v2_cpmm\")) return false;\n const stack = await runGet(leg.pool, \"get_pool_data\");\n const assets = [stackCell(stack?.[3]), stackCell(stack?.[4])].map((cell) => {\n if (!cell) return undefined;\n const address = cell.beginParse().loadAddressAny();\n if (address === null) return null;\n return address instanceof Address ? address.toString() : undefined;\n });\n if (assets.some((asset) => asset === undefined)) return false;\n return samePair(assets as (string | null)[], [leg.inputJetton, leg.outputJetton]);\n } catch {\n return false;\n }\n },\n /** The contract a swap pays into must carry a recognised DEX code\n * interface on the indexer — an EOA, an unknown contract or a fresh\n * resolver-deployed proxy is refused. */\n async validateTonSwapTarget({address}) {\n try {\n Address.parse(address);\n const account = await readAccount(address);\n if (!account || account.isWallet) return false;\n if (isDexContract(account)) return true;\n // Native input on STON.fi: the target is the router's proxy-TON jetton\n // wallet. Accept it only as \"pTON wallet owned by a DEX router\" —\n // both facts read from the chain, never from the quote.\n if (!account.interfaces.includes(\"jetton_wallet\")) return false;\n const data = await get(`/v2/blockchain/accounts/${encodeURIComponent(address)}/methods/get_wallet_data`);\n if (!data.ok) return false;\n const body = await data.json() as {success?: boolean; decoded?: {owner?: string; jetton?: string}};\n const owner = body.decoded?.owner;\n const master = body.decoded?.jetton;\n if (!body.success || !owner || !master || !proxyTonMasters.has(Address.parse(master).toRawString())) return false;\n const ownerAccount = await readAccount(owner);\n return ownerAccount !== null && isDexContract(ownerAccount);\n } catch {\n return false;\n }\n },\n };\n}\n\n// ── EVM → TON delivery ───────────────────────────────────────────────────────\n\nexport interface OmnistonTonDeliveryLocatorOptions {\n fetch?: typeof fetch;\n tonApiUrl?: string;\n tonApiKey?: string;\n /** Recipient events scanned per call (newest first; the delivery is recent by construction). */\n limit?: number;\n}\n\nexport interface OmnistonTonDeliveryInput {\n /** The output position that paid out; when absent any sender of a matching transfer counts (backfills). */\n positionAddress?: string;\n recipientAddress: string;\n jettonMasterAddress: string;\n minUnits: string;\n /** Unix seconds; events before it are not this delivery (backfills). With it set, the EARLIEST match wins — the one closest to the order, not a later swap's payout. */\n afterTimestamp?: number;\n /** Unix seconds; events after it are not this delivery (backfills: the row's completion time plus slack). */\n beforeTimestamp?: number;\n}\n\ninterface TonapiDeliveryEvent {\n event_id?: string;\n timestamp?: number;\n in_progress?: boolean;\n actions?: Array<{\n type?: string;\n status?: string;\n JettonTransfer?: {\n sender?: {address?: string};\n recipient?: {address?: string};\n jetton?: {address?: string};\n amount?: string | number;\n };\n }>;\n}\n\n/**\n * Finds an Omniston TON delivery: the jetton transfer from the output position\n * to the recipient of at least `minUnits`, in the recipient's tonapi events.\n * Returns tonapi's `event_id` — the hash `@anywalletkit/wallet-ton`'s history\n * source gives the same event as a row, so a wallet can pair the TON receive\n * with the swap. Feeds `omnistonProvider({locateTonDelivery})`; a server may\n * also call it with no position to backfill rows completed before the locator\n * existed. Never throws: null when nothing matched or tonapi did not answer.\n */\nexport function createOmnistonTonDeliveryLocator(options: OmnistonTonDeliveryLocatorOptions = {}) {\n const request = options.fetch ?? fetch;\n const base = (options.tonApiUrl ?? \"https://tonapi.io\").replace(/\\/$/, \"\");\n const headers = options.tonApiKey ? {Authorization: `Bearer ${options.tonApiKey}`} : undefined;\n const limit = Math.min(100, Math.max(1, Math.floor(options.limit ?? 20)));\n return async (input: OmnistonTonDeliveryInput): Promise<string | null> => {\n try {\n const recipient = Address.parse(input.recipientAddress);\n const master = Address.parse(input.jettonMasterAddress);\n const position = input.positionAddress ? Address.parse(input.positionAddress) : null;\n const min = BigInt(input.minUnits);\n if (min <= 0n) return null;\n const since = Number.isFinite(input.afterTimestamp) ? `&start_date=${Math.max(0, Math.floor(input.afterTimestamp!))}` : \"\";\n const until = Number.isFinite(input.beforeTimestamp) ? `&end_date=${Math.max(0, Math.floor(input.beforeTimestamp!))}` : \"\";\n const url = `${base}/v2/accounts/${encodeURIComponent(recipient.toString())}/events?limit=${limit}${since}${until}`;\n const response = await request(url, {...(headers ? {headers} : {}), signal: AbortSignal.timeout(8_000)});\n if (!response.ok) return null;\n const body = await response.json() as {events?: TonapiDeliveryEvent[]};\n // tonapi lists newest first. With a position the newest match is the delivery; a\n // windowed backfill wants the earliest match instead (a later swap's payout to the\n // same recipient would otherwise be taken for this one).\n const events = [...(body.events ?? [])];\n if (input.afterTimestamp !== undefined) events.sort((a, b) => (a.timestamp ?? 0) - (b.timestamp ?? 0));\n for (const event of events) {\n if (!event.event_id || event.in_progress === true) continue;\n if (input.afterTimestamp !== undefined && typeof event.timestamp === \"number\" && event.timestamp < input.afterTimestamp) continue;\n if (input.beforeTimestamp !== undefined && typeof event.timestamp === \"number\" && event.timestamp > input.beforeTimestamp) continue;\n for (const action of event.actions ?? []) {\n if (action.type !== \"JettonTransfer\" || action.status !== \"ok\") continue;\n const t = action.JettonTransfer;\n if (!t?.jetton?.address || !t.recipient?.address || t.amount === undefined) continue;\n if (!sameAddress(Address.parse(t.jetton.address), master.toString())) continue;\n if (!sameAddress(Address.parse(t.recipient.address), recipient.toString())) continue;\n if (position && (!t.sender?.address || !sameAddress(Address.parse(t.sender.address), position.toString()))) continue;\n let amount: bigint;\n try {\n amount = BigInt(t.amount);\n } catch {\n continue;\n }\n if (amount < min) continue;\n return event.event_id.toLowerCase();\n }\n }\n return null;\n } catch {\n return null;\n }\n };\n}\n","/**\n * Settlement contracts this deployment trusts for Omniston, per CAIP-2 chain.\n * Audited public addresses — no secret — so both the server wiring and the\n * browser-side provider import them from here.\n * See how-to-project/OMNISTON-NETWORK-ONBOARDING.md before adding a network.\n */\nexport const AUDITED_OMNISTON_SETTLEMENT_CONTRACTS: Record<string, string[]> = {\n \"ton:-239\": [\"EQAbWJ3Y1HgIIvcMq1prG1anlDC0T3cZlAU7luPT6LmTpmrZ\"],\n \"eip155:1\": [\"0xafCF681272AF10959736f45616eeCBC22D7095E2\"],\n \"eip155:56\": [\"0xafCF681272AF10959736f45616eeCBC22D7095E2\"],\n \"eip155:137\": [\"0x41A392062A4307a6961d48e30FF20bF6823715B8\"],\n \"eip155:4663\": [\"0xafCF681272AF10959736f45616eeCBC22D7095E2\"],\n \"eip155:8453\": [\"0xACa3E2F9b61a44892926bC6c3e104192E7D1c3cd\"],\n \"eip155:42161\": [\"0xafCF681272AF10959736f45616eeCBC22D7095E2\"],\n \"eip155:43114\": [\"0xafCF681272AF10959736f45616eeCBC22D7095E2\"],\n // 2026-10-20: one factory address on X Layer, HyperEVM and Plasma. Runtime\n // bytecode equals Ethereum's 0xafCF… byte for byte except the immutable slots\n // (escrow implementations, its order protocol, domain hash); it references\n // the order protocol trusted below on the same chain.\n \"eip155:196\": [\"0xd602079AFa5c38F550510a2a988CbFa698Fa0189\"],\n \"eip155:999\": [\"0xd602079AFa5c38F550510a2a988CbFa698Fa0189\"],\n \"eip155:9745\": [\"0xd602079AFa5c38F550510a2a988CbFa698Fa0189\"],\n};\n\n/**\n * EVM order protocols (Omniston's fork of the 1inch Limit Order Protocol v4 —\n * NOT the canonical 1inch deployment) an EVM→TON order is signed against. The\n * wallet approves this contract for the input amount and signs an EIP-712\n * order whose domain names it; on fill it moves the input into the escrow the\n * factory above deploys. One address, different roles per chain (0xafCF… is\n * the factory elsewhere and the order protocol on Polygon), so this table is\n * separate from the factory table and CAIP-scoped. Runtime code hashes are in\n * how-to-project/OMNISTON-NETWORK-ONBOARDING.md (snapshot 2026-10-16).\n */\nexport const AUDITED_OMNISTON_EVM_ORDER_PROTOCOLS: Record<string, string[]> = {\n \"eip155:1\": [\"0xb5810aCfD45D85Eaa938bF90a5857295513DA7E9\"],\n \"eip155:56\": [\"0xb5810aCfD45D85Eaa938bF90a5857295513DA7E9\"],\n \"eip155:137\": [\"0xafCF681272AF10959736f45616eeCBC22D7095E2\"],\n \"eip155:8453\": [\"0xe7405fAcDEDB2512e91F2886BDff13231343aF5E\"],\n \"eip155:42161\": [\"0xb5810aCfD45D85Eaa938bF90a5857295513DA7E9\"],\n \"eip155:43114\": [\"0xb5810aCfD45D85Eaa938bF90a5857295513DA7E9\"],\n // 2026-10-20: bytecode equals Ethereum's 0xb581… except immutables (wrapped\n // native, own address, chain id 196 / 9745 / 999 at the chain-id slot).\n \"eip155:196\": [\"0xb5810aCfD45D85Eaa938bF90a5857295513DA7E9\"],\n \"eip155:9745\": [\"0xb5810aCfD45D85Eaa938bF90a5857295513DA7E9\"],\n \"eip155:999\": [\"0xD84778bbeEC5D2a8d17c6424249C438EC0b1ABE3\"],\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAUO;AACP,kBAA+B;AAE/B,IAAM,qBAAqB;AAAA,EACzB;AAAA,IACE,MAAM;AAAA,IACN,MAAM;AAAA,IACN,iBAAiB;AAAA,IACjB,QAAQ;AAAA,MACN;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,YAAY;AAAA,UACV,EAAC,MAAM,aAAa,MAAM,UAAS;AAAA,UACnC,EAAC,MAAM,YAAY,MAAM,UAAS;AAAA,UAClC,EAAC,MAAM,SAAS,MAAM,U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5G,cAAI;AACJ,cAAI;AACF,qBAAS,OAAO,EAAE,MAAM;AAAA,UAC1B,QAAQ;AACN;AAAA,UACF;AACA,cAAI,SAAS,IAAK;AAClB,iBAAO,MAAM,SAAS,YAAY;AAAA,QACpC;AAAA,MACF;AACA,aAAO;AAAA,IACT,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACF;;;AC9oBO,IAAM,wCAAkE;AAAA,EAC7E,YAAY,CAAC,kDAAkD;AAAA,EAC/D,YAAY,CAAC,4CAA4C;AAAA,EACzD,aAAa,CAAC,4CAA4C;AAAA,EAC1D,cAAc,CAAC,4CAA4C;AAAA,EAC3D,eAAe,CAAC,4CAA4C;AAAA,EAC5D,eAAe,CAAC,4CAA4C;AAAA,EAC5D,gBAAgB,CAAC,4CAA4C;AAAA,EAC7D,gBAAgB,CAAC,4CAA4C;AAAA;AAAA;AAAA;AAAA;AAAA,EAK7D,cAAc,CAAC,4CAA4C;AAAA,EAC3D,cAAc,CAAC,4CAA4C;AAAA,EAC3D,eAAe,CAAC,4CAA4C;AAC9D;AAYO,IAAM,uCAAiE;AAAA,EAC5E,YAAY,CAAC,4CAA4C;AAAA,EACzD,aAAa,CAAC,4CAA4C;AAAA,EAC1D,cAAc,CAAC,4CAA4C;AAAA,EAC3D,eAAe,CAAC,4CAA4C;AAAA,EAC5D,gBAAgB,CAAC,4CAA4C;AAAA,EAC7D,gBAAgB,CAAC,4CAA4C;AAAA;AAAA;AAAA,EAG7D,cAAc,CAAC,4CAA4C;AAAA,EAC3D,eAAe,CAAC,4CAA4C;AAAA,EAC5D,cAAc,CAAC,4CAA4C;AAC7D;","names":["import_viem","FACTORY_ABI","DISCLOSURE_MARGIN_SECONDS","UINT32_MASK","ADDRESS_MASK","quantity","uintAddress","bytesHex","stage","ethCall","log","import_core","stack","assets"]}
1
+ {"version":3,"sources":["../src/validators/index.ts","../src/validators/evm-output.ts","../src/validators/evm-input.ts","../src/validators/ton.ts","../src/validators/settlement.ts"],"sourcesContent":["export * from \"./evm-output.js\";\nexport * from \"./evm-input.js\";\nexport * from \"./ton.js\";\nexport * from \"./settlement.js\";\n","import {\n decodeAbiParameters,\n decodeFunctionData,\n decodeFunctionResult,\n encodeFunctionData,\n getAddress,\n isAddress,\n keccak256,\n stringToHex,\n type Hex,\n} from \"viem\";\nimport { bigintToNumber } from '@anywalletkit/core'\n\nconst ESCROW_FACTORY_ABI = [\n {\n type: \"function\",\n name: \"createDstEscrow\",\n stateMutability: \"payable\",\n inputs: [\n {\n name: \"dstImmutables\",\n type: \"tuple\",\n components: [\n {name: \"orderHash\", type: \"bytes32\"},\n {name: \"hashlock\", type: \"bytes32\"},\n {name: \"maker\", type: \"uint256\"},\n {name: \"taker\", type: \"uint256\"},\n {name: \"token\", type: \"uint256\"},\n {name: \"amount\", type: \"uint256\"},\n {name: \"safetyDeposit\", type: \"uint256\"},\n {name: \"timelocks\", type: \"uint256\"},\n {name: \"parameters\", type: \"bytes\"},\n ],\n },\n {name: \"srcCancellationTimestamp\", type: \"uint256\"},\n ],\n outputs: [],\n },\n {\n type: \"function\",\n name: \"addressOfEscrowDst\",\n stateMutability: \"view\",\n inputs: [\n {\n name: \"immutables\",\n type: \"tuple\",\n components: [\n {name: \"orderHash\", type: \"bytes32\"},\n {name: \"hashlock\", type: \"bytes32\"},\n {name: \"maker\", type: \"uint256\"},\n {name: \"taker\", type: \"uint256\"},\n {name: \"token\", type: \"uint256\"},\n {name: \"amount\", type: \"uint256\"},\n {name: \"safetyDeposit\", type: \"uint256\"},\n {name: \"timelocks\", type: \"uint256\"},\n {name: \"parameters\", type: \"bytes\"},\n ],\n },\n ],\n outputs: [{name: \"escrow\", type: \"address\"}],\n },\n] as const;\n\nconst FACTORY_ABI = [{\n type: \"function\", name: \"FACTORY\", stateMutability: \"view\", inputs: [], outputs: [{type: \"address\"}],\n}] as const;\nconst BALANCE_OF_ABI = [{\n type: \"function\", name: \"balanceOf\", stateMutability: \"view\", inputs: [{name: \"account\", type: \"address\"}], outputs: [{type: \"uint256\"}],\n}] as const;\n\n// Address is a uint256 user-defined value type in the 1inch factory ABI.\nconst DST_ESCROW_CREATED_TOPIC = keccak256(stringToHex(\"DstEscrowCreated(address,bytes32,uint256)\"));\nconst UINT32_MASK = (1n << 32n) - 1n;\nconst DEPLOYED_AT_OFFSET = 224n;\nconst DEPLOYED_AT_MASK = UINT32_MASK << DEPLOYED_AT_OFFSET;\nconst ADDRESS_MASK = (1n << 160n) - 1n;\n\n/** Destination timelock stages (seconds after deploy, words 4–6): dst\n * withdrawal, dst public withdrawal, dst cancellation. Every Omniston\n * destination escrow sampled on Base, Arbitrum, BNB and Polygon (39/39,\n * 2026-10-22) carries 1/120/180 — the dst half of `SRC_STAGES` in\n * evm-input.ts and of `POSITION_STAGES` in ton.ts. Words 0–3 (source stages)\n * differ by source chain (0/0/0/0 for TON-source, 1/120/240/300 for\n * EVM-source) and are not this escrow's to enforce. */\nconst DST_STAGES = [1n, 120n, 180n] as const;\nconst DST_STAGE_WORD = 4;\nconst DST_CANCELLATION_STAGE = 2;\n/** Disclosure is refused this close to the destination cancellation stage: past\n * it the resolver can cancel this escrow and still withdraw the source leg\n * with the disclosed secret. Same margin as evm-input.ts and ton.ts. */\nconst DISCLOSURE_MARGIN_SECONDS = 45n;\n/** `immutables.parameters` of the Omniston EscrowDst: abi(uint256 protocolFee,\n * uint256 integratorFee, uint256 protocolFeeRecipient, uint256\n * integratorFeeRecipient) — paid out of `amount` on withdrawal. */\nconst FEE_PARAMETERS = [{type: \"uint256\"}, {type: \"uint256\"}, {type: \"uint256\"}, {type: \"uint256\"}] as const;\nconst FEE_PARAMETERS_HEX_LENGTH = 2 + 128 * 2;\n\n/** Public fallback endpoints only; deployments pass their own via `rpcUrls`. */\nconst DEFAULT_RPC_URLS: Readonly<Record<string, readonly string[]>> = {\n \"eip155:1\": [\"https://ethereum-rpc.publicnode.com\"],\n \"eip155:56\": [\"https://bsc-rpc.publicnode.com\"],\n \"eip155:137\": [\"https://polygon-bor-rpc.publicnode.com\"],\n \"eip155:4663\": [\"https://rpc.mainnet.chain.robinhood.com\"],\n \"eip155:8453\": [\"https://base-rpc.publicnode.com\"],\n \"eip155:42161\": [\"https://arbitrum-one-rpc.publicnode.com\"],\n \"eip155:43114\": [\"https://avalanche-c-chain-rpc.publicnode.com\"],\n \"eip155:196\": [\"https://rpc.xlayer.tech\"],\n \"eip155:999\": [\"https://rpc.hyperliquid.xyz/evm\"],\n \"eip155:9745\": [\"https://rpc.plasma.to\"],\n};\n\n/** How far back (blocks) a factory event is searched, per chain — shared with the EVM input validator. */\nexport const OMNISTON_EVM_LOOKBACK_BLOCKS: Readonly<Record<string, bigint>> = {\n \"eip155:1\": 3_000n,\n \"eip155:56\": 40_000n,\n \"eip155:137\": 20_000n,\n \"eip155:4663\": 100_000n,\n \"eip155:8453\": 20_000n,\n \"eip155:42161\": 100_000n,\n \"eip155:43114\": 20_000n,\n // ~1 s blocks (measured 2026-10-20): ~11 h, past the 6 h quote horizon.\n \"eip155:196\": 40_000n,\n \"eip155:999\": 40_000n,\n \"eip155:9745\": 40_000n,\n};\n\n/** Confirmations before a factory event counts as final, per chain. */\nexport const OMNISTON_EVM_MIN_CONFIRMATIONS: Readonly<Record<string, bigint>> = {\n \"eip155:1\": 2n,\n \"eip155:56\": 5n,\n \"eip155:137\": 20n,\n \"eip155:4663\": 20n,\n \"eip155:8453\": 20n,\n \"eip155:42161\": 20n,\n \"eip155:43114\": 5n,\n \"eip155:196\": 20n, // sequencer rollup\n \"eip155:999\": 5n, // HyperBFT, fast finality\n \"eip155:9745\": 5n, // PlasmaBFT, fast finality\n};\n\nexport type OmnistonRpcRequest = (chain: string, method: string, params: unknown[]) => Promise<unknown>;\n/** CAIP-2 chain → JSON-RPC URLs, tried in order before the public fallbacks. */\nexport type OmnistonRpcUrls = Readonly<Record<string, readonly string[]>>;\ntype RpcRequest = OmnistonRpcRequest;\n\nexport interface EvmOutputValidationInput {\n chain: string;\n positionAddress: string;\n factoryAddress: string;\n quoteTimestamp: number;\n executionIndex: number;\n recipientAddress: string;\n outputTokenAddress: string;\n inputUnits: string;\n outputUnits: string;\n resolverSendsUnits: string;\n srcHtlcSecurityDepositUnits: string;\n dstSecurityDepositUnits: string;\n protocolFeeUnits: string;\n integratorFeeUnits: string;\n integratorAddress?: string;\n /** The quote's `settlementData.protocolFeeRecipientAddress` (destination\n * chain): the only address the escrow may pay a non-zero protocol fee to. */\n protocolFeeRecipientAddress?: string;\n secretHash: Uint8Array;\n}\n\n/** Diagnostics hook: every refusal names its check and the numbers it compared (never a secret). */\nexport type OmnistonEvmOutputRefusal = (reason: string, details?: Record<string, unknown>) => void;\n\ninterface RpcLog {\n data: Hex;\n transactionHash: Hex;\n blockNumber: Hex;\n}\n\ninterface RpcTransaction {\n to: string;\n input: Hex;\n value: Hex;\n}\n\nfunction quantity(value: bigint): Hex {\n return `0x${value.toString(16)}`;\n}\n\nfunction uintAddress(value: bigint): string {\n return getAddress(`0x${(value & ADDRESS_MASK).toString(16).padStart(40, \"0\")}`);\n}\n\nfunction bytesHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction stage(timelocks: bigint, index: number): bigint {\n return (timelocks >> BigInt(index * 32)) & UINT32_MASK;\n}\n\n/** Fee split of a destination escrow, or null when `parameters` is not the 4-word layout. */\nfunction decodeFeeParameters(parameters: Hex): {protocolFee: bigint; integratorFee: bigint; protocolFeeRecipient: bigint; integratorFeeRecipient: bigint} | null {\n if (parameters.length !== FEE_PARAMETERS_HEX_LENGTH) return null;\n try {\n const [protocolFee, integratorFee, protocolFeeRecipient, integratorFeeRecipient] = decodeAbiParameters(FEE_PARAMETERS, parameters);\n return {protocolFee, integratorFee, protocolFeeRecipient, integratorFeeRecipient};\n } catch {\n return null;\n }\n}\n\n/** JSON-RPC over the caller's endpoints (`rpcUrls`) with public failover (reads only). */\nexport async function omnistonEvmRpcRequest(chain: string, method: string, params: unknown[], rpcUrls?: OmnistonRpcUrls): Promise<unknown> {\n const urls = [...(rpcUrls?.[chain] ?? []), ...(DEFAULT_RPC_URLS[chain] ?? [])].filter((url): url is string => !!url);\n if (!urls.length) throw new Error(`omniston: no RPC configured for ${chain}`);\n let lastError: unknown;\n for (const url of urls) {\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\"content-type\": \"application/json\"},\n body: JSON.stringify({jsonrpc: \"2.0\", id: 1, method, params}),\n signal: AbortSignal.timeout(10_000),\n });\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n const body = await response.json() as {result?: unknown; error?: unknown};\n if (body.error !== undefined || body.result === undefined) throw new Error(\"invalid JSON-RPC response\");\n return body.result;\n } catch (error) {\n lastError = error;\n }\n }\n throw lastError instanceof Error ? lastError : new Error(`omniston: RPC failed for ${chain}`);\n}\n\nasync function ethCall(request: RpcRequest, chain: string, to: string, data: Hex): Promise<Hex> {\n return await request(chain, \"eth_call\", [{to, data}, \"latest\"]) as Hex;\n}\n\n/**\n * Builds the mandatory disclosure verifier for TON-source Omniston orders.\n * The feed supplies an address only; this routine proves the actual finalized\n * factory transaction and deterministic escrow before the secret can leave.\n */\n\n/**\n * Find the escrow immutables inside a resolver's calldata.\n *\n * The tuple is ABI-encoded wherever it is passed, so anchoring on the 32-byte\n * hashlock (word 1 of the tuple) yields the static words at fixed offsets and\n * the `parameters` bytes through the tuple's own offset word. What is found\n * here is only a CANDIDATE: the caller proves it by deriving the escrow address\n * from it through the trusted factory (CREATE2 over the immutables), so a\n * decoy tuple planted in the calldata cannot pass.\n */\nfunction locateImmutables(input: Hex, secretHash: Hex): {\n orderHash: Hex;\n hashlock: Hex;\n maker: bigint;\n taker: bigint;\n token: bigint;\n amount: bigint;\n safetyDeposit: bigint;\n timelocks: bigint;\n parameters: Hex;\n} | null {\n const data = input.slice(2).toLowerCase();\n const needle = secretHash.slice(2).toLowerCase();\n const at = data.indexOf(needle);\n // Must be word-aligned, preceded by orderHash and followed by seven words.\n if (at < 72 || (at - 8) % 64 !== 0 || data.length < at + 64 * 8) return null;\n const start = at - 64;\n const word = (i: number): bigint => BigInt(`0x${data.slice(at + 64 * i, at + 64 * (i + 1))}`);\n try {\n const offset = word(7);\n if (offset % 32n !== 0n || offset < 288n || offset > 4096n) return null;\n const lengthAt = start + bigintToNumber(offset) * 2; // offset ≤ 4096, checked above\n if (data.length < lengthAt + 64) return null;\n const length = BigInt(`0x${data.slice(lengthAt, lengthAt + 64)}`);\n if (length > 1024n || data.length < lengthAt + 64 + bigintToNumber(length) * 2) return null;\n return {\n orderHash: `0x${data.slice(start, at)}`,\n hashlock: `0x${needle}`,\n maker: word(1), taker: word(2), token: word(3), amount: word(4), safetyDeposit: word(5), timelocks: word(6),\n parameters: `0x${data.slice(lengthAt + 64, lengthAt + 64 + bigintToNumber(length) * 2)}`,\n };\n } catch {\n return null;\n }\n}\n\nexport function createOmnistonEvmOutputValidator(options: {request?: RpcRequest; rpcUrls?: OmnistonRpcUrls; now?: () => number; onRefusal?: OmnistonEvmOutputRefusal} = {}) {\n const refuse = (reason: string, details?: Record<string, unknown>): false => {\n try { options.onRefusal?.(reason, details); } catch { /* diagnostics never break validation */ }\n return false;\n };\n const request: RpcRequest = options.request ?? ((chain, method, params) => omnistonEvmRpcRequest(chain, method, params, options.rpcUrls));\n const now = options.now ?? Date.now;\n return async (input: EvmOutputValidationInput): Promise<boolean> => {\n try {\n if (\n !OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain] || input.executionIndex !== 0 ||\n !isAddress(input.positionAddress) || !isAddress(input.factoryAddress) ||\n !isAddress(input.recipientAddress) || !isAddress(input.outputTokenAddress) ||\n !Number.isInteger(input.quoteTimestamp) || input.quoteTimestamp * 1000 > now() + 120_000 ||\n now() - input.quoteTimestamp * 1000 > 6 * 60 * 60 * 1000\n ) return refuse(\"input-shape\");\n\n const position = getAddress(input.positionAddress);\n const factory = getAddress(input.factoryAddress);\n const recipient = getAddress(input.recipientAddress);\n const token = getAddress(input.outputTokenAddress);\n const secretHash = bytesHex(input.secretHash);\n const outputUnits = BigInt(input.outputUnits);\n const resolverSendsUnits = BigInt(input.resolverSendsUnits);\n const protocolFeeUnits = BigInt(input.protocolFeeUnits);\n const integratorFeeUnits = BigInt(input.integratorFeeUnits);\n const dstDeposit = BigInt(input.dstSecurityDepositUnits);\n if (\n BigInt(input.inputUnits) <= 0n || outputUnits <= 0n || dstDeposit <= 0n ||\n resolverSendsUnits !== outputUnits + protocolFeeUnits + integratorFeeUnits ||\n input.secretHash.length !== 32\n ) return refuse(\"quote-amounts\", {outputUnits: String(outputUnits), resolverSendsUnits: String(resolverSendsUnits), protocolFeeUnits: String(protocolFeeUnits), integratorFeeUnits: String(integratorFeeUnits)});\n if (protocolFeeUnits < 0n || integratorFeeUnits < 0n) return refuse(\"quote-amounts\", {protocolFeeUnits: String(protocolFeeUnits), integratorFeeUnits: String(integratorFeeUnits)});\n // The recipients a non-zero fee may go to come from the quote, never from\n // the escrow: a missing quote field is a refusal, not a skipped check.\n if (protocolFeeUnits > 0n && (!input.protocolFeeRecipientAddress || !isAddress(input.protocolFeeRecipientAddress))) {\n return refuse(\"quote-missing-protocol-fee-recipient\", {protocolFeeUnits: String(protocolFeeUnits)});\n }\n if (integratorFeeUnits > 0n && (!input.integratorAddress || !isAddress(input.integratorAddress))) {\n return refuse(\"quote-missing-integrator-address\", {integratorFeeUnits: String(integratorFeeUnits)});\n }\n\n const latest = BigInt(await request(input.chain, \"eth_blockNumber\", []) as string);\n const minConfirmations = OMNISTON_EVM_MIN_CONFIRMATIONS[input.chain] ?? 20n;\n const newestFinal = latest >= minConfirmations ? latest - minConfirmations : 0n;\n const oldest = newestFinal > OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain]!\n ? newestFinal - OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain]!\n : 0n;\n let matchingLog: RpcLog | undefined;\n for (let to = newestFinal; to >= oldest && !matchingLog;) {\n const from = to - oldest > 4_999n ? to - 4_999n : oldest;\n const logs = await request(input.chain, \"eth_getLogs\", [{\n address: factory,\n topics: [DST_ESCROW_CREATED_TOPIC],\n fromBlock: quantity(from),\n toBlock: quantity(to),\n }]) as RpcLog[];\n matchingLog = logs.find((log) => {\n try {\n const [escrow, hashlock] = decodeAbiParameters(\n [{type: \"address\"}, {type: \"bytes32\"}, {type: \"uint256\"}],\n log.data,\n );\n return getAddress(escrow) === position && hashlock.toLowerCase() === secretHash.toLowerCase();\n } catch {\n return false;\n }\n });\n if (from === oldest) break;\n to = from - 1n;\n }\n if (!matchingLog) return refuse(\"no-escrow-event\", {factory, lookback: String(OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain])});\n\n const [transaction, receipt, block, code] = await Promise.all([\n request(input.chain, \"eth_getTransactionByHash\", [matchingLog.transactionHash]) as Promise<RpcTransaction | null>,\n request(input.chain, \"eth_getTransactionReceipt\", [matchingLog.transactionHash]) as Promise<{status: Hex; blockNumber: Hex} | null>,\n request(input.chain, \"eth_getBlockByNumber\", [matchingLog.blockNumber, false]) as Promise<{timestamp: Hex} | null>,\n request(input.chain, \"eth_getCode\", [position, \"latest\"]) as Promise<Hex>,\n ]);\n if (\n !transaction || !receipt || !block || !code || code === \"0x\" || receipt.status !== \"0x1\" ||\n BigInt(receipt.blockNumber) !== BigInt(matchingLog.blockNumber) ||\n latest - BigInt(receipt.blockNumber) < minConfirmations ||\n BigInt(block.timestamp) + 120n < BigInt(input.quoteTimestamp)\n ) return refuse(\"receipt-or-confirmations\", {receiptStatus: receipt?.status, receiptBlock: receipt?.blockNumber, logBlock: matchingLog.blockNumber, latest: String(latest), minConfirmations: String(minConfirmations), codeLength: code ? code.length : 0, blockTimestamp: block?.timestamp});\n\n // Resolvers deploy the destination escrow through their OWN contract, not\n // by calling the factory directly: the observed transaction targets the\n // resolver, carries its private selector and sends no value, while the\n // factory only emits the event. Reconstructing `createDstEscrow` from that\n // calldata therefore never matches, which silently blocked every\n // disclosure. What the trader actually needs is provable without it: an\n // escrow the TRUSTED factory announced for THIS hashlock, deployed, and\n // already holding the promised output.\n //\n // The immutables still ride through that calldata as a contiguous ABI\n // tuple, so when the hashlock can be located we verify the fields that\n // decide who gets paid, and a contradiction is fatal. When the wrapper\n // hides them, the on-chain evidence below still has to hold.\n // Fail closed: the immutables decide who gets paid, so they must be\n // found AND proven to be this escrow's — the factory derives the escrow\n // address from them (deployedAt is stamped with the deployment block's\n // timestamp before the CREATE2 salt is taken). Seen live on Base\n // 2026-10-20 for every Omniston destination escrow.\n const immutables = locateImmutables(transaction.input, secretHash);\n if (!immutables) return refuse(\"immutables-not-found\", {transaction: matchingLog.transactionHash});\n const stamped = {...immutables, timelocks: (immutables.timelocks & ~DEPLOYED_AT_MASK) | (BigInt(block.timestamp) << DEPLOYED_AT_OFFSET)};\n const derived = decodeFunctionResult({\n abi: ESCROW_FACTORY_ABI,\n functionName: \"addressOfEscrowDst\",\n data: await ethCall(request, input.chain, factory, encodeFunctionData({abi: ESCROW_FACTORY_ABI, functionName: \"addressOfEscrowDst\", args: [stamped]})),\n });\n if (getAddress(derived) !== position) return refuse(\"derived-address\", {derived, position});\n if (!(\n uintAddress(immutables.maker) === recipient &&\n uintAddress(immutables.token) === token &&\n immutables.amount === resolverSendsUnits &&\n immutables.safetyDeposit === dstDeposit\n )) return refuse(\"escrow-terms\", {maker: uintAddress(immutables.maker), recipient, token: uintAddress(immutables.token), expectedToken: token, amount: String(immutables.amount), resolverSendsUnits: String(resolverSendsUnits), safetyDeposit: String(immutables.safetyDeposit), dstDeposit: String(dstDeposit)});\n\n // The fee split is paid OUT of `amount` on withdrawal (scan F12): the\n // amounts must be exactly the quoted fees, a non-zero fee may only go to\n // the quote's recipient, and what is left must be the quoted output.\n const fees = decodeFeeParameters(immutables.parameters);\n if (!fees || fees.protocolFeeRecipient > ADDRESS_MASK || fees.integratorFeeRecipient > ADDRESS_MASK) {\n return refuse(\"fee-parameters-shape\", {parametersLength: (immutables.parameters.length - 2) / 2});\n }\n if (fees.protocolFee !== protocolFeeUnits || fees.integratorFee !== integratorFeeUnits || immutables.amount - fees.protocolFee - fees.integratorFee !== outputUnits) {\n return refuse(\"fee-amounts\", {protocolFee: String(fees.protocolFee), protocolFeeUnits: String(protocolFeeUnits), integratorFee: String(fees.integratorFee), integratorFeeUnits: String(integratorFeeUnits), amount: String(immutables.amount), outputUnits: String(outputUnits)});\n }\n if (fees.protocolFee > 0n && uintAddress(fees.protocolFeeRecipient) !== getAddress(input.protocolFeeRecipientAddress!)) {\n return refuse(\"protocol-fee-recipient\", {escrow: uintAddress(fees.protocolFeeRecipient), quote: getAddress(input.protocolFeeRecipientAddress!)});\n }\n // A zero integrator fee pays nothing, whatever recipient word it carries\n // (live escrows often name one with integratorFee = 0).\n if (fees.integratorFee > 0n && uintAddress(fees.integratorFeeRecipient) !== getAddress(input.integratorAddress!)) {\n return refuse(\"integrator-fee-recipient\", {escrow: uintAddress(fees.integratorFeeRecipient), quote: getAddress(input.integratorAddress!)});\n }\n\n // Destination stages pinned to the audited profile (withdrawal opens\n // before cancellation), and the secret only leaves while there is still\n // time for the maker's withdrawal to land before cancellation opens.\n // deployedAt is the deployment block's timestamp (the factory stamps it).\n if (DST_STAGES.some((expected, index) => stage(immutables.timelocks, DST_STAGE_WORD + index) !== expected)) {\n return refuse(\"dst-timelocks\", {stages: DST_STAGES.map((_, index) => String(stage(immutables.timelocks, DST_STAGE_WORD + index)))});\n }\n const deployedAt = BigInt(block.timestamp);\n const nowSeconds = BigInt(Math.floor(now() / 1000));\n if (nowSeconds + DISCLOSURE_MARGIN_SECONDS >= deployedAt + DST_STAGES[DST_CANCELLATION_STAGE]) {\n return refuse(\"dst-cancellation-window\", {now: String(nowSeconds), deployedAt: String(deployedAt), cancellationAt: String(deployedAt + DST_STAGES[DST_CANCELLATION_STAGE]), marginSeconds: String(DISCLOSURE_MARGIN_SECONDS)});\n }\n\n const [reportedFactory, tokenBalance, nativeBalance] = await Promise.all([\n ethCall(request, input.chain, position, encodeFunctionData({abi: FACTORY_ABI, functionName: \"FACTORY\"}))\n .then((data) => decodeFunctionResult({abi: FACTORY_ABI, functionName: \"FACTORY\", data})),\n ethCall(request, input.chain, token, encodeFunctionData({abi: BALANCE_OF_ABI, functionName: \"balanceOf\", args: [position]}))\n .then((data) => decodeFunctionResult({abi: BALANCE_OF_ABI, functionName: \"balanceOf\", data})),\n request(input.chain, \"eth_getBalance\", [position, \"latest\"]) as Promise<Hex>,\n ]);\n // The escrow points back at the trusted factory, holds the output the\n // resolver promised, and carries its own safety deposit — none of which a\n // resolver can fake by merely reporting a phase.\n const ok = getAddress(reportedFactory) === factory &&\n tokenBalance >= resolverSendsUnits &&\n BigInt(nativeBalance) >= dstDeposit;\n return ok || refuse(\"escrow-state\", {reportedFactory, factory, tokenBalance: String(tokenBalance), resolverSendsUnits: String(resolverSendsUnits), nativeBalance: String(BigInt(nativeBalance)), dstDeposit: String(dstDeposit)});\n } catch (error) {\n return refuse(\"error\", {message: error instanceof Error ? error.message : String(error)});\n }\n };\n}\n\nconst TRANSFER_TOPIC = keccak256(stringToHex(\"Transfer(address,address,uint256)\"));\nconst topicAddress = (address: string): Hex => `0x${getAddress(address).slice(2).toLowerCase().padStart(64, \"0\")}`;\n\n/**\n * Finds an Omniston EVM delivery: the ERC-20 `Transfer` from the destination\n * escrow to the recipient of at least `minUnits`, within the chain's lookback\n * window. Feeds `omnistonProvider({locateEvmDelivery})` so a completed order\n * reports the transaction that actually paid the recipient.\n */\nexport function createOmnistonEvmDeliveryLocator(options: {request?: RpcRequest; rpcUrls?: OmnistonRpcUrls} = {}) {\n const request: RpcRequest = options.request ?? ((chain, method, params) => omnistonEvmRpcRequest(chain, method, params, options.rpcUrls));\n return async (input: {chain: string; positionAddress: string; recipientAddress: string; tokenAddress: string; minUnits: string}): Promise<string | null> => {\n try {\n const lookback = OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain];\n if (!lookback || !isAddress(input.positionAddress) || !isAddress(input.recipientAddress) || !isAddress(input.tokenAddress)) return null;\n const min = BigInt(input.minUnits);\n const latest = BigInt(await request(input.chain, \"eth_blockNumber\", []) as string);\n const oldest = latest > lookback ? latest - lookback : 0n;\n for (let to = latest; to >= oldest;) {\n const from = to - oldest > 4_999n ? to - 4_999n : oldest;\n const logs = await request(input.chain, \"eth_getLogs\", [{\n address: getAddress(input.tokenAddress),\n topics: [TRANSFER_TOPIC, topicAddress(input.positionAddress), topicAddress(input.recipientAddress)],\n fromBlock: quantity(from),\n toBlock: quantity(to),\n }]) as (RpcLog & {address: string})[];\n const hit = [...logs].reverse().find((log) => {\n try {\n return getAddress(log.address) === getAddress(input.tokenAddress) && BigInt(log.data) >= min;\n } catch {\n return false;\n }\n });\n if (hit) return hit.transactionHash;\n if (from === oldest) break;\n to = from - 1n;\n }\n return null;\n } catch {\n return null;\n }\n };\n}\n","import {\n decodeEventLog,\n decodeFunctionResult,\n encodeFunctionData,\n getAddress,\n isAddress,\n keccak256,\n stringToHex,\n type Hex,\n} from \"viem\";\nimport {\n OMNISTON_EVM_LOOKBACK_BLOCKS,\n OMNISTON_EVM_MIN_CONFIRMATIONS,\n omnistonEvmRpcRequest,\n type OmnistonRpcRequest,\n type OmnistonRpcUrls,\n} from \"./evm-output.js\";\n\n/**\n * EVM→TON: proves the trader's SOURCE position before the HTLC secret is\n * disclosed. The Omniston escrow factory (a 1inch cross-chain-swap fork with a\n * `parameters` tail on both immutables structs) emits `SrcEscrowCreated` from\n * the order's post-interaction once the resolver filled the signed order and\n * the maker's tokens plus the resolver's safety deposit sit in the\n * deterministic escrow. Everything below is read from the trusted factory and\n * the escrow itself; the Omniston tracking feed only supplied the address.\n */\n\nconst IMMUTABLES = [\n {name: \"orderHash\", type: \"bytes32\"},\n {name: \"hashlock\", type: \"bytes32\"},\n {name: \"maker\", type: \"uint256\"},\n {name: \"taker\", type: \"uint256\"},\n {name: \"token\", type: \"uint256\"},\n {name: \"amount\", type: \"uint256\"},\n {name: \"safetyDeposit\", type: \"uint256\"},\n {name: \"timelocks\", type: \"uint256\"},\n {name: \"parameters\", type: \"bytes\"},\n] as const;\nconst DST_COMPLEMENT = [\n {name: \"maker\", type: \"uint256\"},\n {name: \"amount\", type: \"uint256\"},\n {name: \"token\", type: \"uint256\"},\n {name: \"safetyDeposit\", type: \"uint256\"},\n {name: \"chainId\", type: \"uint256\"},\n {name: \"parameters\", type: \"bytes\"},\n] as const;\nconst FACTORY_ABI = [\n {\n type: \"event\",\n name: \"SrcEscrowCreated\",\n inputs: [\n {name: \"srcImmutables\", type: \"tuple\", components: IMMUTABLES, indexed: false},\n {name: \"dstImmutablesComplement\", type: \"tuple\", components: DST_COMPLEMENT, indexed: false},\n ],\n },\n {\n type: \"function\",\n name: \"addressOfEscrowSrc\",\n stateMutability: \"view\",\n inputs: [{name: \"immutables\", type: \"tuple\", components: IMMUTABLES}],\n outputs: [{name: \"escrow\", type: \"address\"}],\n },\n {type: \"function\", name: \"FACTORY\", stateMutability: \"view\", inputs: [], outputs: [{type: \"address\"}]},\n {type: \"function\", name: \"balanceOf\", stateMutability: \"view\", inputs: [{name: \"account\", type: \"address\"}], outputs: [{type: \"uint256\"}]},\n] as const;\n\n/** keccak256 of the event signature with the structs expanded (live Base 2026-10-16: 0x1140dcf8…). */\nexport const SRC_ESCROW_CREATED_TOPIC = keccak256(stringToHex(\n \"SrcEscrowCreated((bytes32,bytes32,uint256,uint256,uint256,uint256,uint256,uint256,bytes),(uint256,uint256,uint256,uint256,uint256,bytes))\",\n));\n\n/** Timelock stages (seconds after deploy) of the audited v1beta8 profile:\n * src withdrawal, src public withdrawal, src cancellation, src public\n * cancellation, dst withdrawal, dst public withdrawal, dst cancellation. */\nconst SRC_STAGES = [1n, 120n, 240n, 300n, 1n, 120n, 180n] as const;\nconst SRC_CANCELLATION_STAGE = 2;\n/** Disclosure is refused this close to the source cancellation stage: the\n * resolver could otherwise withdraw the input while the TON position (which\n * cancels 60 s earlier) can no longer be completed. */\nconst DISCLOSURE_MARGIN_SECONDS = 45n;\nconst UINT32_MASK = (1n << 32n) - 1n;\nconst ADDRESS_MASK = (1n << 160n) - 1n;\n\nexport interface EvmInputValidationInput {\n chain: string;\n positionAddress: string;\n factoryAddress: string;\n orderProtocolAddress: string;\n ownerAddress: string;\n resolverAddress: string;\n inputTokenAddress: string;\n inputUnits: string;\n resolverSendsUnits: string;\n srcHtlcSecurityDepositUnits: string;\n quoteTimestamp: number;\n secretHash: Uint8Array;\n /** EVM destination only: the destination complement must name this chain, token and deposit. */\n destinationChainId?: number;\n destinationTokenAddress?: string;\n dstSecurityDepositUnits?: string;\n}\n\ninterface RpcLog {\n address: string;\n data: Hex;\n topics: Hex[];\n transactionHash: Hex;\n blockNumber: Hex;\n}\n\nfunction quantity(value: bigint): Hex {\n return `0x${value.toString(16)}`;\n}\n\nfunction uintAddress(value: bigint): string {\n return getAddress(`0x${(value & ADDRESS_MASK).toString(16).padStart(40, \"0\")}`);\n}\n\nfunction bytesHex(bytes: Uint8Array): Hex {\n return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\nfunction stage(timelocks: bigint, index: number): bigint {\n return (timelocks >> BigInt(index * 32)) & UINT32_MASK;\n}\n\nasync function ethCall(request: OmnistonRpcRequest, chain: string, to: string, data: Hex): Promise<Hex> {\n return await request(chain, \"eth_call\", [{to, data}, \"latest\"]) as Hex;\n}\n\n/** Diagnostics hook: every refusal names its check and the numbers it compared (never a secret). */\nexport type OmnistonValidatorRefusal = (reason: string, details?: Record<string, unknown>) => void;\n\nexport function createOmnistonEvmInputValidator(options: {request?: OmnistonRpcRequest; rpcUrls?: OmnistonRpcUrls; now?: () => number; onRefusal?: OmnistonValidatorRefusal} = {}) {\n const refuse = (reason: string, details?: Record<string, unknown>): false => {\n try { options.onRefusal?.(reason, details); } catch { /* diagnostics never break validation */ }\n return false;\n };\n const request: OmnistonRpcRequest = options.request ?? ((chain, method, params) => omnistonEvmRpcRequest(chain, method, params, options.rpcUrls));\n const now = options.now ?? Date.now;\n return async (input: EvmInputValidationInput): Promise<boolean> => {\n try {\n if (\n !OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain] ||\n !isAddress(input.positionAddress) || !isAddress(input.factoryAddress) || !isAddress(input.orderProtocolAddress) ||\n !isAddress(input.ownerAddress) || !isAddress(input.resolverAddress) || !isAddress(input.inputTokenAddress) ||\n !Number.isInteger(input.quoteTimestamp) || input.quoteTimestamp * 1000 > now() + 120_000 ||\n now() - input.quoteTimestamp * 1000 > 6 * 60 * 60 * 1000 || input.secretHash.length !== 32\n ) return refuse(\"input-shape\");\n const position = getAddress(input.positionAddress);\n const factory = getAddress(input.factoryAddress);\n const owner = getAddress(input.ownerAddress);\n const resolver = getAddress(input.resolverAddress);\n const token = getAddress(input.inputTokenAddress);\n const secretHash = bytesHex(input.secretHash).toLowerCase();\n const inputUnits = BigInt(input.inputUnits);\n const resolverSendsUnits = BigInt(input.resolverSendsUnits);\n const safetyDeposit = BigInt(input.srcHtlcSecurityDepositUnits);\n if (inputUnits <= 0n || resolverSendsUnits <= 0n || safetyDeposit <= 0n) return refuse(\"non-positive-amounts\");\n\n const latest = BigInt(await request(input.chain, \"eth_blockNumber\", []) as string);\n const minConfirmations = OMNISTON_EVM_MIN_CONFIRMATIONS[input.chain] ?? 20n;\n const newestFinal = latest >= minConfirmations ? latest - minConfirmations : 0n;\n const lookback = OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain]!;\n const oldest = newestFinal > lookback ? newestFinal - lookback : 0n;\n let match: {log: RpcLog; immutables: {\n orderHash: Hex; hashlock: Hex; maker: bigint; taker: bigint; token: bigint; amount: bigint; safetyDeposit: bigint; timelocks: bigint; parameters: Hex;\n }; complement: {maker: bigint; amount: bigint; token: bigint; safetyDeposit: bigint; chainId: bigint; parameters: Hex}} | undefined;\n for (let to = newestFinal; to >= oldest && !match;) {\n const from = to - oldest > 4_999n ? to - 4_999n : oldest;\n const logs = await request(input.chain, \"eth_getLogs\", [{\n address: factory,\n topics: [SRC_ESCROW_CREATED_TOPIC],\n fromBlock: quantity(from),\n toBlock: quantity(to),\n }]) as RpcLog[];\n for (const log of logs) {\n if (getAddress(log.address) !== factory) continue;\n try {\n const decoded = decodeEventLog({abi: FACTORY_ABI, eventName: \"SrcEscrowCreated\", data: log.data, topics: log.topics as [Hex, ...Hex[]]});\n if (decoded.args.srcImmutables.hashlock.toLowerCase() === secretHash) {\n match = {log, immutables: decoded.args.srcImmutables, complement: decoded.args.dstImmutablesComplement};\n break;\n }\n } catch {\n /* a foreign log shape is not ours */\n }\n }\n if (from === oldest) break;\n to = from - 1n;\n }\n if (!match) return refuse(\"no-fill-event\", {factory, lookback: String(OMNISTON_EVM_LOOKBACK_BLOCKS[input.chain])});\n const {immutables, complement, log} = match;\n const deployedAt = stage(immutables.timelocks, 7);\n // What the resolver filled must be exactly what the wallet signed: the\n // trader's full input, for this resolver, with the quoted deposit and\n // the pinned timelocks; the complement binds the TON output amount.\n if (\n uintAddress(immutables.maker) !== owner || uintAddress(immutables.taker) !== resolver ||\n uintAddress(immutables.token) !== token || immutables.amount !== inputUnits ||\n immutables.safetyDeposit !== safetyDeposit || immutables.parameters !== \"0x\" ||\n SRC_STAGES.some((expected, index) => stage(immutables.timelocks, index) !== expected) ||\n deployedAt < BigInt(input.quoteTimestamp) - 120n || deployedAt > BigInt(input.quoteTimestamp) + 900n ||\n // EVM destination: the complement is the destination escrow's amount, enforced by its CREATE2\n // derivation — exact. TON destination: Omniston records a larger figure here (live 2026-10-20,\n // both orders: 1.089 × resolverSendsUnits — 4 485 039 for 4 118 665, 791 340 for 726 690); the\n // delivered amount is proven on the TON position itself (validateTonOutputPosition), so this\n // only has to be no smaller than the promise. Strict equality blocked every EVM → TON disclosure.\n (input.destinationChainId !== undefined ? complement.amount !== resolverSendsUnits : complement.amount < resolverSendsUnits)\n ) return refuse(\"refused\");\n // EVM destination: the complement the factory recorded must point at the\n // quoted chain, token and destination deposit (TON keeps its own terms).\n if (input.destinationChainId !== undefined && (\n complement.chainId !== BigInt(input.destinationChainId) ||\n !input.destinationTokenAddress || !isAddress(input.destinationTokenAddress) ||\n uintAddress(complement.token) !== getAddress(input.destinationTokenAddress) ||\n complement.safetyDeposit !== BigInt(input.dstSecurityDepositUnits ?? \"-1\")\n )) return refuse(\"complement-destination\");\n\n // The escrow address is a function of the immutables (CREATE2 through\n // the factory): the feed's address must be that function's value.\n const derived = decodeFunctionResult({\n abi: FACTORY_ABI,\n functionName: \"addressOfEscrowSrc\",\n data: await ethCall(request, input.chain, factory, encodeFunctionData({abi: FACTORY_ABI, functionName: \"addressOfEscrowSrc\", args: [immutables]})),\n });\n if (getAddress(derived) !== position) return refuse(\"derived-address\", {derived, position});\n\n const [receipt, block, code] = await Promise.all([\n request(input.chain, \"eth_getTransactionReceipt\", [log.transactionHash]) as Promise<{status: Hex; blockNumber: Hex} | null>,\n request(input.chain, \"eth_getBlockByNumber\", [log.blockNumber, false]) as Promise<{timestamp: Hex} | null>,\n request(input.chain, \"eth_getCode\", [position, \"latest\"]) as Promise<Hex>,\n ]);\n if (\n !receipt || !block || !code || code === \"0x\" || receipt.status !== \"0x1\" ||\n BigInt(receipt.blockNumber) !== BigInt(log.blockNumber) ||\n latest - BigInt(receipt.blockNumber) < minConfirmations ||\n BigInt(block.timestamp) !== deployedAt\n ) return refuse(\"receipt-or-confirmations\", {receiptStatus: receipt?.status, receiptBlock: receipt?.blockNumber, logBlock: log.blockNumber, latest: String(latest), minConfirmations: String(minConfirmations), codeLength: code ? code.length : 0, blockTimestamp: block?.timestamp, deployedAt: String(deployedAt)});\n // Still early enough to complete: the resolver must not be able to\n // cancel the source leg (and keep the TON side) once the secret is out.\n const nowSeconds = BigInt(Math.floor(now() / 1000));\n if (nowSeconds + DISCLOSURE_MARGIN_SECONDS >= deployedAt + SRC_STAGES[SRC_CANCELLATION_STAGE]) return refuse(\"receipt-or-confirmations\", {receiptStatus: receipt?.status, receiptBlock: receipt?.blockNumber, logBlock: log.blockNumber, latest: String(latest), minConfirmations: String(minConfirmations), codeLength: code ? code.length : 0, blockTimestamp: block?.timestamp, deployedAt: String(deployedAt)});\n\n const [reportedFactory, tokenBalance, nativeBalance] = await Promise.all([\n ethCall(request, input.chain, position, encodeFunctionData({abi: FACTORY_ABI, functionName: \"FACTORY\"}))\n .then((data) => decodeFunctionResult({abi: FACTORY_ABI, functionName: \"FACTORY\", data})),\n ethCall(request, input.chain, token, encodeFunctionData({abi: FACTORY_ABI, functionName: \"balanceOf\", args: [position]}))\n .then((data) => decodeFunctionResult({abi: FACTORY_ABI, functionName: \"balanceOf\", data})),\n request(input.chain, \"eth_getBalance\", [position, \"latest\"]) as Promise<Hex>,\n ]);\n const ok = getAddress(reportedFactory) === factory && tokenBalance >= inputUnits && BigInt(nativeBalance) >= safetyDeposit;\n return ok || refuse(\"escrow-state\", {reportedFactory, factory, tokenBalance: String(tokenBalance), inputUnits: String(inputUnits), nativeBalance: String(BigInt(nativeBalance)), safetyDeposit: String(safetyDeposit)});\n } catch (error) {\n return refuse(\"error\", {message: error instanceof Error ? error.message : String(error)});\n }\n };\n}\n","import \"../buffer-global.js\";\nimport {Buffer} from \"buffer\";\nimport {Address, Cell} from \"@ton/core\";\nimport type {OmnistonProviderOptions} from \"../provider.js\";\nimport type {TonSwapLeg} from \"../ton-swap.js\";\nimport {bigintToNumber} from \"@anywalletkit/core\";\nimport {AUDITED_OMNISTON_SETTLEMENT_CONTRACTS} from \"./settlement.js\";\n\nconst JETTON_TRANSFER_OP = 0x0f8a7ea5;\nconst ESCROW_CREATE_OP = 0xc0a5f0d9;\nconst ESCROW_CONFIG_OP = 0xf2c6fa63;\nconst ESCROW_EXECUTION_KECCAK_OP = 0xc8d4b428;\nconst MAX_FORWARD_NANO = 2_000_000_000n;\n\n/** Audited from the active mainnet Escrow builder on 2026-08-13. These are\n * immutable TVM code cells, not resolver-controlled addresses. A contract\n * upgrade must deliberately update these hashes after reviewing its schema.\n *\n * `authorityKeys` is the optional 256-bit public key in the escrow config: the\n * escrow code checks `CHKSIGNU` against it for its signature-gated operations\n * (disassembly of code 9e77cb9e…, 2026-10-11). It has been the same key since\n * the August audit, so it stays pinned. */\nexport const DEFAULT_OMNISTON_TON_CODE_HASHES = {\n escrow: [\"9e77cb9e8fd7406d4e85e5f57378eb51e51b862424cf988306c783d50ade697a\"],\n execution: [\"f6edbc76e6fbcd6bac573cb942401a3d9198ee9605f9403b0f5c8081259210e5\"],\n authorityKeys: [\"ed210da12aa96ea42de4f2f61dc172bbaa3da86051a1b2a6f342f69a777d2770\"],\n /** EVM→TON output position: the contract the factory deploys for the\n * resolver's jetton lock (observed on every resolver-created position,\n * 2026-10-15/16), and the escrow code cell it carries in its state. */\n position: [\"e4d5115a321ade7b827e38fb522c20d2f2cd46e4c6b0b5f7dd8b6b096792d77b\"],\n outputEscrow: [\"d30423575384773abaad8d3c6f763898afa3d57a5693005904b7c61e95cee630\"],\n} as const;\n\n/** The factory's message that installs a position's state (op of the deploy\n * message every resolver-created output position received, 2026-10-15). */\nconst POSITION_DEPLOY_OP = \"0xf240cd30\";\n/** Position timelocks after deploy: withdrawal, public withdrawal, cancellation\n * (the EVM extension's dst timelocks 1/120/180; the position stores absolute\n * timestamps = deploy time + stage, with the first one rounded 1 s later). */\nconst POSITION_STAGES = {publicWithdrawalAfterWithdrawal: 119n, cancellationAfterWithdrawal: 179n};\n/** Disclosure is refused this close to the position's cancellation boundary:\n * after it the resolver can take the jettons back while it already holds the\n * secret for the EVM source escrow. */\nconst OUTPUT_DISCLOSURE_MARGIN_SECONDS = 45;\n\n/** Upper bound on the exclusivity window the escrow config may carry. It is\n * how long the trader's input stays locked when no resolver reserves the\n * position (SDK: \"at the end of this period trader's position becomes\n * available for manual withdrawal\"); the live value is 300 s. */\nexport const MAX_OMNISTON_EXCLUSIVITY_SECONDS = 3_600;\n\n// `exclusivityTimeout` optional: the parked web path still runs a module build\n// that predates it (validatePayload refuses when it is absent).\ntype PayloadInput = Omit<Parameters<NonNullable<OmnistonProviderOptions[\"validateTonEscrowPayload\"]>>[0], \"exclusivityTimeout\"> & {\n exclusivityTimeout?: number;\n};\n\n/** Code interfaces (tonapi's by-code-hash labels) a same-chain swap message\n * may pay into. The resolver picks the pool/vault per route, so the check is\n * \"a STON.fi or DeDust contract by code\", not a fixed address list — seen\n * live: native GRAM → DeDust CPMM v2 pool, jettons → STON.fi router v2. */\nexport const DEFAULT_OMNISTON_TON_SWAP_INTERFACES = [\n \"stonfi_router\",\n \"stonfi_router_v2\",\n \"stonfi_pool\",\n \"stonfi_pool_v2\",\n \"dedust_vault\",\n \"dedust_v2_cpmm\",\n \"dedust_pool\",\n] as const;\n\n/** Proxy-TON (pTON) jetton masters STON.fi routes native TON through. A\n * native-input swap pays the ROUTER'S pTON wallet — a plain `jetton_wallet`\n * to tonapi, no DEX code interface — so such a target is accepted only when\n * its jetton master is pTON AND its owner carries a DEX router interface.\n * Seen live 2026-09-05: GRAM → USDT on StonFiV2 targeted the router's pTON\n * v2 wallet and the code-interface check alone refused it. */\nexport const DEFAULT_OMNISTON_TON_PROXY_TON_MASTERS = [\n \"EQCM3B12QK1e4yZSf8GtBRT0aLMNyEsBc_DhVfRRtOEffLez\", // pTON v1\n \"EQBnGWMCf3-FZZq1W4IWcWiGAc3PHuZ0_H-7sad2oY00o83S\", // pTON v2\n] as const;\n\nexport interface OmnistonTonValidationOptions {\n fetch?: typeof fetch;\n /** Diagnostics hook: every refusal of validateTonOutputPosition names its check (never a secret). */\n onRefusal?: (reason: string, details?: Record<string, unknown>) => void;\n tonApiUrl?: string;\n tonApiKey?: string;\n /** Code interfaces accepted as swap targets (default: the STON.fi / DeDust set above). */\n swapTargetInterfaces?: readonly string[];\n /** Proxy-TON masters whose router-owned wallets may receive native input (default: pTON v1/v2). */\n proxyTonMasters?: readonly string[];\n escrowCodeHashes?: readonly string[];\n executionCodeHashes?: readonly string[];\n /** Pinned escrow authority public keys (hex, 32 bytes). */\n authorityKeys?: readonly string[];\n /** EVM→TON output position code hashes (default: the observed factory position). */\n positionCodeHashes?: readonly string[];\n /** Escrow code cells an output position may carry (default: the observed one). */\n outputEscrowCodeHashes?: readonly string[];\n /**\n * The Omniston protocol contracts a TON → EVM escrow transfer may pay (`verifyTonEscrowBuild`). Default: the audited\n * `AUDITED_OMNISTON_SETTLEMENT_CONTRACTS[\"ton:-239\"]`.\n */\n trustedProtocolAddresses?: readonly string[];\n now?: () => number;\n}\n\nexport type TonOutputPositionInput = Parameters<NonNullable<OmnistonProviderOptions[\"validateTonOutputPosition\"]>>[0];\n\nfunction cellFromApi(value: string): Cell {\n const roots = Cell.fromBoc(Buffer.from(value, /^b5ee9c/i.test(value) ? \"hex\" : \"base64\"));\n if (roots.length !== 1) throw new Error(\"omniston TON validator: account cell must have one root\");\n return roots[0]!;\n}\n\n/**\n * EVM→TON output position, as the factory writes it (decoded from live\n * resolver-created positions, 2026-10-15/16 — every field is checked in its\n * slot, nothing is located by search):\n *\n * ```text\n * data: phase:uint8 quoteId:bits256 factory:MsgAddressStd\n * jettonWallet:MsgAddressStd (the factory's wallet of the output\n * jetton — custody stays there) flags:bits5\n * ref0: owner:MsgAddressStd (resolver) jettonMaster:MsgAddressStd bits6\n * ref0: fee profile (constant, not security-relevant)\n * ref1: jettonWallet, gas, owner\n * ref1: hashlock:bits256 amount:Coins withdrawalAt:uint64\n * publicWithdrawalAt:uint64 cancellationAt:uint64\n * ref0: recipient:MsgAddressStd resolver:MsgAddressStd deposit:Coins\n * ref1: authority:(Maybe bits256) recipient:MsgAddressStd\n * ref2: escrow code cell\n * ```\n */\nlet lastStateRefusal: string | null = null;\nfunction validateOutputPositionState(\n data: Cell,\n input: TonOutputPositionInput,\n expected: {jettonWallet: string; trusted: {outputEscrow: ReadonlySet<string>; authorityKeys: ReadonlySet<string>}; nowSeconds: number},\n): {withdrawalAt: bigint} | null {\n if (!/^[0-9a-fA-F]{48,64}$/.test(input.quoteId) || input.secretHash.length !== 32) { lastStateRefusal = \"state#1: if (!/^[0-9a-fA-F]{48,64}$/.test(input.quoteId) || input.secretHash.length !== 32) return null;\"; return null; }\n if (!/^\\d+$/.test(input.resolverSendsUnits) || !/^\\d+$/.test(input.outputUnits) || !/^\\d+$/.test(input.dstSecurityDepositUnits)) { lastStateRefusal = \"state#2: if (!/^\\\\d+$/.test(input.resolverSendsUnits) || !/^\\\\d+$/.test(input.outputUnits) || !/^\\\\d+$/.test(inp\"; return null; }\n if (data.refs.length !== 3) { lastStateRefusal = \"state#3: if (data.refs.length !== 3) return null;\"; return null; }\n const root = data.beginParse();\n root.loadUint(8); // phase — not trusted for custody; the factory deploy + timelocks are\n if (!sameHex(root.loadBuffer(32), input.quoteId.padStart(64, \"0\"))) { lastStateRefusal = \"state#4: if (!sameHex(root.loadBuffer(32), input.quoteId.padStart(64, \\\"0\\\"))) return null;\"; return null; }\n if (!sameAddress(root.loadAddressAny(), input.protocolAddress)) { lastStateRefusal = \"state#5: if (!sameAddress(root.loadAddressAny(), input.protocolAddress)) return null;\"; return null; }\n if (!sameAddress(root.loadAddressAny(), expected.jettonWallet)) { lastStateRefusal = \"state#6: if (!sameAddress(root.loadAddressAny(), expected.jettonWallet)) return null;\"; return null; }\n // Root tail: 5 bits once the position is settled or rolled back (tag 2 / 3 — the shape the\n // fixtures were cut from), 29 bits while it is live and awaiting completion (tag 1, live\n // 2026-10-20 on every Base → TON position; the 24 extra bits are not fund-critical — every\n // binding field is checked in the refs below). Any other width is a foreign layout.\n if ((root.remainingBits !== 5 && root.remainingBits !== 29) || root.remainingRefs !== 3) { lastStateRefusal = `state#7: root tail ${root.remainingBits} bits / ${root.remainingRefs} refs`; return null; }\n\n const parties = data.refs[0]!;\n if (parties.refs.length !== 2) { lastStateRefusal = \"state#8: if (parties.refs.length !== 2) return null;\"; return null; }\n const partySlice = parties.beginParse();\n if (!(partySlice.loadAddressAny() instanceof Address)) { lastStateRefusal = \"state#9: if (!(partySlice.loadAddressAny() instanceof Address)) return null; // owner (resolver) — any\"; return null; } // owner (resolver) — any\n if (!sameAddress(partySlice.loadAddressAny(), input.outputJettonMasterAddress)) { lastStateRefusal = \"state#10: if (!sameAddress(partySlice.loadAddressAny(), input.outputJettonMasterAddress)) return null;\"; return null; }\n if (partySlice.remainingBits !== 6) { lastStateRefusal = \"state#11: if (partySlice.remainingBits !== 6) return null;\"; return null; }\n\n const lock = data.refs[1]!;\n if (lock.refs.length !== 2) { lastStateRefusal = \"state#12: if (lock.refs.length !== 2) return null;\"; return null; }\n const lockSlice = lock.beginParse();\n if (!Buffer.from(lockSlice.loadBuffer(32)).equals(Buffer.from(input.secretHash))) { lastStateRefusal = \"state#13: if (!Buffer.from(lockSlice.loadBuffer(32)).equals(Buffer.from(input.secretHash))) return null;\"; return null; }\n if (lockSlice.loadCoins() < BigInt(input.resolverSendsUnits)) { lastStateRefusal = \"state#14: if (lockSlice.loadCoins() < BigInt(input.resolverSendsUnits)) return null;\"; return null; }\n const withdrawalAt = lockSlice.loadUintBig(64);\n const publicWithdrawalAt = lockSlice.loadUintBig(64);\n const cancellationAt = lockSlice.loadUintBig(64);\n if (lockSlice.remainingBits !== 0) { lastStateRefusal = \"state#15: if (lockSlice.remainingBits !== 0) return null; // its two refs are the terms and authority cells be\"; return null; } // its two refs are the terms and authority cells below\n if (publicWithdrawalAt - withdrawalAt !== POSITION_STAGES.publicWithdrawalAfterWithdrawal) { lastStateRefusal = \"state#16: if (publicWithdrawalAt - withdrawalAt !== POSITION_STAGES.publicWithdrawalAfterWithdrawal) return nu\"; return null; }\n if (cancellationAt - withdrawalAt !== POSITION_STAGES.cancellationAfterWithdrawal) { lastStateRefusal = \"state#17: if (cancellationAt - withdrawalAt !== POSITION_STAGES.cancellationAfterWithdrawal) return null;\"; return null; }\n // Deployed after the quote (resolvers lock within minutes of the fill) and\n // still far enough from cancellation to be completed.\n if (withdrawalAt < BigInt(input.quoteTimestamp) - 120n || withdrawalAt > BigInt(input.quoteTimestamp) + 900n) { lastStateRefusal = \"state#18: if (withdrawalAt < BigInt(input.quoteTimestamp) - 120n || withdrawalAt > BigInt(input.quoteTimestamp\"; return null; }\n if (BigInt(expected.nowSeconds + OUTPUT_DISCLOSURE_MARGIN_SECONDS) >= cancellationAt) { lastStateRefusal = \"state#19: if (BigInt(expected.nowSeconds + OUTPUT_DISCLOSURE_MARGIN_SECONDS) >= cancellationAt) return null;\"; return null; }\n\n const terms = lock.refs[0]!.beginParse();\n if (!sameAddress(terms.loadAddressAny(), input.recipientAddress)) { lastStateRefusal = \"state#20: if (!sameAddress(terms.loadAddressAny(), input.recipientAddress)) return null;\"; return null; }\n if (!(terms.loadAddressAny() instanceof Address)) { lastStateRefusal = \"state#21: if (!(terms.loadAddressAny() instanceof Address)) return null; // resolver — any\"; return null; } // resolver — any\n if (terms.loadCoins() !== BigInt(input.dstSecurityDepositUnits) || !exactCellEnd(terms)) { lastStateRefusal = \"state#22: if (terms.loadCoins() !== BigInt(input.dstSecurityDepositUnits) || !exactCellEnd(terms)) return null\"; return null; }\n\n const authority = lock.refs[1]!.beginParse();\n if (!authority.loadBit() || !expected.trusted.authorityKeys.has(Buffer.from(authority.loadBuffer(32)).toString(\"hex\"))) { lastStateRefusal = \"state#23: if (!authority.loadBit() || !expected.trusted.authorityKeys.has(Buffer.from(authority.loadBuffer(32)\"; return null; }\n // Authority address: the trader's TON address on TON-source positions; `addr_none` on EVM-source\n // positions (live 2026-10-20, every Base → TON order) — the payout target is bound in the terms cell\n // above, and the pinned authority key is what the public path checks. Anything else is foreign.\n const authorityAddress = authority.loadAddressAny();\n if ((authorityAddress !== null && !sameAddress(authorityAddress, input.recipientAddress)) || !exactCellEnd(authority)) { lastStateRefusal = \"state#24: if ((authorityAddress !== null && !sameAddress(authorityAddress, input.recipientAddress)) || !exactC\"; return null; }\n\n if (!expected.trusted.outputEscrow.has(data.refs[2]!.hash().toString(\"hex\"))) { lastStateRefusal = \"state#25: if (!expected.trusted.outputEscrow.has(data.refs[2]!.hash().toString(\\\"hex\\\"))) return null;\"; return null; }\n return {withdrawalAt};\n}\n\nfunction oneRoot(hex: string, label: string): Cell {\n if (!/^(?:[0-9a-fA-F]{2})+$/.test(hex)) throw new Error(`omniston TON validator: malformed ${label} hex`);\n const roots = Cell.fromBoc(Buffer.from(hex, \"hex\"));\n if (roots.length !== 1) throw new Error(`omniston TON validator: ${label} must have one root`);\n return roots[0]!;\n}\n\nfunction sameAddress(actual: unknown, expected: string): boolean {\n try {\n return actual instanceof Address && actual.equals(Address.parse(expected));\n } catch {\n return false;\n }\n}\n\nfunction sameHex(actual: Uint8Array, expected: string): boolean {\n const clean = expected.replace(/^0x/, \"\").toLowerCase();\n return clean.length === actual.length * 2 && Buffer.from(actual).toString(\"hex\") === clean;\n}\n\nfunction exactCellEnd(slice: {remainingBits: number; remainingRefs: number}): boolean {\n return slice.remainingBits === 0 && slice.remainingRefs === 0;\n}\n\nfunction destinationChainId(chain: string): bigint | null {\n // The client knows the chain as CAIP-2 (`eip155:8453`), the provider as Omniston's name (`base`): both resolve.\n const caip2 = /^eip155:([0-9]{1,10})$/.exec(chain);\n if (caip2) {\n const id = BigInt(caip2[1]!);\n return [1n, 56n, 137n, 4663n, 8453n, 42161n, 43114n, 196n, 999n, 9745n].includes(id) ? id : null;\n }\n const ids: Record<string, bigint> = {\n ethereum: 1n,\n bnb: 56n,\n polygon: 137n,\n robinhood: 4663n,\n base: 8453n,\n arbitrum: 42161n,\n avalanche: 43114n,\n xlayer: 196n,\n hyperevm: 999n,\n plasma: 9745n,\n };\n return ids[chain] ?? null;\n}\n\n/** What a TON → EVM escrow build must carry, as the app knows it (`verifyTonEscrowBuild`). */\nexport interface TonEscrowBuildExpectation {\n /** The message body: the jetton transfer that funds the escrow, hex. */\n payloadBocHex: string;\n /** The trader's TON address: the jetton transfer's excess and the escrow's owner (refunds go there). */\n ownerAddress: string;\n /** The exact jetton amount the swap sells. */\n inputUnits: string;\n /** The destination chain, CAIP-2 (`eip155:8453`) or Omniston's name (`base`). */\n destinationChain: string;\n /** The trader's address on the destination chain. */\n destinationAddress: string;\n /** The ERC-20 the trader receives there. */\n outputTokenAddress: string;\n /** The least the resolver may be bound to deliver: the quote's minimum (and the app's own floor). */\n minResolverSendsUnits: string;\n}\n\n/**\n * The fields of a TON → EVM escrow body the app cannot know in advance — chosen by the server and the resolver: the\n * quote id, the resolver, the hashlock, the exclusivity window, the resolver's deposit and what it sends — read from\n * the body itself, in the layout `validatePayload` checks, plus the transfer's destination and amount. Throws when\n * the body is not that layout.\n */\nfunction readTonEscrowBody(payloadBocHex: string): {\n amount: bigint; protocolAddress: string; forwardPayloadBocHex: string; quoteId: string; initialResolverAddress: string;\n exclusivityTimeout: number; secretHash: Uint8Array; depositUnits: string; resolverSendsUnits: string;\n} {\n const outer = oneRoot(payloadBocHex, \"payload\").beginParse();\n if (outer.loadUint(32) !== JETTON_TRANSFER_OP) throw new Error(\"not a jetton transfer\");\n outer.loadUintBig(64);\n const amount = outer.loadCoins();\n const protocol = outer.loadAddressAny();\n if (!(protocol instanceof Address)) throw new Error(\"no protocol address\");\n outer.loadAddressAny();\n if (outer.loadMaybeRef() !== null) throw new Error(\"custom payload\");\n outer.loadCoins();\n if (!outer.loadBit() || outer.remainingRefs !== 1) throw new Error(\"no forward payload\");\n const forward = outer.loadRef();\n const root = forward.beginParse();\n if (root.loadUint(32) !== ESCROW_CREATE_OP) throw new Error(\"not an escrow create\");\n const quoteId = Buffer.from(root.loadBuffer(32)).toString(\"hex\");\n root.loadBit(); root.loadAddressAny(); root.loadCoins(); root.loadBit();\n if (root.remainingRefs !== 4) throw new Error(\"escrow refs\");\n const config = root.loadRef().beginParse();\n if (config.loadUint(32) !== ESCROW_CONFIG_OP) throw new Error(\"escrow config\");\n const resolver = config.loadAddressAny();\n if (!(resolver instanceof Address)) throw new Error(\"no resolver\");\n if (config.loadBit()) config.loadBuffer(32);\n const exclusivity = config.loadUintBig(64);\n config.loadUintBig(64);\n if (config.remainingRefs !== 2) throw new Error(\"escrow config refs\");\n const state = config.loadRef();\n if (!config.loadBit()) throw new Error(\"no destination\");\n const destination = config.loadRef().beginParse();\n if (state.refs.length !== 2) throw new Error(\"escrow state\");\n const execution = state.refs[1]!.beginParse();\n execution.loadUint(32);\n const secretHash = new Uint8Array(execution.loadBuffer(32));\n execution.loadAddressAny();\n for (let i = 0; i < 4; i++) execution.loadUintBig(64);\n const ownerData = execution.loadRef().beginParse();\n ownerData.loadAddressAny(); ownerData.loadBit();\n const deposit = ownerData.loadCoins();\n destination.loadUintBig(64); destination.loadBuffer(20); destination.loadBuffer(20);\n const resolverSends = destination.loadCoins();\n if (exclusivity > BigInt(MAX_OMNISTON_EXCLUSIVITY_SECONDS)) throw new Error(\"exclusivity\");\n return {\n amount, protocolAddress: protocol.toString(), forwardPayloadBocHex: Buffer.from(forward.toBoc()).toString(\"hex\"), quoteId,\n initialResolverAddress: resolver.toString(), exclusivityTimeout: Number(exclusivity.toString()), // bounded above\n secretHash, depositUnits: deposit.toString(), resolverSendsUnits: resolverSends.toString(),\n };\n}\n\nfunction validatePayload(input: PayloadInput, trusted: {\n escrow: ReadonlySet<string>;\n execution: ReadonlySet<string>;\n authorityKeys: ReadonlySet<string>;\n}): boolean {\n // Read structurally so this stays type-compatible with module builds that\n // predate the field; absent → refused below.\n const exclusivityTimeout = (input as {exclusivityTimeout?: unknown}).exclusivityTimeout;\n if (\n typeof exclusivityTimeout !== \"number\" || !Number.isSafeInteger(exclusivityTimeout) ||\n exclusivityTimeout < 1 || exclusivityTimeout > MAX_OMNISTON_EXCLUSIVITY_SECONDS\n ) return false;\n if (\n !/^\\d+$/.test(input.inputUnits) || !/^\\d+$/.test(input.resolverSendsUnits) ||\n !/^\\d+$/.test(input.srcHtlcSecurityDepositUnits) || !/^[0-9a-fA-F]{48,64}$/.test(input.quoteId) ||\n input.secretHashes.length !== 1 || input.secretHashes[0]?.length !== 32 ||\n input.hashingFunction !== \"HASHING_FUNCTION_KECCAK256\"\n ) return false;\n\n const payload = oneRoot(input.payloadBocHex, \"payload\");\n const outer = payload.beginParse();\n if (outer.loadUint(32) !== JETTON_TRANSFER_OP) return false;\n outer.loadUintBig(64); // query id is intentionally wallet/resolver-selected\n if (outer.loadCoins() !== BigInt(input.inputUnits)) return false;\n if (!sameAddress(outer.loadAddressAny(), input.protocolAddress)) return false;\n if (!sameAddress(outer.loadAddressAny(), input.ownerAddress)) return false;\n if (outer.loadMaybeRef() !== null) return false;\n const forwardNano = outer.loadCoins();\n if (forwardNano <= 0n || forwardNano > MAX_FORWARD_NANO || !outer.loadBit()) return false;\n if (outer.remainingBits !== 0 || outer.remainingRefs !== 1) return false;\n const embeddedForward = outer.loadRef();\n const forward = oneRoot(input.forwardPayloadBocHex, \"forward payload\");\n if (!embeddedForward.hash().equals(forward.hash())) return false;\n\n const root = forward.beginParse();\n if (root.loadUint(32) !== ESCROW_CREATE_OP || !sameHex(root.loadBuffer(32), input.quoteId.padStart(64, \"0\"))) return false;\n if (root.loadBit() || !sameAddress(root.loadAddressAny(), input.ownerAddress)) return false;\n const escrowForwardNano = root.loadCoins();\n if (escrowForwardNano <= 0n || escrowForwardNano > MAX_FORWARD_NANO || root.loadBit()) return false;\n if (root.remainingBits !== 0 || root.remainingRefs !== 4) return false;\n const [config, escrowCode, auxiliary, flags] = [root.loadRef(), root.loadRef(), root.loadRef(), root.loadRef()];\n if (!trusted.escrow.has(escrowCode.hash().toString(\"hex\"))) return false;\n\n // Escrow config, as the escrow code's deploy handler parses it (disassembly\n // of 9e77cb9e…, 2026-10-11):\n // op:uint32 resolver:MsgAddressStd authority:(Maybe uint256)\n // exclusivity:uint64 postExclusivity:uint64 state:^Cell\n // destination:(Maybe ^Cell) parts:uint16\n // On deploy the escrow stores now+exclusivity and now+exclusivity+postExclusivity\n // as its phase boundaries. Every field is checked in its slot; nothing is\n // compared as an opaque blob, so a protocol-side timing change shows up as a\n // named field instead of a silent refusal.\n const configSlice = config.beginParse();\n if (configSlice.loadUint(32) !== ESCROW_CONFIG_OP || !sameAddress(configSlice.loadAddressAny(), input.initialResolverAddress)) return false;\n if (!configSlice.loadBit() || !trusted.authorityKeys.has(Buffer.from(configSlice.loadBuffer(32)).toString(\"hex\"))) return false;\n // Bound to the quote the user accepted: the resolver cannot lengthen the\n // window the trader's funds are locked for without a reservation.\n if (configSlice.loadUintBig(64) !== BigInt(exclusivityTimeout)) return false;\n // A non-zero window after exclusivity is the Dutch-auction phase (\"Dutch\n // auction starts if specified by escrow condition\"); its price curve is not\n // part of the trader quote, so only the no-auction profile is accepted.\n if (configSlice.loadUintBig(64) !== 0n) return false;\n if (configSlice.remainingRefs !== 2) return false;\n const state = configSlice.loadRef();\n if (!configSlice.loadBit()) return false; // destination is mandatory\n const destination = configSlice.loadRef();\n // 0 = single full fill, which is what the one-hash execution below commits to.\n if (configSlice.loadUint(16) !== 0 || !exactCellEnd(configSlice)) return false;\n if (state.bits.length !== 0 || state.refs.length !== 2) return false;\n if (!trusted.execution.has(state.refs[0]!.hash().toString(\"hex\"))) return false;\n\n const execution = state.refs[1]!.beginParse();\n if (\n execution.loadUint(32) !== ESCROW_EXECUTION_KECCAK_OP ||\n !Buffer.from(execution.loadBuffer(32)).equals(Buffer.from(input.secretHashes[0]!)) ||\n !sameAddress(execution.loadAddressAny(), input.initialResolverAddress)\n ) return false;\n // Current audited escrow policy: one execution, then 120/240/300-second\n // exclusivity, cancellation and refund boundaries.\n if ([1n, 120n, 240n, 300n].some((expected) => execution.loadUintBig(64) !== expected)) return false;\n if (execution.remainingBits !== 0 || execution.remainingRefs !== 1) return false;\n const ownerData = execution.loadRef().beginParse();\n if (!sameAddress(ownerData.loadAddressAny(), input.ownerAddress) || ownerData.loadBit()) return false;\n if (ownerData.loadCoins() !== BigInt(input.srcHtlcSecurityDepositUnits) || !exactCellEnd(ownerData)) return false;\n\n const destinationSlice = destination.beginParse();\n const chainId = destinationChainId(input.destinationChain);\n if (chainId === null || destinationSlice.loadUintBig(64) !== chainId) return false;\n if (!sameHex(destinationSlice.loadBuffer(20), input.outputTokenAddress)) return false;\n if (!sameHex(destinationSlice.loadBuffer(20), input.destinationAddress)) return false;\n if (destinationSlice.loadCoins() !== BigInt(input.resolverSendsUnits) || !exactCellEnd(destinationSlice)) return false;\n\n // These cells contain optional escrow bookkeeping. Their exact shapes and\n // reference counts are part of the reviewed ABI; fund destinations above\n // are never located by byte search.\n if (auxiliary.bits.length !== 537 || auxiliary.refs.length !== 1) return false;\n if (flags.bits.length !== 98 || flags.refs.length !== 0) return false;\n return true;\n}\n\nexport function createOmnistonTonValidators(options: OmnistonTonValidationOptions = {}): Required<Pick<\n OmnistonProviderOptions,\n \"validateTonJettonWallet\" | \"validateTonSwapTarget\" | \"validateTonOutputPosition\" | \"validateTonSwapLeg\"\n>> & {\n validateTonEscrowPayload: (input: PayloadInput) => boolean | Promise<boolean>;\n verifyTonEscrowBuild: (input: TonEscrowBuildExpectation) => string | null;\n} {\n const now = options.now ?? Date.now;\n const swapInterfaces = new Set(options.swapTargetInterfaces ?? DEFAULT_OMNISTON_TON_SWAP_INTERFACES);\n const proxyTonMasters = new Set(\n (options.proxyTonMasters ?? DEFAULT_OMNISTON_TON_PROXY_TON_MASTERS).map((value) => Address.parse(value).toRawString()),\n );\n const request = options.fetch ?? fetch;\n const base = (options.tonApiUrl ?? \"https://tonapi.io\").replace(/\\/$/, \"\");\n const headers = options.tonApiKey ? {Authorization: `Bearer ${options.tonApiKey}`} : undefined;\n const get = (path: string) => request(`${base}${path}`, {...(headers ? {headers} : {}), signal: AbortSignal.timeout(5_000)});\n /** Same, retrying tonapi's rate limit (keyless: ~1 rps) — the swap-leg\n * checks run a few reads back to back right after the target checks. */\n const getRetry = async (path: string): Promise<Response> => {\n for (let attempt = 0; ; attempt++) {\n const response = await get(path);\n if (response.status !== 429 || attempt >= 3) return response;\n await new Promise((resolve) => setTimeout(resolve, 1_100 * (attempt + 1)));\n }\n };\n /** A get-method's stack (tonapi), or null when the call failed. */\n const runGet = async (address: string, method: string, args: readonly string[] = []): Promise<{type: string; cell?: string}[] | null> => {\n const query = args.length ? `?${args.map((arg) => `args=${encodeURIComponent(arg)}`).join(\"&\")}` : \"\";\n const response = await getRetry(`/v2/blockchain/accounts/${encodeURIComponent(address)}/methods/${method}${query}`);\n if (!response.ok) return null;\n const body = await response.json() as {success?: boolean; exit_code?: number; stack?: {type: string; cell?: string}[]};\n return body.success === true && (body.exit_code ?? 0) === 0 && Array.isArray(body.stack) ? body.stack : null;\n };\n const stackCell = (entry: {type: string; cell?: string} | undefined): Cell | null =>\n entry && (entry.type === \"cell\" || entry.type === \"slice\") && entry.cell ? cellFromApi(entry.cell) : null;\n /** The jetton wallet a master derives for an owner — computed by the master, not looked up. */\n const derivedWallet = async (master: string, owner: string): Promise<Address | null> => {\n const cell = stackCell((await runGet(master, \"get_wallet_address\", [Address.parse(owner).toRawString()]))?.[0]);\n return cell ? cell.beginParse().loadAddress() : null;\n };\n /** get_wallet_data of a jetton wallet: owner + master, read from the wallet itself. */\n const walletData = async (wallet: string): Promise<{owner: Address; master: Address} | null> => {\n const stack = await runGet(wallet, \"get_wallet_data\");\n const owner = stackCell(stack?.[1]);\n const master = stackCell(stack?.[2]);\n return owner && master ? {owner: owner.beginParse().loadAddress(), master: master.beginParse().loadAddress()} : null;\n };\n const accountHas = async (address: string, iface: string): Promise<boolean> => {\n const response = await getRetry(`/v2/accounts/${encodeURIComponent(address)}`);\n if (!response.ok) return false;\n const body = await response.json() as {address?: string; interfaces?: string[]; is_wallet?: boolean};\n return !!body.address && sameAddress(Address.parse(body.address), address) && body.is_wallet !== true && (body.interfaces ?? []).includes(iface);\n };\n /** Unordered pair equality of jetton masters (null = native GRAM). */\n const samePair = (pool: readonly (string | null)[], leg: readonly (string | null)[]): boolean => {\n const key = (value: string | null) => value === null ? \"native\" : Address.parse(value).toRawString();\n const a = pool.map(key).sort();\n const b = leg.map(key).sort();\n return a.length === 2 && a[0] === b[0] && a[1] === b[1] && a[0] !== a[1];\n };\n /** tonapi's view of a contract: null when unreachable or not the address asked for. */\n const readAccount = async (address: string): Promise<{interfaces: string[]; isWallet: boolean} | null> => {\n const response = await get(`/v2/accounts/${encodeURIComponent(address)}`);\n if (!response.ok) return null;\n const body = await response.json() as {address?: string; interfaces?: string[]; is_wallet?: boolean};\n if (!body.address || !sameAddress(Address.parse(body.address), address)) return null;\n return {interfaces: body.interfaces ?? [], isWallet: body.is_wallet === true};\n };\n const isDexContract = (account: {interfaces: string[]; isWallet: boolean}): boolean =>\n !account.isWallet && account.interfaces.some((name) => swapInterfaces.has(name));\n const trusted = {\n escrow: new Set((options.escrowCodeHashes ?? DEFAULT_OMNISTON_TON_CODE_HASHES.escrow).map((value) => value.toLowerCase())),\n execution: new Set((options.executionCodeHashes ?? DEFAULT_OMNISTON_TON_CODE_HASHES.execution).map((value) => value.toLowerCase())),\n authorityKeys: new Set((options.authorityKeys ?? DEFAULT_OMNISTON_TON_CODE_HASHES.authorityKeys).map((value) => value.toLowerCase())),\n position: new Set((options.positionCodeHashes ?? DEFAULT_OMNISTON_TON_CODE_HASHES.position).map((value) => value.toLowerCase())),\n outputEscrow: new Set((options.outputEscrowCodeHashes ?? DEFAULT_OMNISTON_TON_CODE_HASHES.outputEscrow).map((value) => value.toLowerCase())),\n };\n const trustedProtocols = new Set((options.trustedProtocolAddresses ?? AUDITED_OMNISTON_SETTLEMENT_CONTRACTS[\"ton:-239\"] ?? []).map((value) => Address.parse(value).toRawString()));\n /** The factory's jetton wallet for a master, from the indexer — the same\n * lookup the TON-source path uses for the trader's wallet. */\n const jettonWalletOf = async (ownerAddress: string, jettonMasterAddress: string): Promise<string | null> => {\n const response = await get(`/v2/accounts/${encodeURIComponent(ownerAddress)}/jettons/${encodeURIComponent(jettonMasterAddress)}`);\n if (!response.ok) return null;\n const body = await response.json() as {wallet_address?: {address?: string}; jetton?: {address?: string}};\n const wallet = body.wallet_address?.address;\n if (!wallet || (body.jetton?.address !== undefined && !sameAddress(Address.parse(body.jetton.address), jettonMasterAddress))) return null;\n return Address.parse(wallet).toString();\n };\n\n return {\n async validateTonJettonWallet({ownerAddress, jettonMasterAddress, walletAddress}) {\n try {\n const url = `${base}/v2/accounts/${encodeURIComponent(ownerAddress)}/jettons/${encodeURIComponent(jettonMasterAddress)}`;\n const response = await request(url, {\n ...(headers ? {headers} : {}),\n signal: AbortSignal.timeout(5_000),\n });\n if (!response.ok) return false;\n const body = await response.json() as {\n wallet_address?: {address?: string};\n jetton?: {address?: string};\n };\n if (!sameAddress(body.wallet_address?.address ? Address.parse(body.wallet_address.address) : null, walletAddress)) return false;\n return body.jetton?.address === undefined || sameAddress(Address.parse(body.jetton.address), jettonMasterAddress);\n } catch {\n return false;\n }\n },\n validateTonEscrowPayload(input: PayloadInput) {\n try {\n return validatePayload(input, trusted);\n } catch {\n return false;\n }\n },\n /**\n * The app's own check of a TON → EVM escrow build behind `remoteProvider` (through `omnistonVerifyBuild`): the\n * structural check `validateTonEscrowPayload` runs on the server, with every field that decides where the\n * trader's money goes taken from the app — the jetton amount, the owner the excess and refunds go to, the\n * destination chain, address and token, a delivery of at least `minResolverSendsUnits`, and a protocol contract\n * from `trustedProtocolAddresses`. The fields the server and the resolver choose (quote id, resolver, hashlock,\n * exclusivity, deposit) are read from the body and held to the same pins and bounds: audited escrow and\n * execution code, authority key, one execution, the reviewed timelocks, no Dutch auction. A reason, or `null`.\n */\n verifyTonEscrowBuild(input: TonEscrowBuildExpectation): string | null {\n let body: ReturnType<typeof readTonEscrowBody>;\n try {\n body = readTonEscrowBody(input.payloadBocHex);\n } catch {\n return \"the escrow body is not an Omniston escrow transfer\";\n }\n if (!trustedProtocols.has(Address.parse(body.protocolAddress).toRawString())) return `the escrow transfer pays ${body.protocolAddress}, not an Omniston protocol contract this app trusts`;\n if (!/^\\d{1,40}$/.test(input.inputUnits) || body.amount !== BigInt(input.inputUnits)) return `the escrow transfer moves ${body.amount}, not the ${input.inputUnits} this swap sells`;\n if (!/^\\d{1,80}$/.test(input.minResolverSendsUnits) || BigInt(body.resolverSendsUnits) < BigInt(input.minResolverSendsUnits)) {\n return `the resolver is bound to deliver ${body.resolverSendsUnits}, under the quote's minimum ${input.minResolverSendsUnits}`;\n }\n let ok = false;\n try {\n ok = validatePayload({\n payloadBocHex: input.payloadBocHex, forwardPayloadBocHex: body.forwardPayloadBocHex, quoteId: body.quoteId,\n inputUnits: input.inputUnits, resolverSendsUnits: body.resolverSendsUnits, srcHtlcSecurityDepositUnits: body.depositUnits,\n protocolAddress: body.protocolAddress, ownerAddress: input.ownerAddress, destinationChain: input.destinationChain,\n destinationAddress: input.destinationAddress, outputTokenAddress: input.outputTokenAddress,\n initialResolverAddress: body.initialResolverAddress, secretHashes: [body.secretHash], hashingFunction: \"HASHING_FUNCTION_KECCAK256\",\n exclusivityTimeout: body.exclusivityTimeout,\n }, trusted);\n } catch {\n ok = false;\n }\n return ok ? null : \"the escrow body is not this swap's (owner, destination chain, address or token) or not the audited escrow (code, authority, timelocks)\";\n },\n /**\n * EVM→TON: the position the tracking feed named must be (1) an active\n * contract with the pinned position code, (2) carrying state that binds\n * this quote, hashlock, recipient, output jetton, amount, deposit and the\n * pinned timelocks — still inside the completion window — with jetton\n * custody at the factory's own wallet, and (3) deployed by the trusted\n * factory itself (its deploy message is only sent after the factory's\n * jetton wallet notified it of the resolver's transfer). Nothing here\n * trusts the feed beyond the address it suggested.\n */\n async validateTonOutputPosition(input) {\n const refuse = (reason: string, details?: Record<string, unknown>): false => { try { options.onRefusal?.(reason, details); } catch { /* diagnostics never break validation */ } return false; };\n lastStateRefusal = null;\n try {\n Address.parse(input.positionAddress);\n Address.parse(input.recipientAddress);\n const nowSeconds = Math.floor(now() / 1000);\n if (!Number.isInteger(input.quoteTimestamp) || input.quoteTimestamp > nowSeconds + 120 || nowSeconds - input.quoteTimestamp > 6 * 60 * 60) return refuse(\"quote-age\");\n const accountResponse = await get(`/v2/blockchain/accounts/${encodeURIComponent(input.positionAddress)}`);\n if (!accountResponse.ok) return refuse(\"account-fetch\", {status: accountResponse.status});\n const account = await accountResponse.json() as {address?: string; status?: string; code?: string; data?: string};\n if (!account.address || !sameAddress(Address.parse(account.address), input.positionAddress) || account.status !== \"active\" || !account.code || !account.data) return refuse(\"account-state\", {status: account.status, hasCode: !!account.code, hasData: !!account.data});\n if (!trusted.position.has(cellFromApi(account.code).hash().toString(\"hex\"))) return refuse(\"position-code-hash\", {hash: cellFromApi(account.code).hash().toString(\"hex\")});\n const jettonWallet = await jettonWalletOf(input.protocolAddress, input.outputJettonMasterAddress);\n if (!jettonWallet) return refuse(\"jetton-wallet\");\n const state = validateOutputPositionState(cellFromApi(account.data), input, {jettonWallet, trusted, nowSeconds});\n if (!state) return refuse(\"state\", {check: lastStateRefusal});\n const txResponse = await get(`/v2/blockchain/accounts/${encodeURIComponent(input.positionAddress)}/transactions?limit=25`);\n if (!txResponse.ok) return refuse(\"transactions-fetch\", {status: txResponse.status});\n const body = await txResponse.json() as {transactions?: {success?: boolean; aborted?: boolean; utime?: number; in_msg?: {source?: {address?: string}; op_code?: string}}[]};\n const deployedByFactory = (body.transactions ?? []).some((tx) =>\n tx.success === true && tx.aborted !== true && tx.in_msg?.op_code?.toLowerCase() === POSITION_DEPLOY_OP &&\n !!tx.in_msg.source?.address && sameAddress(Address.parse(tx.in_msg.source.address), input.protocolAddress) &&\n typeof tx.utime === \"number\" && Math.abs(bigintToNumber(BigInt(state.withdrawalAt)) - 1 - tx.utime) <= 5);\n return deployedByFactory || refuse(\"deploy-transaction\", {transactions: (body.transactions ?? []).length});\n } catch (error) {\n return refuse(\"error\", {message: error instanceof Error ? error.message : String(error)});\n }\n },\n /**\n * Scan F11: one chain fact a decoded TON swap body depends on.\n * - STON.fi hop: the router carries the STON.fi router interface of its\n * version; for native input the pTON wallet the message pays is a\n * proxy-TON wallet OWNED BY that router; the hop's ask wallet is the\n * router's own wallet of the hop's output (of a proxy-TON master for\n * native output), as the output's master derives it.\n * - DeDust pool: the pool carries the DeDust pool interface of its version\n * and trades exactly the hop's pair.\n */\n async validateTonSwapLeg(leg: TonSwapLeg) {\n try {\n if (leg.kind === \"stonfi-router\") {\n let router = leg.router ? Address.parse(leg.router) : null;\n if (leg.proxyTonWallet) {\n const data = await walletData(leg.proxyTonWallet);\n if (!data || !proxyTonMasters.has(data.master.toRawString())) return false;\n if (router && !router.equals(data.owner)) return false;\n router = data.owner;\n }\n if (!router) return false;\n if (!await accountHas(router.toString(), leg.version === 1 ? \"stonfi_router\" : \"stonfi_router_v2\")) return false;\n const masters = leg.outputJetton ? [leg.outputJetton] : [...proxyTonMasters];\n for (const master of masters) {\n const wallet = await derivedWallet(master, router.toString());\n if (wallet && wallet.equals(Address.parse(leg.askWallet))) return true;\n }\n return false;\n }\n if (leg.version === 1) {\n if (!await accountHas(leg.pool, \"dedust_pool\")) return false;\n const stack = await runGet(leg.pool, \"get_assets\");\n const assets = [stackCell(stack?.[0]), stackCell(stack?.[1])].map((cell) => {\n if (!cell) return undefined;\n const slice = cell.beginParse();\n const tag = slice.loadUint(4);\n if (tag === 0) return null;\n if (tag !== 1) return undefined;\n return new Address(slice.loadInt(8), slice.loadBuffer(32)).toString();\n });\n if (assets.some((asset) => asset === undefined)) return false;\n return samePair(assets as (string | null)[], [leg.inputJetton, leg.outputJetton]);\n }\n if (!await accountHas(leg.pool, \"dedust_v2_cpmm\")) return false;\n const stack = await runGet(leg.pool, \"get_pool_data\");\n const assets = [stackCell(stack?.[3]), stackCell(stack?.[4])].map((cell) => {\n if (!cell) return undefined;\n const address = cell.beginParse().loadAddressAny();\n if (address === null) return null;\n return address instanceof Address ? address.toString() : undefined;\n });\n if (assets.some((asset) => asset === undefined)) return false;\n return samePair(assets as (string | null)[], [leg.inputJetton, leg.outputJetton]);\n } catch {\n return false;\n }\n },\n /** The contract a swap pays into must carry a recognised DEX code\n * interface on the indexer — an EOA, an unknown contract or a fresh\n * resolver-deployed proxy is refused. */\n async validateTonSwapTarget({address}) {\n try {\n Address.parse(address);\n const account = await readAccount(address);\n if (!account || account.isWallet) return false;\n if (isDexContract(account)) return true;\n // Native input on STON.fi: the target is the router's proxy-TON jetton\n // wallet. Accept it only as \"pTON wallet owned by a DEX router\" —\n // both facts read from the chain, never from the quote.\n if (!account.interfaces.includes(\"jetton_wallet\")) return false;\n const data = await get(`/v2/blockchain/accounts/${encodeURIComponent(address)}/methods/get_wallet_data`);\n if (!data.ok) return false;\n const body = await data.json() as {success?: boolean; decoded?: {owner?: string; jetton?: string}};\n const owner = body.decoded?.owner;\n const master = body.decoded?.jetton;\n if (!body.success || !owner || !master || !proxyTonMasters.has(Address.parse(master).toRawString())) return false;\n const ownerAccount = await readAccount(owner);\n return ownerAccount !== null && isDexContract(ownerAccount);\n } catch {\n return false;\n }\n },\n };\n}\n\n// ── EVM → TON delivery ───────────────────────────────────────────────────────\n\nexport interface OmnistonTonDeliveryLocatorOptions {\n fetch?: typeof fetch;\n tonApiUrl?: string;\n tonApiKey?: string;\n /** Recipient events scanned per call (newest first; the delivery is recent by construction). */\n limit?: number;\n}\n\nexport interface OmnistonTonDeliveryInput {\n /** The output position that paid out; when absent any sender of a matching transfer counts (backfills). */\n positionAddress?: string;\n recipientAddress: string;\n jettonMasterAddress: string;\n minUnits: string;\n /** Unix seconds; events before it are not this delivery (backfills). With it set, the EARLIEST match wins — the one closest to the order, not a later swap's payout. */\n afterTimestamp?: number;\n /** Unix seconds; events after it are not this delivery (backfills: the row's completion time plus slack). */\n beforeTimestamp?: number;\n}\n\ninterface TonapiDeliveryEvent {\n event_id?: string;\n timestamp?: number;\n in_progress?: boolean;\n actions?: Array<{\n type?: string;\n status?: string;\n JettonTransfer?: {\n sender?: {address?: string};\n recipient?: {address?: string};\n jetton?: {address?: string};\n amount?: string | number;\n };\n }>;\n}\n\n/**\n * Finds an Omniston TON delivery: the jetton transfer from the output position\n * to the recipient of at least `minUnits`, in the recipient's tonapi events.\n * Returns tonapi's `event_id` — the hash `@anywalletkit/wallet-ton`'s history\n * source gives the same event as a row, so a wallet can pair the TON receive\n * with the swap. Feeds `omnistonProvider({locateTonDelivery})`; a server may\n * also call it with no position to backfill rows completed before the locator\n * existed. Never throws: null when nothing matched or tonapi did not answer.\n */\nexport function createOmnistonTonDeliveryLocator(options: OmnistonTonDeliveryLocatorOptions = {}) {\n const request = options.fetch ?? fetch;\n const base = (options.tonApiUrl ?? \"https://tonapi.io\").replace(/\\/$/, \"\");\n const headers = options.tonApiKey ? {Authorization: `Bearer ${options.tonApiKey}`} : undefined;\n const limit = Math.min(100, Math.max(1, Math.floor(options.limit ?? 20)));\n return async (input: OmnistonTonDeliveryInput): Promise<string | null> => {\n try {\n const recipient = Address.parse(input.recipientAddress);\n const master = Address.parse(input.jettonMasterAddress);\n const position = input.positionAddress ? Address.parse(input.positionAddress) : null;\n const min = BigInt(input.minUnits);\n if (min <= 0n) return null;\n const since = Number.isFinite(input.afterTimestamp) ? `&start_date=${Math.max(0, Math.floor(input.afterTimestamp!))}` : \"\";\n const until = Number.isFinite(input.beforeTimestamp) ? `&end_date=${Math.max(0, Math.floor(input.beforeTimestamp!))}` : \"\";\n const url = `${base}/v2/accounts/${encodeURIComponent(recipient.toString())}/events?limit=${limit}${since}${until}`;\n const response = await request(url, {...(headers ? {headers} : {}), signal: AbortSignal.timeout(8_000)});\n if (!response.ok) return null;\n const body = await response.json() as {events?: TonapiDeliveryEvent[]};\n // tonapi lists newest first. With a position the newest match is the delivery; a\n // windowed backfill wants the earliest match instead (a later swap's payout to the\n // same recipient would otherwise be taken for this one).\n const events = [...(body.events ?? [])];\n if (input.afterTimestamp !== undefined) events.sort((a, b) => (a.timestamp ?? 0) - (b.timestamp ?? 0));\n for (const event of events) {\n if (!event.event_id || event.in_progress === true) continue;\n if (input.afterTimestamp !== undefined && typeof event.timestamp === \"number\" && event.timestamp < input.afterTimestamp) continue;\n if (input.beforeTimestamp !== undefined && typeof event.timestamp === \"number\" && event.timestamp > input.beforeTimestamp) continue;\n for (const action of event.actions ?? []) {\n if (action.type !== \"JettonTransfer\" || action.status !== \"ok\") continue;\n const t = action.JettonTransfer;\n if (!t?.jetton?.address || !t.recipient?.address || t.amount === undefined) continue;\n if (!sameAddress(Address.parse(t.jetton.address), master.toString())) continue;\n if (!sameAddress(Address.parse(t.recipient.address), recipient.toString())) continue;\n if (position && (!t.sender?.address || !sameAddress(Address.parse(t.sender.address), position.toString()))) continue;\n let amount: bigint;\n try {\n amount = BigInt(t.amount);\n } catch {\n continue;\n }\n if (amount < min) continue;\n return event.event_id.toLowerCase();\n }\n }\n return null;\n } catch {\n return null;\n }\n };\n}\n","/**\n * Settlement contracts this deployment trusts for Omniston, per CAIP-2 chain.\n * Audited public addresses — no secret — so both the server wiring and the\n * browser-side provider import them from here.\n * See how-to-project/OMNISTON-NETWORK-ONBOARDING.md before adding a network.\n */\nexport const AUDITED_OMNISTON_SETTLEMENT_CONTRACTS: Record<string, string[]> = {\n \"ton:-239\": [\"EQAbWJ3Y1HgIIvcMq1prG1anlDC0T3cZlAU7luPT6LmTpmrZ\"],\n \"eip155:1\": [\"0xafCF681272AF10959736f45616eeCBC22D7095E2\"],\n \"eip155:56\": [\"0xafCF681272AF10959736f45616eeCBC22D7095E2\"],\n \"eip155:137\": [\"0x41A392062A4307a6961d48e30FF20bF6823715B8\"],\n \"eip155:4663\": [\"0xafCF681272AF10959736f45616eeCBC22D7095E2\"],\n \"eip155:8453\": [\"0xACa3E2F9b61a44892926bC6c3e104192E7D1c3cd\"],\n \"eip155:42161\": [\"0xafCF681272AF10959736f45616eeCBC22D7095E2\"],\n \"eip155:43114\": [\"0xafCF681272AF10959736f45616eeCBC22D7095E2\"],\n // 2026-10-20: one factory address on X Layer, HyperEVM and Plasma. Runtime\n // bytecode equals Ethereum's 0xafCF… byte for byte except the immutable slots\n // (escrow implementations, its order protocol, domain hash); it references\n // the order protocol trusted below on the same chain.\n \"eip155:196\": [\"0xd602079AFa5c38F550510a2a988CbFa698Fa0189\"],\n \"eip155:999\": [\"0xd602079AFa5c38F550510a2a988CbFa698Fa0189\"],\n \"eip155:9745\": [\"0xd602079AFa5c38F550510a2a988CbFa698Fa0189\"],\n};\n\n/**\n * EVM order protocols (Omniston's fork of the 1inch Limit Order Protocol v4 —\n * NOT the canonical 1inch deployment) an EVM→TON order is signed against. The\n * wallet approves this contract for the input amount and signs an EIP-712\n * order whose domain names it; on fill it moves the input into the escrow the\n * factory above deploys. One address, different roles per chain (0xafCF… is\n * the factory elsewhere and the order protocol on Polygon), so this table is\n * separate from the factory table and CAIP-scoped. Runtime code hashes are in\n * how-to-project/OMNISTON-NETWORK-ONBOARDING.md (snapshot 2026-10-16).\n */\nexport const AUDITED_OMNISTON_EVM_ORDER_PROTOCOLS: Record<string, string[]> = {\n \"eip155:1\": [\"0xb5810aCfD45D85Eaa938bF90a5857295513DA7E9\"],\n \"eip155:56\": [\"0xb5810aCfD45D85Eaa938bF90a5857295513DA7E9\"],\n \"eip155:137\": [\"0xafCF681272AF10959736f45616eeCBC22D7095E2\"],\n \"eip155:8453\": [\"0xe7405fAcDEDB2512e91F2886BDff13231343aF5E\"],\n \"eip155:42161\": [\"0xb5810aCfD45D85Eaa938bF90a5857295513DA7E9\"],\n \"eip155:43114\": [\"0xb5810aCfD45D85Eaa938bF90a5857295513DA7E9\"],\n // 2026-10-20: bytecode equals Ethereum's 0xb581… except immutables (wrapped\n // native, own address, chain id 196 / 9745 / 999 at the chain-id slot).\n \"eip155:196\": [\"0xb5810aCfD45D85Eaa938bF90a5857295513DA7E9\"],\n \"eip155:9745\": [\"0xb5810aCfD45D85Eaa938bF90a5857295513DA7E9\"],\n \"eip155:999\": [\"0xD84778bbeEC5D2a8d17c6424249C438EC0b1ABE3\"],\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAUO;AACP,kBAA+B;AAE/B,IAAM,qBAAqB;AAAA,EACzB;AAAA,IACE,MAAM;AAAA,IACN,MAAM;AAAA,IACN,iBAAiB;AAAA,IACjB,QAAQ;AAAA,MACN;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,YAAY;AAAA,UACV,EAAC,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ets"]}