@anywalletkit/protocol-swap2-omniston 0.2.7 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -1
- package/dist/{chunk-IIFNHGC5.js → chunk-CRYYP6X3.js} +2 -2
- package/dist/{chunk-PKDRSR7N.js → chunk-JVFDD7PV.js} +116 -9
- package/dist/chunk-JVFDD7PV.js.map +1 -0
- package/dist/index.cjs +116 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +10 -4
- package/dist/protocol.cjs +52 -8
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.d.cts +1 -1
- package/dist/protocol.d.ts +1 -1
- package/dist/protocol.js +2 -2
- package/dist/provider.cjs +116 -9
- package/dist/provider.cjs.map +1 -1
- package/dist/provider.d.cts +64 -2
- package/dist/provider.d.ts +64 -2
- package/dist/provider.js +9 -3
- package/dist/validators.cjs.map +1 -1
- package/dist/validators.d.cts +1 -1
- package/dist/validators.d.ts +1 -1
- package/dist/validators.js.map +1 -1
- package/package.json +16 -8
- package/dist/chunk-PKDRSR7N.js.map +0 -1
- /package/dist/{chunk-IIFNHGC5.js.map → chunk-CRYYP6X3.js.map} +0 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/provider.ts","../src/activity.ts","../src/ton-swap.ts","../src/protocol.ts"],"sourcesContent":["import './buffer-global.js'\nexport * from \"./config.js\";\nexport * from \"./provider.js\";\nexport {OmnistonSwap2Protocol} from \"./protocol.js\";\nexport {OmnistonSwap2Protocol as default} from \"./protocol.js\";\nexport * from \"./activity.js\";\n","import {evmRef, isEvm, namespace} from \"@anywalletkit/protocol-swap2-core/util\";\n\n// ── Omniston (STON.fi) — stable corridors over a WebSocket RFQ ───────────────\n// Operational matrix (docs.ston.fi \"Supported Chains\", re-checked 2026-10-20):\n// Arbitrum, Avalanche, Base, BNB, Ethereum, Polygon, Robinhood, X Layer (196),\n// HyperEVM (999), Plasma (9745), ARC (5042), TON, TRON. ARC waits for the asset\n// catalog; TRON needs its own order/position path. Live RFQ 2026-10-20: every\n// listed chain quotes against TON USDT both ways, and EVM↔EVM pairs quote too.\nconst OMNISTON_EVM = new Set([1, 56, 137, 196, 999, 4663, 8453, 9745, 42161, 43114]);\nexport const omniston = {\n enabled: () => true,\n integratorAddress: () => \"\",\n integratorFeePips: () => \"\",\n wsUrl: () => \"wss://omni-ws.ston.fi\",\n /** Per-swap USD cap — the resolver quotes the corridor up to ~$1000. */\n maxUsd: () => {\n return 1000;\n },\n supportsChain(chain: string): boolean {\n if (namespace(chain) === \"ton\") return true;\n return isEvm(chain) && OMNISTON_EVM.has(evmRef(chain));\n },\n // TON↔EVM and EVM↔EVM cross-chain (order settlement), TON↔TON same-chain\n // (swap settlement — immediate DEX routes). Same-chain EVM is not an order\n // corridor.\n supports(from: string, to: string): boolean {\n if (!this.supportsChain(from) || !this.supportsChain(to)) return false;\n const tonSide = namespace(from) === \"ton\" || namespace(to) === \"ton\";\n return tonSide || from !== to;\n },\n};\n","import {Address as TonAddress, Cell as TonCell} from \"@ton/core\";\nimport {describeOmnistonActivity} from \"./activity.js\";\nimport \"./buffer-global.js\";\nimport {Buffer} from \"buffer\";\nimport {encodeAbiParameters, getAddress, hexToBytes as viemHexToBytes, keccak256, sha256} from \"viem\";\nimport {ccAsset, ccAssetByToken, type CcAsset} from \"@anywalletkit/swap2-assets\";\nimport {omniston as cfg} from \"./config.js\";\nimport {checkTonSwapPayload, TonSwapPayloadError, type TonSwapCheckResult, type TonSwapLeg} from \"./ton-swap.js\";\nexport {checkTonSwapPayload, TonSwapPayloadError, TON_SWAP_PROTOCOL_LAYOUTS} from \"./ton-swap.js\";\nexport type {TonSwapLeg, TonSwapCheckInput, TonSwapCheckResult} from \"./ton-swap.js\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {bigintToNumber} from \"@anywalletkit/core\";\n\n/**\n * Omniston (STON.fi) — TON ↔ EVM stable corridors over a WebSocket RFQ\n * (`@ston-fi/omniston-sdk`), settled through HTLC orders (resolver `Arbiter`,\n * ~$1000/swap cap). This is the audited server/module-side adaptation; the\n * legacy browser-direct execution path is disabled.\n *\n * - getQuote: opens an RFQ stream, collects `quoteUpdated` for a short window,\n * returns the latest quote normalized to the engine `Quote`.\n * - buildDeposit (TON-source): generates the HTLC secret(s), persists them\n * in the injectable {@link HtlcSecretStore}, asks the SDK for the escrow\n * transfer and returns it as an `UnsignedTx` with a serialized cell body\n * (`bodyBoc`) — NOT a text memo.\n * - buildDeposit (EVM-source, EVM→TON): generates the secret, asks the SDK for\n * the EIP-712 order (Omniston's 1inch-LOP fork), verifies every signed byte\n * against the quote (order fields, extension, serialized order details) and\n * returns a gasless typed-order `UnsignedTx`; `registerSignedOrder` hands\n * the wallet's signature back to Omniston. Needs `trustedEvmOrderProtocols`\n * plus the EVM input-position and TON output-position validators.\n * - trackIntent: treats `orderTrack` only as a discovery hint and discloses a\n * pending secret only after independent finalized validation of the\n * counter-position (EVM escrow for TON→EVM; EVM source fill AND TON output\n * position for EVM→TON).\n *\n * CONSUMER CONTRACT — closing an intent is the caller's job. `trackIntent`\n * never returns a terminal refunded/failed state, not even on a reported\n * cancellation, because a resolver-controlled feed is not proof that the\n * signed source order can no longer fill. An integration without its own\n * chain-backed backstop will therefore report an already-refunded escrow as\n * pending indefinitely: close such intents by observing the exact input amount\n * returning from an allowlisted settlement contract to the trader's wallet.\n *\n * CONSUMER CONTRACT — `validateEvmOutputPosition` decides whether the swap can\n * complete at all, so verify what a resolver actually does on chain. It does\n * NOT call the escrow factory directly: the destination escrow is deployed\n * through the resolver's own contract, so the transaction targets that\n * contract, carries a private selector and usually sends no value, while the\n * factory only emits `DstEscrowCreated`. A verifier that expects a direct\n * `createDstEscrow` call therefore rejects every legitimate escrow, the secret\n * is never disclosed, and both positions roll back — which looks exactly like a\n * venue that quotes and walks away. Anchor on evidence the wrapper cannot\n * forge: the factory's own event for your hashlock, the escrow's `FACTORY()`,\n * and the balances it actually holds.\n *\n * The HTLC secret is the difference between \"swap completes\" and \"funds sit in\n * escrow until the refund timeout\". The default store is in-memory — fine for a\n * long-lived process, NOT for serverless. Callers on serverless MUST inject a\n * durable store.\n */\n\n/** CAIP-2 eip155 refs → the SDK's chain `$case` names. */\nconst EVM_CASE: Record<number, \"ethereum\" | \"bnb\" | \"base\" | \"arbitrum\" | \"avalanche\" | \"polygon\" | \"robinhood\" | \"xlayer\" | \"hyperevm\" | \"plasma\"> = {\n 1: \"ethereum\",\n 56: \"bnb\",\n 137: \"polygon\",\n 196: \"xlayer\",\n 999: \"hyperevm\",\n 4663: \"robinhood\",\n 8453: \"base\",\n 9745: \"plasma\",\n 42161: \"arbitrum\",\n 43114: \"avalanche\",\n};\n\nconst TON_NS = \"ton\";\nconst INTENT_PREFIX = \"omn1\";\n/** How long getQuote lets resolvers compete before taking the latest quote. */\nconst QUOTE_SETTLE_MS = 3_000;\n/**\n * Execution quotes settle far sooner than display ones. A resolver's\n * `tradeStartDeadline` is only ~25-30s away, and it is measured to the escrow\n * being ON-CHAIN — not to the broadcast — so every second spent collecting\n * competing offers is a second the source leg no longer has to be built,\n * signed, broadcast and included. A late escrow is not filled and sits until\n * the HTLC refunds, which costs the trader far more than the price difference\n * between the first quote and the best of a 3s auction on a stable corridor.\n */\nconst EXECUTION_SETTLE_MS = 600;\n/**\n * Refuse to build an escrow that cannot realistically reach the chain before\n * `tradeStartDeadline`: signing, broadcast and TON inclusion need roughly this\n * long, and funding a doomed escrow locks the trader's money until the HTLC\n * times out. Failing here is instant and costs nothing.\n */\nconst MIN_START_HEADROOM_MS = 12_000;\n/** Hard ceiling on waiting for the FIRST quote (router timeout is 8s). */\nconst QUOTE_MAX_MS = 6_500;\n/** One orderTrack snapshot per trackIntent call. */\nconst TRACK_SNAPSHOT_MS = 6_000;\n// One execution: the live TON escrow commits a single hash and the EVM order is\n// single-fill, so more secrets only make the TON payload validator refuse.\nconst DEFAULT_MAX_HTLC_EXECUTIONS = 1;\n/** Normalized quote validity shown to the router/UI. */\nconst QUOTE_TTL_MS = 45_000;\n/** Quote/security context must outlive delayed fills and cancellation signals. */\nconst CACHE_TTL_MS = 6 * 60 * 60 * 1000;\n/**\n * Context entries written before intent binding (scan F3/F15) carry no bound\n * trader/dest/srcChain/kind. They are honoured — with a `legacy-intent` trace —\n * only while younger than this (the store TTL), then disclosure is refused.\n */\nconst LEGACY_INTENT_WINDOW_MS = 6 * 60 * 60 * 1000;\n\n// ── HTLC secret store (injectable) ───────────────────────────────────────────\n\n/**\n * Persists HTLC secret preimages by quoteId between buildDeposit and the\n * trackIntent poll that discloses them. Losing a secret does NOT lose funds —\n * the escrow refunds after the HTLC timeout — but it does fail the swap.\n */\nexport interface HtlcSecretStore {\n save(quoteId: string, secretsHex: string[]): void | Promise<void>;\n load(quoteId: string): string[] | undefined | Promise<string[] | undefined>;\n clear(quoteId: string): void | Promise<void>;\n}\n\n/**\n * Persists the quote/build context between getQuote, buildDeposit and\n * registerSignedOrder. On SERVERLESS these run on different instances, so the\n * default in-memory map strands executions (\"quote expired\") — inject a\n * durable store there. Values are JSON-safe (byte fields base64-encoded).\n */\nexport interface OmnistonQuoteStore {\n save(quoteId: string, valueJson: string): void | Promise<void>;\n load(quoteId: string): string | undefined | Promise<string | undefined>;\n clear(quoteId: string): void | Promise<void>;\n}\n\n/** Default quote store — long-lived processes and tests only. */\nexport function inMemoryQuoteStore(): OmnistonQuoteStore {\n const map = new Map<string, string>();\n return {\n save: (id, v) => void map.set(id, v),\n load: (id) => map.get(id),\n clear: (id) => void map.delete(id),\n };\n}\n\n/** Default store — suitable for long-lived processes and tests only. */\nexport function inMemorySecretStore(): HtlcSecretStore {\n const map = new Map<string, string[]>();\n return {\n save: (id, secrets) => void map.set(id, secrets),\n load: (id) => map.get(id),\n clear: (id) => void map.delete(id),\n };\n}\n\n// ── Minimal structural view of the SDK client (injectable for tests) ─────────\n\ninterface ObservableLike<T> {\n subscribe(observer: {next?: (value: T) => void; error?: (err: unknown) => void; complete?: () => void}): {unsubscribe(): void};\n}\n\n/** Self-contained structural SDK types. Keeping these local prevents the\n * optional Omniston peer from leaking into every consumer's declaration graph. */\ninterface AssetId {\n chain: {\n $case: string;\n value: string | {kind?: {$case: string; value?: unknown}};\n };\n}\n\ninterface ChainAddress {\n chain: {$case: string; value: string};\n}\n\ninterface QuoteRequest {\n inputAsset: AssetId;\n outputAsset: AssetId;\n amount: {$case: string; value: string};\n settlementParams: {params: {$case: string; value: Record<string, unknown>}}[];\n integratorAddress?: ChainAddress;\n integratorFeePips?: number;\n}\n\ninterface OmnistonQuote {\n rfqId: string;\n quoteId: string;\n inputAsset: AssetId;\n outputAsset: AssetId;\n inputUnits: string;\n outputUnits: string;\n protocolFeeUnits?: string;\n integratorFeeUnits?: string;\n integratorAddress?: ChainAddress;\n quoteTimestamp: number;\n /** Total TON the trade needs on top of the input (swap settlement); omitted for gasless quotes. */\n gasBudget?: string | undefined;\n /** Omniston's estimate of the gas the route actually burns (swap settlement); the rest of the budget returns. */\n estimatedGasConsumption?: string | undefined;\n settlementData: {$case: \"order\"; value: OrderSettlement} | {$case: \"swap\"; value: SwapSettlement};\n}\n\n/** Order settlement (HTLC / escrow) — the cross-chain branch. */\ninterface OrderSettlement {\n srcProtocolContractAddress: ChainAddress;\n dstProtocolContractAddress?: ChainAddress;\n srcInitialResolverAddress?: ChainAddress;\n resolverSendsUnits: string;\n srcHtlcSecurityDepositUnits?: string;\n dstSecurityDepositUnits?: string;\n tradeStartDeadline: number;\n /**\n * Seconds after the trader creates the position before a resolver must\n * reserve it; after that the position is withdrawable by the trader (SDK\n * docs). The TON escrow config carries it, so the payload validator binds\n * the built escrow to the quoted value.\n */\n exclusivityTimeout?: number;\n htlcHashingFunction?: string;\n /** Fee profile the EVM order extension must mirror (EVM-source orders). */\n protocolFeePips?: number;\n integratorFeePips?: number;\n /** Destination-chain wallet the protocol fee must be paid to (EVM-destination\n * orders); the EVM output validator binds the escrow's fee split to it. */\n protocolFeeRecipientAddress?: ChainAddress;\n}\n\n/** Swap settlement — immediate DEX routes, the TON same-chain branch. */\ninterface SwapSettlement {\n routes: {steps: {inputAsset?: AssetId; outputAsset?: AssetId; chunks: {protocol: string; inputUnits: string; outputUnits: string}[]}[]}[];\n minOutputAmount: string;\n recommendedMinOutputAmount?: string;\n recommendedSlippagePips?: number;\n priceImpactPips?: number | undefined;\n}\n\ntype RfqEvent =\n | {$case: \"ack\"; value: {rfqId: string}}\n | {$case: \"quoteUpdated\"; rfqId?: string; value: OmnistonQuote}\n | {$case: \"noQuote\"; rfqId?: string; value: unknown}\n | {$case: string; value?: unknown};\n\ninterface EscrowMessage {\n targetAddress: string;\n sendAmount: string;\n payload: string; // hex-encoded cell BoC\n jettonWalletStateInit?: string | undefined;\n}\n\ninterface OrderExecution {\n index: number;\n inputUnits: string;\n outputUnits: string;\n resolverSendsUnits: string;\n secretHash?: Uint8Array | undefined;\n inputPositionPhase?: string | undefined;\n inputPositionAddress?: ChainAddress | undefined;\n outputPositionPhase?: string | undefined;\n outputPositionAddress?: ChainAddress | undefined;\n}\n\ninterface OrderSnapshot {\n status: string;\n executions: OrderExecution[];\n}\n\ntype OrderEvent = {$case: \"order\"; value: OrderSnapshot} | {$case: string; value?: unknown};\n\ntype SwapTrackEvent =\n | {$case: \"awaitingTransfer\"; value?: unknown}\n | {$case: \"progress\"; value: {status: string; outgoingTxHash?: string}}\n | {$case: string; value?: unknown};\n\n/** The slice of `Omniston` this provider uses — a real instance satisfies it. */\nexport interface OmnistonClientLike {\n requestForQuote(request: QuoteRequest): ObservableLike<RfqEvent>;\n tonBuildEscrowTransfer(request: {\n quoteId: string;\n ownerSrcAddress: ChainAddress;\n transferSrcAddress: ChainAddress;\n refundSrcAddress: ChainAddress;\n gasExcessAddress: ChainAddress;\n traderDstAddress: ChainAddress;\n htlcSecrets: {secretMode: {$case: \"provided\"; value: {hashes: Uint8Array[]}}};\n }): Promise<{messages: EscrowMessage[]}>;\n evmBuildOrderPayload(request: {\n quoteId: string;\n ownerSrcAddress: ChainAddress;\n traderDstAddress?: ChainAddress;\n htlcSecrets?: {secretMode: {$case: \"provided\"; value: {hashes: Uint8Array[]}}};\n }): Promise<{typedData: string; orderExtension: Uint8Array; serializedOrderDetails?: Uint8Array | undefined}>;\n orderRegisterSignedOrder(request: {\n quoteId: string;\n ownerSrcAddress: ChainAddress;\n signedOrder: {order: {$case: \"evmV1\"; value: {encodedOrder: Uint8Array; signature: Uint8Array; orderExtension: Uint8Array}}};\n serializedOrderDetails?: Uint8Array | undefined;\n }): Promise<void>;\n /** Swap settlement (TON↔TON). Optional so older injected clients keep working; without them same-chain swaps fail closed. */\n tonBuildSwap?(request: {\n quoteId: string;\n transferSrcAddress: ChainAddress;\n refundSrcAddress: ChainAddress;\n gasExcessAddress: ChainAddress;\n traderDstAddress: ChainAddress;\n useRecommendedSlippage?: boolean;\n }): Promise<{messages: EscrowMessage[]}>;\n swapTrack?(request: {quoteId: string; traderAddress: ChainAddress; outgoingTxQuery: string}): ObservableLike<SwapTrackEvent>;\n orderTrack(request: {quoteId: string; traderAddress: ChainAddress}): ObservableLike<OrderEvent>;\n orderDiscloseHtlcSecret(request: {quoteId: string; executionIndex: number; secret: Uint8Array}): Promise<void>;\n close?: () => void;\n transport?: {close(): void};\n}\n\nexport interface OmnistonProviderOptions {\n /** Injected SDK client (tests); defaults to a lazy `new Omniston({apiUrl})`. */\n client?: OmnistonClientLike;\n /** WebSocket API URL; defaults to the public ston.fi endpoint. */\n apiUrl?: string;\n /** HTLC preimage persistence; defaults to in-memory (NOT serverless-safe). */\n secretStore?: HtlcSecretStore;\n /** Quote/build context persistence; defaults to in-memory (NOT serverless-safe). */\n quoteStore?: OmnistonQuoteStore;\n /** Maximum number of HTLC execution attempts covered by generated secrets. */\n maxHtlcExecutions?: number;\n /** Hard cap for resolver-requested TON gas/forward value (default: 2 TON). */\n maxTonExecutionNano?: string;\n /** Resolver competition window; primarily useful for deterministic tests. */\n quoteSettleMs?: number;\n /** Explicit constructor configuration; no deployment environment is read. */\n enabled?: boolean;\n /** Exact decimal USD cap; string form avoids binary-float rounding. */\n maxUsd?: number | string;\n integratorAddress?: string;\n integratorFeePips?: number;\n /** Independently trusted settlement contracts, keyed by CAIP-2 chain. */\n trustedSettlementContracts?: Readonly<Record<string, readonly string[]>>;\n /**\n * Independently trusted EVM order protocols — the Omniston fork of the 1inch\n * Limit Order Protocol an EVM-source order is signed against and that moves\n * the input token on fill — keyed by CAIP-2 chain. Kept apart from\n * `trustedSettlementContracts` because one address plays different roles on\n * different chains (0xafCF… is the escrow factory on Ethereum and the order\n * protocol on Polygon). EVM→TON is advertised only for chains listed here.\n */\n trustedEvmOrderProtocols?: Readonly<Record<string, readonly string[]>>;\n /**\n * RPC-backed TON jetton-wallet verification. A TON-source order is rejected\n * when this hook is absent or does not prove that `walletAddress` belongs to\n * the quoted jetton master for `ownerAddress`.\n */\n validateTonJettonWallet?: (input: {\n ownerAddress: string;\n jettonMasterAddress: string;\n walletAddress: string;\n }) => boolean | Promise<boolean>;\n /**\n * Independent semantic verifier for the Omniston TON escrow forward cell.\n * The resolver-built BoC is never accepted through byte-search heuristics.\n * A TON-source route is disabled unless this hook parses the documented\n * contract schema and proves every expected field below in its exact slot.\n */\n /**\n * TON↔TON swap settlement: independently confirm that the contract a swap\n * message pays into — directly for native GRAM, as the jetton-transfer\n * destination for jettons — is a DEX contract of a protocol the quote named\n * (e.g. by its code interface on an indexer). Without it, same-chain TON\n * swaps are not advertised.\n */\n validateTonSwapTarget?: (input: {address: string; protocols: readonly string[]}) => Promise<boolean> | boolean;\n /**\n * TON↔TON swap settlement (scan F11): confirm one chain fact the decoded\n * swap body depends on — that a STON.fi hop's ask wallet is its router's\n * wallet of the quoted output (and, for native input, that the pTON wallet\n * the message pays belongs to that router), or that a DeDust pool trades the\n * quoted pair. `createOmnistonTonValidators` supplies it. When absent the\n * decoded-body rules still apply and each skipped leg is traced as\n * `ton-swap-payload legs-unverified`; STON.fi v1 native input (pTON v1) is\n * refused without it.\n */\n validateTonSwapLeg?: (leg: TonSwapLeg) => Promise<boolean> | boolean;\n /**\n * TON↔TON swap settlement (scan F11): what a built swap body that fails the\n * decoder (receiver ≠ destination, refund/excess ≠ trader, on-chain minimum\n * below the quote, unknown layout, unverifiable leg) does. \"enforce\"\n * (default) refuses the build; \"report\" traces `ton-swap-payload <reason>`\n * and still builds — a rollout escape hatch, not a steady state.\n */\n tonSwapPayloadCheck?: \"report\" | \"enforce\";\n validateTonEscrowPayload?: (input: {\n payloadBocHex: string;\n forwardPayloadBocHex: string;\n quoteId: string;\n inputUnits: string;\n resolverSendsUnits: string;\n srcHtlcSecurityDepositUnits: string;\n protocolAddress: string;\n ownerAddress: string;\n destinationChain: string;\n destinationAddress: string;\n outputTokenAddress: string;\n initialResolverAddress: string;\n secretHashes: readonly Uint8Array[];\n hashingFunction?: string;\n /** The quote's `exclusivityTimeout` (seconds) the escrow config must carry. */\n exclusivityTimeout: number;\n }) => boolean | Promise<boolean>;\n /**\n * RPC-backed proof of the destination EVM escrow. The tracking feed is only\n * a discovery hint: no HTLC preimage is disclosed until this hook proves the\n * independently finalized on-chain position matches the signed quote.\n */\n validateEvmOutputPosition?: (input: {\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 chain). */\n protocolFeeRecipientAddress?: string;\n secretHash: Uint8Array;\n }) => boolean | Promise<boolean>;\n /**\n * RPC-backed proof of the finalized EVM source position (EVM→TON). The\n * tracking feed only hints at the address; no secret is disclosed until this\n * hook proves — from the trusted factory's own `SrcEscrowCreated` event, the\n * deterministic escrow address and the escrow's balances — that the\n * trader's FULL input is locked for this hashlock under the quoted terms\n * (owner, token, amount, resolver, deposit, timelocks, TON output amount).\n */\n validateEvmInputPosition?: (input: {\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 escrow event's destination complement must name this chain, token and deposit. */\n destinationChainId?: number;\n destinationTokenAddress?: string;\n dstSecurityDepositUnits?: string;\n }) => boolean | Promise<boolean>;\n /**\n * Indexer/RPC-backed proof of the TON output position (EVM→TON): deployed by\n * the trusted factory for THIS quote, pinned position/escrow code, hashlock,\n * recipient, amount, security deposit, and a cancellation boundary still far\n * enough away to complete. The tracking feed is only a discovery hint.\n */\n validateTonOutputPosition?: (input: {\n positionAddress: string;\n protocolAddress: string;\n outputJettonMasterAddress: string;\n recipientAddress: string;\n quoteId: string;\n quoteTimestamp: number;\n inputUnits: string;\n outputUnits: string;\n resolverSendsUnits: string;\n dstSecurityDepositUnits: string;\n secretHash: Uint8Array;\n }) => boolean | Promise<boolean>;\n /**\n * EVM destination: find the delivery transaction — the destination escrow's\n * payout to the recipient — so a completed order carries `destTxHash`.\n * Omniston's tracking feed names the escrow but not that transaction.\n */\n locateEvmDelivery?: (input: {\n chain: string;\n positionAddress: string;\n recipientAddress: string;\n tokenAddress: string;\n minUnits: string;\n }) => Promise<string | null>;\n /**\n * TON destination: find the delivery — the output position's jetton transfer\n * to the recipient — so a completed EVM → TON order carries `destTxHash` in\n * the form the TON history source uses (tonapi event id). Without it the\n * wallet's feed cannot pair the TON receive with the swap.\n */\n locateTonDelivery?: (input: {\n positionAddress: string;\n recipientAddress: string;\n jettonMasterAddress: string;\n minUnits: string;\n }) => Promise<string | null>;\n /** Close an injected client when the provider closes (default: caller owns it). */\n closeInjectedClient?: boolean;\n /**\n * Diagnostics: why a poll did not disclose (`disclosure-skipped` with the gate\n * and its fields, `validator-refused`, `validator-threw`) and when it did\n * (`secret-disclosed`). Never carries secrets. Wire it to your logger: a\n * silent \"pending\" cost a live order its 2-minute window (2026-10-20).\n */\n trace?: (event: string, details?: Record<string, unknown>) => void;\n}\n\n// ── Chain / asset mapping ────────────────────────────────────────────────────\n\nfunction evmRef(caip2: string): number | null {\n if (!caip2.startsWith(\"eip155:\")) return null;\n const n = Number(caip2.slice(\"eip155:\".length));\n return Number.isInteger(n) ? n : null;\n}\n\nfunction isTon(caip2: string): boolean {\n return caip2.split(\":\")[0] === TON_NS;\n}\n\nfunction caipForChainCase($case: string): string | null {\n if ($case === \"ton\") return \"ton:-239\";\n const entry = Object.entries(EVM_CASE).find(([, value]) => value === $case);\n return entry ? `eip155:${entry[0]}` : null;\n}\n\n/** Catalog asset → SDK AssetId. Stable corridors only: a `contract` is REQUIRED\n * (jetton master / ERC-20) — native assets have no Omniston order corridor. */\nfunction toAssetId(caip2: string, asset: CcAsset, allowNative = false): AssetId | null {\n if (!asset.contract) {\n // Native GRAM only exists on the swap-settlement branch (same-chain DEX routes).\n return allowNative && isTon(caip2) ? {chain: {$case: \"ton\", value: {kind: {$case: \"native\", value: {}}}}} : null;\n }\n if (isTon(caip2)) {\n return {chain: {$case: \"ton\", value: {kind: {$case: \"jetton\", value: asset.contract}}}};\n }\n const ref = evmRef(caip2);\n const $case = ref === null ? undefined : EVM_CASE[ref];\n if (!$case) return null;\n return {chain: {$case, value: {kind: {$case: \"erc20\", value: getAddress(asset.contract)}}}};\n}\n\nfunction toChainAddress(caip2: string, address: string): ChainAddress | null {\n if (isTon(caip2)) return {chain: {$case: \"ton\", value: address}};\n const ref = evmRef(caip2);\n const $case = ref === null ? undefined : EVM_CASE[ref];\n if (!$case) return null;\n return {chain: {$case, value: getAddress(address)}};\n}\n\n// ── intentId: quoteId + the trader/dest context tracking and building need ───\n\nfunction encodeIntent(quoteId: string, trader: string, dest: string, srcChain: string, kind: \"order\" | \"swap\" = \"order\"): string {\n // Swap-settlement intents carry a sixth segment so tracking can branch\n // without the (TTL-bound) quote cache; order intents keep the legacy shape.\n return [INTENT_PREFIX, quoteId, trader, dest, srcChain, ...(kind === \"swap\" ? [\"swap\"] : [])].map(encodeURIComponent).join(\"|\");\n}\n\n/**\n * A quote id is a 256-bit value in hex WITHOUT leading-zero padding (live\n * 2026-10-12: 63-char ids, ~1 in 16 quotes) — requiring exactly 64 chars\n * refused those as \"malformed quote id\". Binary comparisons pad it to 32 bytes.\n */\nconst QUOTE_ID = /^[0-9a-fA-F]{48,64}$/;\n\nfunction decodeIntent(\n intentId: string,\n): {quoteId: string; trader: string; dest: string; srcChain: string; kind: \"order\" | \"swap\"} | null {\n try {\n const parts = intentId.split(\"|\");\n if ((parts.length !== 5 && parts.length !== 6) || parts[0] !== INTENT_PREFIX) return null;\n const [, quoteId = \"\", trader = \"\", dest = \"\", srcChain = \"\", kindPart = \"\"] = parts.map(decodeURIComponent);\n if (!QUOTE_ID.test(quoteId) || !trader || !dest || !srcChain) return null;\n if (parts.length === 6 && kindPart !== \"swap\") return null;\n return {quoteId, trader, dest, srcChain, kind: parts.length === 6 ? \"swap\" : \"order\"};\n } catch {\n return null;\n }\n}\n\n/**\n * What an intentId was minted for, persisted with the quote at getQuote time\n * (scan F3/F15). The intentId itself is an unsigned caller-supplied string: the\n * stored copy — never the decoded one — names the trader and recipient the\n * secret-release validators, the builders and the delivery locators check.\n */\ninterface IntentBinding {\n trader: string;\n dest: string;\n srcChain: string;\n kind: \"order\" | \"swap\";\n}\n\n/** Same address in another spelling: EVM case-insensitive, TON any notation. */\nfunction sameIntentAddress(a: string, b: string): boolean {\n if (a === b) return true;\n const evm = /^0x[0-9a-fA-F]{40}$/;\n if (evm.test(a) || evm.test(b)) return evm.test(a) && evm.test(b) && a.toLowerCase() === b.toLowerCase();\n try {\n return TonAddress.parse(a).equals(TonAddress.parse(b));\n } catch {\n return false;\n }\n}\n\n/** EIP-712 typed data → the ABI-encoded order struct `SignedOrderEvmV1` wants.\n * Structs referenced in `types` become tuples, recursively. */\nexport function encodeTypedMessage(td: {\n types: Record<string, {name: string; type: string}[]>;\n primaryType: string;\n message: unknown;\n}): Uint8Array {\n type AbiParam = {type: string; name?: string; components?: AbiParam[]};\n const paramFor = (typeName: string, name?: string): AbiParam => {\n const isArray = typeName.endsWith(\"[]\");\n const base = isArray ? typeName.slice(0, -2) : typeName;\n const fields = td.types[base];\n if (!fields) return {type: typeName, ...(name ? {name} : {})};\n return {\n type: isArray ? \"tuple[]\" : \"tuple\",\n ...(name ? {name} : {}),\n components: fields.map((f) => paramFor(f.type, f.name)),\n };\n };\n return viemHexToBytes(\n encodeAbiParameters([paramFor(td.primaryType)] as never, [td.message] as never),\n );\n}\n\n// ── HTLC helpers (ported from app/lib/omniston/htlc.ts) ──────────────────────\n\nfunction generateSecret(): Uint8Array {\n return crypto.getRandomValues(new Uint8Array(32));\n}\n\nfunction hashlock(secret: Uint8Array, hashingFunction: string | undefined): Uint8Array {\n switch (hashingFunction) {\n case \"HASHING_FUNCTION_KECCAK256\":\n return keccak256(secret, \"bytes\");\n case \"HASHING_FUNCTION_SHA256\":\n return sha256(secret, \"bytes\");\n default:\n throw new Error(`omniston: unsupported HTLC hashing function ${String(hashingFunction)}`);\n }\n}\n\nfunction sameAsset(a: AssetId, b: AssetId): boolean {\n const key = (asset: AssetId): string => {\n const chain = asset.chain;\n const value = chain.value as {kind?: {$case: string; value?: unknown}} | string;\n const normalize = (text: string) => chain.$case === \"ton\" ? text : text.toLowerCase();\n if (typeof value === \"string\") return `${chain.$case}:${normalize(value)}`;\n const kind = value.kind;\n return `${chain.$case}:${kind?.$case ?? \"\"}:${typeof kind?.value === \"string\" ? normalize(kind.value) : JSON.stringify(kind?.value ?? null)}`;\n };\n return key(a) === key(b);\n}\n\nfunction sameChainAddress(a: ChainAddress | undefined, b: ChainAddress | undefined): boolean {\n if (a === undefined || b === undefined) return a === b;\n if (a.chain.$case !== b.chain.$case) return false;\n if (a.chain.$case !== \"ton\") return a.chain.value.toLowerCase() === b.chain.value.toLowerCase();\n // The SDK may echo a TON address in another notation (EQ…/UQ…/raw).\n try {\n return TonAddress.parse(a.chain.value).equals(TonAddress.parse(b.chain.value));\n } catch {\n return a.chain.value === b.chain.value;\n }\n}\n\nfunction assetContract(asset: AssetId): string | null {\n const value = asset.chain.value;\n if (typeof value === \"string\") return null;\n const kind = value.kind;\n return kind && typeof kind.value === \"string\" ? kind.value : null;\n}\n\n/** A route step's asset as a jetton master (null = native GRAM, undefined = not stated). */\nfunction stepJetton(asset: AssetId | undefined): string | null | undefined {\n if (!asset || asset.chain.$case !== \"ton\" || typeof asset.chain.value === \"string\") return undefined;\n const kind = asset.chain.value.kind;\n if (kind?.$case === \"native\") return null;\n return kind?.$case === \"jetton\" && typeof kind.value === \"string\" ? kind.value : undefined;\n}\n\nfunction readBigEndian(bytes: Uint8Array, offset: number, length: number): bigint {\n if (!Number.isInteger(offset) || !Number.isInteger(length) || length < 1 || offset < 0 || offset + length > bytes.length) {\n throw new Error(\"omniston: truncated EVM order extension\");\n }\n let value = 0n;\n for (let index = offset; index < offset + length; index++) value = (value << 8n) | BigInt(bytes[index]!);\n return value;\n}\n\nfunction sliceEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((value, index) => value === b[index]);\n}\n\nfunction zeroBytes(bytes: Uint8Array): boolean {\n return bytes.every((value) => value === 0);\n}\n\n/** `value` within [center - before, center + after] (seconds). */\nfunction within(value: bigint, center: number, before: number, after: number): boolean {\n return value >= BigInt(center - before) && value <= BigInt(center + after);\n}\n\nconst ORDER_FIELDS = [\n [\"salt\", \"uint256\"],\n [\"maker\", \"address\"],\n [\"receiver\", \"address\"],\n [\"makerAsset\", \"address\"],\n [\"takerAsset\", \"address\"],\n [\"makingAmount\", \"uint256\"],\n [\"takingAmount\", \"uint256\"],\n [\"makerTraits\", \"uint256\"],\n] as const;\n\nfunction validUint256(value: unknown): boolean {\n try {\n const n = BigInt(value as string | number | bigint);\n return n >= 0n && n < 1n << 256n;\n } catch {\n return false;\n }\n}\n\nfunction validEvmAddress(value: unknown): boolean {\n try {\n getAddress(String(value));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * The protocol-fee recipient Omniston names in the post-interaction of\n * EVM-destination orders (live 2026-10-20: the same EOA on Base→Arbitrum and\n * Plasma→Base; TON-destination orders still carry zero). It only receives the\n * quoted protocol fee — what the trader gives and gets is bound elsewhere — but\n * it is pinned so an unexpected recipient fails closed.\n */\nconst EVM_DEST_PROTOCOL_FEE_RECIPIENTS = new Set([\"0x076268146b4ec6d21fc49c27586cfa91b9079a00\"]);\n\n/**\n * Strict decoder for the currently observed Omniston v1beta8 EVM→TON 1inch\n * extension profile. It deliberately rejects unknown auction/fee/timelock\n * profiles: signing a merely well-formed extension is not enough because the\n * resolver-controlled tail contains the actual on-chain HTLC terms.\n *\n * This binds what the wallet signs to the quote; it does not by itself make\n * the swap complete. Secret disclosure additionally needs the independently\n * finalized EVM source-fill and TON output-position proofs (trackIntent).\n * `dstSecurityDepositUnits` is the value the EVM deposits word carries — for a\n * TON destination that word is 0 (the TON deposit is bound in the TON position).\n */\nexport async function validateEvmToTonOrderExtension(\n extension: Uint8Array,\n expected: {\n quoteId: string;\n quoteTimestamp: number;\n tradeStartDeadline: number;\n protocolFeePips: number;\n integratorFeePips: number;\n initialResolverAddress: string;\n outputTokenAddress: string;\n traderDstAddress: string;\n takerAsset: string;\n srcSecurityDepositUnits: string;\n dstSecurityDepositUnits: string;\n secretHash: Uint8Array;\n trustedTarget: (address: string) => boolean;\n /** EVM destination (EIP-155 id): ExtraDataArgs carry it and the destination\n * ERC-20 (`outputTokenAddress`, `traderDstAddress` are EVM then). Absent = TON. */\n dstChainId?: number;\n },\n): Promise<void> {\n const evmDest = expected.dstChainId !== undefined;\n if (evmDest && (!Number.isSafeInteger(expected.dstChainId) || expected.dstChainId! <= 0)) throw new Error(\"omniston: invalid EVM destination chain id\");\n if (extension.length < 32) throw new Error(\"omniston: malformed EVM order extension\");\n const view = new DataView(extension.buffer, extension.byteOffset, extension.byteLength);\n const fields: Uint8Array[] = [];\n let begin = 0;\n const concatLength = extension.length - 32;\n for (let index = 0; index < 8; index++) {\n const end = view.getUint32(28 - index * 4, false);\n if (end < begin || end > concatLength) throw new Error(\"omniston: malformed EVM order extension offsets\");\n fields.push(extension.slice(32 + begin, 32 + end));\n begin = end;\n }\n // Omniston's audited 1inch profile uses only amount getters (2/3) and a\n // post-interaction (7). Suffixes can alter token calls; permit/predicate/pre\n // interaction are separate programs and are not authorized by this adapter.\n for (const index of [0, 1, 4, 5, 6]) {\n if (fields[index]!.length !== 0) throw new Error(\"omniston: unsupported EVM order extension field\");\n }\n if (!sliceEqual(fields[2]!, fields[3]!)) {\n throw new Error(\"omniston: making/taking amount getters use different programs\");\n }\n let target: string | undefined;\n for (const index of [2, 3, 7]) {\n const field = fields[index]!;\n if (field.length <= 20) throw new Error(\"omniston: incomplete EVM order extension program\");\n const address = getAddress(`0x${bytesToHex(field.slice(0, 20))}`);\n if (!expected.trustedTarget(address) || (target !== undefined && getAddress(target) !== address)) {\n throw new Error(\"omniston: EVM order extension target is not independently trusted\");\n }\n target = address;\n }\n\n // SimpleSettlement auction + AmountGetterWithFee. The current trader quote\n // does not describe the curve, so only the audited live v1beta8 profile is\n // accepted. A contract/profile upgrade must add a new explicit decoder.\n const getter = fields[2]!;\n let cursor = 20;\n const gasBump = readBigEndian(getter, cursor, 3); cursor += 3;\n const gasPrice = readBigEndian(getter, cursor, 4); cursor += 4;\n const auctionStart = readBigEndian(getter, cursor, 4); cursor += 4;\n const duration = readBigEndian(getter, cursor, 3); cursor += 3;\n const initialRateBump = readBigEndian(getter, cursor, 3); cursor += 3;\n const pointCount = bigintToNumber(readBigEndian(getter, cursor, 1)); cursor += 1;\n if (pointCount !== 5) throw new Error(\"omniston: unsupported EVM auction profile\");\n const points: [bigint, bigint][] = [];\n for (let index = 0; index < pointCount; index++) {\n points.push([readBigEndian(getter, cursor, 3), readBigEndian(getter, cursor + 3, 2)]);\n cursor += 5;\n }\n const integratorFee = readBigEndian(getter, cursor, 2); cursor += 2;\n const integratorShare = readBigEndian(getter, cursor, 1); cursor += 1;\n const resolverFee = readBigEndian(getter, cursor, 2); cursor += 2;\n const whitelistDiscount = readBigEndian(getter, cursor, 1); cursor += 1;\n const getterWhitelistCount = bigintToNumber(readBigEndian(getter, cursor, 1)); cursor += 1;\n if (getterWhitelistCount !== 1 || cursor + getterWhitelistCount * 10 !== getter.length) {\n throw new Error(\"omniston: malformed EVM amount-getter whitelist\");\n }\n const getterResolver = readBigEndian(getter, cursor, 10);\n const expectedPoints = [[800000n, 100n], [700000n, 100n], [600000n, 100n], [500000n, 100n], [400000n, 100n]];\n const quoteResolverFee = expected.protocolFeePips % 10 === 0 ? BigInt(expected.protocolFeePips / 10) : -1n;\n const resolverLow80 = BigInt(getAddress(expected.initialResolverAddress)) & ((1n << 80n) - 1n);\n if (\n gasBump !== 0n || gasPrice !== 0n || !within(auctionStart, expected.quoteTimestamp, 5, 5) ||\n duration !== 1800n || initialRateBump !== 900000n ||\n points.some((point, index) => point[0] !== expectedPoints[index]![0] || point[1] !== expectedPoints[index]![1]) ||\n expected.integratorFeePips !== 0 || integratorFee !== 0n || integratorShare !== 100n ||\n quoteResolverFee < 0n || resolverFee !== quoteResolverFee || whitelistDiscount !== 50n ||\n getterResolver !== resolverLow80\n ) {\n throw new Error(\"omniston: EVM amount-getter terms do not match the pinned v1beta8 profile\");\n }\n\n // BaseEscrowFactory postInteraction: exact fee/whitelist prefix followed by\n // five uint256 ExtraDataArgs words. Unknown recipients and trailing bytes are\n // rejected because the corresponding EVM→TON mapping is not public.\n // `allowedTime` is stamped by the resolver a few seconds BEFORE the quote\n // timestamp (live 2026-10-16: 14–18 s on every chain); the auction start is\n // the quote timestamp (±1 s on Polygon). Both windows are bounded.\n const post = fields[7]!;\n cursor = 20;\n const integratorRecipient = post.slice(cursor, cursor + 20); cursor += 20;\n const protocolRecipient = post.slice(cursor, cursor + 20); cursor += 20;\n const postIntegratorFee = readBigEndian(post, cursor, 2); cursor += 2;\n const postIntegratorShare = readBigEndian(post, cursor, 1); cursor += 1;\n const postResolverFee = readBigEndian(post, cursor, 2); cursor += 2;\n const postDiscount = readBigEndian(post, cursor, 1); cursor += 1;\n const allowedTime = readBigEndian(post, cursor, 4); cursor += 4;\n const whitelistCount = bigintToNumber(readBigEndian(post, cursor, 1)); cursor += 1;\n if (whitelistCount !== 1 || cursor + whitelistCount * 12 + 160 !== post.length) {\n throw new Error(\"omniston: malformed EVM post-interaction whitelist\");\n }\n const postResolver = readBigEndian(post, cursor, 10); cursor += 10;\n const resolverTimeDelta = readBigEndian(post, cursor, 2); cursor += 2;\n if (\n !zeroBytes(integratorRecipient) || !(zeroBytes(protocolRecipient) || (evmDest && EVM_DEST_PROTOCOL_FEE_RECIPIENTS.has(`0x${bytesToHex(protocolRecipient)}`))) ||\n postIntegratorFee !== 0n || postIntegratorShare !== 100n || postResolverFee !== quoteResolverFee ||\n postDiscount !== 50n || !within(allowedTime, expected.quoteTimestamp, 60, 5) ||\n postResolver !== resolverLow80 || resolverTimeDelta !== 0n\n ) {\n throw new Error(\"omniston: EVM post-interaction terms do not match the pinned v1beta8 profile\");\n }\n const extra = Array.from({length: 5}, () => {\n const value = readBigEndian(post, cursor, 32);\n cursor += 32;\n return value;\n });\n const hashlock = readBigEndian(expected.secretHash, 0, expected.secretHash.length);\n // ExtraDataArgs word 2 is the destination token: the real ERC-20 for an EVM\n // destination, the order's takerAsset placeholder for TON.\n const dstToken = evmDest ? BigInt(getAddress(expected.outputTokenAddress)) : BigInt(getAddress(expected.takerAsset));\n const deposits = (BigInt(expected.srcSecurityDepositUnits) << 128n) | BigInt(expected.dstSecurityDepositUnits);\n const timelocks = [1n, 120n, 240n, 300n, 1n, 120n, 180n, 0n]\n .reduce((packed, value, index) => packed | (value << BigInt(index * 32)), 0n);\n if (\n expected.secretHash.length !== 32 || extra[0] !== hashlock || extra[1] !== (evmDest ? BigInt(expected.dstChainId!) : 0n) ||\n extra[2] !== dstToken || extra[3] !== deposits || extra[4] !== timelocks\n ) {\n throw new Error(\"omniston: signed EVM HTLC terms do not match the validated order details\");\n }\n\n const customData = extension.slice(32 + begin);\n if (customData.length !== 131) throw new Error(\"omniston: malformed EVM order extension custom data\");\n if (evmDest) {\n // The TON jetton/recipient slots are empty for an EVM destination (live\n // 2026-10-20). The EVM recipient is NOT in anything the wallet signs: it\n // travels in the unsigned order details only, so the destination escrow's\n // maker is what the disclosure gate (validateEvmOutputPosition) must prove.\n if (!zeroBytes(customData.slice(0, 66))) throw new Error(\"omniston: unexpected TON addresses in an EVM-destination order\");\n } else {\n const {Address} = await import(\"@ton/core\");\n const expectedTon = [expected.outputTokenAddress, expected.traderDstAddress].map((value) => Address.parse(value));\n for (let index = 0; index < expectedTon.length; index++) {\n const offset = index * 33;\n const workchain = customData[offset] === 255 ? -1 : customData[offset]!;\n if (workchain !== expectedTon[index]!.workChain || !sliceEqual(customData.slice(offset + 1, offset + 33), expectedTon[index]!.hash)) {\n throw new Error(\"omniston: signed EVM→TON address does not match the validated request\");\n }\n }\n }\n if (!zeroBytes(customData.slice(66, 99))) {\n throw new Error(\"omniston: unexpected private TON disclosure address\");\n }\n const quoteId = expected.quoteId.replace(/^0x/, \"\");\n if (!QUOTE_ID.test(quoteId) || !sliceEqual(customData.slice(99), hexToBytes(quoteId.padStart(64, \"0\")))) {\n throw new Error(\"omniston: EVM order extension custom data is not bound to the quote id\");\n }\n if (expected.tradeStartDeadline < expected.quoteTimestamp) {\n throw new Error(\"omniston: invalid EVM order quote deadline\");\n }\n}\n\nfunction validateEvmTypedOrder(\n td: unknown,\n expected: {\n chainId: number;\n settlementContract: string;\n owner: string;\n receiver: string;\n makerAsset: string;\n makingAmount: string;\n takingAmount: string;\n orderExtension: Uint8Array;\n quoteTimestamp: number;\n tradeStartDeadline: number;\n },\n): asserts td is {\n domain: {verifyingContract: string; chainId: string | number};\n types: Record<string, {name: string; type: string}[]>;\n primaryType: string;\n message: Record<string, unknown>;\n} {\n const value = td as {\n domain?: {name?: unknown; version?: unknown; verifyingContract?: unknown; chainId?: unknown};\n types?: Record<string, {name?: unknown; type?: unknown}[]>;\n primaryType?: unknown;\n message?: Record<string, unknown>;\n };\n const order = value.types?.Order;\n const exactSchema = Array.isArray(order) && order.length === ORDER_FIELDS.length &&\n order.every((field, i) => field.name === ORDER_FIELDS[i]![0] && field.type === ORDER_FIELDS[i]![1]);\n const message = value.message;\n const salt = message?.salt;\n const traits = validUint256(message?.makerTraits) ? BigInt(message!.makerTraits as string) : -1n;\n const flagMask = ((1n << 56n) - 1n) << 200n;\n // POST_INTERACTION + HAS_EXTENSION are mandatory and ALLOW_MULTIPLE_FILLS\n // must be clear, so the order fills at most once; no permit2/unwrap/epoch/\n // pre-interaction programs. Live v1beta8 orders leave NO_PARTIAL_FILLS clear\n // (one partial fill is possible). Disclosure still requires the finalized\n // fill to lock the FULL input, so a partial fill is never completed — it\n // rolls back on its own timelocks.\n const baseFlags = (1n << 251n) | (1n << 249n);\n const flags = traits < 0n ? -1n : traits & flagMask;\n const flagsOk = flags === baseFlags || flags === (baseFlags | (1n << 255n));\n const allowedSender = traits & ((1n << 80n) - 1n);\n const expiration = (traits >> 80n) & ((1n << 40n) - 1n);\n const series = (traits >> 160n) & ((1n << 40n) - 1n);\n const extensionHash = BigInt(keccak256(expected.orderExtension));\n const exactMessage = !!message && Object.keys(message).length === ORDER_FIELDS.length &&\n ORDER_FIELDS.every(([name]) => Object.hasOwn(message, name));\n if (\n value.domain?.name !== \"1inch Limit Order Protocol\" || value.domain.version !== \"4\" ||\n typeof value.domain.verifyingContract !== \"string\" ||\n getAddress(value.domain.verifyingContract) !== getAddress(expected.settlementContract) ||\n Number(value.domain.chainId) !== expected.chainId || value.primaryType !== \"Order\" || !exactSchema || !message || !exactMessage ||\n getAddress(String(message.maker)) !== getAddress(expected.owner) ||\n getAddress(String(message.receiver)) !== getAddress(expected.receiver) ||\n getAddress(String(message.makerAsset)) !== getAddress(expected.makerAsset) ||\n !validUint256(salt) || (BigInt(salt as string) & ((1n << 160n) - 1n)) !== (extensionHash & ((1n << 160n) - 1n)) ||\n // The order expires at the quote's trade-start deadline (±15 s of clock\n // skew between the quote and the order builder), never later.\n traits < 0n || !flagsOk || allowedSender !== 0n || series !== 0n ||\n !within(expiration, expected.tradeStartDeadline, 15, 15) || expiration <= BigInt(expected.quoteTimestamp) ||\n !validEvmAddress(message.takerAsset) || getAddress(String(message.takerAsset)) === getAddress(expected.makerAsset) ||\n !validUint256(message.makingAmount) || BigInt(message.makingAmount as string) !== BigInt(expected.makingAmount) ||\n !validUint256(message.takingAmount) || BigInt(message.takingAmount as string) !== BigInt(expected.takingAmount)\n ) {\n throw new Error(\"omniston: EVM order fields do not match the validated quote/request\");\n }\n}\n\nasync function validateTonEscrowPayload(\n message: EscrowMessage,\n expected: {\n quoteId: string;\n inputUnits: string;\n resolverSendsUnits: string;\n srcHtlcSecurityDepositUnits: string;\n protocolAddress: string;\n ownerAddress: string;\n destinationChain: string;\n destinationAddress: string;\n outputTokenAddress: string;\n initialResolverAddress: string;\n hashes: Uint8Array[];\n hashingFunction?: string;\n exclusivityTimeout: number;\n },\n validateForwardPayload: NonNullable<OmnistonProviderOptions[\"validateTonEscrowPayload\"]>,\n): Promise<void> {\n const {Address, Cell} = await import(\"@ton/core\");\n const boc = hexToBytes(message.payload);\n let roots: InstanceType<typeof Cell>[];\n try {\n roots = Cell.fromBoc(Buffer.from(boc));\n } catch {\n throw new Error(\"omniston: malformed TON escrow BoC\");\n }\n if (roots.length !== 1) throw new Error(\"omniston: TON escrow must contain exactly one root cell\");\n const slice = roots[0]!.beginParse();\n const op = slice.loadUint(32);\n slice.loadUintBig(64); // query id is resolver-chosen and not security-critical\n const amount = slice.loadCoins();\n const destination = slice.loadAddressAny();\n const response = slice.loadAddressAny();\n const customPayload = slice.loadMaybeRef();\n const forwardAmount = slice.loadCoins();\n const payloadByRef = slice.loadBit();\n if (\n op !== 0x0f8a7ea5 || amount !== BigInt(expected.inputUnits) || !(destination instanceof Address) ||\n !destination.equals(Address.parse(expected.protocolAddress)) ||\n (response !== null && (!(response instanceof Address) || !response.equals(Address.parse(expected.ownerAddress)))) || customPayload !== null ||\n forwardAmount <= 0n || forwardAmount > BigInt(message.sendAmount) || !payloadByRef ||\n slice.remainingBits !== 0 || slice.remainingRefs !== 1\n ) {\n throw new Error(\"omniston: TON jetton transfer does not match the validated quote/request\");\n }\n const forwardPayload = slice.loadRef();\n const verified = await validateForwardPayload({\n payloadBocHex: message.payload,\n forwardPayloadBocHex: Buffer.from(forwardPayload.toBoc()).toString(\"hex\"),\n quoteId: expected.quoteId,\n inputUnits: expected.inputUnits,\n resolverSendsUnits: expected.resolverSendsUnits,\n srcHtlcSecurityDepositUnits: expected.srcHtlcSecurityDepositUnits,\n protocolAddress: expected.protocolAddress,\n ownerAddress: expected.ownerAddress,\n destinationChain: expected.destinationChain,\n destinationAddress: expected.destinationAddress,\n outputTokenAddress: expected.outputTokenAddress,\n initialResolverAddress: expected.initialResolverAddress,\n secretHashes: expected.hashes.map((hash) => hash.slice()),\n ...(expected.hashingFunction ? {hashingFunction: expected.hashingFunction} : {}),\n exclusivityTimeout: expected.exclusivityTimeout,\n });\n if (!verified) throw new Error(\"omniston: TON escrow forward payload failed independent semantic validation\");\n}\n\n/** Fee token id: the catalog's 1Click asset id, or the on-chain contract for\n * assets 1Click does not list (BNB/Polygon USDC) — an empty id fails validQuote. */\nfunction feeToken(asset: CcAsset): string {\n return asset.assetId || asset.contract || asset.symbol;\n}\n\nfunction chainCase(asset: AssetId): string {\n return asset.chain.$case;\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;\n return diff === 0;\n}\n\n/** Minimal, bounded protobuf reader for the exact v1beta8 HTLC-details schema.\n * The SDK deliberately exposes these bytes as opaque, so independently decode\n * the security-critical fields before asking the wallet to sign their hash. */\nclass ProtoReader {\n private pos = 0;\n constructor(private readonly bytes: Uint8Array) {}\n get done(): boolean { return this.pos === this.bytes.length; }\n varint(): number {\n let out = 0;\n let shift = 0;\n while (this.pos < this.bytes.length && shift <= 49) {\n const byte = this.bytes[this.pos++]!;\n out += (byte & 0x7f) * 2 ** shift;\n if ((byte & 0x80) === 0) {\n if (!Number.isSafeInteger(out)) throw new Error(\"omniston: unsafe protobuf varint\");\n return out;\n }\n shift += 7;\n }\n throw new Error(\"omniston: malformed protobuf varint\");\n }\n field(): {number: number; wire: number} {\n const tag = this.varint();\n const number = Math.floor(tag / 8);\n const wire = tag & 7;\n if (number < 1) throw new Error(\"omniston: malformed protobuf field\");\n return {number, wire};\n }\n lengthDelimited(): Uint8Array {\n const length = this.varint();\n const end = this.pos + length;\n if (length < 0 || end > this.bytes.length) throw new Error(\"omniston: truncated protobuf payload\");\n const value = this.bytes.slice(this.pos, end);\n this.pos = end;\n return value;\n }\n skip(wire: number): void {\n if (wire === 0) { this.varint(); return; }\n if (wire === 1) { this.advance(8); return; }\n if (wire === 2) { this.lengthDelimited(); return; }\n if (wire === 5) { this.advance(4); return; }\n throw new Error(\"omniston: unsupported protobuf wire type\");\n }\n private advance(length: number): void {\n if (this.pos + length > this.bytes.length) throw new Error(\"omniston: truncated protobuf payload\");\n this.pos += length;\n }\n}\n\nconst utf8 = new TextDecoder(\"utf-8\", {fatal: true});\n// stonfi/common/v1/types/{chain_address,asset_id}.proto (omniston-sdk main, re-read 2026-10-20).\nconst PROTO_CASE_BY_FIELD: Record<number, string> = {\n 1: \"arbitrum\", 2: \"avalanche\", 3: \"base\", 4: \"bnb\", 5: \"ethereum\",\n 6: \"polygon\", 7: \"robinhood\", 8: \"xlayer\", 9: \"arc\", 10: \"monad\", 11: \"plasma\", 12: \"hyperevm\",\n 50: \"ton\", 60: \"tron\",\n};\n\nfunction decodeChainAddress(bytes: Uint8Array): ChainAddress {\n const reader = new ProtoReader(bytes);\n let address: ChainAddress | undefined;\n while (!reader.done) {\n const {number, wire} = reader.field();\n const $case = PROTO_CASE_BY_FIELD[number];\n if (!$case || wire !== 2 || address) throw new Error(\"omniston: malformed chain address in order details\");\n address = {chain: {$case, value: utf8.decode(reader.lengthDelimited())}};\n }\n if (!address?.chain.value) throw new Error(\"omniston: empty chain address in order details\");\n return address;\n}\n\nfunction decodeAssetId(bytes: Uint8Array): AssetId {\n const reader = new ProtoReader(bytes);\n let asset: AssetId | undefined;\n while (!reader.done) {\n const {number, wire} = reader.field();\n const $case = PROTO_CASE_BY_FIELD[number];\n if (!$case || wire !== 2 || asset) throw new Error(\"omniston: malformed asset id in order details\");\n const kindReader = new ProtoReader(reader.lengthDelimited());\n const kindField = kindReader.field();\n if (kindField.wire !== 2 || (kindField.number !== 1 && kindField.number !== 2)) {\n throw new Error(\"omniston: unsupported asset kind in order details\");\n }\n const kindCase = kindField.number === 1 ? \"native\" : ($case === \"ton\" ? \"jetton\" : $case === \"tron\" ? \"trc20\" : \"erc20\");\n const value = kindField.number === 1 ? {} : utf8.decode(kindReader.lengthDelimited());\n if (!kindReader.done || (kindField.number === 2 && !value)) throw new Error(\"omniston: malformed asset kind in order details\");\n asset = {chain: {$case, value: {kind: {$case: kindCase, value}}}};\n }\n if (!asset) throw new Error(\"omniston: empty asset id in order details\");\n return asset;\n}\n\nfunction validateSerializedOrderDetails(\n bytes: Uint8Array | undefined,\n expected: {quoteId: string; outputAsset: AssetId; traderDstAddress: ChainAddress; secretHashes: Uint8Array[]},\n): void {\n if (!bytes?.length) throw new Error(\"omniston: EVM HTLC order payload has no serialized details\");\n const wrapper = new ProtoReader(bytes);\n const outer = wrapper.field();\n if (outer.number !== 1 || outer.wire !== 2) throw new Error(\"omniston: unsupported HTLC order-details version\");\n const detailsBytes = wrapper.lengthDelimited();\n if (!wrapper.done) throw new Error(\"omniston: ambiguous HTLC order-details wrapper\");\n const reader = new ProtoReader(detailsBytes);\n let quoteId: string | undefined;\n let outputAsset: AssetId | undefined;\n let traderDstAddress: ChainAddress | undefined;\n const hashes: Uint8Array[] = [];\n while (!reader.done) {\n const {number, wire} = reader.field();\n if (wire !== 2) throw new Error(\"omniston: malformed HTLC order details\");\n const value = reader.lengthDelimited();\n if (number === 1 && quoteId === undefined) quoteId = utf8.decode(value);\n else if (number === 2 && outputAsset === undefined) outputAsset = decodeAssetId(value);\n else if (number === 3 && traderDstAddress === undefined) traderDstAddress = decodeChainAddress(value);\n else if (number === 5) hashes.push(value);\n else throw new Error(\"omniston: duplicate or unexpected HTLC order-details field\");\n }\n if (\n quoteId !== expected.quoteId ||\n !outputAsset || !sameAsset(outputAsset, expected.outputAsset) ||\n !traderDstAddress || !sameChainAddress(traderDstAddress, expected.traderDstAddress) ||\n hashes.length !== expected.secretHashes.length ||\n hashes.some((hash, i) => !bytesEqual(hash, expected.secretHashes[i]!))\n ) {\n throw new Error(\"omniston: resolver order payload does not match the validated quote/request\");\n }\n}\n\nfunction isPositiveInteger(value: string): boolean {\n try {\n return BigInt(value) > 0n;\n } catch {\n return false;\n }\n}\n\nfunction isNonNegativeInteger(value: string | undefined): boolean {\n if (value === undefined) return true;\n return /^[0-9]+$/.test(value);\n}\n\nfunction decimalToUnits(value: string, decimals: number): bigint | null {\n const match = value.match(/^(\\d+)(?:\\.(\\d+))?$/);\n if (!match || !Number.isInteger(decimals) || decimals < 0) return null;\n const fraction = match[2] ?? \"\";\n if (fraction.length > decimals) return null;\n const units = BigInt(match[1]!) * 10n ** BigInt(decimals) +\n BigInt((fraction + \"0\".repeat(decimals)).slice(0, decimals) || \"0\");\n return units > 0n ? units : null;\n}\n\nfunction validDisclosurePhase(phase: string | undefined): boolean {\n return phase === \"EXECUTION_PHASE_READY_FOR_PRIVATE_COMPLETION\" ||\n phase === \"EXECUTION_PHASE_READY_FOR_PUBLIC_COMPLETION\" ||\n phase === \"OUTPUT_LOCKED\"; // legacy client representation\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const clean = hex.replace(/^0x/, \"\");\n if (!clean || !/^(?:[0-9a-fA-F]{2})+$/.test(clean)) {\n throw new Error(\"omniston: malformed hex payload\");\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n return out;\n}\n\nfunction hexToBase64(hex: string): string {\n const bytes = hexToBytes(hex);\n let bin = \"\";\n bytes.forEach((b) => (bin += String.fromCharCode(b)));\n return btoa(bin);\n}\n\n// ── RFQ stream → single quote ────────────────────────────────────────────────\n\n/** Let resolvers compete for QUOTE_SETTLE_MS, then take the latest valid quote.\n * `noQuote` invalidates all previous updates because v1beta8 uses it to signal\n * that the previous quote expired. */\n/** The order-settlement fields every cross-chain quote must bind. */\nfunction validOrderSettlement(q: OmnistonQuote): boolean {\n if (q.settlementData?.$case !== \"order\") return false;\n const v = q.settlementData.value;\n return !!v.srcProtocolContractAddress &&\n v.srcProtocolContractAddress.chain.$case === chainCase(q.inputAsset) &&\n !!v.srcInitialResolverAddress &&\n v.srcInitialResolverAddress.chain.$case === chainCase(q.inputAsset) &&\n !!v.dstProtocolContractAddress &&\n v.dstProtocolContractAddress.chain.$case === chainCase(q.outputAsset) &&\n isPositiveInteger(v.srcHtlcSecurityDepositUnits ?? \"\") &&\n isPositiveInteger(v.dstSecurityDepositUnits ?? \"\") &&\n (v.htlcHashingFunction === \"HASHING_FUNCTION_KECCAK256\" || v.htlcHashingFunction === \"HASHING_FUNCTION_SHA256\") &&\n Number.isSafeInteger(v.exclusivityTimeout) && v.exclusivityTimeout! > 0 &&\n isPositiveInteger(v.resolverSendsUnits) &&\n BigInt(v.resolverSendsUnits) === BigInt(q.outputUnits) + BigInt(q.protocolFeeUnits || \"0\") + BigInt(q.integratorFeeUnits || \"0\");\n}\n\n/** The swap-settlement fields a same-chain quote must carry: at least one\n * route of named-protocol chunks, and a minimum output within the quote. */\nfunction validSwapSettlement(q: OmnistonQuote): boolean {\n if (q.settlementData?.$case !== \"swap\") return false;\n const v = q.settlementData.value;\n return Array.isArray(v.routes) && v.routes.length > 0 &&\n v.routes.every((route) => Array.isArray(route?.steps) && route.steps.length > 0 &&\n route.steps.every((step) => Array.isArray(step?.chunks) && step.chunks.length > 0 &&\n step.chunks.every((chunk) => typeof chunk?.protocol === \"string\" && chunk.protocol.length > 0 &&\n isPositiveInteger(chunk.inputUnits) && isPositiveInteger(chunk.outputUnits)))) &&\n isPositiveInteger(v.minOutputAmount) && BigInt(v.minOutputAmount) <= BigInt(q.outputUnits) &&\n (v.recommendedMinOutputAmount === undefined ||\n (isPositiveInteger(v.recommendedMinOutputAmount) && BigInt(v.recommendedMinOutputAmount) <= BigInt(q.outputUnits))) &&\n (q.gasBudget === undefined || isPositiveInteger(q.gasBudget));\n}\n\n/** Every DEX protocol name the quote's routes touch, deduplicated. */\nfunction swapProtocols(v: SwapSettlement): string[] {\n const names = new Set<string>();\n for (const route of v.routes) for (const step of route.steps) for (const chunk of step.chunks) names.add(chunk.protocol);\n return [...names];\n}\n\n/** Why an RFQ produced no usable quote — the caller turns it into a refusal. */\ninterface RfqOutcome {\n /** Number of `quoteUpdated` events seen for this RFQ. */\n updates: number;\n /** The first check the latest rejected update failed, if any. */\n rejected?: string;\n /** The stream errored (socket/SDK) before a usable quote arrived. */\n error?: string;\n}\n\n/** The first failing check of a `quoteUpdated` event, or null when it is usable. */\nfunction quoteRejection(\n q: OmnistonQuote | undefined,\n update: {rfqId?: string},\n acknowledgedRfqId: string | null,\n request: QuoteRequest,\n settlement: \"order\" | \"swap\",\n): string | null {\n if (!q) return \"empty quote\";\n if (!acknowledgedRfqId || update.rfqId !== acknowledgedRfqId || q.rfqId !== acknowledgedRfqId) return \"quote for another RFQ\";\n if (!sameAsset(q.inputAsset, request.inputAsset) || !sameAsset(q.outputAsset, request.outputAsset)) return \"quote assets differ from the request\";\n const requestedAmount = request.amount.$case === \"inputUnits\" ? request.amount.value : \"\";\n if (q.inputUnits !== requestedAmount) return \"quote input differs from the request\";\n if (!QUOTE_ID.test(q.quoteId)) return \"malformed quote id\";\n if (!isPositiveInteger(q.inputUnits) || !isPositiveInteger(q.outputUnits)) return \"non-positive quote amounts\";\n if (!isNonNegativeInteger(q.protocolFeeUnits) || !isNonNegativeInteger(q.integratorFeeUnits) ||\n BigInt(q.protocolFeeUnits || \"0\") + BigInt(q.integratorFeeUnits || \"0\") > BigInt(q.outputUnits)) return \"malformed quote fees\";\n if (!Number.isInteger(q.quoteTimestamp) || Math.abs(Math.floor(Date.now() / 1000) - q.quoteTimestamp) > 120) return \"quote timestamp out of range\";\n if (settlement === \"order\" ? !validOrderSettlement(q) : !validSwapSettlement(q)) return `incomplete ${settlement} settlement data`;\n if (!sameChainAddress(q.integratorAddress, request.integratorAddress)) return \"quote integrator differs from the request\";\n return null;\n}\n\nfunction awaitQuote(\n stream: ObservableLike<RfqEvent>,\n request: QuoteRequest,\n signal?: AbortSignal,\n settleMs = QUOTE_SETTLE_MS,\n settlement: \"order\" | \"swap\" = \"order\",\n outcome: RfqOutcome = {updates: 0},\n): Promise<OmnistonQuote | null> {\n return new Promise((resolve) => {\n let latest: OmnistonQuote | null = null;\n let done = false;\n let sub: {unsubscribe(): void} | null = null;\n let acknowledgedRfqId: string | null = null;\n const onAbort = () => finish(null);\n const finish = (value: OmnistonQuote | null) => {\n if (done) return;\n done = true;\n clearTimeout(settle);\n clearTimeout(max);\n signal?.removeEventListener(\"abort\", onAbort);\n try {\n sub?.unsubscribe();\n } catch {\n /* socket already gone */\n }\n resolve(value);\n };\n const settle = setTimeout(() => {\n if (latest) finish(latest);\n }, settleMs);\n const max = setTimeout(() => finish(latest), QUOTE_MAX_MS);\n sub = stream.subscribe({\n next: (event) => {\n if (event.$case === \"ack\") {\n acknowledgedRfqId = (event as {$case: \"ack\"; value: {rfqId: string}}).value.rfqId || null;\n } else if (event.$case === \"quoteUpdated\") {\n const update = event as {rfqId?: string; value: OmnistonQuote};\n outcome.updates += 1;\n const rejection = quoteRejection(update.value, update, acknowledgedRfqId, request, settlement);\n if (rejection) {\n outcome.rejected = rejection;\n latest = null;\n return;\n }\n latest = update.value;\n } else if (event.$case === \"noQuote\") {\n // v1beta8 streams resolver state: null invalidates the previous\n // update, but another resolver may still publish a later quote.\n // Keep the RFQ alive until the normal settle/max window.\n const noQuote = event as {$case: \"noQuote\"; rfqId?: string};\n if (acknowledgedRfqId && noQuote.rfqId === acknowledgedRfqId) latest = null;\n }\n },\n error: (err) => {\n outcome.error = String((err as {message?: unknown})?.message ?? err).slice(0, 200);\n finish(null);\n },\n complete: () => finish(latest),\n });\n signal?.addEventListener(\"abort\", onAbort, {once: true});\n if (done) sub.unsubscribe(); // finished synchronously before sub was set\n });\n}\n\n/** Collect the latest swap-progress event for the snapshot window. */\nfunction awaitSwapProgress(stream: ObservableLike<SwapTrackEvent>): Promise<{status: string; outgoingTxHash?: string} | null | \"awaiting\"> {\n return new Promise((resolve) => {\n let done = false;\n let latest: {status: string; outgoingTxHash?: string} | null | \"awaiting\" = null;\n let sub: {unsubscribe(): void} | null = null;\n const finish = (value: typeof latest) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n try {\n sub?.unsubscribe();\n } catch {\n /* socket already gone */\n }\n resolve(value);\n };\n const timer = setTimeout(() => finish(latest), TRACK_SNAPSHOT_MS);\n sub = stream.subscribe({\n next: (event) => {\n if (event.$case === \"progress\") {\n latest = (event as {value: {status: string; outgoingTxHash?: string}}).value;\n if ([\"TRADE_STATUS_FULLY_FILLED\", \"TRADE_STATUS_PARTIALLY_FILLED\", \"TRADE_STATUS_CANCELLED\", \"TRADE_STATUS_FAILED\"].includes(latest.status)) finish(latest);\n } else if (event.$case === \"awaitingTransfer\" && latest === null) {\n latest = \"awaiting\";\n }\n },\n error: () => finish(null),\n complete: () => finish(latest),\n });\n if (done) sub.unsubscribe();\n });\n}\n\nconst JETTON_TRANSFER_OP = 0x0f8a7ea5;\n\n/** A built TON swap message body: either a jetton transfer (jetton input,\n * forwarding to the DEX) or a DEX-native call (native GRAM input). */\nfunction parseSwapPayload(payloadHex: string): {\n op: number;\n jettonTransfer: null | {amount: bigint; destination: string; responseDestination: string | null; forwardTon: bigint};\n} {\n if (!/^(?:[0-9a-fA-F]{2})+$/.test(payloadHex)) throw new Error(\"omniston: malformed swap payload hex\");\n const roots = TonCell.fromBoc(Buffer.from(payloadHex, \"hex\"));\n if (roots.length !== 1) throw new Error(\"omniston: swap payload must have one root\");\n const s = roots[0]!.beginParse();\n const op = s.loadUint(32);\n if (op !== JETTON_TRANSFER_OP) return {op, jettonTransfer: null};\n s.loadUintBig(64); // query id — wallet/resolver-selected\n const amount = s.loadCoins();\n const destination = s.loadAddress();\n const responseDestination = s.loadMaybeAddress();\n s.loadMaybeRef(); // custom payload\n const forwardTon = s.loadCoins();\n return {\n op,\n jettonTransfer: {\n amount,\n destination: destination.toString(),\n responseDestination: responseDestination ? responseDestination.toString() : null,\n forwardTon,\n },\n };\n}\n\nfunction sameTonAddress(a: string, b: string): boolean {\n try {\n return TonAddress.parse(a).equals(TonAddress.parse(b));\n } catch {\n return false;\n }\n}\n\n/** Collect the latest order event for the snapshot window. */\nfunction awaitOrder(stream: ObservableLike<OrderEvent>): Promise<OrderSnapshot | null> {\n return new Promise((resolve) => {\n let done = false;\n let latest: OrderSnapshot | null = null;\n let sub: {unsubscribe(): void} | null = null;\n const finish = (value: OrderSnapshot | null) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n try {\n sub?.unsubscribe();\n } catch {\n /* socket already gone */\n }\n resolve(value);\n };\n const timer = setTimeout(() => finish(latest), TRACK_SNAPSHOT_MS);\n sub = stream.subscribe({\n next: (event) => {\n if (event.$case === \"order\") {\n latest = (event as {value: OrderSnapshot}).value;\n if ([\"TRADE_STATUS_FULLY_FILLED\", \"TRADE_STATUS_CANCELLED\", \"TRADE_STATUS_FAILED\"].includes(latest.status)) finish(latest);\n }\n },\n error: () => finish(null),\n complete: () => finish(latest),\n });\n if (done) sub.unsubscribe();\n });\n}\n\nfunction mapOrderStatus(order: OrderSnapshot): IntentStatus {\n const depositReceived = order.executions.length > 0;\n switch (order.status) {\n case \"TRADE_STATUS_FULLY_FILLED\":\n return {state: \"completed\", depositReceived: true};\n case \"TRADE_STATUS_PARTIALLY_FILLED\":\n // NOT terminal: tranches still need their secrets disclosed — keep the\n // store and keep polling (audit H2). Only FULLY_FILLED clears it.\n return {state: \"pending\", depositReceived: true};\n case \"TRADE_STATUS_CANCELLED\":\n case \"TRADE_STATUS_FAILED\":\n // Resolver-controlled tracking is not proof that the signed source order\n // can no longer fill. Keep polling until completion or the caller's\n // independent HTLC/expiry refund backstop closes the intent.\n return {state: \"pending\", depositReceived};\n default:\n return {state: \"pending\", depositReceived};\n }\n}\n\n// ── Provider ─────────────────────────────────────────────────────────────────\n\nexport function omnistonProvider(opts: OmnistonProviderOptions = {}): CrossChainProvider {\n opts = Object.freeze({...opts});\n const apiUrl = opts.apiUrl ?? \"wss://omni-ws.ston.fi\";\n const parsedApiUrl = new URL(apiUrl);\n if (parsedApiUrl.protocol !== \"wss:\" && parsedApiUrl.protocol !== \"ws:\") {\n throw new Error(\"omniston: apiUrl must use ws or wss\");\n }\n const maxUsdText = String(opts.maxUsd ?? 1000);\n if (!/^(?:0|[1-9]\\d*)(?:\\.\\d+)?$/.test(maxUsdText) || Number(maxUsdText) <= 0 || !Number.isFinite(Number(maxUsdText))) {\n throw new Error(\"omniston: maxUsd must be a positive plain decimal\");\n }\n const hasIntegrator = opts.integratorAddress !== undefined;\n const hasIntegratorPips = opts.integratorFeePips !== undefined;\n if (hasIntegrator !== hasIntegratorPips) throw new Error(\"omniston: integratorAddress and integratorFeePips must be configured together\");\n if (hasIntegrator && (!opts.integratorAddress!.trim() || !Number.isInteger(opts.integratorFeePips) || opts.integratorFeePips! < 0 || opts.integratorFeePips! > 1_000_000)) {\n throw new Error(\"omniston: integrator fee config is invalid\");\n }\n const trustedContracts = new Map<string, Set<string>>();\n for (const [chain, addresses] of Object.entries(opts.trustedSettlementContracts ?? {})) {\n const normalized = new Set<string>();\n for (const address of addresses) {\n try {\n normalized.add(isTon(chain) ? address : getAddress(address).toLowerCase());\n } catch {\n throw new Error(`omniston: invalid trusted settlement contract for ${chain}`);\n }\n }\n if (normalized.size) trustedContracts.set(chain, normalized);\n }\n const isTrusted = (chain: string, address: string): boolean => {\n try {\n return trustedContracts.get(chain)?.has(isTon(chain) ? address : getAddress(address).toLowerCase()) ?? false;\n } catch {\n return false;\n }\n };\n const trustedOrderProtocols = new Map<string, Set<string>>();\n for (const [chain, addresses] of Object.entries(opts.trustedEvmOrderProtocols ?? {})) {\n const normalized = new Set<string>();\n for (const address of addresses) {\n try {\n if (evmRef(chain) === null) throw new Error(\"not an EVM chain\");\n normalized.add(getAddress(address).toLowerCase());\n } catch {\n throw new Error(`omniston: invalid trusted EVM order protocol for ${chain}`);\n }\n }\n if (normalized.size) trustedOrderProtocols.set(chain, normalized);\n }\n const isTrustedOrderProtocol = (chain: string, address: string): boolean => {\n try {\n return trustedOrderProtocols.get(chain)?.has(getAddress(address).toLowerCase()) ?? false;\n } catch {\n return false;\n }\n };\n const store = opts.secretStore ?? inMemorySecretStore();\n const requestedMaxExecutions = opts.maxHtlcExecutions ?? DEFAULT_MAX_HTLC_EXECUTIONS;\n if (!Number.isFinite(requestedMaxExecutions) || !Number.isInteger(requestedMaxExecutions) || requestedMaxExecutions < 1) {\n throw new Error(\"omniston: maxHtlcExecutions must be a positive integer\");\n }\n const maxExecutions = Math.min(16, requestedMaxExecutions);\n const maxTonExecutionNano = opts.maxTonExecutionNano ?? \"2000000000\";\n if (!isPositiveInteger(maxTonExecutionNano)) {\n throw new Error(\"omniston: maxTonExecutionNano must be a positive integer\");\n }\n const quoteSettleMs = opts.quoteSettleMs ?? QUOTE_SETTLE_MS;\n if (!Number.isInteger(quoteSettleMs) || quoteSettleMs < 0 || quoteSettleMs >= QUOTE_MAX_MS) {\n throw new Error(`omniston: quoteSettleMs must be an integer in [0, ${QUOTE_MAX_MS})`);\n }\n const injectedClient = opts.client ?? null;\n let client: OmnistonClientLike | null = injectedClient;\n let clientPromise: Promise<OmnistonClientLike> | null = null;\n let clientGeneration = 0;\n /** Lazy: never open the WebSocket unless a quote is actually requested. */\n async function getClient(): Promise<OmnistonClientLike> {\n if (client) return client;\n if (clientPromise) return clientPromise;\n const generation = clientGeneration;\n clientPromise = (async () => {\n const sdk = await import(\"@ston-fi/omniston-sdk\");\n // omniston-sdk 0.8.9's Node WebSocketTransport listens for open/message/\n // close but not the EventEmitter `error` event. A refused connection can\n // therefore terminate the whole process before AutoReconnectTransport\n // sees the following close. Attach a no-op error listener to each socket;\n // close remains the authoritative status/retry signal.\n const webSocketTransport = new sdk.WebSocketTransport(apiUrl);\n const connect = webSocketTransport.connect.bind(webSocketTransport);\n webSocketTransport.connect = () => {\n const pending = connect();\n const socket = (webSocketTransport as unknown as {webSocket?: {addEventListener(type: string, listener: () => void): void}}).webSocket;\n socket?.addEventListener(\"error\", () => {});\n return pending;\n };\n webSocketTransport.reconnect = () => webSocketTransport.connect();\n // SDK race (0.8.11): a socket read can carry a Quote response AND its\n // subscription's `ack` notification; both are dispatched synchronously,\n // before the SDK registers the stream consumer, so the ack is dropped\n // and the next update errors with \"quoteUpdated before ack\" (live\n // 2026-10-12: 1–3 of 4 parallel RFQs, occasionally a single one).\n // Deliver each frame in its own macrotask so registration runs between.\n const messages = (webSocketTransport as unknown as {messagesSubject?: {next(m: string): void}}).messagesSubject;\n if (messages) {\n const deliver = messages.next.bind(messages);\n messages.next = (m: string) => { setTimeout(() => deliver(m), 0); };\n }\n const transport = new sdk.AutoReconnectTransport({transport: webSocketTransport});\n const created = new sdk.Omniston({apiUrl, transport}) as unknown as OmnistonClientLike;\n if (generation !== clientGeneration) {\n if (created.close) created.close(); else created.transport?.close();\n throw new Error(\"omniston: provider closed while client was being created\");\n }\n client = created;\n return created;\n })();\n try {\n return await clientPromise;\n } finally {\n clientPromise = null;\n }\n }\n\n /** buildDeposit/registerSignedOrder need the context getQuote produced —\n * persisted via quoteStore so serverless instances share it. */\n const quotes = opts.quoteStore ?? inMemoryQuoteStore();\n interface BuiltEntry {\n quote: OmnistonQuote;\n at: number;\n /** What the intentId was minted for (absent on entries written before scan F3/F15). */\n bound?: IntentBinding;\n /** EVM-source orders: what registration and tracking need after signing. */\n evmOrder?: {\n typedData: string;\n orderExtension: string;\n serializedOrderDetails: string;\n owner: string;\n chainCase: string;\n /** Escrow factory the signed extension targets (trusted for the source chain). */\n factory: string;\n };\n }\n async function saveBuilt(quoteId: string, entry: BuiltEntry): Promise<void> {\n await quotes.save(quoteId, JSON.stringify(entry));\n }\n async function loadBuilt(quoteId: string): Promise<BuiltEntry | undefined> {\n const raw = await quotes.load(quoteId);\n if (!raw) return undefined;\n try {\n const e = JSON.parse(raw) as BuiltEntry;\n if (!Number.isFinite(e.at) || Date.now() - e.at > CACHE_TTL_MS) {\n await quotes.clear(quoteId);\n return undefined;\n }\n return e;\n } catch {\n await quotes.clear(quoteId);\n return undefined;\n }\n }\n\n type Decoded = NonNullable<ReturnType<typeof decodeIntent>>;\n type BindResult =\n | {ok: true; ref: Decoded; legacy: boolean}\n | {ok: false; reason: \"mismatch\"; field: string}\n | {ok: false; reason: \"legacy-expired\"};\n /**\n * Resolve the caller's intentId against the context stored for its quote:\n * any field that differs from what getQuote bound is refused, and the\n * returned ref carries ONLY the stored values. Pre-binding (legacy) entries\n * fall back to the signed order's owner (EVM source) or the decoded values,\n * for at most LEGACY_INTENT_WINDOW_MS after they were written.\n */\n function bindIntent(decoded: Decoded, entry: BuiltEntry): BindResult {\n const owner = entry.evmOrder?.owner;\n const bound = entry.bound;\n if (bound) {\n if (bound.kind !== decoded.kind) return {ok: false, reason: \"mismatch\", field: \"kind\"};\n if (bound.srcChain !== decoded.srcChain) return {ok: false, reason: \"mismatch\", field: \"srcChain\"};\n if (!sameIntentAddress(bound.trader, decoded.trader)) return {ok: false, reason: \"mismatch\", field: \"trader\"};\n if (!sameIntentAddress(bound.dest, decoded.dest)) return {ok: false, reason: \"mismatch\", field: \"dest\"};\n if (owner !== undefined && !sameIntentAddress(owner, bound.trader)) return {ok: false, reason: \"mismatch\", field: \"owner\"};\n return {ok: true, legacy: false, ref: {quoteId: decoded.quoteId, trader: owner ?? bound.trader, dest: bound.dest, srcChain: bound.srcChain, kind: bound.kind}};\n }\n if (!Number.isFinite(entry.at) || Date.now() - entry.at > LEGACY_INTENT_WINDOW_MS) return {ok: false, reason: \"legacy-expired\"};\n if (owner !== undefined && !sameIntentAddress(owner, decoded.trader)) return {ok: false, reason: \"mismatch\", field: \"owner\"};\n return {ok: true, legacy: true, ref: {...decoded, trader: owner ?? decoded.trader}};\n }\n const traceFor = (quoteId: string) => (event: string, details?: Record<string, unknown>) => {\n try { opts.trace?.(event, {quoteId, ...details}); } catch { /* diagnostics never break the flow */ }\n };\n /** buildDeposit / registerSignedOrder: the bound ref, or a named refusal. */\n function requireBinding(decoded: Decoded, entry: BuiltEntry, where: string): Decoded {\n const trace = traceFor(decoded.quoteId);\n const bound = bindIntent(decoded, entry);\n if (!bound.ok) {\n if (bound.reason === \"legacy-expired\") {\n trace(\"legacy-intent-expired\", {where});\n throw new Error(\"omniston: quote expired — request a fresh quote\");\n }\n trace(\"intent-mismatch\", {where, field: bound.field});\n throw new Error(`omniston: intent id does not match the quote it was issued for (${bound.field})`);\n }\n if (bound.legacy) trace(\"legacy-intent\", {where});\n return bound.ref;\n }\n\n /**\n * HTLC secrets for a quote: a second build of the SAME order reuses the\n * stored secrets (same hashlock) instead of overwriting them, so a repeated\n * or concurrent build can never strand an order that was already signed.\n * `created` says whether THIS call wrote them (only then may it clear them).\n *\n * The quoteId is chosen by the platform, so it alone must never decide which\n * preimage an order locks to (scan 2026-10-23 F6): secrets are stored with a\n * hash of the order they were made for (trader, dest, chain, assets, units)\n * and reused only for that exact order, and a secret that was disclosed is\n * never handed to a new build.\n */\n const bindKey = (quoteId: string) => `${quoteId}#bind`;\n const disclosedKey = (quoteId: string) => `${quoteId}#disclosed`;\n function orderBinding(ref: Decoded, q: OmnistonQuote): string {\n return sha256(new TextEncoder().encode(JSON.stringify([\n ref.quoteId, ref.trader ?? null, ref.dest ?? null, ref.srcChain ?? null,\n q.inputUnits, q.outputUnits, JSON.stringify(q.inputAsset), JSON.stringify(q.outputAsset),\n ]))).slice(2);\n }\n async function clearSecrets(quoteId: string): Promise<void> {\n await store.clear(quoteId);\n await store.clear(bindKey(quoteId));\n await store.clear(disclosedKey(quoteId));\n }\n async function secretsFor(ref: Decoded, q: OmnistonQuote, count: number): Promise<{secrets: Uint8Array[]; created: boolean}> {\n const quoteId = ref.quoteId;\n const binding = orderBinding(ref, q);\n const existing = await store.load(quoteId);\n if (existing && existing.length > 0) {\n const [boundTo] = (await store.load(bindKey(quoteId))) ?? [];\n const disclosed = ((await store.load(disclosedKey(quoteId))) ?? []).length > 0;\n if (boundTo !== binding || disclosed) {\n traceFor(quoteId)(\"secret-reuse-refused\", {disclosed, bound: boundTo !== undefined});\n throw new Error(\"omniston: this quote id already belongs to another order — request a fresh quote\");\n }\n if (existing.length !== count || !existing.every((s) => /^[0-9a-fA-F]{64}$/.test(s))) {\n throw new Error(\"omniston: stored HTLC secrets for this quote do not fit the order — request a fresh quote\");\n }\n traceFor(quoteId)(\"secret-reused\", {count});\n return {secrets: existing.map(hexToBytes), created: false};\n }\n const secrets = Array.from({length: count}, generateSecret);\n // Persist BEFORE anything can be signed: if the process dies after the\n // lock, the poll path still has the preimage to disclose.\n await store.save(bindKey(quoteId), [binding]);\n await store.save(quoteId, secrets.map(bytesToHex));\n return {secrets, created: true};\n }\n\n /** A quote whose id already carries an order (secrets on file) is the platform reusing an id: refuse it. */\n async function quoteIdInUse(quoteId: string): Promise<boolean> {\n const existing = await store.load(quoteId);\n return !!existing && existing.length > 0;\n }\n\n // ── TON ↔ TON: swap settlement (immediate DEX routes, no escrow) ──────────\n const SWAP_SLIPPAGE_PIPS_DEFAULT = 5_000; // 0.5%\n /** Same-chain swaps need the jetton-wallet validator (jetton input goes\n * through the trader's own wallet) and a swap-target validator (the DEX\n * contract the funds land in is resolver-chosen per route). */\n const sameChainTonReady = (): boolean =>\n typeof opts.validateTonJettonWallet === \"function\" && typeof opts.validateTonSwapTarget === \"function\";\n /** TON→EVM: the TON factory and the EVM factory are allowlisted, and the\n * jetton-wallet, escrow-payload and EVM output-position validators exist. */\n const tonSourceReady = (from: string, to: string): boolean =>\n cfg.supports(from, to) && trustedContracts.has(from) && trustedContracts.has(to) &&\n typeof opts.validateTonJettonWallet === \"function\" &&\n typeof opts.validateTonEscrowPayload === \"function\" &&\n typeof opts.validateEvmOutputPosition === \"function\";\n /** EVM→TON: the order protocol the wallet signs against AND the factory the\n * signed extension targets are allowlisted for the source chain, the TON\n * factory for the destination, and both finalized-position validators exist. */\n const evmSourceReady = (from: string, to: string): boolean =>\n cfg.supports(from, to) && trustedOrderProtocols.has(from) && trustedContracts.has(from) && trustedContracts.has(to) &&\n typeof opts.validateEvmInputPosition === \"function\" &&\n typeof opts.validateTonOutputPosition === \"function\";\n /** EVM→EVM: the source order protocol and factory, the destination factory,\n * and both EVM position validators (source fill + destination escrow). */\n const evmToEvmReady = (from: string, to: string): boolean =>\n cfg.supports(from, to) && trustedOrderProtocols.has(from) && trustedContracts.has(from) && trustedContracts.has(to) &&\n typeof opts.validateEvmInputPosition === \"function\" &&\n typeof opts.validateEvmOutputPosition === \"function\";\n\n async function getSwapQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n if (!cfg.supports(params.sourceChain, params.destChain) || !trustedContracts.has(params.sourceChain) || !sameChainTonReady()) return null;\n const source = ccAsset(params.sourceChain, params.sourceToken);\n const dest = ccAssetByToken(params.destChain, params.destToken);\n if (!source || !dest || source.symbol === dest.symbol) return null;\n const inputAsset = toAssetId(params.sourceChain, source, true);\n const outputAsset = toAssetId(params.destChain, dest, true);\n if (!inputAsset || !outputAsset || sameAsset(inputAsset, outputAsset) || !isPositiveInteger(params.amountIn)) return null;\n const trader = params.refundAddress ?? \"\";\n if (!trader && !params.dry) return null;\n const slippagePips = params.slippageBps !== undefined ? Math.round(params.slippageBps * 100) : SWAP_SLIPPAGE_PIPS_DEFAULT;\n if (!Number.isInteger(slippagePips) || slippagePips < 0 || slippagePips > 500_000) return null;\n\n const omni = await getClient();\n const settle = params.dry === false ? Math.min(quoteSettleMs, EXECUTION_SETTLE_MS) : quoteSettleMs;\n const outcome: RfqOutcome = {updates: 0};\n const rfq = async (pips: number): Promise<OmnistonQuote | null> => {\n const request: QuoteRequest = {\n inputAsset,\n outputAsset,\n amount: {$case: \"inputUnits\", value: params.amountIn},\n // One route → one outgoing message: a TON account sends exactly one.\n settlementParams: [{params: {$case: \"swap\", value: {maxPriceSlippagePips: pips, maxRoutes: 1}}}],\n };\n if (hasIntegrator) {\n const address = opts.integratorAddress ? toChainAddress(params.destChain, opts.integratorAddress) : null;\n if (!address) return null;\n request.integratorAddress = address;\n request.integratorFeePips = opts.integratorFeePips!;\n }\n // The SDK can still drop an ack (see getClient: frame delivery is now\n // deferred, which removed it in live runs) — give the socket a beat and\n // try once more.\n for (let attempt = 0; attempt < 2; attempt++) {\n if (attempt > 0) await new Promise((resolve) => setTimeout(resolve, 300));\n const quote = await awaitQuote(omni.requestForQuote(request), request, signal, settle, \"swap\", outcome);\n if (quote && quote.settlementData.$case === \"swap\") return quote;\n if (signal?.aborted) return null;\n }\n return null;\n };\n\n let q = await rfq(slippagePips);\n if (!q) {\n if (!signal?.aborted) {\n params.onRefusal?.(`omniston: ${outcome.error ? `RFQ failed: ${outcome.error}` : outcome.rejected ? `swap quote rejected: ${outcome.rejected}` : \"no TON DEX route quoted this pair/amount\"}`);\n }\n return null;\n }\n let swap = q.settlementData.$case === \"swap\" ? q.settlementData.value : null;\n if (!swap) return null;\n // Two floors the router holds a quote to, both of which a DEX quote can\n // miss by a rounding unit or a price tick: the absolute one the user saw\n // (`minAmountOut`, execution re-quotes) and the slippage one, computed by\n // the router as ceil(out × (1 − bps/10000)) where Omniston rounds its own\n // minimum down. The floor is what the trade must honour on-chain, so\n // re-quote (at most twice) with the slippage that puts the minimum on it —\n // the DEX then refunds below it.\n const absoluteFloor = params.minAmountOut !== undefined && isPositiveInteger(params.minAmountOut) ? BigInt(params.minAmountOut) : 0n;\n const requiredMin = (outputUnits: string): bigint => {\n const out = BigInt(outputUnits);\n const slippageFloor = params.slippageBps !== undefined\n ? (out * BigInt(10_000 - params.slippageBps) + 9_999n) / 10_000n\n : 0n;\n return absoluteFloor > slippageFloor ? absoluteFloor : slippageFloor;\n };\n for (let attempt = 0; attempt < 2 && BigInt(swap.minOutputAmount) < requiredMin(q.outputUnits); attempt++) {\n const out = BigInt(q.outputUnits);\n const floor = requiredMin(q.outputUnits);\n if (out < floor) return null;\n const tightened = bigintToNumber(((out - floor) * 1_000_000n) / out);\n const again = await rfq(Math.max(0, Math.min(tightened, slippagePips)));\n const againSwap = again?.settlementData.$case === \"swap\" ? again.settlementData.value : null;\n if (!again || !againSwap) return null;\n q = again;\n swap = againSwap;\n }\n if (BigInt(swap.minOutputAmount) < requiredMin(q.outputUnits)) return null;\n // The gas the route needs rides on the message; keep it under the same cap\n // that bounds escrow execution value.\n if (q.gasBudget !== undefined && BigInt(q.gasBudget) > BigInt(maxTonExecutionNano)) return null;\n // The on-chain minimum is the one at the REQUESTED slippage (the build\n // below asks for exactly that, never Omniston's \"recommended\" one, which\n // may be looser than what this quote promises).\n const minOut = swap.minOutputAmount;\n await saveBuilt(q.quoteId, {quote: q, at: Date.now(), bound: {trader, dest: params.destAddress, srcChain: params.sourceChain, kind: \"swap\"}});\n\n // Fees are charged in the OUTPUT asset; only a stable output approximates\n // USD. The TON gas budget is NOT a fee: it rides on the message and the\n // unused part returns, so it stays out of `fees` (the router's fee caps\n // would otherwise read 0.1 GRAM of gas on a 1 GRAM swap as a 10% fee).\n const feeUnits = Number(q.protocolFeeUnits || \"0\") + Number(q.integratorFeeUnits || \"0\");\n const stableOut = /^(USDT|USDC|USD₮|jUSDT)$/.test(dest.symbol);\n const feeUsd = stableOut ? feeUnits / 10 ** dest.decimals : 0;\n return {\n provider: \"omniston\",\n intentId: encodeIntent(q.quoteId, trader, params.destAddress, params.sourceChain, \"swap\"),\n depositAddress: \"\", // swap settlement — the built message pays the DEX directly\n depositMemo: null,\n sourceAmount: q.inputUnits,\n destAmount: q.outputUnits,\n minDestAmount: minOut,\n feeUsd: Number.isFinite(feeUsd) ? feeUsd : 0,\n fees: [\n ...(q.protocolFeeUnits && q.protocolFeeUnits !== \"0\" ? [{type: \"protocol\" as const, amount: q.protocolFeeUnits, token: feeToken(dest), included: true}] : []),\n ...(q.integratorFeeUnits && q.integratorFeeUnits !== \"0\" ? [{type: \"affiliate\" as const, amount: q.integratorFeeUnits, token: feeToken(dest), included: true}] : []),\n ],\n etaSeconds: 30,\n reliability: 0.9,\n validUntilMs: Date.now() + QUOTE_TTL_MS,\n // gasBudget = TON the message carries on top of the input; gasEstimate =\n // what the route is expected to burn. Consumers show both so the user\n // sees the 1.1 GRAM leaving for a 1 GRAM swap — and the refund.\n providerData: {\n settlement: \"swap\",\n protocols: swapProtocols(swap).join(\",\"),\n ...(q.gasBudget ? {gasBudget: q.gasBudget} : {}),\n ...(q.estimatedGasConsumption ? {gasEstimate: q.estimatedGasConsumption} : {}),\n },\n };\n }\n\n async function buildSwapDeposit(\n ref: {quoteId: string; trader: string; dest: string; srcChain: string},\n q: OmnistonQuote,\n swap: SwapSettlement,\n ): Promise<UnsignedTx> {\n if (!ref.trader) throw new Error(\"omniston: quote was requested without a refund/source address\");\n if (!isTon(ref.srcChain) || q.inputAsset.chain.$case !== \"ton\" || q.outputAsset.chain.$case !== \"ton\") {\n throw new Error(\"omniston: swap quote is not a TON same-chain swap\");\n }\n if (!sameChainTonReady()) throw new Error(\"omniston: TON same-chain swaps need independent jetton-wallet and swap-target validators\");\n const owner: ChainAddress = {chain: {$case: \"ton\", value: ref.trader}};\n const receiver: ChainAddress = {chain: {$case: \"ton\", value: ref.dest}};\n const omni = await getClient();\n if (typeof omni.tonBuildSwap !== \"function\") throw new Error(\"omniston: client does not support swap settlement (tonBuildSwap)\");\n const tx = await omni.tonBuildSwap({\n quoteId: ref.quoteId,\n transferSrcAddress: owner,\n refundSrcAddress: owner,\n gasExcessAddress: owner,\n traderDstAddress: receiver,\n // Build at the slippage the quote was requested with: its\n // minOutputAmount is the minimum this module reported to the router.\n useRecommendedSlippage: false,\n });\n const [message, ...rest] = tx.messages;\n if (!message || rest.length > 0) throw new Error(`omniston: expected exactly one swap message, got ${tx.messages.length}`);\n if (message.jettonWalletStateInit) throw new Error(\"omniston: deploying a resolver-provided jetton wallet is not supported\");\n if (!isPositiveInteger(message.sendAmount)) throw new Error(\"omniston: malformed swap message value\");\n const sendAmount = BigInt(message.sendAmount);\n const gasCap = BigInt(maxTonExecutionNano);\n const gasBudget = q.gasBudget && isPositiveInteger(q.gasBudget) ? BigInt(q.gasBudget) : gasCap;\n const protocols = swapProtocols(swap);\n const inputJetton = assetContract(q.inputAsset);\n const payload = parseSwapPayload(message.payload);\n\n const routeSteps = swap.routes.length === 1 ? swap.routes[0]!.steps : [];\n const singleV1 = routeSteps.length === 1 && routeSteps[0]!.chunks.length === 1 && routeSteps[0]!.chunks[0]!.protocol === \"StonFiV1\";\n // STON.fi v1 native input (pTON v1): the message is a jetton transfer to the\n // ROUTER's pTON v1 wallet naming the router as destination (STON.fi SDK v1\n // shape; seen live 2026-10-22 for GRAM→USDT from ~100 GRAM up). Native\n // input, so the message carries input + gas.\n const ptonV1Native = !inputJetton && !!payload.jettonTransfer && singleV1;\n\n if (inputJetton) {\n // Jetton input: a transfer from the trader's OWN jetton wallet whose\n // forward lands in the DEX. The TON attached is gas only.\n const transfer = payload.jettonTransfer;\n if (!transfer) throw new Error(\"omniston: jetton-input swap message is not a jetton transfer\");\n if (sendAmount > gasCap || sendAmount > gasBudget) throw new Error(`omniston: swap message attaches more TON than the quoted gas budget (${sendAmount} > ${gasBudget} nanoTON, cap ${gasCap}, ${protocols.join(\"+\")})`);\n if (transfer.amount !== BigInt(q.inputUnits)) throw new Error(\"omniston: swap message moves a different amount than quoted\");\n if (!transfer.responseDestination || !sameTonAddress(transfer.responseDestination, ref.trader)) {\n throw new Error(\"omniston: swap message returns excess to a wallet other than the trader\");\n }\n if (transfer.forwardTon >= sendAmount) throw new Error(\"omniston: swap message forwards more TON than it carries\");\n const walletValid = await opts.validateTonJettonWallet!({\n ownerAddress: ref.trader,\n jettonMasterAddress: inputJetton,\n walletAddress: message.targetAddress,\n });\n if (!walletValid) throw new Error(\"omniston: TON jetton wallet was not independently validated\");\n const targetValid = await opts.validateTonSwapTarget!({address: transfer.destination, protocols});\n if (!targetValid) throw new Error(\"omniston: swap destination is not a recognized DEX contract for the quoted protocol\");\n } else if (ptonV1Native) {\n const transfer = payload.jettonTransfer!;\n const input = BigInt(q.inputUnits);\n if (transfer.amount !== input) throw new Error(\"omniston: swap message moves a different amount than quoted\");\n if (sendAmount < input) throw new Error(\"omniston: swap message carries less than the quoted input\");\n const gas = sendAmount - input;\n if (gas > gasCap || gas > gasBudget) throw new Error(`omniston: swap message attaches more TON than the quoted gas budget (${gas} > ${gasBudget} nanoTON, cap ${gasCap}, ${protocols.join(\"+\")})`);\n // pTON v1 forwards exactly the gas share of the value to the router (live: 0.1 of 0.1 GRAM).\n if (transfer.forwardTon > gas) throw new Error(\"omniston: swap message forwards more TON than its gas\");\n if (!transfer.responseDestination || !sameTonAddress(transfer.responseDestination, ref.trader)) {\n throw new Error(\"omniston: swap message returns excess to a wallet other than the trader\");\n }\n if (typeof opts.validateTonSwapLeg !== \"function\") throw new Error(\"omniston: STON.fi v1 native input needs the validateTonSwapLeg validator (pTON v1 wallet ownership)\");\n // The pTON v1 wallet (a router-owned proxy-TON wallet) and the router it names.\n const targetValid = await opts.validateTonSwapTarget!({address: message.targetAddress, protocols});\n if (!targetValid) throw new Error(\"omniston: swap target is not a recognized DEX contract for the quoted protocol\");\n const routerValid = await opts.validateTonSwapTarget!({address: transfer.destination, protocols});\n if (!routerValid) throw new Error(\"omniston: swap destination is not a recognized DEX contract for the quoted protocol\");\n } else {\n // Native input: the message itself pays the DEX — value = input + gas.\n if (payload.jettonTransfer) {\n // Name what came back so the refusal can be triaged: which protocol route, where the message goes and what the jetton transfer targets.\n throw new Error(`omniston: native-input swap message must not be a jetton transfer (route ${protocols.join(\"+\") || \"?\"}, target ${message.targetAddress}, transfer ${payload.jettonTransfer.amount} to ${payload.jettonTransfer.destination}, forwardTon ${payload.jettonTransfer.forwardTon}, value ${sendAmount})`);\n }\n const input = BigInt(q.inputUnits);\n if (sendAmount < input) throw new Error(\"omniston: swap message carries less than the quoted input\");\n const gas = sendAmount - input;\n if (gas > gasCap || gas > gasBudget) throw new Error(`omniston: swap message attaches more TON than the quoted gas budget (${gas} > ${gasBudget} nanoTON, cap ${gasCap}, ${protocols.join(\"+\")})`);\n const targetValid = await opts.validateTonSwapTarget!({address: message.targetAddress, protocols});\n if (!targetValid) throw new Error(\"omniston: swap target is not a recognized DEX contract for the quoted protocol\");\n }\n\n // Scan F11: open the DEX call and bind receiver, refund/excess, minimum\n // output and the route's contracts to the quote. The pTON v1 path is new\n // and always enforced; elsewhere `tonSwapPayloadCheck` decides.\n const mode = ptonV1Native ? \"enforce\" : (opts.tonSwapPayloadCheck ?? \"enforce\");\n const trace = traceFor(ref.quoteId);\n const payloadRefusal = (reason: string, detail: string): void => {\n trace(\"ton-swap-payload\", {reason, detail, mode, protocols: protocols.join(\"+\")});\n if (mode === \"enforce\") throw new Error(`omniston: ton-swap-payload ${reason} — ${detail}`);\n };\n let checked: TonSwapCheckResult | null = null;\n try {\n checked = checkTonSwapPayload({\n payloadHex: message.payload,\n targetAddress: message.targetAddress,\n sendAmount,\n trader: ref.trader,\n dest: ref.dest,\n inputUnits: q.inputUnits,\n minOutputAmount: swap.minOutputAmount,\n inputJetton,\n outputJetton: assetContract(q.outputAsset),\n steps: swap.routes.length === 1\n ? routeSteps.map((step) => {\n if (step.chunks.length !== 1) return {protocol: `split(${step.chunks.map((c) => c.protocol).join(\"|\")})`, inputJetton: undefined, outputJetton: undefined};\n return {protocol: step.chunks[0]!.protocol, inputJetton: stepJetton(step.inputAsset), outputJetton: stepJetton(step.outputAsset)};\n })\n : [{protocol: `${swap.routes.length}-routes`, inputJetton: undefined, outputJetton: undefined}],\n integratorAddress: q.integratorAddress?.chain.$case === \"ton\" ? q.integratorAddress.chain.value : null,\n });\n } catch (error) {\n if (error instanceof TonSwapPayloadError) payloadRefusal(error.reason, error.message);\n else payloadRefusal(\"malformed\", error instanceof Error ? error.message : String(error));\n }\n if (checked) {\n if (typeof opts.validateTonSwapLeg !== \"function\") {\n trace(\"ton-swap-payload\", {reason: \"legs-unverified\", detail: \"no validateTonSwapLeg hook\", mode, legs: checked.legs.length});\n } else {\n for (const leg of checked.legs) {\n let ok = false;\n try { ok = await opts.validateTonSwapLeg(leg); } catch { ok = false; }\n if (!ok) {\n payloadRefusal(\"leg-unverified\", `${leg.kind} v${leg.version} ${leg.kind === \"dedust-pool\" ? `pool ${leg.pool}` : `ask wallet ${leg.askWallet}`}`);\n break;\n }\n }\n }\n }\n\n return {\n chain: ref.srcChain,\n to: message.targetAddress,\n value: message.sendAmount, // nanotons: gas only (jetton input) or input + gas (native)\n bodyBoc: hexToBase64(message.payload),\n };\n }\n\n async function trackSwap(decoded: {quoteId: string; trader: string}, sourceTxHash: string | null): Promise<IntentStatus> {\n // swapTrack needs a handle on the outgoing transaction; until the caller\n // knows it, the trade is simply pending.\n if (!sourceTxHash) return {state: \"pending\"};\n const omni = await getClient();\n if (typeof omni.swapTrack !== \"function\") return {state: \"pending\"};\n const progress = await awaitSwapProgress(\n omni.swapTrack({quoteId: decoded.quoteId, traderAddress: {chain: {$case: \"ton\", value: decoded.trader}}, outgoingTxQuery: sourceTxHash}),\n );\n if (!progress || progress === \"awaiting\") return {state: \"pending\"};\n switch (progress.status) {\n case \"TRADE_STATUS_FULLY_FILLED\":\n await quotes.clear(decoded.quoteId);\n return {state: \"completed\", depositReceived: true, ...(progress.outgoingTxHash ? {destTxHash: progress.outgoingTxHash} : {})};\n case \"TRADE_STATUS_PARTIALLY_FILLED\":\n // One route, so a partial fill means the DEX returned the rest to the\n // trader: the trade is over, and partial — not completed (round 3, L16).\n await quotes.clear(decoded.quoteId);\n return {state: \"partial\", depositReceived: true, ...(progress.outgoingTxHash ? {destTxHash: progress.outgoingTxHash} : {})};\n case \"TRADE_STATUS_CANCELLED\":\n case \"TRADE_STATUS_FAILED\":\n // A failed DEX swap bounces the input back to the trader on-chain: refunded (round 3, L16).\n await quotes.clear(decoded.quoteId);\n return {state: \"refunded\", depositReceived: true};\n default:\n return {state: \"pending\", depositReceived: true};\n }\n }\n\n /**\n * EVM→TON: generate the HTLC secret, ask Omniston for the EIP-712 order,\n * verify every byte the wallet is about to sign against the quote (order\n * fields, the 1inch extension the salt commits to, the serialized order\n * details), persist what registration needs, and hand the engine a gasless\n * typed-order `UnsignedTx` whose `approvalAddress` is the order protocol.\n */\n async function buildEvmOrder(\n ref: Decoded,\n q: OmnistonQuote,\n settlement: OrderSettlement,\n bound: IntentBinding | undefined,\n ): Promise<UnsignedTx> {\n const srcChain = ref.srcChain;\n const chainId = evmRef(srcChain);\n const srcCase = q.inputAsset.chain.$case;\n if (chainId === null || EVM_CASE[chainId] !== srcCase) throw new Error(\"omniston: source chain does not match the EVM quote\");\n const destCase = q.outputAsset.chain.$case;\n const destChain = caipForChainCase(destCase);\n const tonDest = destCase === \"ton\";\n if (!destChain || destChain === srcChain) throw new Error(\"omniston: EVM-source order has no supported destination chain\");\n if (\n !trustedOrderProtocols.has(srcChain) || typeof opts.validateEvmInputPosition !== \"function\" ||\n typeof (tonDest ? opts.validateTonOutputPosition : opts.validateEvmOutputPosition) !== \"function\"\n ) {\n throw new Error(`omniston: EVM→${tonDest ? \"TON\" : \"EVM\"} needs a trusted order protocol and both position validators`);\n }\n let owner: string;\n try {\n owner = getAddress(ref.trader);\n } catch {\n throw new Error(\"omniston: trader is not an EVM address\");\n }\n let dest: string;\n if (tonDest) {\n try {\n TonAddress.parse(ref.dest);\n } catch {\n throw new Error(\"omniston: destination is not a TON address\");\n }\n dest = ref.dest;\n } else {\n try {\n dest = getAddress(ref.dest);\n } catch {\n throw new Error(\"omniston: destination is not an EVM address\");\n }\n }\n const traderDst = {chain: {$case: destCase, value: dest}} as ChainAddress;\n const protocol = settlement.srcProtocolContractAddress;\n const resolver = settlement.srcInitialResolverAddress;\n const factory = settlement.dstProtocolContractAddress;\n const inputToken = assetContract(q.inputAsset);\n const outputToken = assetContract(q.outputAsset);\n const destChainId = tonDest ? null : evmRef(destChain);\n if (\n protocol.chain.$case !== srcCase || !isTrustedOrderProtocol(srcChain, protocol.chain.value) ||\n resolver?.chain.$case !== srcCase || !validEvmAddress(resolver.chain.value) ||\n factory?.chain.$case !== destCase || !isTrusted(destChain, factory.chain.value) ||\n !inputToken || !outputToken || !Number.isSafeInteger(settlement.protocolFeePips) ||\n (!tonDest && (destChainId === null || !validEvmAddress(outputToken) || !isPositiveInteger(settlement.dstSecurityDepositUnits ?? \"\")))\n ) throw new Error(\"omniston: incomplete EVM order settlement binding in quote\");\n\n // One execution: the signed order has ALLOW_MULTIPLE_FILLS clear and the\n // TON position commits a single hash. Persist BEFORE anything is signed.\n const {secrets, created} = await secretsFor(ref, q, 1);\n const hashes = secrets.map((secret) => hashlock(secret, settlement.htlcHashingFunction));\n // Clear only what this call created: a failed rebuild must not take the\n // secret of an order an earlier build already handed out for signing.\n const forget = async () => { if (created) await clearSecrets(ref.quoteId); };\n const omni = await getClient();\n let payload: Awaited<ReturnType<OmnistonClientLike[\"evmBuildOrderPayload\"]>>;\n try {\n payload = await omni.evmBuildOrderPayload({\n quoteId: ref.quoteId,\n ownerSrcAddress: {chain: {$case: srcCase, value: owner}} as ChainAddress,\n traderDstAddress: traderDst,\n htlcSecrets: {secretMode: {$case: \"provided\", value: {hashes}}},\n });\n } catch (error) {\n await forget();\n throw error;\n }\n let td: unknown;\n try {\n try {\n td = JSON.parse(payload.typedData);\n } catch {\n throw new Error(\"omniston: malformed EVM order typed data\");\n }\n validateSerializedOrderDetails(payload.serializedOrderDetails, {\n quoteId: ref.quoteId,\n outputAsset: q.outputAsset,\n traderDstAddress: traderDst,\n secretHashes: hashes,\n });\n validateEvmTypedOrder(td, {\n chainId,\n settlementContract: protocol.chain.value,\n owner,\n receiver: resolver.chain.value,\n makerAsset: inputToken,\n makingAmount: q.inputUnits,\n takingAmount: settlement.resolverSendsUnits,\n orderExtension: payload.orderExtension,\n quoteTimestamp: q.quoteTimestamp,\n tradeStartDeadline: settlement.tradeStartDeadline,\n });\n await validateEvmToTonOrderExtension(payload.orderExtension, {\n quoteId: ref.quoteId,\n quoteTimestamp: q.quoteTimestamp,\n tradeStartDeadline: settlement.tradeStartDeadline,\n protocolFeePips: settlement.protocolFeePips!,\n integratorFeePips: settlement.integratorFeePips ?? 0,\n initialResolverAddress: resolver.chain.value,\n outputTokenAddress: outputToken,\n traderDstAddress: dest,\n takerAsset: String(td.message.takerAsset),\n srcSecurityDepositUnits: settlement.srcHtlcSecurityDepositUnits ?? \"\",\n // TON destination: the TON deposit is bound in the TON position, not in\n // the EVM deposits word (live: 0 for every TON-destination order). EVM\n // destination: the word carries the quote's destination deposit and\n // ExtraDataArgs name the destination chain and token (live 2026-10-20).\n dstSecurityDepositUnits: tonDest ? \"0\" : settlement.dstSecurityDepositUnits!,\n ...(tonDest ? {} : {dstChainId: destChainId!}),\n secretHash: hashes[0]!,\n trustedTarget: (address) => isTrusted(srcChain, address),\n });\n } catch (error) {\n await forget();\n throw error;\n }\n // The validated extension targets one trusted factory on the source chain.\n const extensionTarget = getAddress(`0x${bytesToHex(payload.orderExtension.slice(32 + new DataView(payload.orderExtension.buffer, payload.orderExtension.byteOffset).getUint32(4, false), 32 + new DataView(payload.orderExtension.buffer, payload.orderExtension.byteOffset).getUint32(4, false) + 20))}`);\n // The SDK sends the domain chainId as a hex string (\"0x2105\"). Hand the\n // wallet a numeric chainId: signers that derive the EIP712Domain type from\n // the value types (viem) would otherwise sign a domain WITHOUT chainId and\n // the order protocol would reject the signature (live 2026-10-16).\n const typedData = JSON.stringify({...(td as object), domain: {...(td as {domain: object}).domain, chainId}});\n // Re-save the WHOLE entry: carry the binding forward, or every later\n // disclosure for this order would be refused as unbound.\n await saveBuilt(ref.quoteId, {\n quote: q,\n at: Date.now(),\n ...(bound ? {bound} : {}),\n evmOrder: {\n typedData,\n orderExtension: bytesToHex(payload.orderExtension),\n serializedOrderDetails: bytesToHex(payload.serializedOrderDetails ?? new Uint8Array()),\n owner,\n chainCase: srcCase,\n factory: extensionTarget,\n },\n });\n const orderProtocol = getAddress(protocol.chain.value);\n return {chain: srcChain, to: orderProtocol, value: \"0\", chainId, approvalAddress: orderProtocol, typedData};\n }\n\n return {\n name: \"omniston\",\n describeActivity: describeOmnistonActivity,\n enabled: () => (opts.enabled ?? true) && trustedContracts.size > 0,\n\n // Capability discovery comes from the provider itself, so it can run alone\n // or inside the optional aggregator without a central capability table.\n supportsChain: (chain: string) => cfg.supportsChain(chain),\n supportsChainPair: (fromChain: string, toChain: string) => cfg.supports(fromChain, toChain), // TON↔TON swap settlement is same-chain by definition.\n supportsSameChain: true,\n\n supportsRoute(from: Asset, to: Asset): boolean {\n if (isTon(from.chain) && isTon(to.chain)) {\n return cfg.supports(from.chain, to.chain) && trustedContracts.has(from.chain) && sameChainTonReady();\n }\n if (isTon(from.chain) && !isTon(to.chain)) return tonSourceReady(from.chain, to.chain);\n if (!isTon(from.chain) && isTon(to.chain)) return evmSourceReady(from.chain, to.chain);\n return evmToEvmReady(from.chain, to.chain);\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n // Amount-flexible deposits need a static deposit address — orders don't have one.\n if (params.flex) return null;\n if (isTon(params.sourceChain) && isTon(params.destChain)) return await getSwapQuote(params, signal);\n const refuse = (reason: string): null => {\n params.onRefusal?.(`omniston: ${reason}`);\n return null;\n };\n const evmSource = !isTon(params.sourceChain);\n const tonDest = isTon(params.destChain);\n if (!cfg.supports(params.sourceChain, params.destChain)) return refuse(\"route is not an Omniston order corridor\");\n if (!trustedContracts.has(params.sourceChain) || !trustedContracts.has(params.destChain)) {\n return refuse(`no trusted settlement contract configured for ${trustedContracts.has(params.sourceChain) ? params.destChain : params.sourceChain}`);\n }\n if (evmSource) {\n if (!trustedOrderProtocols.has(params.sourceChain)) return refuse(`no trusted EVM order protocol configured for ${params.sourceChain}`);\n if (typeof opts.validateEvmInputPosition !== \"function\" || typeof (tonDest ? opts.validateTonOutputPosition : opts.validateEvmOutputPosition) !== \"function\") {\n return refuse(tonDest\n ? \"EVM→TON needs the EVM input-position and TON output-position validators\"\n : \"EVM→EVM needs the EVM input-position and EVM output-position validators\");\n }\n if (params.dry === false) {\n if (tonDest) {\n try {\n TonAddress.parse(params.destAddress);\n } catch {\n return refuse(\"destination is not a TON address\");\n }\n } else if (!validEvmAddress(params.destAddress)) return refuse(\"destination is not an EVM address\");\n }\n } else if (\n typeof opts.validateTonJettonWallet !== \"function\" ||\n typeof opts.validateTonEscrowPayload !== \"function\" ||\n typeof opts.validateEvmOutputPosition !== \"function\"\n ) return refuse(\"TON→EVM needs the jetton-wallet, escrow-payload and EVM output-position validators\");\n\n const source = ccAsset(params.sourceChain, params.sourceToken);\n const dest = ccAssetByToken(params.destChain, params.destToken);\n if (!source || !dest) return refuse(\"asset is not in the catalog\");\n const inputAsset = toAssetId(params.sourceChain, source);\n const outputAsset = toAssetId(params.destChain, dest);\n if (!inputAsset || !outputAsset) {\n return refuse(`cross-chain orders are token corridors only (no ${!inputAsset ? source.symbol : dest.symbol} native leg)`);\n }\n\n // The resolver only fills the corridor up to ~$1000 a swap (stables 1:1).\n const maxUnits = decimalToUnits(maxUsdText, source.decimals);\n if (!maxUnits || !isPositiveInteger(params.amountIn)) return refuse(\"invalid amount\");\n if (BigInt(params.amountIn) > maxUnits) return refuse(`amount above the ${maxUsdText} USD per-swap cap`);\n\n // Execution and tracking both need the trader's source-chain wallet.\n const trader = params.refundAddress ?? \"\";\n if (!trader && !params.dry) return refuse(`execution quote needs the trader's ${evmSource ? \"EVM\" : \"TON\"} address (refundAddress)`);\n if (evmSource && trader && !validEvmAddress(trader)) return refuse(\"refundAddress is not an EVM address\");\n\n const request: QuoteRequest = {\n inputAsset,\n outputAsset,\n amount: {$case: \"inputUnits\", value: params.amountIn},\n settlementParams: [{params: {$case: \"order\", value: {}}}],\n } as QuoteRequest;\n const integrator = opts.integratorAddress ?? \"\";\n if (hasIntegrator) {\n const pips = opts.integratorFeePips!;\n const address = integrator ? toChainAddress(params.destChain, integrator) : null;\n if (!address) return refuse(\"integrator address is not valid on the destination chain\");\n request.integratorAddress = address;\n request.integratorFeePips = pips;\n }\n\n const omni = await getClient();\n const rfq: RfqOutcome = {updates: 0};\n const q = await awaitQuote(\n omni.requestForQuote(request),\n request,\n signal,\n params.dry === false ? Math.min(quoteSettleMs, EXECUTION_SETTLE_MS) : quoteSettleMs,\n \"order\",\n rfq,\n );\n if (!q) {\n if (signal?.aborted) return null;\n return refuse(\n rfq.error ? `RFQ failed: ${rfq.error}`\n : rfq.rejected ? `resolver quote rejected: ${rfq.rejected}`\n : \"no resolver quoted this route/amount\",\n );\n }\n const orderData = q.settlementData.$case === \"order\" ? q.settlementData.value : null;\n if (!orderData) return refuse(\"resolver answered without order settlement\");\n const srcContract = orderData.srcProtocolContractAddress.chain.value;\n if (evmSource ? !isTrustedOrderProtocol(params.sourceChain, srcContract) : !isTrusted(params.sourceChain, srcContract)) {\n return refuse(evmSource ? `untrusted ${params.sourceChain} order protocol ${srcContract}` : `untrusted TON settlement contract ${srcContract}`);\n }\n if (!orderData.dstProtocolContractAddress || !isTrusted(params.destChain, orderData.dstProtocolContractAddress.chain.value)) {\n return refuse(`untrusted ${params.destChain} settlement contract ${orderData.dstProtocolContractAddress?.chain.value ?? \"(none)\"}`);\n }\n const deadlineMs = orderData.tradeStartDeadline * 1000;\n if (!Number.isFinite(deadlineMs) || deadlineMs <= Date.now()) return refuse(\"quote trade-start deadline already passed\");\n // An execution quote whose deadline cannot outlast signing + inclusion\n // would fund an escrow no resolver will fill.\n if (params.dry === false && deadlineMs - Date.now() < MIN_START_HEADROOM_MS) return refuse(\"quote trade-start deadline too close to execute\");\n\n // The advertised corridors are stable-to-stable. Bound a resolver's\n // optimistic amount before it can dominate the router auction with an\n // impossible quote; settlement remains all-or-refund within this range.\n const inputScaled = BigInt(q.inputUnits) * 10n ** BigInt(dest.decimals);\n const outputScaled = BigInt(q.outputUnits) * 10n ** BigInt(source.decimals);\n if (outputScaled * 2n < inputScaled || outputScaled > inputScaled * 2n) return refuse(\"quoted output is outside 0.5x–2x of the input\");\n\n if (await quoteIdInUse(q.quoteId)) return refuse(\"the platform reused a quote id that already belongs to an order\");\n await saveBuilt(q.quoteId, {quote: q, at: Date.now(), bound: {trader, dest: params.destAddress, srcChain: params.sourceChain, kind: \"order\"}});\n\n // Fees are charged in the OUTPUT asset; the corridor is stables, so units\n // scaled by the dest decimals approximate USD.\n const feeUnits = Number(q.protocolFeeUnits || \"0\") + Number(q.integratorFeeUnits || \"0\");\n const feeUsd = feeUnits / 10 ** dest.decimals;\n\n return {\n provider: \"omniston\",\n intentId: encodeIntent(q.quoteId, trader, params.destAddress, params.sourceChain),\n depositAddress: \"\", // order settlement — no static deposit address\n depositMemo: null,\n sourceAmount: q.inputUnits,\n destAmount: q.outputUnits,\n minDestAmount: q.outputUnits, // HTLC fills at the quoted amount or refunds\n feeUsd: Number.isFinite(feeUsd) ? feeUsd : 0,\n fees: [\n ...(q.protocolFeeUnits && q.protocolFeeUnits !== \"0\" ? [{type: \"protocol\" as const, amount: q.protocolFeeUnits, token: feeToken(dest), included: true}] : []),\n ...(q.integratorFeeUnits && q.integratorFeeUnits !== \"0\" ? [{type: \"affiliate\" as const, amount: q.integratorFeeUnits, token: feeToken(dest), included: true}] : []),\n ],\n etaSeconds: 240,\n reliability: 0.9,\n validUntilMs: Math.min(Date.now() + QUOTE_TTL_MS, deadlineMs),\n };\n },\n\n /**\n * TON-source only: generate the HTLC secret, persist it, build the escrow\n * transfer. The returned tx carries the payload as a serialized CELL\n * (`bodyBoc`, base64) — sending it as a text comment would strand the swap.\n */\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n if (!Number.isFinite(quote.validUntilMs) || quote.validUntilMs <= Date.now()) {\n throw new Error(\"omniston: quote expired — request a fresh quote\");\n }\n const decoded = decodeIntent(quote.intentId);\n if (!decoded) throw new Error(\"omniston: malformed intent id\");\n const cached = await loadBuilt(decoded.quoteId);\n if (!cached) throw new Error(\"omniston: quote expired — request a fresh quote\");\n const ref = requireBinding(decoded, cached, \"buildDeposit\");\n const q = cached.quote;\n if (q.settlementData.$case === \"swap\") return await buildSwapDeposit(ref, q, q.settlementData.value);\n if (q.settlementData.$case !== \"order\" || q.settlementData.value.tradeStartDeadline * 1000 <= Date.now()) {\n throw new Error(\"omniston: quote trade deadline expired — request a fresh quote\");\n }\n\n if (!ref.trader) throw new Error(\"omniston: quote was requested without a refund/source address\");\n const srcCase = q.inputAsset.chain.$case;\n if (srcCase !== \"ton\") return await buildEvmOrder(ref, q, q.settlementData.value, cached.bound);\n const srcChain = ref.srcChain;\n if (!isTon(srcChain)) throw new Error(\"omniston: source chain does not match TON quote\");\n const destCase = q.outputAsset.chain.$case;\n const traderDst = destCase === \"ton\" ? null : {chain: {$case: destCase, value: getAddress(ref.dest)}};\n if (!traderDst) throw new Error(\"omniston: TON-destination orders are not supported\");\n\n const settlement = q.settlementData;\n const hashingFunction = settlement.$case === \"order\" ? settlement.value.htlcHashingFunction : undefined;\n const {secrets, created} = await secretsFor(ref, q, maxExecutions);\n const hashes = secrets.map((s) => hashlock(s, hashingFunction));\n // Clear only what this call created (see buildEvmOrder).\n const forget = async () => { if (created) await clearSecrets(ref.quoteId); };\n\n const owner: ChainAddress = {chain: {$case: \"ton\", value: ref.trader}};\n const omni = await getClient();\n let tx: {messages: EscrowMessage[]};\n try {\n tx = await omni.tonBuildEscrowTransfer({\n quoteId: ref.quoteId,\n ownerSrcAddress: owner,\n transferSrcAddress: owner,\n refundSrcAddress: owner,\n gasExcessAddress: owner,\n traderDstAddress: traderDst as ChainAddress,\n htlcSecrets: {secretMode: {$case: \"provided\", value: {hashes}}},\n });\n } catch (error) {\n await forget();\n throw error;\n }\n const [message, ...rest] = tx.messages;\n if (!message || rest.length > 0) {\n await forget();\n throw new Error(`omniston: expected exactly one escrow message, got ${tx.messages.length}`);\n }\n if (!isPositiveInteger(message.sendAmount) || BigInt(message.sendAmount) > BigInt(maxTonExecutionNano)) {\n await forget();\n throw new Error(\"omniston: resolver TON execution value exceeds the configured safety cap\");\n }\n const expectedProtocol = q.settlementData.value.srcProtocolContractAddress;\n const initialResolver = q.settlementData.value.srcInitialResolverAddress;\n const jettonMaster = assetContract(q.inputAsset);\n if (expectedProtocol.chain.$case !== \"ton\" || initialResolver?.chain.$case !== \"ton\" || !jettonMaster) {\n await forget();\n throw new Error(\"omniston: incomplete TON settlement binding in quote\");\n }\n if (message.jettonWalletStateInit) {\n await forget();\n throw new Error(\"omniston: deploying a resolver-provided jetton wallet is not supported\");\n }\n let walletValid = false;\n try {\n walletValid = opts.validateTonJettonWallet\n ? await opts.validateTonJettonWallet({\n ownerAddress: ref.trader,\n jettonMasterAddress: jettonMaster,\n walletAddress: message.targetAddress,\n })\n : false;\n } catch (error) {\n await forget();\n throw error;\n }\n if (!walletValid) {\n await forget();\n throw new Error(\"omniston: TON jetton wallet was not independently validated\");\n }\n try {\n if (!opts.validateTonEscrowPayload) {\n throw new Error(\"omniston: TON source requires an independent escrow-payload validator\");\n }\n await validateTonEscrowPayload(message, {\n quoteId: ref.quoteId,\n inputUnits: q.inputUnits,\n resolverSendsUnits: q.settlementData.value.resolverSendsUnits,\n srcHtlcSecurityDepositUnits: q.settlementData.value.srcHtlcSecurityDepositUnits ?? \"\",\n protocolAddress: expectedProtocol.chain.value,\n ownerAddress: ref.trader,\n destinationChain: q.outputAsset.chain.$case,\n destinationAddress: ref.dest,\n outputTokenAddress: assetContract(q.outputAsset) ?? \"\",\n initialResolverAddress: initialResolver.chain.value,\n hashes,\n ...(hashingFunction ? {hashingFunction} : {}),\n exclusivityTimeout: q.settlementData.value.exclusivityTimeout ?? 0,\n }, opts.validateTonEscrowPayload);\n } catch (error) {\n await forget();\n throw error;\n }\n\n return {\n chain: srcChain,\n to: message.targetAddress,\n value: message.sendAmount, // nanotons (gas + forward), NOT the jetton amount\n bodyBoc: hexToBase64(message.payload),\n };\n },\n\n /**\n * Snapshot the order and use ready phases only to discover candidate EVM\n * escrows. Disclosure follows only after independent finalized on-chain\n * validation; transient failures are retried on the next poll.\n */\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n const decoded = decodeIntent(ref.intentId);\n if (!decoded) throw new Error(\"omniston: malformed intent id\");\n // Swap settlement never discloses anything: tracked from the feed alone.\n if (decoded.kind === \"swap\") return await trackSwap(decoded, ref.sourceTxHash ?? null);\n const trace = traceFor(decoded.quoteId);\n // The secret is released only against the context stored when the quote\n // was minted — never against trader/dest from the caller's intentId\n // (scan F3/F15). Without a cached context (completed, TTL) this is a plain\n // status read of the feed, exactly as before.\n const stored = await loadBuilt(decoded.quoteId);\n let cached: BuiltEntry | undefined;\n let bound: Decoded = decoded;\n if (stored) {\n const result = bindIntent(decoded, stored);\n if (!result.ok && result.reason === \"mismatch\") {\n trace(\"intent-mismatch\", {where: \"trackIntent\", field: result.field});\n throw new Error(`omniston: intent id does not match the quote it was issued for (${result.field})`);\n }\n if (result.ok) {\n if (result.legacy) trace(\"legacy-intent\", {where: \"trackIntent\"});\n cached = stored;\n bound = result.ref;\n } else {\n trace(\"legacy-intent-expired\", {where: \"trackIntent\"});\n }\n }\n const omni = await getClient();\n const order = await awaitOrder(\n omni.orderTrack({\n quoteId: decoded.quoteId,\n traderAddress:\n toChainAddress(bound.srcChain, bound.trader) ??\n ({chain: {$case: \"ton\", value: bound.trader}} as ChainAddress),\n }),\n );\n if (!order) return {state: \"pending\"};\n\n const secretsHex = await store.load(decoded.quoteId);\n if (!secretsHex || cached?.quote.settlementData.$case !== \"order\") trace(\"disclosure-skipped\", {gate: \"context\", secrets: !!secretsHex, cached: !!cached, feedStatus: order.status});\n if (secretsHex && cached?.quote.settlementData.$case === \"order\") {\n const q = cached.quote;\n const settlement = q.settlementData.value as OrderSettlement;\n const indices = order.executions.map((execution) => execution.index);\n const validIndices = indices.every((index) => Number.isSafeInteger(index) && index >= 0 && index < secretsHex.length) &&\n new Set(indices).size === indices.length;\n const outputTokenAddress = assetContract(q.outputAsset);\n const outputChain = q.outputAsset.chain.$case;\n const outputCaip = caipForChainCase(outputChain);\n const factory = settlement.dstProtocolContractAddress;\n const evmSource = q.inputAsset.chain.$case !== \"ton\";\n const tonDest = outputChain === \"ton\";\n const inputChain = q.inputAsset.chain.$case;\n const inputCaip = caipForChainCase(inputChain);\n const inputTokenAddress = assetContract(q.inputAsset);\n const evmOrder = cached.evmOrder;\n await Promise.all(\n order.executions.map(async (execution) => {\n const i = execution.index;\n const secret = validIndices ? secretsHex[i] : undefined;\n const phase = execution.outputPositionPhase;\n const position = execution.outputPositionAddress;\n const inputPosition = execution.inputPositionAddress;\n if (\n !secret || !validDisclosurePhase(phase) || !position || position.chain.$case !== outputChain ||\n !position.chain.value || !factory || factory.chain.$case !== outputChain || !outputTokenAddress || !outputCaip\n ) { trace(\"disclosure-skipped\", {gate: \"position\", index: i, phase, positionChain: position?.chain.$case, outputChain}); return; }\n if (evmSource\n ? (!evmOrder || !inputCaip || !inputTokenAddress || !inputPosition || inputPosition.chain.$case !== inputChain || !inputPosition.chain.value ||\n !settlement.srcInitialResolverAddress || typeof opts.validateEvmInputPosition !== \"function\" ||\n typeof (tonDest ? opts.validateTonOutputPosition : opts.validateEvmOutputPosition) !== \"function\")\n : typeof opts.validateEvmOutputPosition !== \"function\"\n ) { trace(\"disclosure-skipped\", {gate: \"context-fields\", index: i, evmSource, evmOrder: !!evmOrder, inputPositionChain: inputPosition?.chain.$case}); return; }\n const secretBytes = hexToBytes(secret);\n const expectedHash = hashlock(secretBytes, settlement.htlcHashingFunction);\n if (\n !execution.secretHash || !bytesEqual(execution.secretHash, expectedHash) ||\n execution.inputUnits !== q.inputUnits || execution.outputUnits !== q.outputUnits ||\n execution.resolverSendsUnits !== settlement.resolverSendsUnits\n ) { trace(\"disclosure-skipped\", {gate: \"terms\", index: i, hashMatches: !!execution.secretHash && bytesEqual(execution.secretHash, expectedHash), inputUnits: [execution.inputUnits, q.inputUnits], outputUnits: [execution.outputUnits, q.outputUnits], resolverSendsUnits: [execution.resolverSendsUnits, settlement.resolverSendsUnits]}); return; }\n let verified = false;\n try {\n const evmOutput = () => opts.validateEvmOutputPosition!({\n chain: outputCaip,\n positionAddress: position.chain.value,\n factoryAddress: factory.chain.value,\n quoteTimestamp: q.quoteTimestamp,\n executionIndex: i,\n recipientAddress: bound.dest,\n outputTokenAddress,\n inputUnits: execution.inputUnits,\n outputUnits: execution.outputUnits,\n resolverSendsUnits: execution.resolverSendsUnits,\n srcHtlcSecurityDepositUnits: settlement.srcHtlcSecurityDepositUnits ?? \"\",\n dstSecurityDepositUnits: settlement.dstSecurityDepositUnits ?? \"\",\n protocolFeeUnits: q.protocolFeeUnits ?? \"0\",\n integratorFeeUnits: q.integratorFeeUnits ?? \"0\",\n ...(q.integratorAddress?.chain.value ? {integratorAddress: q.integratorAddress.chain.value} : {}),\n ...(settlement.protocolFeeRecipientAddress?.chain.value ? {protocolFeeRecipientAddress: settlement.protocolFeeRecipientAddress.chain.value} : {}),\n secretHash: expectedHash,\n });\n // EVM source: BOTH positions must be proven before the secret\n // leaves — the trader's full input locked on the source chain for\n // this hashlock, and the destination position (TON or EVM) the\n // trusted factory deployed for this quote, paying the recipient.\n verified = evmSource\n ? await opts.validateEvmInputPosition!({\n chain: inputCaip!,\n positionAddress: inputPosition!.chain.value,\n factoryAddress: evmOrder!.factory,\n orderProtocolAddress: settlement.srcProtocolContractAddress.chain.value,\n ownerAddress: evmOrder!.owner,\n resolverAddress: settlement.srcInitialResolverAddress!.chain.value,\n inputTokenAddress: inputTokenAddress!,\n inputUnits: execution.inputUnits,\n resolverSendsUnits: execution.resolverSendsUnits,\n srcHtlcSecurityDepositUnits: settlement.srcHtlcSecurityDepositUnits ?? \"\",\n quoteTimestamp: q.quoteTimestamp,\n secretHash: expectedHash,\n ...(tonDest ? {} : {\n destinationChainId: evmRef(outputCaip)!,\n destinationTokenAddress: outputTokenAddress,\n dstSecurityDepositUnits: settlement.dstSecurityDepositUnits ?? \"\",\n }),\n }) && (tonDest\n ? await opts.validateTonOutputPosition!({\n positionAddress: position.chain.value,\n protocolAddress: factory.chain.value,\n outputJettonMasterAddress: outputTokenAddress,\n recipientAddress: bound.dest,\n quoteId: decoded.quoteId,\n quoteTimestamp: q.quoteTimestamp,\n inputUnits: execution.inputUnits,\n outputUnits: execution.outputUnits,\n resolverSendsUnits: execution.resolverSendsUnits,\n dstSecurityDepositUnits: settlement.dstSecurityDepositUnits ?? \"\",\n secretHash: expectedHash,\n })\n : await evmOutput())\n : await evmOutput();\n } catch (error) {\n verified = false;\n trace(\"validator-threw\", {index: i, error: error instanceof Error ? error.message : String(error)});\n }\n if (!verified) { trace(\"validator-refused\", {index: i, evmSource, tonDest}); return; }\n await omni\n .orderDiscloseHtlcSecret({quoteId: decoded.quoteId, executionIndex: i, secret: secretBytes})\n .then(async () => {\n trace(\"secret-disclosed\", {index: i});\n // Disclosed = known to the counterparty: never lock a new order to it (scan F6).\n await store.save(disclosedKey(decoded.quoteId), [\"1\"]);\n }, (error) => trace(\"disclose-failed\", {index: i, error: error instanceof Error ? error.message : String(error)})); // retried on the next poll\n }),\n );\n }\n\n const status = mapOrderStatus(order);\n const delivered = order.executions[0]?.outputPositionAddress;\n const outCase = cached?.quote.outputAsset.chain.$case;\n const outCaip = outCase ? caipForChainCase(outCase) : null;\n const outToken = cached ? assetContract(cached.quote.outputAsset) : null;\n if (\n status.state === \"completed\" && opts.locateEvmDelivery && outCase && outCase !== \"ton\" && outCaip && outToken &&\n order.executions.length === 1 && delivered?.chain.$case === outCase && delivered.chain.value\n ) {\n const hash = await opts.locateEvmDelivery({\n chain: outCaip, positionAddress: delivered.chain.value, recipientAddress: bound.dest,\n tokenAddress: outToken, minUnits: order.executions[0]!.outputUnits,\n }).catch(() => null);\n if (hash) status.destTxHash = hash;\n }\n if (\n status.state === \"completed\" && !status.destTxHash && opts.locateTonDelivery && outCase === \"ton\" && outToken &&\n order.executions.length === 1 && delivered?.chain.$case === \"ton\" && delivered.chain.value\n ) {\n const hash = await opts.locateTonDelivery({\n positionAddress: delivered.chain.value, recipientAddress: bound.dest,\n jettonMasterAddress: outToken, minUnits: order.executions[0]!.outputUnits,\n }).catch(() => null);\n if (hash) status.destTxHash = hash;\n }\n // A feed-only CANCELLED/FAILED signal is not on-chain invalidation of a\n // signed order. Retain secrets/context until proven completion or TTL so\n // a late valid output lock can still be completed safely.\n if (status.state === \"completed\") {\n await clearSecrets(decoded.quoteId);\n await quotes.clear(decoded.quoteId);\n }\n return status;\n },\n /** EVM→TON: hand the wallet's EIP-712 signature over the validated order to Omniston. */\n async registerSignedOrder(intentId: string, signature: string): Promise<void> {\n const ref = decodeIntent(intentId);\n if (!ref) throw new Error(\"omniston: malformed intent id\");\n const cached = await loadBuilt(ref.quoteId);\n const order = cached?.evmOrder;\n if (!order) throw new Error(\"omniston: no signed-order context for this quote — build the order again\");\n // Same binding as buildDeposit: the intentId must be the one this order was built for.\n requireBinding(ref, cached!, \"registerSignedOrder\");\n if (!/^0x[0-9a-fA-F]{130}$/.test(signature)) throw new Error(\"omniston: malformed order signature\");\n const td = JSON.parse(order.typedData) as Parameters<typeof encodeTypedMessage>[0];\n const omni = await getClient();\n await omni.orderRegisterSignedOrder({\n quoteId: ref.quoteId,\n ownerSrcAddress: {chain: {$case: order.chainCase, value: order.owner}} as ChainAddress,\n signedOrder: {order: {$case: \"evmV1\", value: {\n encodedOrder: encodeTypedMessage(td),\n signature: hexToBytes(signature),\n orderExtension: hexToBytes(order.orderExtension),\n }}},\n ...(order.serializedOrderDetails ? {serializedOrderDetails: hexToBytes(order.serializedOrderDetails)} : {}),\n });\n },\n\n close(): void {\n clientGeneration += 1;\n if (client && (client !== injectedClient || opts.closeInjectedClient)) {\n if (client.close) client.close();\n else client.transport?.close();\n }\n client = null;\n },\n };\n}\n","/**\n * Activity recognition for Omniston on TON.\n *\n * Same-chain swaps settle through the STON.fi DEX router (the wallet pays TON /\n * a jetton to the router and the output jetton or TON comes back) → `swap`.\n * TON → EVM orders lock the input in the Omniston HTLC escrow (\"Omniston Escrow\n * Minter\", the `srcProtocolContractAddress` of every live quote) → `bridge`;\n * the EVM leg is paid by the resolver and is not recognizable offline.\n * Addresses are compared in raw form, so friendly (EQ…/UQ…) and raw (0:…)\n * notations all match.\n */\nimport {Address} from \"@ton/core\";\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {describeSwapLike} from \"@anywalletkit/protocol-swap2-core/activity\";\n\nexport const OMNISTON_MODULE = \"@anywalletkit/protocol-swap2-omniston\";\n\n/** STON.fi DEX routers (tonapi \"STON.fi DEX\"; v2.2 observed in the test wallet's swaps, v1 kept for older history). */\nexport const STONFI_ROUTERS: readonly string[] = [\n \"EQCS4UEa5UaJLzOyyKieqQOQ2P9M-7kXpkO5HnP3Bv250cN3\",\n \"EQB3ncyBUTjZUA5EnFKR5_EnOMI9V1tTEAAPaiU71gc4TiUt\",\n];\n/** Omniston HTLC escrow on TON (Omniston Escrow Minter) — the `srcProtocolContractAddress` of TON→EVM orders. */\nexport const OMNISTON_ESCROWS: readonly string[] = [\"EQAbWJ3Y1HgIIvcMq1prG1anlDC0T3cZlAU7luPT6LmTpmrZ\"];\n\nfunction raw(address: string | null | undefined): string | null {\n if (!address) return null;\n try {\n return Address.parse(address).toRawString();\n } catch {\n return null;\n }\n}\n\nconst ROUTER_RAW = new Set(STONFI_ROUTERS.map((a) => raw(a)!));\nconst ESCROW_RAW = new Set(OMNISTON_ESCROWS.map((a) => raw(a)!));\n\n/** Every non-own party of the transaction in raw form: the destination contract and each transfer's other side. */\nfunction counterparties(tx: ChainTx, own: Set<string>): string[] {\n const ownRaw = new Set<string>();\n for (const a of own) {\n const r = raw(a);\n if (r) ownRaw.add(r);\n }\n const out = new Set<string>();\n const add = (a: string | null | undefined) => {\n const r = raw(a);\n if (r && !ownRaw.has(r)) out.add(r);\n };\n add(tx.call?.to);\n add(tx.to);\n for (const t of tx.transfers) {\n add(t.from);\n add(t.to);\n }\n return [...out];\n}\n\nexport function describeOmnistonActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n if (!tx.chain.startsWith(\"ton:\")) return null;\n const parties = counterparties(tx, ctx.own);\n const escrow = parties.find((p) => ESCROW_RAW.has(p));\n if (escrow) {\n return describeSwapLike(tx, ctx, {protocol: OMNISTON_MODULE, subtitle: \"Omniston · STON.fi\", kind: \"bridge\", counterparty: tx.call?.to ?? tx.to ?? escrow});\n }\n const router = parties.find((p) => ROUTER_RAW.has(p));\n if (router) {\n return describeSwapLike(tx, ctx, {protocol: OMNISTON_MODULE, subtitle: \"STON.fi · TON\", kind: \"swap\", counterparty: tx.call?.to ?? tx.to ?? router});\n }\n return null;\n}\n","import \"./buffer-global.js\";\nimport {Buffer} from \"buffer\";\nimport {Address, Cell, type Slice} from \"@ton/core\";\n\n/**\n * TON same-chain swap message decoder (scan F11).\n *\n * `tonBuildSwap` returns the body of the one message the trader's wallet\n * signs. The provider's structural checks bind the amount, the attached TON\n * and the contract the message pays into; this module opens the DEX call the\n * body carries and binds what those checks cannot see: who receives the\n * output, where refunds and excesses go, and the on-chain minimum output.\n *\n * Every layout below was decoded from real Omniston builds (fixtures\n * `tests/fixtures/live-ton-swaps-2026-10-22.json`) and cross-checked against\n * the protocols' own SDKs; anything else is refused by name:\n *\n * ```text\n * STON.fi v2 jetton_transfer → router, forward swap#6664de2a; native input\n * as pTON v2 ton_transfer#01f3835d to the router's pTON wallet;\n * multi-hop = cross swap: a hop's receiver is the next router\n * and its custom payload is the next swap#6664de2a.\n * STON.fi v1 jetton_transfer → router, forward swap#25938561; native input\n * as a jetton_transfer to the router's pTON v1 wallet whose\n * destination is the router (STON.fi SDK v1 shape).\n * DeDust v1 jetton_transfer → jetton vault, forward swap#e3a0d482; native\n * vault swap#ea06185d. SwapStep + ^SwapParams.\n * DeDust CPMM v2 native: pay_native#a5a7cbf8 to the pool; jetton:\n * jetton_transfer → pool, forward pay_jetton#cbc33949. Payment\n * payload swap#c442500f + extended payout config.\n * ```\n *\n * The decoder is pure (no network). Facts that need the chain — that an ask\n * wallet is the router's wallet of the quoted output, that a pool trades the\n * quoted pair, that a pTON wallet belongs to the router — are returned as\n * `legs` for the `validateTonSwapLeg` hook (`createOmnistonTonValidators`).\n */\n\nexport const TON_JETTON_TRANSFER_OP = 0x0f8a7ea5;\nconst PTON_V2_TON_TRANSFER_OP = 0x01f3835d;\nconst STONFI_V2_SWAP_OP = 0x6664de2a;\nconst STONFI_V1_SWAP_OP = 0x25938561;\nconst DEDUST_V1_NATIVE_SWAP_OP = 0xea06185d;\nconst DEDUST_V1_JETTON_SWAP_OP = 0xe3a0d482;\nconst DEDUST_V2_PAY_NATIVE_OP = 0xa5a7cbf8;\nconst DEDUST_V2_PAY_JETTON_OP = 0xcbc33949;\nconst DEDUST_V2_SWAP_OP = 0xc442500f;\n\n/** Omniston's `SwapChunk.protocol` names and the layout each one builds. */\nexport const TON_SWAP_PROTOCOL_LAYOUTS: Readonly<Record<string, \"stonfi-v1\" | \"stonfi-v2\" | \"dedust-v1\" | \"dedust-v2\">> = {\n StonFiV1: \"stonfi-v1\",\n StonFiV2: \"stonfi-v2\",\n DeDust: \"dedust-v1\",\n DeDustCPMMV2: \"dedust-v2\",\n};\n\n/** A chain fact the payload depends on; checked by `validateTonSwapLeg`. A\n * jetton is named by its master address; `null` is native GRAM. */\nexport type TonSwapLeg =\n | {\n kind: \"stonfi-router\";\n version: 1 | 2;\n /** The router that executes this hop; null = the owner of `proxyTonWallet`. */\n router: string | null;\n /** Native input: the router's proxy-TON wallet the message pays into. */\n proxyTonWallet?: string;\n /** The router's wallet the hop asks for — must be the router's wallet of `outputJetton`\n * (of a proxy-TON master when the output is native). */\n askWallet: string;\n inputJetton: string | null;\n outputJetton: string | null;\n }\n | {\n kind: \"dedust-pool\";\n version: 1 | 2;\n pool: string;\n inputJetton: string | null;\n outputJetton: string | null;\n };\n\nexport interface TonSwapCheckInput {\n /** The built message's body (BoC hex) and destination. */\n payloadHex: string;\n targetAddress: string;\n /** Value attached to the message, nanoTON. */\n sendAmount: bigint;\n /** The trader's wallet (signs; refunds and excesses return to it). */\n trader: string;\n /** Where the output must land. */\n dest: string;\n /** Quote fields the body must honour. */\n inputUnits: string;\n minOutputAmount: string;\n inputJetton: string | null;\n outputJetton: string | null;\n steps: readonly {protocol: string; inputJetton: string | null | undefined; outputJetton: string | null | undefined}[];\n /** The integrator the quote was requested with: the only referral a body may name. */\n integratorAddress?: string | null;\n}\n\nexport interface TonSwapCheckResult {\n layout: \"stonfi-v1\" | \"stonfi-v2\" | \"dedust-v1\" | \"dedust-v2\";\n /** On-chain minimum of the final hop. */\n minOut: bigint;\n legs: TonSwapLeg[];\n}\n\n/** A refusal with a stable, loggable reason code (never carries secrets). */\nexport class TonSwapPayloadError extends Error {\n constructor(readonly reason: string, detail?: string) {\n super(`omniston: ton-swap-payload ${reason}${detail ? ` (${detail})` : \"\"}`);\n this.name = \"TonSwapPayloadError\";\n }\n}\n\nconst refuse = (reason: string, detail?: string): never => {\n throw new TonSwapPayloadError(reason, detail);\n};\n\nfunction sameAddr(a: Address | null | undefined, b: string | null | undefined): boolean {\n if (!a || !b) return false;\n try {\n return a.equals(Address.parse(b));\n } catch {\n return false;\n }\n}\n\nfunction end(s: Slice, where: string): void {\n if (s.remainingBits !== 0 || s.remainingRefs !== 0) refuse(\"unknown-layout\", `${where}: ${s.remainingBits} bits / ${s.remainingRefs} refs left over`);\n}\n\n/** Either Cell ^Cell forward payload: the rest of this slice or one ref. */\nfunction eitherRef(s: Slice): Slice {\n return s.loadBit() ? s.loadRef().beginParse() : s;\n}\n\nfunction readAddress(s: Slice): Address | null {\n const a = s.loadAddressAny();\n if (a === null) return null;\n if (!(a instanceof Address)) refuse(\"unknown-layout\", \"external address\");\n return a as Address;\n}\n\n/** addr_none means \"the sender\" (DeDust) — the trader's wallet here. */\nfunction isTraderOrNone(a: Address | null, trader: string): boolean {\n return a === null || sameAddr(a, trader);\n}\n\n/** Receiver of the output: exactly the destination, or addr_none (\"the sender\")\n * only when the destination IS the trader. */\nfunction receiverOk(a: Address | null, dest: string, trader: string): boolean {\n if (a === null) {\n try {\n return Address.parse(dest).equals(Address.parse(trader));\n } catch {\n return false;\n }\n }\n return sameAddr(a, dest);\n}\n\nfunction referralOk(address: Address | null, fee: number | null, integrator: string | null | undefined): boolean {\n if (address === null) return true;\n if (fee === 0) return true;\n return !!integrator && sameAddr(address, integrator);\n}\n\ninterface StonFiV2Hop {\n askWallet: Address;\n minOut: bigint;\n receiver: Address | null;\n next: Slice | null;\n}\n\n/** STON.fi v2 swap body; follows cross-swap custom payloads. */\nfunction decodeStonFiV2(s: Slice, ctx: TonSwapCheckInput): StonFiV2Hop[] {\n const hops: StonFiV2Hop[] = [];\n let cur: Slice | null = s;\n for (let depth = 0; cur; depth++) {\n if (depth >= 4) refuse(\"unsupported-ton-route\", \"STON.fi v2 cross-swap deeper than 4 hops\");\n if (cur.loadUint(32) !== STONFI_V2_SWAP_OP) refuse(\"unknown-layout\", `STON.fi v2 hop ${depth} is not swap#6664de2a`);\n const askWallet = readAddress(cur);\n const refund = readAddress(cur);\n const excess = readAddress(cur);\n cur.loadUintBig(64); // tx deadline\n const body = cur.loadRef().beginParse();\n end(cur, \"STON.fi v2 swap\");\n const minOut = body.loadCoins();\n const receiver = readAddress(body);\n const fwdGas = body.loadCoins();\n const custom = body.loadMaybeRef();\n body.loadCoins(); // refund forward gas\n const refundPayload = body.loadMaybeRef();\n const refFee = body.loadUint(16);\n const refAddress = readAddress(body);\n end(body, \"STON.fi v2 cross-swap body\");\n if (!askWallet) refuse(\"unknown-layout\", \"STON.fi v2 swap without an ask wallet\");\n if (!sameAddr(refund, ctx.trader)) refuse(\"refund-not-trader\", `STON.fi v2 hop ${depth}`);\n if (!sameAddr(excess, ctx.trader)) refuse(\"excess-not-trader\", `STON.fi v2 hop ${depth}`);\n if (refundPayload) refuse(\"unknown-layout\", \"STON.fi v2 refund payload\");\n if (!referralOk(refAddress, refFee, ctx.integratorAddress)) refuse(\"referral\", `STON.fi v2 hop ${depth}`);\n if (custom && fwdGas === 0n) refuse(\"unknown-layout\", \"STON.fi v2 custom payload without forward gas\");\n hops.push({askWallet: askWallet!, minOut, receiver, next: custom ? custom.beginParse() : null});\n cur = custom ? custom.beginParse() : null;\n }\n return hops;\n}\n\ninterface DeDustV1Swap {\n pool: Address;\n limit: bigint;\n recipient: Address | null;\n referral: Address | null;\n}\n\n/** DeDust v1 SwapStep (inline) + ^SwapParams. */\nfunction decodeDeDustV1(s: Slice): DeDustV1Swap {\n const pool = readAddress(s);\n if (!pool) refuse(\"unknown-layout\", \"DeDust v1 swap without a pool\");\n if (s.loadUint(1) !== 0) refuse(\"unknown-layout\", \"DeDust v1 swap kind is not given_in\");\n const limit = s.loadCoins();\n if (s.loadMaybeRef()) refuse(\"unsupported-ton-route\", \"DeDust v1 multi-hop (next step)\");\n const params = s.loadRef().beginParse();\n end(s, \"DeDust v1 swap step\");\n params.loadUint(32); // deadline\n const recipient = readAddress(params);\n const referral = readAddress(params);\n params.loadMaybeRef(); // fulfill payload — delivered to the recipient with the output\n params.loadMaybeRef(); // reject payload — delivered back to the sender with the refund\n end(params, \"DeDust v1 swap params\");\n return {pool: pool!, limit, recipient, referral};\n}\n\ninterface DeDustV2Swap {\n minOut: bigint;\n fulfill: Address | null;\n reject: Address | null;\n excessesTo: Address | null;\n}\n\n/** DeDust CPMM v2 payment payload (swap#c442500f) + extended payout config. */\nfunction decodeDeDustV2(payment: Slice, payout: Slice): DeDustV2Swap {\n if (payment.loadUint(32) !== DEDUST_V2_SWAP_OP) refuse(\"unknown-layout\", \"DeDust CPMM v2 payment payload is not swap#c442500f\");\n const minOut = payment.loadCoins();\n payment.loadUint(40); // deadline\n if (payment.loadMaybeRef()) refuse(\"unsupported-ton-route\", \"DeDust CPMM v2 multi-hop (next step)\");\n // Partner / referrer fee configs are not part of an Omniston quote.\n if (payment.loadBit()) refuse(\"referral\", \"DeDust CPMM v2 partner config\");\n if (payment.loadBit()) refuse(\"referral\", \"DeDust CPMM v2 referrer config\");\n end(payment, \"DeDust CPMM v2 swap payload\");\n const options = (): Address | null => {\n const destination = readAddress(payout);\n payout.loadCoins(); // extra gas — bounded by the message value\n payout.loadMaybeRef(); // payload delivered with the payout (to the trader / destination)\n payout.loadBit(); // wrap payload\n return destination;\n };\n const fulfill = options();\n const reject = options();\n const excessesTo = readAddress(payout);\n end(payout, \"DeDust CPMM v2 payout config\");\n return {minOut, fulfill, reject, excessesTo};\n}\n\n/**\n * Decode and check a built TON same-chain swap message. Throws\n * `TonSwapPayloadError` with a reason code on the first violated rule; returns\n * the chain facts (`legs`) still to be confirmed by `validateTonSwapLeg`.\n *\n * Rules (all protocols): one route of single-protocol steps; the body's\n * layout is the one the quoted protocol builds; the DEX call moves exactly the\n * quoted input; the final receiver is the destination; refunds / excesses go\n * to the trader; the final on-chain minimum is ≥ the quote's minOutputAmount;\n * no referral other than the configured integrator; no trailing data.\n */\nexport function checkTonSwapPayload(ctx: TonSwapCheckInput): TonSwapCheckResult {\n if (!/^(?:[0-9a-fA-F]{2})+$/.test(ctx.payloadHex)) refuse(\"malformed\", \"payload hex\");\n const roots = Cell.fromBoc(Buffer.from(ctx.payloadHex, \"hex\"));\n if (roots.length !== 1) refuse(\"malformed\", \"payload must have one root\");\n const steps = ctx.steps;\n if (steps.length === 0) refuse(\"unsupported-ton-route\", \"no route steps\");\n const layouts = steps.map((step) => TON_SWAP_PROTOCOL_LAYOUTS[step.protocol] ?? refuse(\"unsupported-ton-route\", `protocol ${step.protocol}`));\n const layout = layouts[0]!;\n if (layouts.some((l) => l !== layout)) refuse(\"unsupported-ton-route\", `mixed protocols ${steps.map((s) => s.protocol).join(\"+\")}`);\n if (steps.length > 1 && layout !== \"stonfi-v2\") refuse(\"unsupported-ton-route\", `${steps.length}-step ${steps[0]!.protocol} route`);\n // Steps must chain from the quoted input to the quoted output.\n for (let i = 0; i < steps.length; i++) {\n const step = steps[i]!;\n const wantIn = i === 0 ? ctx.inputJetton : steps[i - 1]!.outputJetton;\n const wantOut = i === steps.length - 1 ? ctx.outputJetton : step.outputJetton;\n if (step.inputJetton === undefined || step.outputJetton === undefined) refuse(\"unsupported-ton-route\", `step ${i} without assets`);\n if (!sameJetton(step.inputJetton!, wantIn ?? null) || !sameJetton(step.outputJetton!, wantOut ?? null)) refuse(\"unsupported-ton-route\", `step ${i} assets do not chain`);\n }\n\n const input = BigInt(ctx.inputUnits);\n const quotedMin = BigInt(ctx.minOutputAmount);\n const nativeInput = ctx.inputJetton === null;\n const s = roots[0]!.beginParse();\n const op = s.loadUint(32);\n const legs: TonSwapLeg[] = [];\n const minOk = (minOut: bigint) => {\n if (minOut < quotedMin) refuse(minOut === 0n ? \"min-out-zero\" : \"min-out-below-quote\", `${minOut} < ${quotedMin}`);\n };\n\n // Jetton transfer header: from the trader's jetton wallet (jetton input) or\n // to the router's pTON v1 wallet (STON.fi v1 native input).\n let transfer: null | {destination: Address; forward: Slice; inline: boolean} = null;\n if (op === TON_JETTON_TRANSFER_OP) {\n s.loadUintBig(64);\n const amount = s.loadCoins();\n const destination = readAddress(s);\n const response = readAddress(s);\n if (s.loadMaybeRef()) refuse(\"unknown-layout\", \"jetton transfer custom payload\");\n s.loadCoins(); // forward TON — bounded by the provider's structural checks\n const inline = !s.loadBit();\n const forward = inline ? s : s.loadRef().beginParse();\n if (amount !== input) refuse(\"amount-mismatch\", \"jetton transfer amount\");\n if (!destination) refuse(\"unknown-layout\", \"jetton transfer without a destination\");\n if (!sameAddr(response, ctx.trader)) refuse(\"excess-not-trader\", \"jetton transfer response destination\");\n transfer = {destination: destination!, forward, inline};\n }\n\n let minOut: bigint;\n if (layout === \"stonfi-v2\") {\n let hopsSlice: Slice;\n let router: string | null;\n let proxyTonWallet: string | undefined;\n if (nativeInput) {\n if (op !== PTON_V2_TON_TRANSFER_OP) refuse(\"unknown-layout\", `native STON.fi v2 input op 0x${op.toString(16)}`);\n s.loadUintBig(64);\n const tonAmount = s.loadCoins();\n const refund = readAddress(s);\n hopsSlice = eitherRef(s);\n end(s, \"pTON v2 ton_transfer\");\n if (tonAmount !== input) refuse(\"amount-mismatch\", \"pTON v2 ton_amount\");\n if (!sameAddr(refund, ctx.trader)) refuse(\"refund-not-trader\", \"pTON v2 refund address\");\n router = null;\n proxyTonWallet = ctx.targetAddress;\n } else {\n if (!transfer) refuse(\"unknown-layout\", `jetton-input STON.fi v2 op 0x${op.toString(16)}`);\n if (!transfer!.inline) end(s, \"jetton transfer\");\n hopsSlice = transfer!.forward;\n router = transfer!.destination.toString();\n }\n const hops = decodeStonFiV2(hopsSlice, ctx);\n if (hops.length !== steps.length) refuse(\"unsupported-ton-route\", `${hops.length} STON.fi v2 hops for ${steps.length} quoted steps`);\n hops.forEach((hop, i) => {\n const last = i === hops.length - 1;\n if (last) {\n if (!receiverOk(hop.receiver, ctx.dest, ctx.trader) || hop.receiver === null) refuse(\"receiver-not-destination\", `STON.fi v2 hop ${i}`);\n if (hop.next) refuse(\"unknown-layout\", \"STON.fi v2 final hop carries a custom payload\");\n } else if (!hop.receiver) refuse(\"unknown-layout\", `STON.fi v2 hop ${i} without a receiver`);\n legs.push({\n kind: \"stonfi-router\",\n version: 2,\n router: i === 0 ? router : hops[i - 1]!.receiver!.toString(),\n ...(i === 0 && proxyTonWallet ? {proxyTonWallet} : {}),\n askWallet: hop.askWallet.toString(),\n inputJetton: steps[i]!.inputJetton ?? null,\n outputJetton: steps[i]!.outputJetton ?? null,\n });\n });\n minOut = hops[hops.length - 1]!.minOut;\n } else if (layout === \"stonfi-v1\") {\n if (!transfer) refuse(\"unknown-layout\", `STON.fi v1 op 0x${op.toString(16)}`);\n if (!transfer!.inline) end(s, \"jetton transfer\");\n const f = transfer!.forward;\n if (f.loadUint(32) !== STONFI_V1_SWAP_OP) refuse(\"unknown-layout\", \"STON.fi v1 forward payload is not swap#25938561\");\n const askWallet = readAddress(f);\n minOut = f.loadCoins();\n const to = readAddress(f);\n const referral = f.loadBit() ? readAddress(f) : null;\n end(f, \"STON.fi v1 swap\");\n if (!askWallet) refuse(\"unknown-layout\", \"STON.fi v1 swap without an ask wallet\");\n if (!to || !sameAddr(to, ctx.dest)) refuse(\"receiver-not-destination\", \"STON.fi v1 to_address\");\n if (!referralOk(referral, null, ctx.integratorAddress)) refuse(\"referral\", \"STON.fi v1\");\n // Native input: the message pays the router's pTON v1 wallet, the transfer\n // names the router; jetton input: the transfer goes straight to the router.\n legs.push({\n kind: \"stonfi-router\",\n version: 1,\n router: transfer!.destination.toString(),\n ...(nativeInput ? {proxyTonWallet: ctx.targetAddress} : {}),\n askWallet: askWallet!.toString(),\n inputJetton: ctx.inputJetton,\n outputJetton: ctx.outputJetton,\n });\n } else if (layout === \"dedust-v1\") {\n let swap: DeDustV1Swap;\n if (nativeInput) {\n if (op !== DEDUST_V1_NATIVE_SWAP_OP) refuse(\"unknown-layout\", `native DeDust v1 input op 0x${op.toString(16)}`);\n s.loadUintBig(64);\n const amount = s.loadCoins();\n if (amount !== input) refuse(\"amount-mismatch\", \"DeDust v1 native vault amount\");\n swap = decodeDeDustV1(s);\n } else {\n if (!transfer) refuse(\"unknown-layout\", `jetton-input DeDust v1 op 0x${op.toString(16)}`);\n if (!transfer!.inline) end(s, \"jetton transfer\");\n const f = transfer!.forward;\n if (f.loadUint(32) !== DEDUST_V1_JETTON_SWAP_OP) refuse(\"unknown-layout\", \"DeDust v1 forward payload is not swap#e3a0d482\");\n swap = decodeDeDustV1(f);\n }\n if (!receiverOk(swap.recipient, ctx.dest, ctx.trader)) refuse(\"receiver-not-destination\", \"DeDust v1 recipient\");\n if (!referralOk(swap.referral, null, ctx.integratorAddress)) refuse(\"referral\", \"DeDust v1\");\n minOut = swap.limit;\n legs.push({kind: \"dedust-pool\", version: 1, pool: swap.pool.toString(), inputJetton: ctx.inputJetton, outputJetton: ctx.outputJetton});\n } else {\n let swap: DeDustV2Swap;\n let pool: string;\n if (nativeInput) {\n if (op !== DEDUST_V2_PAY_NATIVE_OP) refuse(\"unknown-layout\", `native DeDust CPMM v2 input op 0x${op.toString(16)}`);\n s.loadUintBig(64);\n const amount = s.loadCoins();\n const payment = s.loadRef().beginParse();\n const payout = s.loadRef().beginParse();\n end(s, \"DeDust CPMM v2 pay_native\");\n if (amount !== input) refuse(\"amount-mismatch\", \"DeDust CPMM v2 pay_native amount\");\n swap = decodeDeDustV2(payment, payout);\n pool = ctx.targetAddress;\n } else {\n if (!transfer) refuse(\"unknown-layout\", `jetton-input DeDust CPMM v2 op 0x${op.toString(16)}`);\n if (!transfer!.inline) end(s, \"jetton transfer\");\n const f = transfer!.forward;\n if (f.loadUint(32) !== DEDUST_V2_PAY_JETTON_OP) refuse(\"unknown-layout\", \"DeDust CPMM v2 forward payload is not pay_jetton#cbc33949\");\n const payment = f.loadRef().beginParse();\n const payout = f.loadRef().beginParse();\n end(f, \"DeDust CPMM v2 pay_jetton\");\n swap = decodeDeDustV2(payment, payout);\n pool = transfer!.destination.toString();\n }\n if (!receiverOk(swap.fulfill, ctx.dest, ctx.trader)) refuse(\"receiver-not-destination\", \"DeDust CPMM v2 fulfill destination\");\n if (!isTraderOrNone(swap.reject, ctx.trader)) refuse(\"refund-not-trader\", \"DeDust CPMM v2 reject destination\");\n if (!isTraderOrNone(swap.excessesTo, ctx.trader)) refuse(\"excess-not-trader\", \"DeDust CPMM v2 excesses\");\n minOut = swap.minOut;\n legs.push({kind: \"dedust-pool\", version: 2, pool, inputJetton: ctx.inputJetton, outputJetton: ctx.outputJetton});\n }\n minOk(minOut);\n return {layout, minOut, legs};\n}\n\nfunction sameJetton(a: string | null, b: string | null): boolean {\n if (a === null || b === null) return a === b;\n try {\n return Address.parse(a).equals(Address.parse(b));\n } catch {\n return false;\n }\n}\n","import \"./buffer-global.js\";\nimport {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {omniston as omnistonCfg} from \"./config.js\";\nimport {omnistonProvider, type OmnistonProviderOptions} from \"./provider.js\";\n\nexport interface OmnistonSwap2Config extends Swap2EngineConfig, OmnistonProviderOptions {}\n\nexport class OmnistonSwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n constructor(account: Swap2Account | undefined, config: OmnistonSwap2Config) {\n super(account, config);\n this.provider = omnistonProvider(config);\n }\n protected override chainSupported(caip2: string): boolean {\n // Network discovery is broad; provider.supportsRoute keeps the currently\n // audited execution direction (TON-source → EVM) fail-closed.\n return omnistonCfg.supportsChain(caip2);\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return this.provider.supportsRoute({chain: fromChain, token: \"\"}, {chain: toChain, token: \"\"});\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAAuC;AAQvC,IAAM,eAAe,oBAAI,IAAI,CAAC,GAAG,IAAI,KAAK,KAAK,KAAK,MAAM,MAAM,MAAM,OAAO,KAAK,CAAC;AAC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ACA,eAAS;AAAA,IACX;AAAA,EACF;AACF;;;AGxuFA,oBAAkC;AAO3B,IAAM,wBAAN,cAAoC,kCAAoB;AAAA,EAC1C;AAAA,EACnB,YAAY,SAAmC,QAA6B;AAC1E,UAAM,SAAS,MAAM;AACrB,SAAK,WAAW,iBAAiB,MAAM;AAAA,EACzC;AAAA,EACmB,eAAe,OAAwB;AAGxD,WAAO,SAAY,cAAc,KAAK;AAAA,EACxC;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,KAAK,SAAS,cAAc,EAAC,OAAO,WAAW,OAAO,GAAE,GAAG,EAAC,OAAO,SAAS,OAAO,GAAE,CAAC;AAAA,EAC/F;AACF;","names":["import_core","import_buffer","import_core","s","minOut","import_core","evmRef","TonAddress","viemHexToBytes","end","hashlock","Address","Cell","TonCell","raw","refuse"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/provider.ts","../src/activity.ts","../src/ton-swap.ts","../src/protocol.ts"],"sourcesContent":["import './buffer-global.js'\nexport * from \"./config.js\";\nexport * from \"./provider.js\";\nexport {OmnistonSwap2Protocol} from \"./protocol.js\";\nexport {OmnistonSwap2Protocol as default} from \"./protocol.js\";\nexport * from \"./activity.js\";\nexport type { OmnistonSwap2Config } from \"./protocol.js\"\n","import {evmRef, isEvm, namespace} from \"@anywalletkit/protocol-swap2-core/util\";\n\n// ── Omniston (STON.fi) — stable corridors over a WebSocket RFQ ───────────────\n// Operational matrix (docs.ston.fi \"Supported Chains\", re-checked 2026-10-20):\n// Arbitrum, Avalanche, Base, BNB, Ethereum, Polygon, Robinhood, X Layer (196),\n// HyperEVM (999), Plasma (9745), ARC (5042), TON, TRON. ARC waits for the asset\n// catalog; TRON needs its own order/position path. Live RFQ 2026-10-20: every\n// listed chain quotes against TON USDT both ways, and EVM↔EVM pairs quote too.\nconst OMNISTON_EVM = new Set([1, 56, 137, 196, 999, 4663, 8453, 9745, 42161, 43114]);\nexport const omniston = {\n enabled: () => true,\n integratorAddress: () => \"\",\n integratorFeePips: () => \"\",\n wsUrl: () => \"wss://omni-ws.ston.fi\",\n /** Per-swap USD cap — the resolver quotes the corridor up to ~$1000. */\n maxUsd: () => {\n return 1000;\n },\n supportsChain(chain: string): boolean {\n if (namespace(chain) === \"ton\") return true;\n return isEvm(chain) && OMNISTON_EVM.has(evmRef(chain));\n },\n // TON↔EVM and EVM↔EVM cross-chain (order settlement), TON↔TON same-chain\n // (swap settlement — immediate DEX routes). Same-chain EVM is not an order\n // corridor.\n supports(from: string, to: string): boolean {\n if (!this.supportsChain(from) || !this.supportsChain(to)) return false;\n const tonSide = namespace(from) === \"ton\" || namespace(to) === \"ton\";\n return tonSide || from !== to;\n },\n};\n","import {Address as TonAddress, Cell as TonCell} from \"@ton/core\";\nimport {describeOmnistonActivity} from \"./activity.js\";\nimport \"./buffer-global.js\";\nimport {Buffer} from \"buffer\";\nimport {encodeAbiParameters, getAddress, hexToBytes as viemHexToBytes, keccak256, sha256} from \"viem\";\nimport {ccAsset, ccAssetByToken, type CcAsset} from \"@anywalletkit/swap2-assets\";\nimport {omniston as cfg} from \"./config.js\";\nimport {checkTonSwapPayload, TonSwapPayloadError, type TonSwapCheckResult, type TonSwapLeg} from \"./ton-swap.js\";\nexport {checkTonSwapPayload, TonSwapPayloadError, TON_SWAP_PROTOCOL_LAYOUTS} from \"./ton-swap.js\";\nexport type {TonSwapLeg, TonSwapCheckInput, TonSwapCheckResult} from \"./ton-swap.js\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, RemotePins, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {bigintToNumber} from \"@anywalletkit/core\";\n\n/**\n * Omniston (STON.fi) — TON ↔ EVM stable corridors over a WebSocket RFQ\n * (`@ston-fi/omniston-sdk`), settled through HTLC orders (resolver `Arbiter`,\n * ~$1000/swap cap). This is the audited server/module-side adaptation; the\n * legacy browser-direct execution path is disabled.\n *\n * - getQuote: opens an RFQ stream, collects `quoteUpdated` for a short window,\n * returns the latest quote normalized to the engine `Quote`.\n * - buildDeposit (TON-source): generates the HTLC secret(s), persists them\n * in the injectable {@link HtlcSecretStore}, asks the SDK for the escrow\n * transfer and returns it as an `UnsignedTx` with a serialized cell body\n * (`bodyBoc`) — NOT a text memo.\n * - buildDeposit (EVM-source, EVM→TON): generates the secret, asks the SDK for\n * the EIP-712 order (Omniston's 1inch-LOP fork), verifies every signed byte\n * against the quote (order fields, extension, serialized order details) and\n * returns a gasless typed-order `UnsignedTx`; `registerSignedOrder` hands\n * the wallet's signature back to Omniston. Needs `trustedEvmOrderProtocols`\n * plus the EVM input-position and TON output-position validators.\n * - trackIntent: treats `orderTrack` only as a discovery hint and discloses a\n * pending secret only after independent finalized validation of the\n * counter-position (EVM escrow for TON→EVM; EVM source fill AND TON output\n * position for EVM→TON).\n *\n * CONSUMER CONTRACT — closing an intent is the caller's job. `trackIntent`\n * never returns a terminal refunded/failed state, not even on a reported\n * cancellation, because a resolver-controlled feed is not proof that the\n * signed source order can no longer fill. An integration without its own\n * chain-backed backstop will therefore report an already-refunded escrow as\n * pending indefinitely: close such intents by observing the exact input amount\n * returning from an allowlisted settlement contract to the trader's wallet.\n *\n * CONSUMER CONTRACT — `validateEvmOutputPosition` decides whether the swap can\n * complete at all, so verify what a resolver actually does on chain. It does\n * NOT call the escrow factory directly: the destination escrow is deployed\n * through the resolver's own contract, so the transaction targets that\n * contract, carries a private selector and usually sends no value, while the\n * factory only emits `DstEscrowCreated`. A verifier that expects a direct\n * `createDstEscrow` call therefore rejects every legitimate escrow, the secret\n * is never disclosed, and both positions roll back — which looks exactly like a\n * venue that quotes and walks away. Anchor on evidence the wrapper cannot\n * forge: the factory's own event for your hashlock, the escrow's `FACTORY()`,\n * and the balances it actually holds.\n *\n * The HTLC secret is the difference between \"swap completes\" and \"funds sit in\n * escrow until the refund timeout\". The default store is in-memory — fine for a\n * long-lived process, NOT for serverless. Callers on serverless MUST inject a\n * durable store.\n */\n\n/** CAIP-2 eip155 refs → the SDK's chain `$case` names. */\nconst EVM_CASE: Record<number, \"ethereum\" | \"bnb\" | \"base\" | \"arbitrum\" | \"avalanche\" | \"polygon\" | \"robinhood\" | \"xlayer\" | \"hyperevm\" | \"plasma\"> = {\n 1: \"ethereum\",\n 56: \"bnb\",\n 137: \"polygon\",\n 196: \"xlayer\",\n 999: \"hyperevm\",\n 4663: \"robinhood\",\n 8453: \"base\",\n 9745: \"plasma\",\n 42161: \"arbitrum\",\n 43114: \"avalanche\",\n};\n\nconst TON_NS = \"ton\";\nconst INTENT_PREFIX = \"omn1\";\n/** How long getQuote lets resolvers compete before taking the latest quote. */\nconst QUOTE_SETTLE_MS = 3_000;\n/**\n * Execution quotes settle far sooner than display ones. A resolver's\n * `tradeStartDeadline` is only ~25-30s away, and it is measured to the escrow\n * being ON-CHAIN — not to the broadcast — so every second spent collecting\n * competing offers is a second the source leg no longer has to be built,\n * signed, broadcast and included. A late escrow is not filled and sits until\n * the HTLC refunds, which costs the trader far more than the price difference\n * between the first quote and the best of a 3s auction on a stable corridor.\n */\nconst EXECUTION_SETTLE_MS = 600;\n/**\n * Refuse to build an escrow that cannot realistically reach the chain before\n * `tradeStartDeadline`: signing, broadcast and TON inclusion need roughly this\n * long, and funding a doomed escrow locks the trader's money until the HTLC\n * times out. Failing here is instant and costs nothing.\n */\nconst MIN_START_HEADROOM_MS = 12_000;\n/** Hard ceiling on waiting for the FIRST quote (router timeout is 8s). */\nconst QUOTE_MAX_MS = 6_500;\n/** One orderTrack snapshot per trackIntent call. */\nconst TRACK_SNAPSHOT_MS = 6_000;\n// One execution: the live TON escrow commits a single hash and the EVM order is\n// single-fill, so more secrets only make the TON payload validator refuse.\nconst DEFAULT_MAX_HTLC_EXECUTIONS = 1;\n/** Normalized quote validity shown to the router/UI. */\nconst QUOTE_TTL_MS = 45_000;\n/** Quote/security context must outlive delayed fills and cancellation signals. */\nconst CACHE_TTL_MS = 6 * 60 * 60 * 1000;\n/**\n * Context entries written before intent binding (scan F3/F15) carry no bound\n * trader/dest/srcChain/kind. They are honoured — with a `legacy-intent` trace —\n * only while younger than this (the store TTL), then disclosure is refused.\n */\nconst LEGACY_INTENT_WINDOW_MS = 6 * 60 * 60 * 1000;\n\n// ── HTLC secret store (injectable) ───────────────────────────────────────────\n\n/**\n * Persists HTLC secret preimages by quoteId between buildDeposit and the\n * trackIntent poll that discloses them. Losing a secret does NOT lose funds —\n * the escrow refunds after the HTLC timeout — but it does fail the swap.\n */\nexport interface HtlcSecretStore {\n save(quoteId: string, secretsHex: string[]): void | Promise<void>;\n load(quoteId: string): string[] | undefined | Promise<string[] | undefined>;\n clear(quoteId: string): void | Promise<void>;\n}\n\n/**\n * Persists the quote/build context between getQuote, buildDeposit and\n * registerSignedOrder. On SERVERLESS these run on different instances, so the\n * default in-memory map strands executions (\"quote expired\") — inject a\n * durable store there. Values are JSON-safe (byte fields base64-encoded).\n */\nexport interface OmnistonQuoteStore {\n save(quoteId: string, valueJson: string): void | Promise<void>;\n load(quoteId: string): string | undefined | Promise<string | undefined>;\n clear(quoteId: string): void | Promise<void>;\n /**\n * Save only if nothing is stored under `quoteId` yet, atomically (Redis `SET NX`, a KV conditional put): true when\n * this call wrote it. A quote id is the platform's choice, so a context must never be overwritten by another user's\n * quote under the same id (scan 2026-10-27 modules, F27). Without it the provider checks then saves — fine for one\n * process, racy across instances.\n */\n claim?(quoteId: string, valueJson: string): boolean | Promise<boolean>;\n}\n\n/** Default quote store — long-lived processes and tests only. */\nexport function inMemoryQuoteStore(): OmnistonQuoteStore {\n const map = new Map<string, string>();\n return {\n save: (id, v) => void map.set(id, v),\n load: (id) => map.get(id),\n clear: (id) => void map.delete(id),\n claim: (id, v) => { if (map.has(id)) return false; map.set(id, v); return true; },\n };\n}\n\n/** Default store — suitable for long-lived processes and tests only. */\nexport function inMemorySecretStore(): HtlcSecretStore {\n const map = new Map<string, string[]>();\n return {\n save: (id, secrets) => void map.set(id, secrets),\n load: (id) => map.get(id),\n clear: (id) => void map.delete(id),\n };\n}\n\n// ── Minimal structural view of the SDK client (injectable for tests) ─────────\n\nexport interface ObservableLike<T> {\n subscribe(observer: {next?: (value: T) => void; error?: (err: unknown) => void; complete?: () => void}): {unsubscribe(): void};\n}\n\n/** Self-contained structural SDK types. Keeping these local prevents the\n * optional Omniston peer from leaking into every consumer's declaration graph. */\nexport interface AssetId {\n chain: {\n $case: string;\n value: string | {kind?: {$case: string; value?: unknown}};\n };\n}\n\nexport interface ChainAddress {\n chain: {$case: string; value: string};\n}\n\nexport interface QuoteRequest {\n inputAsset: AssetId;\n outputAsset: AssetId;\n amount: {$case: string; value: string};\n settlementParams: {params: {$case: string; value: Record<string, unknown>}}[];\n integratorAddress?: ChainAddress;\n integratorFeePips?: number;\n}\n\nexport interface OmnistonQuote {\n rfqId: string;\n quoteId: string;\n inputAsset: AssetId;\n outputAsset: AssetId;\n inputUnits: string;\n outputUnits: string;\n protocolFeeUnits?: string;\n integratorFeeUnits?: string;\n integratorAddress?: ChainAddress;\n quoteTimestamp: number;\n /** Total TON the trade needs on top of the input (swap settlement); omitted for gasless quotes. */\n gasBudget?: string | undefined;\n /** Omniston's estimate of the gas the route actually burns (swap settlement); the rest of the budget returns. */\n estimatedGasConsumption?: string | undefined;\n settlementData: {$case: \"order\"; value: OrderSettlement} | {$case: \"swap\"; value: SwapSettlement};\n}\n\n/** Order settlement (HTLC / escrow) — the cross-chain branch. */\nexport interface OrderSettlement {\n srcProtocolContractAddress: ChainAddress;\n dstProtocolContractAddress?: ChainAddress;\n srcInitialResolverAddress?: ChainAddress;\n resolverSendsUnits: string;\n srcHtlcSecurityDepositUnits?: string;\n dstSecurityDepositUnits?: string;\n tradeStartDeadline: number;\n /**\n * Seconds after the trader creates the position before a resolver must\n * reserve it; after that the position is withdrawable by the trader (SDK\n * docs). The TON escrow config carries it, so the payload validator binds\n * the built escrow to the quoted value.\n */\n exclusivityTimeout?: number;\n htlcHashingFunction?: string;\n /** Fee profile the EVM order extension must mirror (EVM-source orders). */\n protocolFeePips?: number;\n integratorFeePips?: number;\n /** Destination-chain wallet the protocol fee must be paid to (EVM-destination\n * orders); the EVM output validator binds the escrow's fee split to it. */\n protocolFeeRecipientAddress?: ChainAddress;\n}\n\n/** Swap settlement — immediate DEX routes, the TON same-chain branch. */\nexport interface SwapSettlement {\n routes: {steps: {inputAsset?: AssetId; outputAsset?: AssetId; chunks: {protocol: string; inputUnits: string; outputUnits: string}[]}[]}[];\n minOutputAmount: string;\n recommendedMinOutputAmount?: string;\n recommendedSlippagePips?: number;\n priceImpactPips?: number | undefined;\n}\n\nexport type RfqEvent =\n | {$case: \"ack\"; value: {rfqId: string}}\n | {$case: \"quoteUpdated\"; rfqId?: string; value: OmnistonQuote}\n | {$case: \"noQuote\"; rfqId?: string; value: unknown}\n | {$case: string; value?: unknown};\n\nexport interface EscrowMessage {\n targetAddress: string;\n sendAmount: string;\n payload: string; // hex-encoded cell BoC\n jettonWalletStateInit?: string | undefined;\n}\n\nexport interface OrderExecution {\n index: number;\n inputUnits: string;\n outputUnits: string;\n resolverSendsUnits: string;\n secretHash?: Uint8Array | undefined;\n inputPositionPhase?: string | undefined;\n inputPositionAddress?: ChainAddress | undefined;\n outputPositionPhase?: string | undefined;\n outputPositionAddress?: ChainAddress | undefined;\n}\n\nexport interface OrderSnapshot {\n status: string;\n executions: OrderExecution[];\n}\n\nexport type OrderEvent = {$case: \"order\"; value: OrderSnapshot} | {$case: string; value?: unknown};\n\nexport type SwapTrackEvent =\n | {$case: \"awaitingTransfer\"; value?: unknown}\n | {$case: \"progress\"; value: {status: string; outgoingTxHash?: string}}\n | {$case: string; value?: unknown};\n\n/** The slice of `Omniston` this provider uses — a real instance satisfies it. */\nexport interface OmnistonClientLike {\n requestForQuote(request: QuoteRequest): ObservableLike<RfqEvent>;\n tonBuildEscrowTransfer(request: {\n quoteId: string;\n ownerSrcAddress: ChainAddress;\n transferSrcAddress: ChainAddress;\n refundSrcAddress: ChainAddress;\n gasExcessAddress: ChainAddress;\n traderDstAddress: ChainAddress;\n htlcSecrets: {secretMode: {$case: \"provided\"; value: {hashes: Uint8Array[]}}};\n }): Promise<{messages: EscrowMessage[]}>;\n evmBuildOrderPayload(request: {\n quoteId: string;\n ownerSrcAddress: ChainAddress;\n traderDstAddress?: ChainAddress;\n htlcSecrets?: {secretMode: {$case: \"provided\"; value: {hashes: Uint8Array[]}}};\n }): Promise<{typedData: string; orderExtension: Uint8Array; serializedOrderDetails?: Uint8Array | undefined}>;\n orderRegisterSignedOrder(request: {\n quoteId: string;\n ownerSrcAddress: ChainAddress;\n signedOrder: {order: {$case: \"evmV1\"; value: {encodedOrder: Uint8Array; signature: Uint8Array; orderExtension: Uint8Array}}};\n serializedOrderDetails?: Uint8Array | undefined;\n }): Promise<void>;\n /** Swap settlement (TON↔TON). Optional so older injected clients keep working; without them same-chain swaps fail closed. */\n tonBuildSwap?(request: {\n quoteId: string;\n transferSrcAddress: ChainAddress;\n refundSrcAddress: ChainAddress;\n gasExcessAddress: ChainAddress;\n traderDstAddress: ChainAddress;\n useRecommendedSlippage?: boolean;\n }): Promise<{messages: EscrowMessage[]}>;\n swapTrack?(request: {quoteId: string; traderAddress: ChainAddress; outgoingTxQuery: string}): ObservableLike<SwapTrackEvent>;\n orderTrack(request: {quoteId: string; traderAddress: ChainAddress}): ObservableLike<OrderEvent>;\n orderDiscloseHtlcSecret(request: {quoteId: string; executionIndex: number; secret: Uint8Array}): Promise<void>;\n close?: () => void;\n transport?: {close(): void};\n}\n\nexport interface OmnistonProviderOptions {\n /** Injected SDK client (tests); defaults to a lazy `new Omniston({apiUrl})`. */\n client?: OmnistonClientLike;\n /** WebSocket API URL; defaults to the public ston.fi endpoint. */\n apiUrl?: string;\n /** HTLC preimage persistence; defaults to in-memory (NOT serverless-safe). */\n secretStore?: HtlcSecretStore;\n /** Quote/build context persistence; defaults to in-memory (NOT serverless-safe). */\n quoteStore?: OmnistonQuoteStore;\n /** Maximum number of HTLC execution attempts covered by generated secrets. */\n maxHtlcExecutions?: number;\n /** Hard cap for resolver-requested TON gas/forward value (default: 2 TON). */\n maxTonExecutionNano?: string;\n /** Resolver competition window; primarily useful for deterministic tests. */\n quoteSettleMs?: number;\n /** Explicit constructor configuration; no deployment environment is read. */\n enabled?: boolean;\n /** Exact decimal USD cap; string form avoids binary-float rounding. */\n maxUsd?: number | string;\n integratorAddress?: string;\n integratorFeePips?: number;\n /** Independently trusted settlement contracts, keyed by CAIP-2 chain. */\n trustedSettlementContracts?: Readonly<Record<string, readonly string[]>>;\n /**\n * Independently trusted EVM order protocols — the Omniston fork of the 1inch\n * Limit Order Protocol an EVM-source order is signed against and that moves\n * the input token on fill — keyed by CAIP-2 chain. Kept apart from\n * `trustedSettlementContracts` because one address plays different roles on\n * different chains (0xafCF… is the escrow factory on Ethereum and the order\n * protocol on Polygon). EVM→TON is advertised only for chains listed here.\n */\n trustedEvmOrderProtocols?: Readonly<Record<string, readonly string[]>>;\n /**\n * RPC-backed TON jetton-wallet verification. A TON-source order is rejected\n * when this hook is absent or does not prove that `walletAddress` belongs to\n * the quoted jetton master for `ownerAddress`.\n */\n validateTonJettonWallet?: (input: {\n ownerAddress: string;\n jettonMasterAddress: string;\n walletAddress: string;\n }) => boolean | Promise<boolean>;\n /**\n * Independent semantic verifier for the Omniston TON escrow forward cell.\n * The resolver-built BoC is never accepted through byte-search heuristics.\n * A TON-source route is disabled unless this hook parses the documented\n * contract schema and proves every expected field below in its exact slot.\n */\n /**\n * TON↔TON swap settlement: independently confirm that the contract a swap\n * message pays into — directly for native GRAM, as the jetton-transfer\n * destination for jettons — is a DEX contract of a protocol the quote named\n * (e.g. by its code interface on an indexer). Without it, same-chain TON\n * swaps are not advertised.\n */\n validateTonSwapTarget?: (input: {address: string; protocols: readonly string[]}) => Promise<boolean> | boolean;\n /**\n * TON↔TON swap settlement (scan F11): confirm one chain fact the decoded\n * swap body depends on — that a STON.fi hop's ask wallet is its router's\n * wallet of the quoted output (and, for native input, that the pTON wallet\n * the message pays belongs to that router), or that a DeDust pool trades the\n * quoted pair. `createOmnistonTonValidators` supplies it. When absent the\n * decoded-body rules still apply and each skipped leg is traced as\n * `ton-swap-payload legs-unverified`; STON.fi v1 native input (pTON v1) is\n * refused without it.\n */\n validateTonSwapLeg?: (leg: TonSwapLeg) => Promise<boolean> | boolean;\n /**\n * TON↔TON swap settlement (scan F11): what a built swap body that fails the\n * decoder (receiver ≠ destination, refund/excess ≠ trader, on-chain minimum\n * below the quote, unknown layout, unverifiable leg) does. \"enforce\"\n * (default) refuses the build; \"report\" traces `ton-swap-payload <reason>`\n * and still builds — a rollout escape hatch, not a steady state.\n */\n tonSwapPayloadCheck?: \"report\" | \"enforce\";\n validateTonEscrowPayload?: (input: {\n payloadBocHex: string;\n forwardPayloadBocHex: string;\n quoteId: string;\n inputUnits: string;\n resolverSendsUnits: string;\n srcHtlcSecurityDepositUnits: string;\n protocolAddress: string;\n ownerAddress: string;\n destinationChain: string;\n destinationAddress: string;\n outputTokenAddress: string;\n initialResolverAddress: string;\n secretHashes: readonly Uint8Array[];\n hashingFunction?: string;\n /** The quote's `exclusivityTimeout` (seconds) the escrow config must carry. */\n exclusivityTimeout: number;\n }) => boolean | Promise<boolean>;\n /**\n * RPC-backed proof of the destination EVM escrow. The tracking feed is only\n * a discovery hint: no HTLC preimage is disclosed until this hook proves the\n * independently finalized on-chain position matches the signed quote.\n */\n validateEvmOutputPosition?: (input: {\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 chain). */\n protocolFeeRecipientAddress?: string;\n secretHash: Uint8Array;\n }) => boolean | Promise<boolean>;\n /**\n * RPC-backed proof of the finalized EVM source position (EVM→TON). The\n * tracking feed only hints at the address; no secret is disclosed until this\n * hook proves — from the trusted factory's own `SrcEscrowCreated` event, the\n * deterministic escrow address and the escrow's balances — that the\n * trader's FULL input is locked for this hashlock under the quoted terms\n * (owner, token, amount, resolver, deposit, timelocks, TON output amount).\n */\n validateEvmInputPosition?: (input: {\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 escrow event's destination complement must name this chain, token and deposit. */\n destinationChainId?: number;\n destinationTokenAddress?: string;\n dstSecurityDepositUnits?: string;\n }) => boolean | Promise<boolean>;\n /**\n * Indexer/RPC-backed proof of the TON output position (EVM→TON): deployed by\n * the trusted factory for THIS quote, pinned position/escrow code, hashlock,\n * recipient, amount, security deposit, and a cancellation boundary still far\n * enough away to complete. The tracking feed is only a discovery hint.\n */\n validateTonOutputPosition?: (input: {\n positionAddress: string;\n protocolAddress: string;\n outputJettonMasterAddress: string;\n recipientAddress: string;\n quoteId: string;\n quoteTimestamp: number;\n inputUnits: string;\n outputUnits: string;\n resolverSendsUnits: string;\n dstSecurityDepositUnits: string;\n secretHash: Uint8Array;\n }) => boolean | Promise<boolean>;\n /**\n * EVM destination: find the delivery transaction — the destination escrow's\n * payout to the recipient — so a completed order carries `destTxHash`.\n * Omniston's tracking feed names the escrow but not that transaction.\n */\n locateEvmDelivery?: (input: {\n chain: string;\n positionAddress: string;\n recipientAddress: string;\n tokenAddress: string;\n minUnits: string;\n }) => Promise<string | null>;\n /**\n * TON destination: find the delivery — the output position's jetton transfer\n * to the recipient — so a completed EVM → TON order carries `destTxHash` in\n * the form the TON history source uses (tonapi event id). Without it the\n * wallet's feed cannot pair the TON receive with the swap.\n */\n locateTonDelivery?: (input: {\n positionAddress: string;\n recipientAddress: string;\n jettonMasterAddress: string;\n minUnits: string;\n }) => Promise<string | null>;\n /** Close an injected client when the provider closes (default: caller owns it). */\n closeInjectedClient?: boolean;\n /**\n * Diagnostics: why a poll did not disclose (`disclosure-skipped` with the gate\n * and its fields, `validator-refused`, `validator-threw`) and when it did\n * (`secret-disclosed`). Never carries secrets. Wire it to your logger: a\n * silent \"pending\" cost a live order its 2-minute window (2026-10-20).\n */\n trace?: (event: string, details?: Record<string, unknown>) => void;\n}\n\n// ── Chain / asset mapping ────────────────────────────────────────────────────\n\nfunction evmRef(caip2: string): number | null {\n if (!caip2.startsWith(\"eip155:\")) return null;\n const n = Number(caip2.slice(\"eip155:\".length));\n return Number.isInteger(n) ? n : null;\n}\n\nfunction isTon(caip2: string): boolean {\n return caip2.split(\":\")[0] === TON_NS;\n}\n\nfunction caipForChainCase($case: string): string | null {\n if ($case === \"ton\") return \"ton:-239\";\n const entry = Object.entries(EVM_CASE).find(([, value]) => value === $case);\n return entry ? `eip155:${entry[0]}` : null;\n}\n\n/** Catalog asset → SDK AssetId. Stable corridors only: a `contract` is REQUIRED\n * (jetton master / ERC-20) — native assets have no Omniston order corridor. */\nfunction toAssetId(caip2: string, asset: CcAsset, allowNative = false): AssetId | null {\n if (!asset.contract) {\n // Native GRAM only exists on the swap-settlement branch (same-chain DEX routes).\n return allowNative && isTon(caip2) ? {chain: {$case: \"ton\", value: {kind: {$case: \"native\", value: {}}}}} : null;\n }\n if (isTon(caip2)) {\n return {chain: {$case: \"ton\", value: {kind: {$case: \"jetton\", value: asset.contract}}}};\n }\n const ref = evmRef(caip2);\n const $case = ref === null ? undefined : EVM_CASE[ref];\n if (!$case) return null;\n return {chain: {$case, value: {kind: {$case: \"erc20\", value: getAddress(asset.contract)}}}};\n}\n\nfunction toChainAddress(caip2: string, address: string): ChainAddress | null {\n if (isTon(caip2)) return {chain: {$case: \"ton\", value: address}};\n const ref = evmRef(caip2);\n const $case = ref === null ? undefined : EVM_CASE[ref];\n if (!$case) return null;\n return {chain: {$case, value: getAddress(address)}};\n}\n\n// ── intentId: quoteId + the trader/dest context tracking and building need ───\n\nfunction encodeIntent(quoteId: string, trader: string, dest: string, srcChain: string, kind: \"order\" | \"swap\" = \"order\"): string {\n // Swap-settlement intents carry a sixth segment so tracking can branch\n // without the (TTL-bound) quote cache; order intents keep the legacy shape.\n return [INTENT_PREFIX, quoteId, trader, dest, srcChain, ...(kind === \"swap\" ? [\"swap\"] : [])].map(encodeURIComponent).join(\"|\");\n}\n\n/**\n * A quote id is a 256-bit value in hex WITHOUT leading-zero padding (live\n * 2026-10-12: 63-char ids, ~1 in 16 quotes) — requiring exactly 64 chars\n * refused those as \"malformed quote id\". Binary comparisons pad it to 32 bytes.\n */\nconst QUOTE_ID = /^[0-9a-fA-F]{48,64}$/;\n\nfunction decodeIntent(\n intentId: string,\n): {quoteId: string; trader: string; dest: string; srcChain: string; kind: \"order\" | \"swap\"} | null {\n try {\n const parts = intentId.split(\"|\");\n if ((parts.length !== 5 && parts.length !== 6) || parts[0] !== INTENT_PREFIX) return null;\n const [, quoteId = \"\", trader = \"\", dest = \"\", srcChain = \"\", kindPart = \"\"] = parts.map(decodeURIComponent);\n if (!QUOTE_ID.test(quoteId) || !trader || !dest || !srcChain) return null;\n if (parts.length === 6 && kindPart !== \"swap\") return null;\n return {quoteId, trader, dest, srcChain, kind: parts.length === 6 ? \"swap\" : \"order\"};\n } catch {\n return null;\n }\n}\n\n/**\n * What an intentId was minted for, persisted with the quote at getQuote time\n * (scan F3/F15). The intentId itself is an unsigned caller-supplied string: the\n * stored copy — never the decoded one — names the trader and recipient the\n * secret-release validators, the builders and the delivery locators check.\n */\ninterface IntentBinding {\n trader: string;\n dest: string;\n srcChain: string;\n kind: \"order\" | \"swap\";\n}\n\n/** Same address in another spelling: EVM case-insensitive, TON any notation. */\nfunction sameIntentAddress(a: string, b: string): boolean {\n if (a === b) return true;\n const evm = /^0x[0-9a-fA-F]{40}$/;\n if (evm.test(a) || evm.test(b)) return evm.test(a) && evm.test(b) && a.toLowerCase() === b.toLowerCase();\n try {\n return TonAddress.parse(a).equals(TonAddress.parse(b));\n } catch {\n return false;\n }\n}\n\n/** EIP-712 typed data → the ABI-encoded order struct `SignedOrderEvmV1` wants.\n * Structs referenced in `types` become tuples, recursively. */\nexport function encodeTypedMessage(td: {\n types: Record<string, {name: string; type: string}[]>;\n primaryType: string;\n message: unknown;\n}): Uint8Array {\n type AbiParam = {type: string; name?: string; components?: AbiParam[]};\n const paramFor = (typeName: string, name?: string): AbiParam => {\n const isArray = typeName.endsWith(\"[]\");\n const base = isArray ? typeName.slice(0, -2) : typeName;\n const fields = td.types[base];\n if (!fields) return {type: typeName, ...(name ? {name} : {})};\n return {\n type: isArray ? \"tuple[]\" : \"tuple\",\n ...(name ? {name} : {}),\n components: fields.map((f) => paramFor(f.type, f.name)),\n };\n };\n return viemHexToBytes(\n encodeAbiParameters([paramFor(td.primaryType)] as never, [td.message] as never),\n );\n}\n\n// ── HTLC helpers (ported from app/lib/omniston/htlc.ts) ──────────────────────\n\nfunction generateSecret(): Uint8Array {\n return crypto.getRandomValues(new Uint8Array(32));\n}\n\nfunction hashlock(secret: Uint8Array, hashingFunction: string | undefined): Uint8Array {\n switch (hashingFunction) {\n case \"HASHING_FUNCTION_KECCAK256\":\n return keccak256(secret, \"bytes\");\n case \"HASHING_FUNCTION_SHA256\":\n return sha256(secret, \"bytes\");\n default:\n throw new Error(`omniston: unsupported HTLC hashing function ${String(hashingFunction)}`);\n }\n}\n\nfunction sameAsset(a: AssetId, b: AssetId): boolean {\n const key = (asset: AssetId): string => {\n const chain = asset.chain;\n const value = chain.value as {kind?: {$case: string; value?: unknown}} | string;\n const normalize = (text: string) => chain.$case === \"ton\" ? text : text.toLowerCase();\n if (typeof value === \"string\") return `${chain.$case}:${normalize(value)}`;\n const kind = value.kind;\n return `${chain.$case}:${kind?.$case ?? \"\"}:${typeof kind?.value === \"string\" ? normalize(kind.value) : JSON.stringify(kind?.value ?? null)}`;\n };\n return key(a) === key(b);\n}\n\nfunction sameChainAddress(a: ChainAddress | undefined, b: ChainAddress | undefined): boolean {\n if (a === undefined || b === undefined) return a === b;\n if (a.chain.$case !== b.chain.$case) return false;\n if (a.chain.$case !== \"ton\") return a.chain.value.toLowerCase() === b.chain.value.toLowerCase();\n // The SDK may echo a TON address in another notation (EQ…/UQ…/raw).\n try {\n return TonAddress.parse(a.chain.value).equals(TonAddress.parse(b.chain.value));\n } catch {\n return a.chain.value === b.chain.value;\n }\n}\n\nfunction assetContract(asset: AssetId): string | null {\n const value = asset.chain.value;\n if (typeof value === \"string\") return null;\n const kind = value.kind;\n return kind && typeof kind.value === \"string\" ? kind.value : null;\n}\n\n/** A route step's asset as a jetton master (null = native GRAM, undefined = not stated). */\nfunction stepJetton(asset: AssetId | undefined): string | null | undefined {\n if (!asset || asset.chain.$case !== \"ton\" || typeof asset.chain.value === \"string\") return undefined;\n const kind = asset.chain.value.kind;\n if (kind?.$case === \"native\") return null;\n return kind?.$case === \"jetton\" && typeof kind.value === \"string\" ? kind.value : undefined;\n}\n\nfunction readBigEndian(bytes: Uint8Array, offset: number, length: number): bigint {\n if (!Number.isInteger(offset) || !Number.isInteger(length) || length < 1 || offset < 0 || offset + length > bytes.length) {\n throw new Error(\"omniston: truncated EVM order extension\");\n }\n let value = 0n;\n for (let index = offset; index < offset + length; index++) value = (value << 8n) | BigInt(bytes[index]!);\n return value;\n}\n\nfunction sliceEqual(a: Uint8Array, b: Uint8Array): boolean {\n return a.length === b.length && a.every((value, index) => value === b[index]);\n}\n\nfunction zeroBytes(bytes: Uint8Array): boolean {\n return bytes.every((value) => value === 0);\n}\n\n/** `value` within [center - before, center + after] (seconds). */\nfunction within(value: bigint, center: number, before: number, after: number): boolean {\n return value >= BigInt(center - before) && value <= BigInt(center + after);\n}\n\nconst ORDER_FIELDS = [\n [\"salt\", \"uint256\"],\n [\"maker\", \"address\"],\n [\"receiver\", \"address\"],\n [\"makerAsset\", \"address\"],\n [\"takerAsset\", \"address\"],\n [\"makingAmount\", \"uint256\"],\n [\"takingAmount\", \"uint256\"],\n [\"makerTraits\", \"uint256\"],\n] as const;\n\nfunction validUint256(value: unknown): boolean {\n try {\n const n = BigInt(value as string | number | bigint);\n return n >= 0n && n < 1n << 256n;\n } catch {\n return false;\n }\n}\n\nfunction validEvmAddress(value: unknown): boolean {\n try {\n getAddress(String(value));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * The protocol-fee recipient Omniston names in the post-interaction of\n * EVM-destination orders (live 2026-10-20: the same EOA on Base→Arbitrum and\n * Plasma→Base; TON-destination orders still carry zero). It only receives the\n * quoted protocol fee — what the trader gives and gets is bound elsewhere — but\n * it is pinned so an unexpected recipient fails closed.\n */\nconst EVM_DEST_PROTOCOL_FEE_RECIPIENTS = new Set([\"0x076268146b4ec6d21fc49c27586cfa91b9079a00\"]);\n\n/**\n * Strict decoder for the currently observed Omniston v1beta8 EVM→TON 1inch\n * extension profile. It deliberately rejects unknown auction/fee/timelock\n * profiles: signing a merely well-formed extension is not enough because the\n * resolver-controlled tail contains the actual on-chain HTLC terms.\n *\n * This binds what the wallet signs to the quote; it does not by itself make\n * the swap complete. Secret disclosure additionally needs the independently\n * finalized EVM source-fill and TON output-position proofs (trackIntent).\n * `dstSecurityDepositUnits` is the value the EVM deposits word carries — for a\n * TON destination that word is 0 (the TON deposit is bound in the TON position).\n */\nexport async function validateEvmToTonOrderExtension(\n extension: Uint8Array,\n expected: {\n quoteId: string;\n quoteTimestamp: number;\n tradeStartDeadline: number;\n protocolFeePips: number;\n integratorFeePips: number;\n initialResolverAddress: string;\n outputTokenAddress: string;\n traderDstAddress: string;\n takerAsset: string;\n srcSecurityDepositUnits: string;\n dstSecurityDepositUnits: string;\n secretHash: Uint8Array;\n trustedTarget: (address: string) => boolean;\n /** EVM destination (EIP-155 id): ExtraDataArgs carry it and the destination\n * ERC-20 (`outputTokenAddress`, `traderDstAddress` are EVM then). Absent = TON. */\n dstChainId?: number;\n },\n): Promise<void> {\n const evmDest = expected.dstChainId !== undefined;\n if (evmDest && (!Number.isSafeInteger(expected.dstChainId) || expected.dstChainId! <= 0)) throw new Error(\"omniston: invalid EVM destination chain id\");\n if (extension.length < 32) throw new Error(\"omniston: malformed EVM order extension\");\n const view = new DataView(extension.buffer, extension.byteOffset, extension.byteLength);\n const fields: Uint8Array[] = [];\n let begin = 0;\n const concatLength = extension.length - 32;\n for (let index = 0; index < 8; index++) {\n const end = view.getUint32(28 - index * 4, false);\n if (end < begin || end > concatLength) throw new Error(\"omniston: malformed EVM order extension offsets\");\n fields.push(extension.slice(32 + begin, 32 + end));\n begin = end;\n }\n // Omniston's audited 1inch profile uses only amount getters (2/3) and a\n // post-interaction (7). Suffixes can alter token calls; permit/predicate/pre\n // interaction are separate programs and are not authorized by this adapter.\n for (const index of [0, 1, 4, 5, 6]) {\n if (fields[index]!.length !== 0) throw new Error(\"omniston: unsupported EVM order extension field\");\n }\n if (!sliceEqual(fields[2]!, fields[3]!)) {\n throw new Error(\"omniston: making/taking amount getters use different programs\");\n }\n let target: string | undefined;\n for (const index of [2, 3, 7]) {\n const field = fields[index]!;\n if (field.length <= 20) throw new Error(\"omniston: incomplete EVM order extension program\");\n const address = getAddress(`0x${bytesToHex(field.slice(0, 20))}`);\n if (!expected.trustedTarget(address) || (target !== undefined && getAddress(target) !== address)) {\n throw new Error(\"omniston: EVM order extension target is not independently trusted\");\n }\n target = address;\n }\n\n // SimpleSettlement auction + AmountGetterWithFee. The current trader quote\n // does not describe the curve, so only the audited live v1beta8 profile is\n // accepted. A contract/profile upgrade must add a new explicit decoder.\n const getter = fields[2]!;\n let cursor = 20;\n const gasBump = readBigEndian(getter, cursor, 3); cursor += 3;\n const gasPrice = readBigEndian(getter, cursor, 4); cursor += 4;\n const auctionStart = readBigEndian(getter, cursor, 4); cursor += 4;\n const duration = readBigEndian(getter, cursor, 3); cursor += 3;\n const initialRateBump = readBigEndian(getter, cursor, 3); cursor += 3;\n const pointCount = bigintToNumber(readBigEndian(getter, cursor, 1)); cursor += 1;\n if (pointCount !== 5) throw new Error(\"omniston: unsupported EVM auction profile\");\n const points: [bigint, bigint][] = [];\n for (let index = 0; index < pointCount; index++) {\n points.push([readBigEndian(getter, cursor, 3), readBigEndian(getter, cursor + 3, 2)]);\n cursor += 5;\n }\n const integratorFee = readBigEndian(getter, cursor, 2); cursor += 2;\n const integratorShare = readBigEndian(getter, cursor, 1); cursor += 1;\n const resolverFee = readBigEndian(getter, cursor, 2); cursor += 2;\n const whitelistDiscount = readBigEndian(getter, cursor, 1); cursor += 1;\n const getterWhitelistCount = bigintToNumber(readBigEndian(getter, cursor, 1)); cursor += 1;\n if (getterWhitelistCount !== 1 || cursor + getterWhitelistCount * 10 !== getter.length) {\n throw new Error(\"omniston: malformed EVM amount-getter whitelist\");\n }\n const getterResolver = readBigEndian(getter, cursor, 10);\n const expectedPoints = [[800000n, 100n], [700000n, 100n], [600000n, 100n], [500000n, 100n], [400000n, 100n]];\n const quoteResolverFee = expected.protocolFeePips % 10 === 0 ? BigInt(expected.protocolFeePips / 10) : -1n;\n const resolverLow80 = BigInt(getAddress(expected.initialResolverAddress)) & ((1n << 80n) - 1n);\n if (\n gasBump !== 0n || gasPrice !== 0n || !within(auctionStart, expected.quoteTimestamp, 5, 5) ||\n duration !== 1800n || initialRateBump !== 900000n ||\n points.some((point, index) => point[0] !== expectedPoints[index]![0] || point[1] !== expectedPoints[index]![1]) ||\n expected.integratorFeePips !== 0 || integratorFee !== 0n || integratorShare !== 100n ||\n quoteResolverFee < 0n || resolverFee !== quoteResolverFee || whitelistDiscount !== 50n ||\n getterResolver !== resolverLow80\n ) {\n throw new Error(\"omniston: EVM amount-getter terms do not match the pinned v1beta8 profile\");\n }\n\n // BaseEscrowFactory postInteraction: exact fee/whitelist prefix followed by\n // five uint256 ExtraDataArgs words. Unknown recipients and trailing bytes are\n // rejected because the corresponding EVM→TON mapping is not public.\n // `allowedTime` is stamped by the resolver a few seconds BEFORE the quote\n // timestamp (live 2026-10-16: 14–18 s on every chain); the auction start is\n // the quote timestamp (±1 s on Polygon). Both windows are bounded.\n const post = fields[7]!;\n cursor = 20;\n const integratorRecipient = post.slice(cursor, cursor + 20); cursor += 20;\n const protocolRecipient = post.slice(cursor, cursor + 20); cursor += 20;\n const postIntegratorFee = readBigEndian(post, cursor, 2); cursor += 2;\n const postIntegratorShare = readBigEndian(post, cursor, 1); cursor += 1;\n const postResolverFee = readBigEndian(post, cursor, 2); cursor += 2;\n const postDiscount = readBigEndian(post, cursor, 1); cursor += 1;\n const allowedTime = readBigEndian(post, cursor, 4); cursor += 4;\n const whitelistCount = bigintToNumber(readBigEndian(post, cursor, 1)); cursor += 1;\n if (whitelistCount !== 1 || cursor + whitelistCount * 12 + 160 !== post.length) {\n throw new Error(\"omniston: malformed EVM post-interaction whitelist\");\n }\n const postResolver = readBigEndian(post, cursor, 10); cursor += 10;\n const resolverTimeDelta = readBigEndian(post, cursor, 2); cursor += 2;\n if (\n !zeroBytes(integratorRecipient) || !(zeroBytes(protocolRecipient) || (evmDest && EVM_DEST_PROTOCOL_FEE_RECIPIENTS.has(`0x${bytesToHex(protocolRecipient)}`))) ||\n postIntegratorFee !== 0n || postIntegratorShare !== 100n || postResolverFee !== quoteResolverFee ||\n postDiscount !== 50n || !within(allowedTime, expected.quoteTimestamp, 60, 5) ||\n postResolver !== resolverLow80 || resolverTimeDelta !== 0n\n ) {\n throw new Error(\"omniston: EVM post-interaction terms do not match the pinned v1beta8 profile\");\n }\n const extra = Array.from({length: 5}, () => {\n const value = readBigEndian(post, cursor, 32);\n cursor += 32;\n return value;\n });\n const hashlock = readBigEndian(expected.secretHash, 0, expected.secretHash.length);\n // ExtraDataArgs word 2 is the destination token: the real ERC-20 for an EVM\n // destination, the order's takerAsset placeholder for TON.\n const dstToken = evmDest ? BigInt(getAddress(expected.outputTokenAddress)) : BigInt(getAddress(expected.takerAsset));\n const deposits = (BigInt(expected.srcSecurityDepositUnits) << 128n) | BigInt(expected.dstSecurityDepositUnits);\n const timelocks = [1n, 120n, 240n, 300n, 1n, 120n, 180n, 0n]\n .reduce((packed, value, index) => packed | (value << BigInt(index * 32)), 0n);\n if (\n expected.secretHash.length !== 32 || extra[0] !== hashlock || extra[1] !== (evmDest ? BigInt(expected.dstChainId!) : 0n) ||\n extra[2] !== dstToken || extra[3] !== deposits || extra[4] !== timelocks\n ) {\n throw new Error(\"omniston: signed EVM HTLC terms do not match the validated order details\");\n }\n\n const customData = extension.slice(32 + begin);\n if (customData.length !== 131) throw new Error(\"omniston: malformed EVM order extension custom data\");\n if (evmDest) {\n // The TON jetton/recipient slots are empty for an EVM destination (live\n // 2026-10-20). The EVM recipient is NOT in anything the wallet signs: it\n // travels in the unsigned order details only, so the destination escrow's\n // maker is what the disclosure gate (validateEvmOutputPosition) must prove.\n if (!zeroBytes(customData.slice(0, 66))) throw new Error(\"omniston: unexpected TON addresses in an EVM-destination order\");\n } else {\n const {Address} = await import(\"@ton/core\");\n const expectedTon = [expected.outputTokenAddress, expected.traderDstAddress].map((value) => Address.parse(value));\n for (let index = 0; index < expectedTon.length; index++) {\n const offset = index * 33;\n const workchain = customData[offset] === 255 ? -1 : customData[offset]!;\n if (workchain !== expectedTon[index]!.workChain || !sliceEqual(customData.slice(offset + 1, offset + 33), expectedTon[index]!.hash)) {\n throw new Error(\"omniston: signed EVM→TON address does not match the validated request\");\n }\n }\n }\n if (!zeroBytes(customData.slice(66, 99))) {\n throw new Error(\"omniston: unexpected private TON disclosure address\");\n }\n const quoteId = expected.quoteId.replace(/^0x/, \"\");\n if (!QUOTE_ID.test(quoteId) || !sliceEqual(customData.slice(99), hexToBytes(quoteId.padStart(64, \"0\")))) {\n throw new Error(\"omniston: EVM order extension custom data is not bound to the quote id\");\n }\n if (expected.tradeStartDeadline < expected.quoteTimestamp) {\n throw new Error(\"omniston: invalid EVM order quote deadline\");\n }\n}\n\n/**\n * The EVM order checks the provider runs on every build, exported so an app that holds the quote's settlement data\n * can run them itself (scan 2026-10-27 modules, F4): the 1inch Limit Order Protocol v4 domain on the settlement\n * contract and chain, the exact Order schema, this owner as maker, the resolver as receiver, the input asset and\n * amount, single-fill traits, the salt committing the order extension and the expiry at the trade-start deadline.\n * Throws when any of it does not hold.\n */\nexport function validateEvmTypedOrder(\n td: unknown,\n expected: {\n chainId: number;\n settlementContract: string;\n owner: string;\n receiver: string;\n makerAsset: string;\n makingAmount: string;\n takingAmount: string;\n orderExtension: Uint8Array;\n quoteTimestamp: number;\n tradeStartDeadline: number;\n },\n): asserts td is {\n domain: {verifyingContract: string; chainId: string | number};\n types: Record<string, {name: string; type: string}[]>;\n primaryType: string;\n message: Record<string, unknown>;\n} {\n const value = td as {\n domain?: {name?: unknown; version?: unknown; verifyingContract?: unknown; chainId?: unknown};\n types?: Record<string, {name?: unknown; type?: unknown}[]>;\n primaryType?: unknown;\n message?: Record<string, unknown>;\n };\n const order = value.types?.Order;\n const exactSchema = Array.isArray(order) && order.length === ORDER_FIELDS.length &&\n order.every((field, i) => field.name === ORDER_FIELDS[i]![0] && field.type === ORDER_FIELDS[i]![1]);\n const message = value.message;\n const salt = message?.salt;\n const traits = validUint256(message?.makerTraits) ? BigInt(message!.makerTraits as string) : -1n;\n const flagMask = ((1n << 56n) - 1n) << 200n;\n // POST_INTERACTION + HAS_EXTENSION are mandatory and ALLOW_MULTIPLE_FILLS\n // must be clear, so the order fills at most once; no permit2/unwrap/epoch/\n // pre-interaction programs. Live v1beta8 orders leave NO_PARTIAL_FILLS clear\n // (one partial fill is possible). Disclosure still requires the finalized\n // fill to lock the FULL input, so a partial fill is never completed — it\n // rolls back on its own timelocks.\n const baseFlags = (1n << 251n) | (1n << 249n);\n const flags = traits < 0n ? -1n : traits & flagMask;\n const flagsOk = flags === baseFlags || flags === (baseFlags | (1n << 255n));\n const allowedSender = traits & ((1n << 80n) - 1n);\n const expiration = (traits >> 80n) & ((1n << 40n) - 1n);\n const series = (traits >> 160n) & ((1n << 40n) - 1n);\n const extensionHash = BigInt(keccak256(expected.orderExtension));\n const exactMessage = !!message && Object.keys(message).length === ORDER_FIELDS.length &&\n ORDER_FIELDS.every(([name]) => Object.hasOwn(message, name));\n if (\n value.domain?.name !== \"1inch Limit Order Protocol\" || value.domain.version !== \"4\" ||\n typeof value.domain.verifyingContract !== \"string\" ||\n getAddress(value.domain.verifyingContract) !== getAddress(expected.settlementContract) ||\n Number(value.domain.chainId) !== expected.chainId || value.primaryType !== \"Order\" || !exactSchema || !message || !exactMessage ||\n getAddress(String(message.maker)) !== getAddress(expected.owner) ||\n getAddress(String(message.receiver)) !== getAddress(expected.receiver) ||\n getAddress(String(message.makerAsset)) !== getAddress(expected.makerAsset) ||\n !validUint256(salt) || (BigInt(salt as string) & ((1n << 160n) - 1n)) !== (extensionHash & ((1n << 160n) - 1n)) ||\n // The order expires at the quote's trade-start deadline (±15 s of clock\n // skew between the quote and the order builder), never later.\n traits < 0n || !flagsOk || allowedSender !== 0n || series !== 0n ||\n !within(expiration, expected.tradeStartDeadline, 15, 15) || expiration <= BigInt(expected.quoteTimestamp) ||\n !validEvmAddress(message.takerAsset) || getAddress(String(message.takerAsset)) === getAddress(expected.makerAsset) ||\n !validUint256(message.makingAmount) || BigInt(message.makingAmount as string) !== BigInt(expected.makingAmount) ||\n !validUint256(message.takingAmount) || BigInt(message.takingAmount as string) !== BigInt(expected.takingAmount)\n ) {\n throw new Error(\"omniston: EVM order fields do not match the validated quote/request\");\n }\n}\n\nasync function validateTonEscrowPayload(\n message: EscrowMessage,\n expected: {\n quoteId: string;\n inputUnits: string;\n resolverSendsUnits: string;\n srcHtlcSecurityDepositUnits: string;\n protocolAddress: string;\n ownerAddress: string;\n destinationChain: string;\n destinationAddress: string;\n outputTokenAddress: string;\n initialResolverAddress: string;\n hashes: Uint8Array[];\n hashingFunction?: string;\n exclusivityTimeout: number;\n },\n validateForwardPayload: NonNullable<OmnistonProviderOptions[\"validateTonEscrowPayload\"]>,\n): Promise<void> {\n const {Address, Cell} = await import(\"@ton/core\");\n const boc = hexToBytes(message.payload);\n let roots: InstanceType<typeof Cell>[];\n try {\n roots = Cell.fromBoc(Buffer.from(boc));\n } catch {\n throw new Error(\"omniston: malformed TON escrow BoC\");\n }\n if (roots.length !== 1) throw new Error(\"omniston: TON escrow must contain exactly one root cell\");\n const slice = roots[0]!.beginParse();\n const op = slice.loadUint(32);\n slice.loadUintBig(64); // query id is resolver-chosen and not security-critical\n const amount = slice.loadCoins();\n const destination = slice.loadAddressAny();\n const response = slice.loadAddressAny();\n const customPayload = slice.loadMaybeRef();\n const forwardAmount = slice.loadCoins();\n const payloadByRef = slice.loadBit();\n if (\n op !== 0x0f8a7ea5 || amount !== BigInt(expected.inputUnits) || !(destination instanceof Address) ||\n !destination.equals(Address.parse(expected.protocolAddress)) ||\n (response !== null && (!(response instanceof Address) || !response.equals(Address.parse(expected.ownerAddress)))) || customPayload !== null ||\n forwardAmount <= 0n || forwardAmount > BigInt(message.sendAmount) || !payloadByRef ||\n slice.remainingBits !== 0 || slice.remainingRefs !== 1\n ) {\n throw new Error(\"omniston: TON jetton transfer does not match the validated quote/request\");\n }\n const forwardPayload = slice.loadRef();\n const verified = await validateForwardPayload({\n payloadBocHex: message.payload,\n forwardPayloadBocHex: Buffer.from(forwardPayload.toBoc()).toString(\"hex\"),\n quoteId: expected.quoteId,\n inputUnits: expected.inputUnits,\n resolverSendsUnits: expected.resolverSendsUnits,\n srcHtlcSecurityDepositUnits: expected.srcHtlcSecurityDepositUnits,\n protocolAddress: expected.protocolAddress,\n ownerAddress: expected.ownerAddress,\n destinationChain: expected.destinationChain,\n destinationAddress: expected.destinationAddress,\n outputTokenAddress: expected.outputTokenAddress,\n initialResolverAddress: expected.initialResolverAddress,\n secretHashes: expected.hashes.map((hash) => hash.slice()),\n ...(expected.hashingFunction ? {hashingFunction: expected.hashingFunction} : {}),\n exclusivityTimeout: expected.exclusivityTimeout,\n });\n if (!verified) throw new Error(\"omniston: TON escrow forward payload failed independent semantic validation\");\n}\n\n/** Fee token id: the catalog's 1Click asset id, or the on-chain contract for\n * assets 1Click does not list (BNB/Polygon USDC) — an empty id fails validQuote. */\nfunction feeToken(asset: CcAsset): string {\n return asset.assetId || asset.contract || asset.symbol;\n}\n\nfunction chainCase(asset: AssetId): string {\n return asset.chain.$case;\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;\n return diff === 0;\n}\n\n/** Minimal, bounded protobuf reader for the exact v1beta8 HTLC-details schema.\n * The SDK deliberately exposes these bytes as opaque, so independently decode\n * the security-critical fields before asking the wallet to sign their hash. */\nclass ProtoReader {\n private pos = 0;\n constructor(private readonly bytes: Uint8Array) {}\n get done(): boolean { return this.pos === this.bytes.length; }\n varint(): number {\n let out = 0;\n let shift = 0;\n while (this.pos < this.bytes.length && shift <= 49) {\n const byte = this.bytes[this.pos++]!;\n out += (byte & 0x7f) * 2 ** shift;\n if ((byte & 0x80) === 0) {\n if (!Number.isSafeInteger(out)) throw new Error(\"omniston: unsafe protobuf varint\");\n return out;\n }\n shift += 7;\n }\n throw new Error(\"omniston: malformed protobuf varint\");\n }\n field(): {number: number; wire: number} {\n const tag = this.varint();\n const number = Math.floor(tag / 8);\n const wire = tag & 7;\n if (number < 1) throw new Error(\"omniston: malformed protobuf field\");\n return {number, wire};\n }\n lengthDelimited(): Uint8Array {\n const length = this.varint();\n const end = this.pos + length;\n if (length < 0 || end > this.bytes.length) throw new Error(\"omniston: truncated protobuf payload\");\n const value = this.bytes.slice(this.pos, end);\n this.pos = end;\n return value;\n }\n skip(wire: number): void {\n if (wire === 0) { this.varint(); return; }\n if (wire === 1) { this.advance(8); return; }\n if (wire === 2) { this.lengthDelimited(); return; }\n if (wire === 5) { this.advance(4); return; }\n throw new Error(\"omniston: unsupported protobuf wire type\");\n }\n private advance(length: number): void {\n if (this.pos + length > this.bytes.length) throw new Error(\"omniston: truncated protobuf payload\");\n this.pos += length;\n }\n}\n\nconst utf8 = new TextDecoder(\"utf-8\", {fatal: true});\n// stonfi/common/v1/types/{chain_address,asset_id}.proto (omniston-sdk main, re-read 2026-10-20).\nconst PROTO_CASE_BY_FIELD: Record<number, string> = {\n 1: \"arbitrum\", 2: \"avalanche\", 3: \"base\", 4: \"bnb\", 5: \"ethereum\",\n 6: \"polygon\", 7: \"robinhood\", 8: \"xlayer\", 9: \"arc\", 10: \"monad\", 11: \"plasma\", 12: \"hyperevm\",\n 50: \"ton\", 60: \"tron\",\n};\n\nfunction decodeChainAddress(bytes: Uint8Array): ChainAddress {\n const reader = new ProtoReader(bytes);\n let address: ChainAddress | undefined;\n while (!reader.done) {\n const {number, wire} = reader.field();\n const $case = PROTO_CASE_BY_FIELD[number];\n if (!$case || wire !== 2 || address) throw new Error(\"omniston: malformed chain address in order details\");\n address = {chain: {$case, value: utf8.decode(reader.lengthDelimited())}};\n }\n if (!address?.chain.value) throw new Error(\"omniston: empty chain address in order details\");\n return address;\n}\n\nfunction decodeAssetId(bytes: Uint8Array): AssetId {\n const reader = new ProtoReader(bytes);\n let asset: AssetId | undefined;\n while (!reader.done) {\n const {number, wire} = reader.field();\n const $case = PROTO_CASE_BY_FIELD[number];\n if (!$case || wire !== 2 || asset) throw new Error(\"omniston: malformed asset id in order details\");\n const kindReader = new ProtoReader(reader.lengthDelimited());\n const kindField = kindReader.field();\n if (kindField.wire !== 2 || (kindField.number !== 1 && kindField.number !== 2)) {\n throw new Error(\"omniston: unsupported asset kind in order details\");\n }\n const kindCase = kindField.number === 1 ? \"native\" : ($case === \"ton\" ? \"jetton\" : $case === \"tron\" ? \"trc20\" : \"erc20\");\n const value = kindField.number === 1 ? {} : utf8.decode(kindReader.lengthDelimited());\n if (!kindReader.done || (kindField.number === 2 && !value)) throw new Error(\"omniston: malformed asset kind in order details\");\n asset = {chain: {$case, value: {kind: {$case: kindCase, value}}}};\n }\n if (!asset) throw new Error(\"omniston: empty asset id in order details\");\n return asset;\n}\n\nfunction validateSerializedOrderDetails(\n bytes: Uint8Array | undefined,\n expected: {quoteId: string; outputAsset: AssetId; traderDstAddress: ChainAddress; secretHashes: Uint8Array[]},\n): void {\n if (!bytes?.length) throw new Error(\"omniston: EVM HTLC order payload has no serialized details\");\n const wrapper = new ProtoReader(bytes);\n const outer = wrapper.field();\n if (outer.number !== 1 || outer.wire !== 2) throw new Error(\"omniston: unsupported HTLC order-details version\");\n const detailsBytes = wrapper.lengthDelimited();\n if (!wrapper.done) throw new Error(\"omniston: ambiguous HTLC order-details wrapper\");\n const reader = new ProtoReader(detailsBytes);\n let quoteId: string | undefined;\n let outputAsset: AssetId | undefined;\n let traderDstAddress: ChainAddress | undefined;\n const hashes: Uint8Array[] = [];\n while (!reader.done) {\n const {number, wire} = reader.field();\n if (wire !== 2) throw new Error(\"omniston: malformed HTLC order details\");\n const value = reader.lengthDelimited();\n if (number === 1 && quoteId === undefined) quoteId = utf8.decode(value);\n else if (number === 2 && outputAsset === undefined) outputAsset = decodeAssetId(value);\n else if (number === 3 && traderDstAddress === undefined) traderDstAddress = decodeChainAddress(value);\n else if (number === 5) hashes.push(value);\n else throw new Error(\"omniston: duplicate or unexpected HTLC order-details field\");\n }\n if (\n quoteId !== expected.quoteId ||\n !outputAsset || !sameAsset(outputAsset, expected.outputAsset) ||\n !traderDstAddress || !sameChainAddress(traderDstAddress, expected.traderDstAddress) ||\n hashes.length !== expected.secretHashes.length ||\n hashes.some((hash, i) => !bytesEqual(hash, expected.secretHashes[i]!))\n ) {\n throw new Error(\"omniston: resolver order payload does not match the validated quote/request\");\n }\n}\n\nfunction isPositiveInteger(value: string): boolean {\n try {\n return BigInt(value) > 0n;\n } catch {\n return false;\n }\n}\n\nfunction isNonNegativeInteger(value: string | undefined): boolean {\n if (value === undefined) return true;\n return /^[0-9]+$/.test(value);\n}\n\nfunction decimalToUnits(value: string, decimals: number): bigint | null {\n const match = value.match(/^(\\d+)(?:\\.(\\d+))?$/);\n if (!match || !Number.isInteger(decimals) || decimals < 0) return null;\n const fraction = match[2] ?? \"\";\n if (fraction.length > decimals) return null;\n const units = BigInt(match[1]!) * 10n ** BigInt(decimals) +\n BigInt((fraction + \"0\".repeat(decimals)).slice(0, decimals) || \"0\");\n return units > 0n ? units : null;\n}\n\nfunction validDisclosurePhase(phase: string | undefined): boolean {\n return phase === \"EXECUTION_PHASE_READY_FOR_PRIVATE_COMPLETION\" ||\n phase === \"EXECUTION_PHASE_READY_FOR_PUBLIC_COMPLETION\" ||\n phase === \"OUTPUT_LOCKED\"; // legacy client representation\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const clean = hex.replace(/^0x/, \"\");\n if (!clean || !/^(?:[0-9a-fA-F]{2})+$/.test(clean)) {\n throw new Error(\"omniston: malformed hex payload\");\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n return out;\n}\n\nfunction hexToBase64(hex: string): string {\n const bytes = hexToBytes(hex);\n let bin = \"\";\n bytes.forEach((b) => (bin += String.fromCharCode(b)));\n return btoa(bin);\n}\n\n// ── RFQ stream → single quote ────────────────────────────────────────────────\n\n/** Let resolvers compete for QUOTE_SETTLE_MS, then take the latest valid quote.\n * `noQuote` invalidates all previous updates because v1beta8 uses it to signal\n * that the previous quote expired. */\n/** The order-settlement fields every cross-chain quote must bind. */\nfunction validOrderSettlement(q: OmnistonQuote): boolean {\n if (q.settlementData?.$case !== \"order\") return false;\n const v = q.settlementData.value;\n return !!v.srcProtocolContractAddress &&\n v.srcProtocolContractAddress.chain.$case === chainCase(q.inputAsset) &&\n !!v.srcInitialResolverAddress &&\n v.srcInitialResolverAddress.chain.$case === chainCase(q.inputAsset) &&\n !!v.dstProtocolContractAddress &&\n v.dstProtocolContractAddress.chain.$case === chainCase(q.outputAsset) &&\n isPositiveInteger(v.srcHtlcSecurityDepositUnits ?? \"\") &&\n isPositiveInteger(v.dstSecurityDepositUnits ?? \"\") &&\n (v.htlcHashingFunction === \"HASHING_FUNCTION_KECCAK256\" || v.htlcHashingFunction === \"HASHING_FUNCTION_SHA256\") &&\n Number.isSafeInteger(v.exclusivityTimeout) && v.exclusivityTimeout! > 0 &&\n isPositiveInteger(v.resolverSendsUnits) &&\n BigInt(v.resolverSendsUnits) === BigInt(q.outputUnits) + BigInt(q.protocolFeeUnits || \"0\") + BigInt(q.integratorFeeUnits || \"0\");\n}\n\n/** The swap-settlement fields a same-chain quote must carry: at least one\n * route of named-protocol chunks, and a minimum output within the quote. */\nfunction validSwapSettlement(q: OmnistonQuote): boolean {\n if (q.settlementData?.$case !== \"swap\") return false;\n const v = q.settlementData.value;\n return Array.isArray(v.routes) && v.routes.length > 0 &&\n v.routes.every((route) => Array.isArray(route?.steps) && route.steps.length > 0 &&\n route.steps.every((step) => Array.isArray(step?.chunks) && step.chunks.length > 0 &&\n step.chunks.every((chunk) => typeof chunk?.protocol === \"string\" && chunk.protocol.length > 0 &&\n isPositiveInteger(chunk.inputUnits) && isPositiveInteger(chunk.outputUnits)))) &&\n isPositiveInteger(v.minOutputAmount) && BigInt(v.minOutputAmount) <= BigInt(q.outputUnits) &&\n (v.recommendedMinOutputAmount === undefined ||\n (isPositiveInteger(v.recommendedMinOutputAmount) && BigInt(v.recommendedMinOutputAmount) <= BigInt(q.outputUnits))) &&\n (q.gasBudget === undefined || isPositiveInteger(q.gasBudget));\n}\n\n/** Every DEX protocol name the quote's routes touch, deduplicated. */\n/** The route as `checkTonSwapPayload` takes it: one step per hop of a single route; splits and multi-route answers named, not resolved. */\nfunction swapSteps(v: SwapSettlement): Array<{protocol: string; inputJetton: string | null | undefined; outputJetton: string | null | undefined}> {\n if (v.routes.length !== 1) return [{protocol: `${v.routes.length}-routes`, inputJetton: undefined, outputJetton: undefined}];\n return v.routes[0]!.steps.map((step) => {\n if (step.chunks.length !== 1) return {protocol: `split(${step.chunks.map((c) => c.protocol).join(\"|\")})`, inputJetton: undefined, outputJetton: undefined};\n return {protocol: step.chunks[0]!.protocol, inputJetton: stepJetton(step.inputAsset), outputJetton: stepJetton(step.outputAsset)};\n });\n}\n\nfunction swapProtocols(v: SwapSettlement): string[] {\n const names = new Set<string>();\n for (const route of v.routes) for (const step of route.steps) for (const chunk of step.chunks) names.add(chunk.protocol);\n return [...names];\n}\n\n/** Why an RFQ produced no usable quote — the caller turns it into a refusal. */\ninterface RfqOutcome {\n /** Number of `quoteUpdated` events seen for this RFQ. */\n updates: number;\n /** The first check the latest rejected update failed, if any. */\n rejected?: string;\n /** The stream errored (socket/SDK) before a usable quote arrived. */\n error?: string;\n}\n\n/** The first failing check of a `quoteUpdated` event, or null when it is usable. */\nfunction quoteRejection(\n q: OmnistonQuote | undefined,\n update: {rfqId?: string},\n acknowledgedRfqId: string | null,\n request: QuoteRequest,\n settlement: \"order\" | \"swap\",\n): string | null {\n if (!q) return \"empty quote\";\n if (!acknowledgedRfqId || update.rfqId !== acknowledgedRfqId || q.rfqId !== acknowledgedRfqId) return \"quote for another RFQ\";\n if (!sameAsset(q.inputAsset, request.inputAsset) || !sameAsset(q.outputAsset, request.outputAsset)) return \"quote assets differ from the request\";\n const requestedAmount = request.amount.$case === \"inputUnits\" ? request.amount.value : \"\";\n if (q.inputUnits !== requestedAmount) return \"quote input differs from the request\";\n if (!QUOTE_ID.test(q.quoteId)) return \"malformed quote id\";\n if (!isPositiveInteger(q.inputUnits) || !isPositiveInteger(q.outputUnits)) return \"non-positive quote amounts\";\n if (!isNonNegativeInteger(q.protocolFeeUnits) || !isNonNegativeInteger(q.integratorFeeUnits) ||\n BigInt(q.protocolFeeUnits || \"0\") + BigInt(q.integratorFeeUnits || \"0\") > BigInt(q.outputUnits)) return \"malformed quote fees\";\n if (!Number.isInteger(q.quoteTimestamp) || Math.abs(Math.floor(Date.now() / 1000) - q.quoteTimestamp) > 120) return \"quote timestamp out of range\";\n if (settlement === \"order\" ? !validOrderSettlement(q) : !validSwapSettlement(q)) return `incomplete ${settlement} settlement data`;\n if (!sameChainAddress(q.integratorAddress, request.integratorAddress)) return \"quote integrator differs from the request\";\n return null;\n}\n\nfunction awaitQuote(\n stream: ObservableLike<RfqEvent>,\n request: QuoteRequest,\n signal?: AbortSignal,\n settleMs = QUOTE_SETTLE_MS,\n settlement: \"order\" | \"swap\" = \"order\",\n outcome: RfqOutcome = {updates: 0},\n): Promise<OmnistonQuote | null> {\n return new Promise((resolve) => {\n let latest: OmnistonQuote | null = null;\n let done = false;\n let sub: {unsubscribe(): void} | null = null;\n let acknowledgedRfqId: string | null = null;\n const onAbort = () => finish(null);\n const finish = (value: OmnistonQuote | null) => {\n if (done) return;\n done = true;\n clearTimeout(settle);\n clearTimeout(max);\n signal?.removeEventListener(\"abort\", onAbort);\n try {\n sub?.unsubscribe();\n } catch {\n /* socket already gone */\n }\n resolve(value);\n };\n const settle = setTimeout(() => {\n if (latest) finish(latest);\n }, settleMs);\n const max = setTimeout(() => finish(latest), QUOTE_MAX_MS);\n sub = stream.subscribe({\n next: (event) => {\n if (event.$case === \"ack\") {\n acknowledgedRfqId = (event as {$case: \"ack\"; value: {rfqId: string}}).value.rfqId || null;\n } else if (event.$case === \"quoteUpdated\") {\n const update = event as {rfqId?: string; value: OmnistonQuote};\n outcome.updates += 1;\n const rejection = quoteRejection(update.value, update, acknowledgedRfqId, request, settlement);\n if (rejection) {\n outcome.rejected = rejection;\n latest = null;\n return;\n }\n latest = update.value;\n } else if (event.$case === \"noQuote\") {\n // v1beta8 streams resolver state: null invalidates the previous\n // update, but another resolver may still publish a later quote.\n // Keep the RFQ alive until the normal settle/max window.\n const noQuote = event as {$case: \"noQuote\"; rfqId?: string};\n if (acknowledgedRfqId && noQuote.rfqId === acknowledgedRfqId) latest = null;\n }\n },\n error: (err) => {\n outcome.error = String((err as {message?: unknown})?.message ?? err).slice(0, 200);\n finish(null);\n },\n complete: () => finish(latest),\n });\n signal?.addEventListener(\"abort\", onAbort, {once: true});\n if (done) sub.unsubscribe(); // finished synchronously before sub was set\n });\n}\n\n/** Collect the latest swap-progress event for the snapshot window. */\nfunction awaitSwapProgress(stream: ObservableLike<SwapTrackEvent>): Promise<{status: string; outgoingTxHash?: string} | null | \"awaiting\"> {\n return new Promise((resolve) => {\n let done = false;\n let latest: {status: string; outgoingTxHash?: string} | null | \"awaiting\" = null;\n let sub: {unsubscribe(): void} | null = null;\n const finish = (value: typeof latest) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n try {\n sub?.unsubscribe();\n } catch {\n /* socket already gone */\n }\n resolve(value);\n };\n const timer = setTimeout(() => finish(latest), TRACK_SNAPSHOT_MS);\n sub = stream.subscribe({\n next: (event) => {\n if (event.$case === \"progress\") {\n latest = (event as {value: {status: string; outgoingTxHash?: string}}).value;\n if ([\"TRADE_STATUS_FULLY_FILLED\", \"TRADE_STATUS_PARTIALLY_FILLED\", \"TRADE_STATUS_CANCELLED\", \"TRADE_STATUS_FAILED\"].includes(latest.status)) finish(latest);\n } else if (event.$case === \"awaitingTransfer\" && latest === null) {\n latest = \"awaiting\";\n }\n },\n error: () => finish(null),\n complete: () => finish(latest),\n });\n if (done) sub.unsubscribe();\n });\n}\n\nconst JETTON_TRANSFER_OP = 0x0f8a7ea5;\n\n/** A built TON swap message body: either a jetton transfer (jetton input,\n * forwarding to the DEX) or a DEX-native call (native GRAM input). */\nfunction parseSwapPayload(payloadHex: string): {\n op: number;\n jettonTransfer: null | {amount: bigint; destination: string; responseDestination: string | null; forwardTon: bigint};\n} {\n if (!/^(?:[0-9a-fA-F]{2})+$/.test(payloadHex)) throw new Error(\"omniston: malformed swap payload hex\");\n const roots = TonCell.fromBoc(Buffer.from(payloadHex, \"hex\"));\n if (roots.length !== 1) throw new Error(\"omniston: swap payload must have one root\");\n const s = roots[0]!.beginParse();\n const op = s.loadUint(32);\n if (op !== JETTON_TRANSFER_OP) return {op, jettonTransfer: null};\n s.loadUintBig(64); // query id — wallet/resolver-selected\n const amount = s.loadCoins();\n const destination = s.loadAddress();\n const responseDestination = s.loadMaybeAddress();\n s.loadMaybeRef(); // custom payload\n const forwardTon = s.loadCoins();\n return {\n op,\n jettonTransfer: {\n amount,\n destination: destination.toString(),\n responseDestination: responseDestination ? responseDestination.toString() : null,\n forwardTon,\n },\n };\n}\n\nfunction sameTonAddress(a: string, b: string): boolean {\n try {\n return TonAddress.parse(a).equals(TonAddress.parse(b));\n } catch {\n return false;\n }\n}\n\n/** Collect the latest order event for the snapshot window. */\nfunction awaitOrder(stream: ObservableLike<OrderEvent>): Promise<OrderSnapshot | null> {\n return new Promise((resolve) => {\n let done = false;\n let latest: OrderSnapshot | null = null;\n let sub: {unsubscribe(): void} | null = null;\n const finish = (value: OrderSnapshot | null) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n try {\n sub?.unsubscribe();\n } catch {\n /* socket already gone */\n }\n resolve(value);\n };\n const timer = setTimeout(() => finish(latest), TRACK_SNAPSHOT_MS);\n sub = stream.subscribe({\n next: (event) => {\n if (event.$case === \"order\") {\n latest = (event as {value: OrderSnapshot}).value;\n if ([\"TRADE_STATUS_FULLY_FILLED\", \"TRADE_STATUS_CANCELLED\", \"TRADE_STATUS_FAILED\"].includes(latest.status)) finish(latest);\n }\n },\n error: () => finish(null),\n complete: () => finish(latest),\n });\n if (done) sub.unsubscribe();\n });\n}\n\nfunction mapOrderStatus(order: OrderSnapshot): IntentStatus {\n const depositReceived = order.executions.length > 0;\n switch (order.status) {\n case \"TRADE_STATUS_FULLY_FILLED\":\n return {state: \"completed\", depositReceived: true};\n case \"TRADE_STATUS_PARTIALLY_FILLED\":\n // NOT terminal: tranches still need their secrets disclosed — keep the\n // store and keep polling (audit H2). Only FULLY_FILLED clears it.\n return {state: \"pending\", depositReceived: true};\n case \"TRADE_STATUS_CANCELLED\":\n case \"TRADE_STATUS_FAILED\":\n // Resolver-controlled tracking is not proof that the signed source order\n // can no longer fill. Keep polling until completion or the caller's\n // independent HTLC/expiry refund backstop closes the intent.\n return {state: \"pending\", depositReceived};\n default:\n return {state: \"pending\", depositReceived};\n }\n}\n\n// ── Provider ─────────────────────────────────────────────────────────────────\n\n/**\n * The app's side of `remoteProvider({name: \"omniston\", baseUrl, ...omnistonPins(trustedEvmOrderProtocols)})`: the\n * audited order-protocol contracts per EVM chain — the list the provider's `trustedEvmOrderProtocols` takes — are the\n * only spenders, and so the only EIP-712 verifying contracts, a remote typed order may name (scan 2026-10-27 modules,\n * F4). Omniston's EVM orders call no contract from the wallet: there are no call targets.\n */\nexport function omnistonPins(trustedEvmOrderProtocols: Readonly<Record<string, readonly string[]>>): RemotePins {\n const byChain = new Map(Object.entries(trustedEvmOrderProtocols).map(([chain, list]): [string, readonly string[]] => [chain, list.map((a) => getAddress(a))]));\n return Object.freeze({callTargets: (): readonly string[] => [], spenders: (chain: string): readonly string[] => byChain.get(chain) ?? []});\n}\n\n/**\n * The app's check of a remote Omniston TON swap build, for `remoteProvider({name: \"omniston\", baseUrl, verifyBuild:\n * omnistonVerifyBuild({validateTonSwapTarget, validateTonSwapLeg})})` (scan 2026-10-27 modules, F7/F13/F18/F19): the\n * body is opened with `checkTonSwapPayload` against the app's own request — receiver, refund / excess to the trader,\n * the on-chain minimum, the input — and the DEX it pays is confirmed with the app's validators (the same hooks the\n * provider takes; `createOmnistonTonValidators` builds them). Any other cell body (a TON → EVM escrow) cannot be\n * checked without the quote's settlement data and is refused; EVM typed orders pass through to the engine's own\n * order checks. The reason it fails, or null.\n */\nexport function omnistonVerifyBuild(hooks: {\n validateTonSwapTarget: (input: {address: string; protocols: readonly string[]}) => Promise<boolean> | boolean;\n validateTonSwapLeg?: (leg: TonSwapLeg) => Promise<boolean> | boolean;\n /** The integrator your backend's Omniston provider uses: the only referral a body may name. */\n integratorAddress?: string | null;\n}): (quote: Quote, tx: UnsignedTx, params?: QuoteParams) => Promise<string | null> {\n return async (quote, tx, params) => {\n if (tx.bodyBoc === undefined) return null;\n if (!params) return \"the request this quote answered is unknown\";\n if (quote.providerData?.settlement !== \"swap\") return \"only TON swap bodies can be checked on the client\";\n let steps: Array<{protocol: string; inputJetton?: string | null; outputJetton?: string | null}>;\n try { steps = JSON.parse(quote.providerData.routeSteps ?? \"\") as typeof steps; } catch { return \"the quote carries no route steps\"; }\n if (!Array.isArray(steps) || steps.length === 0) return \"the quote carries no route steps\";\n const source = ccAsset(params.sourceChain, params.sourceToken);\n const dest = ccAssetByToken(params.destChain, params.destToken);\n if (!source || !dest) return \"unknown source or destination token\";\n const protocols = (quote.providerData.protocols ?? \"\").split(\",\").filter(Boolean);\n let checked: TonSwapCheckResult;\n try {\n checked = checkTonSwapPayload({\n payloadHex: Buffer.from(tx.bodyBoc, \"base64\").toString(\"hex\"),\n targetAddress: tx.to,\n sendAmount: BigInt(tx.value),\n trader: params.refundAddress ?? \"\",\n dest: params.destAddress,\n inputUnits: quote.sourceAmount,\n minOutputAmount: quote.minDestAmount,\n inputJetton: source.contract ?? null,\n outputJetton: dest.contract ?? null,\n steps: steps.map((st) => ({protocol: String(st.protocol), inputJetton: st.inputJetton, outputJetton: st.outputJetton})),\n integratorAddress: hooks.integratorAddress ?? null,\n });\n } catch (e) {\n return e instanceof Error ? e.message.replace(/^omniston: /, \"\") : String(e);\n }\n // The DEX the message pays: the message target for a native input, the jetton transfer's destination otherwise.\n const payload = parseSwapPayload(Buffer.from(tx.bodyBoc, \"base64\").toString(\"hex\"));\n const target = source.contract ? payload.jettonTransfer?.destination : tx.to;\n if (!target) return \"the body names no swap destination\";\n try { if (!(await hooks.validateTonSwapTarget({address: target, protocols}))) return `${target} is not a recognized DEX contract for ${protocols.join(\"+\")}`; } catch { return \"the swap target could not be checked\"; }\n if (hooks.validateTonSwapLeg) {\n for (const leg of checked.legs) {\n let ok = false;\n try { ok = await hooks.validateTonSwapLeg(leg); } catch { ok = false; }\n if (!ok) return `${leg.kind} v${leg.version} leg not verified`;\n }\n }\n return null;\n };\n}\n\nexport function omnistonProvider(opts: OmnistonProviderOptions = {}): CrossChainProvider {\n opts = Object.freeze({...opts});\n const apiUrl = opts.apiUrl ?? \"wss://omni-ws.ston.fi\";\n const parsedApiUrl = new URL(apiUrl);\n if (parsedApiUrl.protocol !== \"wss:\" && parsedApiUrl.protocol !== \"ws:\") {\n throw new Error(\"omniston: apiUrl must use ws or wss\");\n }\n const maxUsdText = String(opts.maxUsd ?? 1000);\n if (!/^(?:0|[1-9]\\d*)(?:\\.\\d+)?$/.test(maxUsdText) || Number(maxUsdText) <= 0 || !Number.isFinite(Number(maxUsdText))) {\n throw new Error(\"omniston: maxUsd must be a positive plain decimal\");\n }\n const hasIntegrator = opts.integratorAddress !== undefined;\n const hasIntegratorPips = opts.integratorFeePips !== undefined;\n if (hasIntegrator !== hasIntegratorPips) throw new Error(\"omniston: integratorAddress and integratorFeePips must be configured together\");\n if (hasIntegrator && (!opts.integratorAddress!.trim() || !Number.isInteger(opts.integratorFeePips) || opts.integratorFeePips! < 0 || opts.integratorFeePips! > 1_000_000)) {\n throw new Error(\"omniston: integrator fee config is invalid\");\n }\n const trustedContracts = new Map<string, Set<string>>();\n for (const [chain, addresses] of Object.entries(opts.trustedSettlementContracts ?? {})) {\n const normalized = new Set<string>();\n for (const address of addresses) {\n try {\n normalized.add(isTon(chain) ? address : getAddress(address).toLowerCase());\n } catch {\n throw new Error(`omniston: invalid trusted settlement contract for ${chain}`);\n }\n }\n if (normalized.size) trustedContracts.set(chain, normalized);\n }\n const isTrusted = (chain: string, address: string): boolean => {\n try {\n return trustedContracts.get(chain)?.has(isTon(chain) ? address : getAddress(address).toLowerCase()) ?? false;\n } catch {\n return false;\n }\n };\n const trustedOrderProtocols = new Map<string, Set<string>>();\n for (const [chain, addresses] of Object.entries(opts.trustedEvmOrderProtocols ?? {})) {\n const normalized = new Set<string>();\n for (const address of addresses) {\n try {\n if (evmRef(chain) === null) throw new Error(\"not an EVM chain\");\n normalized.add(getAddress(address).toLowerCase());\n } catch {\n throw new Error(`omniston: invalid trusted EVM order protocol for ${chain}`);\n }\n }\n if (normalized.size) trustedOrderProtocols.set(chain, normalized);\n }\n const isTrustedOrderProtocol = (chain: string, address: string): boolean => {\n try {\n return trustedOrderProtocols.get(chain)?.has(getAddress(address).toLowerCase()) ?? false;\n } catch {\n return false;\n }\n };\n const store = opts.secretStore ?? inMemorySecretStore();\n const requestedMaxExecutions = opts.maxHtlcExecutions ?? DEFAULT_MAX_HTLC_EXECUTIONS;\n if (!Number.isFinite(requestedMaxExecutions) || !Number.isInteger(requestedMaxExecutions) || requestedMaxExecutions < 1) {\n throw new Error(\"omniston: maxHtlcExecutions must be a positive integer\");\n }\n const maxExecutions = Math.min(16, requestedMaxExecutions);\n const maxTonExecutionNano = opts.maxTonExecutionNano ?? \"2000000000\";\n if (!isPositiveInteger(maxTonExecutionNano)) {\n throw new Error(\"omniston: maxTonExecutionNano must be a positive integer\");\n }\n const quoteSettleMs = opts.quoteSettleMs ?? QUOTE_SETTLE_MS;\n if (!Number.isInteger(quoteSettleMs) || quoteSettleMs < 0 || quoteSettleMs >= QUOTE_MAX_MS) {\n throw new Error(`omniston: quoteSettleMs must be an integer in [0, ${QUOTE_MAX_MS})`);\n }\n const injectedClient = opts.client ?? null;\n let client: OmnistonClientLike | null = injectedClient;\n let clientPromise: Promise<OmnistonClientLike> | null = null;\n let clientGeneration = 0;\n /** Lazy: never open the WebSocket unless a quote is actually requested. */\n async function getClient(): Promise<OmnistonClientLike> {\n if (client) return client;\n if (clientPromise) return clientPromise;\n const generation = clientGeneration;\n clientPromise = (async () => {\n const sdk = await import(\"@ston-fi/omniston-sdk\");\n // omniston-sdk 0.8.9's Node WebSocketTransport listens for open/message/\n // close but not the EventEmitter `error` event. A refused connection can\n // therefore terminate the whole process before AutoReconnectTransport\n // sees the following close. Attach a no-op error listener to each socket;\n // close remains the authoritative status/retry signal.\n const webSocketTransport = new sdk.WebSocketTransport(apiUrl);\n const connect = webSocketTransport.connect.bind(webSocketTransport);\n webSocketTransport.connect = () => {\n const pending = connect();\n const socket = (webSocketTransport as unknown as {webSocket?: {addEventListener(type: string, listener: () => void): void}}).webSocket;\n socket?.addEventListener(\"error\", () => {});\n return pending;\n };\n webSocketTransport.reconnect = () => webSocketTransport.connect();\n // SDK race (0.8.11): a socket read can carry a Quote response AND its\n // subscription's `ack` notification; both are dispatched synchronously,\n // before the SDK registers the stream consumer, so the ack is dropped\n // and the next update errors with \"quoteUpdated before ack\" (live\n // 2026-10-12: 1–3 of 4 parallel RFQs, occasionally a single one).\n // Deliver each frame in its own macrotask so registration runs between.\n const messages = (webSocketTransport as unknown as {messagesSubject?: {next(m: string): void}}).messagesSubject;\n if (messages) {\n const deliver = messages.next.bind(messages);\n messages.next = (m: string) => { setTimeout(() => deliver(m), 0); };\n }\n const transport = new sdk.AutoReconnectTransport({transport: webSocketTransport});\n const created = new sdk.Omniston({apiUrl, transport}) as unknown as OmnistonClientLike;\n if (generation !== clientGeneration) {\n if (created.close) created.close(); else created.transport?.close();\n throw new Error(\"omniston: provider closed while client was being created\");\n }\n client = created;\n return created;\n })();\n try {\n return await clientPromise;\n } finally {\n clientPromise = null;\n }\n }\n\n /** buildDeposit/registerSignedOrder need the context getQuote produced —\n * persisted via quoteStore so serverless instances share it. */\n const quotes = opts.quoteStore ?? inMemoryQuoteStore();\n interface BuiltEntry {\n quote: OmnistonQuote;\n at: number;\n /** What the intentId was minted for (absent on entries written before scan F3/F15). */\n bound?: IntentBinding;\n /** EVM-source orders: what registration and tracking need after signing. */\n evmOrder?: {\n typedData: string;\n orderExtension: string;\n serializedOrderDetails: string;\n owner: string;\n chainCase: string;\n /** Escrow factory the signed extension targets (trusted for the source chain). */\n factory: string;\n };\n }\n async function saveBuilt(quoteId: string, entry: BuiltEntry): Promise<void> {\n await quotes.save(quoteId, JSON.stringify(entry));\n }\n /**\n * A fresh quote's context, saved only if the quote id is new or already holds THIS context (same trader, dest,\n * chain, kind): a platform reusing an id for another user's quote never rebinds a context (scan 2026-10-27 modules,\n * F27). Atomic with the store's `claim`; check-then-save otherwise.\n */\n async function claimBuilt(quoteId: string, entry: BuiltEntry): Promise<boolean> {\n const json = JSON.stringify(entry);\n if (typeof quotes.claim === \"function\") {\n if (await quotes.claim(quoteId, json)) return true;\n } else if (!(await quotes.load(quoteId))) {\n await quotes.save(quoteId, json);\n return true;\n }\n const existing = await loadBuilt(quoteId);\n if (!existing) {\n // Expired (cleared by loadBuilt): the id is free again.\n if (typeof quotes.claim === \"function\") return await quotes.claim(quoteId, json);\n await quotes.save(quoteId, json);\n return true;\n }\n const a = existing.bound, b = entry.bound;\n const same = !!a && !!b && a.kind === b.kind && a.srcChain === b.srcChain && sameIntentAddress(a.trader, b.trader) && sameIntentAddress(a.dest, b.dest);\n if (!same) return false;\n await quotes.save(quoteId, json);\n return true;\n }\n async function loadBuilt(quoteId: string): Promise<BuiltEntry | undefined> {\n const raw = await quotes.load(quoteId);\n if (!raw) return undefined;\n try {\n const e = JSON.parse(raw) as BuiltEntry;\n if (!Number.isFinite(e.at) || Date.now() - e.at > CACHE_TTL_MS) {\n await quotes.clear(quoteId);\n return undefined;\n }\n return e;\n } catch {\n await quotes.clear(quoteId);\n return undefined;\n }\n }\n\n type Decoded = NonNullable<ReturnType<typeof decodeIntent>>;\n type BindResult =\n | {ok: true; ref: Decoded; legacy: boolean}\n | {ok: false; reason: \"mismatch\"; field: string}\n | {ok: false; reason: \"legacy-expired\"};\n /**\n * Resolve the caller's intentId against the context stored for its quote:\n * any field that differs from what getQuote bound is refused, and the\n * returned ref carries ONLY the stored values. Pre-binding (legacy) entries\n * fall back to the signed order's owner (EVM source) or the decoded values,\n * for at most LEGACY_INTENT_WINDOW_MS after they were written.\n */\n function bindIntent(decoded: Decoded, entry: BuiltEntry): BindResult {\n const owner = entry.evmOrder?.owner;\n const bound = entry.bound;\n if (bound) {\n if (bound.kind !== decoded.kind) return {ok: false, reason: \"mismatch\", field: \"kind\"};\n if (bound.srcChain !== decoded.srcChain) return {ok: false, reason: \"mismatch\", field: \"srcChain\"};\n if (!sameIntentAddress(bound.trader, decoded.trader)) return {ok: false, reason: \"mismatch\", field: \"trader\"};\n if (!sameIntentAddress(bound.dest, decoded.dest)) return {ok: false, reason: \"mismatch\", field: \"dest\"};\n if (owner !== undefined && !sameIntentAddress(owner, bound.trader)) return {ok: false, reason: \"mismatch\", field: \"owner\"};\n return {ok: true, legacy: false, ref: {quoteId: decoded.quoteId, trader: owner ?? bound.trader, dest: bound.dest, srcChain: bound.srcChain, kind: bound.kind}};\n }\n if (!Number.isFinite(entry.at) || Date.now() - entry.at > LEGACY_INTENT_WINDOW_MS) return {ok: false, reason: \"legacy-expired\"};\n if (owner !== undefined && !sameIntentAddress(owner, decoded.trader)) return {ok: false, reason: \"mismatch\", field: \"owner\"};\n return {ok: true, legacy: true, ref: {...decoded, trader: owner ?? decoded.trader}};\n }\n const traceFor = (quoteId: string) => (event: string, details?: Record<string, unknown>) => {\n try { opts.trace?.(event, {quoteId, ...details}); } catch { /* diagnostics never break the flow */ }\n };\n /** buildDeposit / registerSignedOrder: the bound ref, or a named refusal. */\n function requireBinding(decoded: Decoded, entry: BuiltEntry, where: string): Decoded {\n const trace = traceFor(decoded.quoteId);\n const bound = bindIntent(decoded, entry);\n if (!bound.ok) {\n if (bound.reason === \"legacy-expired\") {\n trace(\"legacy-intent-expired\", {where});\n throw new Error(\"omniston: quote expired — request a fresh quote\");\n }\n trace(\"intent-mismatch\", {where, field: bound.field});\n throw new Error(`omniston: intent id does not match the quote it was issued for (${bound.field})`);\n }\n if (bound.legacy) trace(\"legacy-intent\", {where});\n return bound.ref;\n }\n\n /**\n * HTLC secrets for a quote: a second build of the SAME order reuses the\n * stored secrets (same hashlock) instead of overwriting them, so a repeated\n * or concurrent build can never strand an order that was already signed.\n * `created` says whether THIS call wrote them (only then may it clear them).\n *\n * The quoteId is chosen by the platform, so it alone must never decide which\n * preimage an order locks to (scan 2026-10-23 F6): secrets are stored with a\n * hash of the order they were made for (trader, dest, chain, assets, units)\n * and reused only for that exact order, and a secret that was disclosed is\n * never handed to a new build.\n */\n const bindKey = (quoteId: string) => `${quoteId}#bind`;\n const disclosedKey = (quoteId: string) => `${quoteId}#disclosed`;\n function orderBinding(ref: Decoded, q: OmnistonQuote): string {\n return sha256(new TextEncoder().encode(JSON.stringify([\n ref.quoteId, ref.trader ?? null, ref.dest ?? null, ref.srcChain ?? null,\n q.inputUnits, q.outputUnits, JSON.stringify(q.inputAsset), JSON.stringify(q.outputAsset),\n ]))).slice(2);\n }\n async function clearSecrets(quoteId: string): Promise<void> {\n await store.clear(quoteId);\n await store.clear(bindKey(quoteId));\n await store.clear(disclosedKey(quoteId));\n }\n async function secretsFor(ref: Decoded, q: OmnistonQuote, count: number): Promise<{secrets: Uint8Array[]; created: boolean}> {\n const quoteId = ref.quoteId;\n const binding = orderBinding(ref, q);\n const existing = await store.load(quoteId);\n if (existing && existing.length > 0) {\n const [boundTo] = (await store.load(bindKey(quoteId))) ?? [];\n const disclosed = ((await store.load(disclosedKey(quoteId))) ?? []).length > 0;\n if (boundTo !== binding || disclosed) {\n traceFor(quoteId)(\"secret-reuse-refused\", {disclosed, bound: boundTo !== undefined});\n throw new Error(\"omniston: this quote id already belongs to another order — request a fresh quote\");\n }\n if (existing.length !== count || !existing.every((s) => /^[0-9a-fA-F]{64}$/.test(s))) {\n throw new Error(\"omniston: stored HTLC secrets for this quote do not fit the order — request a fresh quote\");\n }\n traceFor(quoteId)(\"secret-reused\", {count});\n return {secrets: existing.map(hexToBytes), created: false};\n }\n const secrets = Array.from({length: count}, generateSecret);\n // Persist BEFORE anything can be signed: if the process dies after the\n // lock, the poll path still has the preimage to disclose.\n await store.save(bindKey(quoteId), [binding]);\n await store.save(quoteId, secrets.map(bytesToHex));\n return {secrets, created: true};\n }\n\n /** A quote whose id already carries an order (secrets on file) is the platform reusing an id: refuse it. */\n async function quoteIdInUse(quoteId: string): Promise<boolean> {\n const existing = await store.load(quoteId);\n return !!existing && existing.length > 0;\n }\n\n // ── TON ↔ TON: swap settlement (immediate DEX routes, no escrow) ──────────\n const SWAP_SLIPPAGE_PIPS_DEFAULT = 5_000; // 0.5%\n /** Same-chain swaps need the jetton-wallet validator (jetton input goes\n * through the trader's own wallet) and a swap-target validator (the DEX\n * contract the funds land in is resolver-chosen per route). */\n const sameChainTonReady = (): boolean =>\n typeof opts.validateTonJettonWallet === \"function\" && typeof opts.validateTonSwapTarget === \"function\";\n /** TON→EVM: the TON factory and the EVM factory are allowlisted, and the\n * jetton-wallet, escrow-payload and EVM output-position validators exist. */\n const tonSourceReady = (from: string, to: string): boolean =>\n cfg.supports(from, to) && trustedContracts.has(from) && trustedContracts.has(to) &&\n typeof opts.validateTonJettonWallet === \"function\" &&\n typeof opts.validateTonEscrowPayload === \"function\" &&\n typeof opts.validateEvmOutputPosition === \"function\";\n /** EVM→TON: the order protocol the wallet signs against AND the factory the\n * signed extension targets are allowlisted for the source chain, the TON\n * factory for the destination, and both finalized-position validators exist. */\n const evmSourceReady = (from: string, to: string): boolean =>\n cfg.supports(from, to) && trustedOrderProtocols.has(from) && trustedContracts.has(from) && trustedContracts.has(to) &&\n typeof opts.validateEvmInputPosition === \"function\" &&\n typeof opts.validateTonOutputPosition === \"function\";\n /** EVM→EVM: the source order protocol and factory, the destination factory,\n * and both EVM position validators (source fill + destination escrow). */\n const evmToEvmReady = (from: string, to: string): boolean =>\n cfg.supports(from, to) && trustedOrderProtocols.has(from) && trustedContracts.has(from) && trustedContracts.has(to) &&\n typeof opts.validateEvmInputPosition === \"function\" &&\n typeof opts.validateEvmOutputPosition === \"function\";\n\n async function getSwapQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n if (!cfg.supports(params.sourceChain, params.destChain) || !trustedContracts.has(params.sourceChain) || !sameChainTonReady()) return null;\n const source = ccAsset(params.sourceChain, params.sourceToken);\n const dest = ccAssetByToken(params.destChain, params.destToken);\n if (!source || !dest || source.symbol === dest.symbol) return null;\n const inputAsset = toAssetId(params.sourceChain, source, true);\n const outputAsset = toAssetId(params.destChain, dest, true);\n if (!inputAsset || !outputAsset || sameAsset(inputAsset, outputAsset) || !isPositiveInteger(params.amountIn)) return null;\n const trader = params.refundAddress ?? \"\";\n if (!trader && !params.dry) return null;\n const slippagePips = params.slippageBps !== undefined ? Math.round(params.slippageBps * 100) : SWAP_SLIPPAGE_PIPS_DEFAULT;\n if (!Number.isInteger(slippagePips) || slippagePips < 0 || slippagePips > 500_000) return null;\n\n const omni = await getClient();\n const settle = params.dry === false ? Math.min(quoteSettleMs, EXECUTION_SETTLE_MS) : quoteSettleMs;\n const outcome: RfqOutcome = {updates: 0};\n const rfq = async (pips: number): Promise<OmnistonQuote | null> => {\n const request: QuoteRequest = {\n inputAsset,\n outputAsset,\n amount: {$case: \"inputUnits\", value: params.amountIn},\n // One route → one outgoing message: a TON account sends exactly one.\n settlementParams: [{params: {$case: \"swap\", value: {maxPriceSlippagePips: pips, maxRoutes: 1}}}],\n };\n if (hasIntegrator) {\n const address = opts.integratorAddress ? toChainAddress(params.destChain, opts.integratorAddress) : null;\n if (!address) return null;\n request.integratorAddress = address;\n request.integratorFeePips = opts.integratorFeePips!;\n }\n // The SDK can still drop an ack (see getClient: frame delivery is now\n // deferred, which removed it in live runs) — give the socket a beat and\n // try once more.\n for (let attempt = 0; attempt < 2; attempt++) {\n if (attempt > 0) await new Promise((resolve) => setTimeout(resolve, 300));\n const quote = await awaitQuote(omni.requestForQuote(request), request, signal, settle, \"swap\", outcome);\n if (quote && quote.settlementData.$case === \"swap\") return quote;\n if (signal?.aborted) return null;\n }\n return null;\n };\n\n let q = await rfq(slippagePips);\n if (!q) {\n if (!signal?.aborted) {\n params.onRefusal?.(`omniston: ${outcome.error ? `RFQ failed: ${outcome.error}` : outcome.rejected ? `swap quote rejected: ${outcome.rejected}` : \"no TON DEX route quoted this pair/amount\"}`);\n }\n return null;\n }\n let swap = q.settlementData.$case === \"swap\" ? q.settlementData.value : null;\n if (!swap) return null;\n // Two floors the router holds a quote to, both of which a DEX quote can\n // miss by a rounding unit or a price tick: the absolute one the user saw\n // (`minAmountOut`, execution re-quotes) and the slippage one, computed by\n // the router as ceil(out × (1 − bps/10000)) where Omniston rounds its own\n // minimum down. The floor is what the trade must honour on-chain, so\n // re-quote (at most twice) with the slippage that puts the minimum on it —\n // the DEX then refunds below it.\n const absoluteFloor = params.minAmountOut !== undefined && isPositiveInteger(params.minAmountOut) ? BigInt(params.minAmountOut) : 0n;\n const requiredMin = (outputUnits: string): bigint => {\n const out = BigInt(outputUnits);\n const slippageFloor = params.slippageBps !== undefined\n ? (out * BigInt(10_000 - params.slippageBps) + 9_999n) / 10_000n\n : 0n;\n return absoluteFloor > slippageFloor ? absoluteFloor : slippageFloor;\n };\n for (let attempt = 0; attempt < 2 && BigInt(swap.minOutputAmount) < requiredMin(q.outputUnits); attempt++) {\n const out = BigInt(q.outputUnits);\n const floor = requiredMin(q.outputUnits);\n if (out < floor) return null;\n const tightened = bigintToNumber(((out - floor) * 1_000_000n) / out);\n const again = await rfq(Math.max(0, Math.min(tightened, slippagePips)));\n const againSwap = again?.settlementData.$case === \"swap\" ? again.settlementData.value : null;\n if (!again || !againSwap) return null;\n q = again;\n swap = againSwap;\n }\n if (BigInt(swap.minOutputAmount) < requiredMin(q.outputUnits)) return null;\n // The gas the route needs rides on the message; keep it under the same cap\n // that bounds escrow execution value.\n if (q.gasBudget !== undefined && BigInt(q.gasBudget) > BigInt(maxTonExecutionNano)) return null;\n // The on-chain minimum is the one at the REQUESTED slippage (the build\n // below asks for exactly that, never Omniston's \"recommended\" one, which\n // may be looser than what this quote promises).\n const minOut = swap.minOutputAmount;\n if (!(await claimBuilt(q.quoteId, {quote: q, at: Date.now(), bound: {trader, dest: params.destAddress, srcChain: params.sourceChain, kind: \"swap\"}}))) {\n traceFor(q.quoteId)(\"quote-id-reused\", {kind: \"swap\"});\n return null;\n }\n\n // Fees are charged in the OUTPUT asset; only a stable output approximates\n // USD. The TON gas budget is NOT a fee: it rides on the message and the\n // unused part returns, so it stays out of `fees` (the router's fee caps\n // would otherwise read 0.1 GRAM of gas on a 1 GRAM swap as a 10% fee).\n const feeUnits = Number(q.protocolFeeUnits || \"0\") + Number(q.integratorFeeUnits || \"0\");\n const stableOut = /^(USDT|USDC|USD₮|jUSDT)$/.test(dest.symbol);\n const feeUsd = stableOut ? feeUnits / 10 ** dest.decimals : 0;\n return {\n provider: \"omniston\",\n intentId: encodeIntent(q.quoteId, trader, params.destAddress, params.sourceChain, \"swap\"),\n depositAddress: \"\", // swap settlement — the built message pays the DEX directly\n depositMemo: null,\n sourceAmount: q.inputUnits,\n destAmount: q.outputUnits,\n minDestAmount: minOut,\n feeUsd: Number.isFinite(feeUsd) ? feeUsd : 0,\n fees: [\n ...(q.protocolFeeUnits && q.protocolFeeUnits !== \"0\" ? [{type: \"protocol\" as const, amount: q.protocolFeeUnits, token: feeToken(dest), included: true}] : []),\n ...(q.integratorFeeUnits && q.integratorFeeUnits !== \"0\" ? [{type: \"affiliate\" as const, amount: q.integratorFeeUnits, token: feeToken(dest), included: true}] : []),\n ],\n etaSeconds: 30,\n reliability: 0.9,\n validUntilMs: Date.now() + QUOTE_TTL_MS,\n // gasBudget = TON the message carries on top of the input; gasEstimate =\n // what the route is expected to burn. Consumers show both so the user\n // sees the 1.1 GRAM leaving for a 1 GRAM swap — and the refund.\n providerData: {\n settlement: \"swap\",\n protocols: swapProtocols(swap).join(\",\"),\n // For the app's own check of a remote build (omnistonVerifyBuild): the route the body must follow.\n routeSteps: JSON.stringify(swapSteps(swap)),\n ...(q.gasBudget ? {gasBudget: q.gasBudget} : {}),\n ...(q.estimatedGasConsumption ? {gasEstimate: q.estimatedGasConsumption} : {}),\n },\n };\n }\n\n async function buildSwapDeposit(\n ref: {quoteId: string; trader: string; dest: string; srcChain: string},\n q: OmnistonQuote,\n swap: SwapSettlement,\n ): Promise<UnsignedTx> {\n if (!ref.trader) throw new Error(\"omniston: quote was requested without a refund/source address\");\n if (!isTon(ref.srcChain) || q.inputAsset.chain.$case !== \"ton\" || q.outputAsset.chain.$case !== \"ton\") {\n throw new Error(\"omniston: swap quote is not a TON same-chain swap\");\n }\n if (!sameChainTonReady()) throw new Error(\"omniston: TON same-chain swaps need independent jetton-wallet and swap-target validators\");\n const owner: ChainAddress = {chain: {$case: \"ton\", value: ref.trader}};\n const receiver: ChainAddress = {chain: {$case: \"ton\", value: ref.dest}};\n const omni = await getClient();\n if (typeof omni.tonBuildSwap !== \"function\") throw new Error(\"omniston: client does not support swap settlement (tonBuildSwap)\");\n const tx = await omni.tonBuildSwap({\n quoteId: ref.quoteId,\n transferSrcAddress: owner,\n refundSrcAddress: owner,\n gasExcessAddress: owner,\n traderDstAddress: receiver,\n // Build at the slippage the quote was requested with: its\n // minOutputAmount is the minimum this module reported to the router.\n useRecommendedSlippage: false,\n });\n const [message, ...rest] = tx.messages;\n if (!message || rest.length > 0) throw new Error(`omniston: expected exactly one swap message, got ${tx.messages.length}`);\n if (message.jettonWalletStateInit) throw new Error(\"omniston: deploying a resolver-provided jetton wallet is not supported\");\n if (!isPositiveInteger(message.sendAmount)) throw new Error(\"omniston: malformed swap message value\");\n const sendAmount = BigInt(message.sendAmount);\n const gasCap = BigInt(maxTonExecutionNano);\n const gasBudget = q.gasBudget && isPositiveInteger(q.gasBudget) ? BigInt(q.gasBudget) : gasCap;\n const protocols = swapProtocols(swap);\n const inputJetton = assetContract(q.inputAsset);\n const payload = parseSwapPayload(message.payload);\n\n const routeSteps = swap.routes.length === 1 ? swap.routes[0]!.steps : [];\n const singleV1 = routeSteps.length === 1 && routeSteps[0]!.chunks.length === 1 && routeSteps[0]!.chunks[0]!.protocol === \"StonFiV1\";\n // STON.fi v1 native input (pTON v1): the message is a jetton transfer to the\n // ROUTER's pTON v1 wallet naming the router as destination (STON.fi SDK v1\n // shape; seen live 2026-10-22 for GRAM→USDT from ~100 GRAM up). Native\n // input, so the message carries input + gas.\n const ptonV1Native = !inputJetton && !!payload.jettonTransfer && singleV1;\n\n if (inputJetton) {\n // Jetton input: a transfer from the trader's OWN jetton wallet whose\n // forward lands in the DEX. The TON attached is gas only.\n const transfer = payload.jettonTransfer;\n if (!transfer) throw new Error(\"omniston: jetton-input swap message is not a jetton transfer\");\n if (sendAmount > gasCap || sendAmount > gasBudget) throw new Error(`omniston: swap message attaches more TON than the quoted gas budget (${sendAmount} > ${gasBudget} nanoTON, cap ${gasCap}, ${protocols.join(\"+\")})`);\n if (transfer.amount !== BigInt(q.inputUnits)) throw new Error(\"omniston: swap message moves a different amount than quoted\");\n if (!transfer.responseDestination || !sameTonAddress(transfer.responseDestination, ref.trader)) {\n throw new Error(\"omniston: swap message returns excess to a wallet other than the trader\");\n }\n if (transfer.forwardTon >= sendAmount) throw new Error(\"omniston: swap message forwards more TON than it carries\");\n const walletValid = await opts.validateTonJettonWallet!({\n ownerAddress: ref.trader,\n jettonMasterAddress: inputJetton,\n walletAddress: message.targetAddress,\n });\n if (!walletValid) throw new Error(\"omniston: TON jetton wallet was not independently validated\");\n const targetValid = await opts.validateTonSwapTarget!({address: transfer.destination, protocols});\n if (!targetValid) throw new Error(\"omniston: swap destination is not a recognized DEX contract for the quoted protocol\");\n } else if (ptonV1Native) {\n const transfer = payload.jettonTransfer!;\n const input = BigInt(q.inputUnits);\n if (transfer.amount !== input) throw new Error(\"omniston: swap message moves a different amount than quoted\");\n if (sendAmount < input) throw new Error(\"omniston: swap message carries less than the quoted input\");\n const gas = sendAmount - input;\n if (gas > gasCap || gas > gasBudget) throw new Error(`omniston: swap message attaches more TON than the quoted gas budget (${gas} > ${gasBudget} nanoTON, cap ${gasCap}, ${protocols.join(\"+\")})`);\n // pTON v1 forwards exactly the gas share of the value to the router (live: 0.1 of 0.1 GRAM).\n if (transfer.forwardTon > gas) throw new Error(\"omniston: swap message forwards more TON than its gas\");\n if (!transfer.responseDestination || !sameTonAddress(transfer.responseDestination, ref.trader)) {\n throw new Error(\"omniston: swap message returns excess to a wallet other than the trader\");\n }\n if (typeof opts.validateTonSwapLeg !== \"function\") throw new Error(\"omniston: STON.fi v1 native input needs the validateTonSwapLeg validator (pTON v1 wallet ownership)\");\n // The pTON v1 wallet (a router-owned proxy-TON wallet) and the router it names.\n const targetValid = await opts.validateTonSwapTarget!({address: message.targetAddress, protocols});\n if (!targetValid) throw new Error(\"omniston: swap target is not a recognized DEX contract for the quoted protocol\");\n const routerValid = await opts.validateTonSwapTarget!({address: transfer.destination, protocols});\n if (!routerValid) throw new Error(\"omniston: swap destination is not a recognized DEX contract for the quoted protocol\");\n } else {\n // Native input: the message itself pays the DEX — value = input + gas.\n if (payload.jettonTransfer) {\n // Name what came back so the refusal can be triaged: which protocol route, where the message goes and what the jetton transfer targets.\n throw new Error(`omniston: native-input swap message must not be a jetton transfer (route ${protocols.join(\"+\") || \"?\"}, target ${message.targetAddress}, transfer ${payload.jettonTransfer.amount} to ${payload.jettonTransfer.destination}, forwardTon ${payload.jettonTransfer.forwardTon}, value ${sendAmount})`);\n }\n const input = BigInt(q.inputUnits);\n if (sendAmount < input) throw new Error(\"omniston: swap message carries less than the quoted input\");\n const gas = sendAmount - input;\n if (gas > gasCap || gas > gasBudget) throw new Error(`omniston: swap message attaches more TON than the quoted gas budget (${gas} > ${gasBudget} nanoTON, cap ${gasCap}, ${protocols.join(\"+\")})`);\n const targetValid = await opts.validateTonSwapTarget!({address: message.targetAddress, protocols});\n if (!targetValid) throw new Error(\"omniston: swap target is not a recognized DEX contract for the quoted protocol\");\n }\n\n // Scan F11: open the DEX call and bind receiver, refund/excess, minimum\n // output and the route's contracts to the quote. The pTON v1 path is new\n // and always enforced; elsewhere `tonSwapPayloadCheck` decides.\n const mode = ptonV1Native ? \"enforce\" : (opts.tonSwapPayloadCheck ?? \"enforce\");\n const trace = traceFor(ref.quoteId);\n const payloadRefusal = (reason: string, detail: string): void => {\n trace(\"ton-swap-payload\", {reason, detail, mode, protocols: protocols.join(\"+\")});\n if (mode === \"enforce\") throw new Error(`omniston: ton-swap-payload ${reason} — ${detail}`);\n };\n let checked: TonSwapCheckResult | null = null;\n try {\n checked = checkTonSwapPayload({\n payloadHex: message.payload,\n targetAddress: message.targetAddress,\n sendAmount,\n trader: ref.trader,\n dest: ref.dest,\n inputUnits: q.inputUnits,\n minOutputAmount: swap.minOutputAmount,\n inputJetton,\n outputJetton: assetContract(q.outputAsset),\n steps: swapSteps(swap),\n integratorAddress: q.integratorAddress?.chain.$case === \"ton\" ? q.integratorAddress.chain.value : null,\n });\n } catch (error) {\n if (error instanceof TonSwapPayloadError) payloadRefusal(error.reason, error.message);\n else payloadRefusal(\"malformed\", error instanceof Error ? error.message : String(error));\n }\n if (checked) {\n if (typeof opts.validateTonSwapLeg !== \"function\") {\n trace(\"ton-swap-payload\", {reason: \"legs-unverified\", detail: \"no validateTonSwapLeg hook\", mode, legs: checked.legs.length});\n } else {\n for (const leg of checked.legs) {\n let ok = false;\n try { ok = await opts.validateTonSwapLeg(leg); } catch { ok = false; }\n if (!ok) {\n payloadRefusal(\"leg-unverified\", `${leg.kind} v${leg.version} ${leg.kind === \"dedust-pool\" ? `pool ${leg.pool}` : `ask wallet ${leg.askWallet}`}`);\n break;\n }\n }\n }\n }\n\n return {\n chain: ref.srcChain,\n to: message.targetAddress,\n value: message.sendAmount, // nanotons: gas only (jetton input) or input + gas (native)\n bodyBoc: hexToBase64(message.payload),\n };\n }\n\n async function trackSwap(decoded: {quoteId: string; trader: string}, sourceTxHash: string | null): Promise<IntentStatus> {\n // swapTrack needs a handle on the outgoing transaction; until the caller\n // knows it, the trade is simply pending.\n if (!sourceTxHash) return {state: \"pending\"};\n const omni = await getClient();\n if (typeof omni.swapTrack !== \"function\") return {state: \"pending\"};\n const progress = await awaitSwapProgress(\n omni.swapTrack({quoteId: decoded.quoteId, traderAddress: {chain: {$case: \"ton\", value: decoded.trader}}, outgoingTxQuery: sourceTxHash}),\n );\n if (!progress || progress === \"awaiting\") return {state: \"pending\"};\n switch (progress.status) {\n case \"TRADE_STATUS_FULLY_FILLED\":\n await quotes.clear(decoded.quoteId);\n return {state: \"completed\", depositReceived: true, ...(progress.outgoingTxHash ? {destTxHash: progress.outgoingTxHash} : {})};\n case \"TRADE_STATUS_PARTIALLY_FILLED\":\n // One route, so a partial fill means the DEX returned the rest to the\n // trader: the trade is over, and partial — not completed (round 3, L16).\n await quotes.clear(decoded.quoteId);\n return {state: \"partial\", depositReceived: true, ...(progress.outgoingTxHash ? {destTxHash: progress.outgoingTxHash} : {})};\n case \"TRADE_STATUS_CANCELLED\":\n case \"TRADE_STATUS_FAILED\":\n // A failed DEX swap bounces the input back to the trader on-chain: refunded (round 3, L16).\n await quotes.clear(decoded.quoteId);\n return {state: \"refunded\", depositReceived: true};\n default:\n return {state: \"pending\", depositReceived: true};\n }\n }\n\n /**\n * EVM→TON: generate the HTLC secret, ask Omniston for the EIP-712 order,\n * verify every byte the wallet is about to sign against the quote (order\n * fields, the 1inch extension the salt commits to, the serialized order\n * details), persist what registration needs, and hand the engine a gasless\n * typed-order `UnsignedTx` whose `approvalAddress` is the order protocol.\n */\n async function buildEvmOrder(\n ref: Decoded,\n q: OmnistonQuote,\n settlement: OrderSettlement,\n bound: IntentBinding | undefined,\n ): Promise<UnsignedTx> {\n const srcChain = ref.srcChain;\n const chainId = evmRef(srcChain);\n const srcCase = q.inputAsset.chain.$case;\n if (chainId === null || EVM_CASE[chainId] !== srcCase) throw new Error(\"omniston: source chain does not match the EVM quote\");\n const destCase = q.outputAsset.chain.$case;\n const destChain = caipForChainCase(destCase);\n const tonDest = destCase === \"ton\";\n if (!destChain || destChain === srcChain) throw new Error(\"omniston: EVM-source order has no supported destination chain\");\n if (\n !trustedOrderProtocols.has(srcChain) || typeof opts.validateEvmInputPosition !== \"function\" ||\n typeof (tonDest ? opts.validateTonOutputPosition : opts.validateEvmOutputPosition) !== \"function\"\n ) {\n throw new Error(`omniston: EVM→${tonDest ? \"TON\" : \"EVM\"} needs a trusted order protocol and both position validators`);\n }\n let owner: string;\n try {\n owner = getAddress(ref.trader);\n } catch {\n throw new Error(\"omniston: trader is not an EVM address\");\n }\n let dest: string;\n if (tonDest) {\n try {\n TonAddress.parse(ref.dest);\n } catch {\n throw new Error(\"omniston: destination is not a TON address\");\n }\n dest = ref.dest;\n } else {\n try {\n dest = getAddress(ref.dest);\n } catch {\n throw new Error(\"omniston: destination is not an EVM address\");\n }\n }\n const traderDst = {chain: {$case: destCase, value: dest}} as ChainAddress;\n const protocol = settlement.srcProtocolContractAddress;\n const resolver = settlement.srcInitialResolverAddress;\n const factory = settlement.dstProtocolContractAddress;\n const inputToken = assetContract(q.inputAsset);\n const outputToken = assetContract(q.outputAsset);\n const destChainId = tonDest ? null : evmRef(destChain);\n if (\n protocol.chain.$case !== srcCase || !isTrustedOrderProtocol(srcChain, protocol.chain.value) ||\n resolver?.chain.$case !== srcCase || !validEvmAddress(resolver.chain.value) ||\n factory?.chain.$case !== destCase || !isTrusted(destChain, factory.chain.value) ||\n !inputToken || !outputToken || !Number.isSafeInteger(settlement.protocolFeePips) ||\n (!tonDest && (destChainId === null || !validEvmAddress(outputToken) || !isPositiveInteger(settlement.dstSecurityDepositUnits ?? \"\")))\n ) throw new Error(\"omniston: incomplete EVM order settlement binding in quote\");\n\n // One execution: the signed order has ALLOW_MULTIPLE_FILLS clear and the\n // TON position commits a single hash. Persist BEFORE anything is signed.\n const {secrets, created} = await secretsFor(ref, q, 1);\n const hashes = secrets.map((secret) => hashlock(secret, settlement.htlcHashingFunction));\n // Clear only what this call created: a failed rebuild must not take the\n // secret of an order an earlier build already handed out for signing.\n const forget = async () => { if (created) await clearSecrets(ref.quoteId); };\n const omni = await getClient();\n let payload: Awaited<ReturnType<OmnistonClientLike[\"evmBuildOrderPayload\"]>>;\n try {\n payload = await omni.evmBuildOrderPayload({\n quoteId: ref.quoteId,\n ownerSrcAddress: {chain: {$case: srcCase, value: owner}} as ChainAddress,\n traderDstAddress: traderDst,\n htlcSecrets: {secretMode: {$case: \"provided\", value: {hashes}}},\n });\n } catch (error) {\n await forget();\n throw error;\n }\n let td: unknown;\n try {\n try {\n td = JSON.parse(payload.typedData);\n } catch {\n throw new Error(\"omniston: malformed EVM order typed data\");\n }\n validateSerializedOrderDetails(payload.serializedOrderDetails, {\n quoteId: ref.quoteId,\n outputAsset: q.outputAsset,\n traderDstAddress: traderDst,\n secretHashes: hashes,\n });\n validateEvmTypedOrder(td, {\n chainId,\n settlementContract: protocol.chain.value,\n owner,\n receiver: resolver.chain.value,\n makerAsset: inputToken,\n makingAmount: q.inputUnits,\n takingAmount: settlement.resolverSendsUnits,\n orderExtension: payload.orderExtension,\n quoteTimestamp: q.quoteTimestamp,\n tradeStartDeadline: settlement.tradeStartDeadline,\n });\n await validateEvmToTonOrderExtension(payload.orderExtension, {\n quoteId: ref.quoteId,\n quoteTimestamp: q.quoteTimestamp,\n tradeStartDeadline: settlement.tradeStartDeadline,\n protocolFeePips: settlement.protocolFeePips!,\n integratorFeePips: settlement.integratorFeePips ?? 0,\n initialResolverAddress: resolver.chain.value,\n outputTokenAddress: outputToken,\n traderDstAddress: dest,\n takerAsset: String(td.message.takerAsset),\n srcSecurityDepositUnits: settlement.srcHtlcSecurityDepositUnits ?? \"\",\n // TON destination: the TON deposit is bound in the TON position, not in\n // the EVM deposits word (live: 0 for every TON-destination order). EVM\n // destination: the word carries the quote's destination deposit and\n // ExtraDataArgs name the destination chain and token (live 2026-10-20).\n dstSecurityDepositUnits: tonDest ? \"0\" : settlement.dstSecurityDepositUnits!,\n ...(tonDest ? {} : {dstChainId: destChainId!}),\n secretHash: hashes[0]!,\n trustedTarget: (address) => isTrusted(srcChain, address),\n });\n } catch (error) {\n await forget();\n throw error;\n }\n // The validated extension targets one trusted factory on the source chain.\n const extensionTarget = getAddress(`0x${bytesToHex(payload.orderExtension.slice(32 + new DataView(payload.orderExtension.buffer, payload.orderExtension.byteOffset).getUint32(4, false), 32 + new DataView(payload.orderExtension.buffer, payload.orderExtension.byteOffset).getUint32(4, false) + 20))}`);\n // The SDK sends the domain chainId as a hex string (\"0x2105\"). Hand the\n // wallet a numeric chainId: signers that derive the EIP712Domain type from\n // the value types (viem) would otherwise sign a domain WITHOUT chainId and\n // the order protocol would reject the signature (live 2026-10-16).\n const typedData = JSON.stringify({...(td as object), domain: {...(td as {domain: object}).domain, chainId}});\n // Re-save the WHOLE entry: carry the binding forward, or every later\n // disclosure for this order would be refused as unbound.\n await saveBuilt(ref.quoteId, {\n quote: q,\n at: Date.now(),\n ...(bound ? {bound} : {}),\n evmOrder: {\n typedData,\n orderExtension: bytesToHex(payload.orderExtension),\n serializedOrderDetails: bytesToHex(payload.serializedOrderDetails ?? new Uint8Array()),\n owner,\n chainCase: srcCase,\n factory: extensionTarget,\n },\n });\n const orderProtocol = getAddress(protocol.chain.value);\n return {chain: srcChain, to: orderProtocol, value: \"0\", chainId, approvalAddress: orderProtocol, typedData};\n }\n\n return {\n name: \"omniston\",\n describeActivity: describeOmnistonActivity,\n enabled: () => (opts.enabled ?? true) && trustedContracts.size > 0,\n\n // Capability discovery comes from the provider itself, so it can run alone\n // or inside the optional aggregator without a central capability table.\n supportsChain: (chain: string) => cfg.supportsChain(chain),\n supportsChainPair: (fromChain: string, toChain: string) => cfg.supports(fromChain, toChain), // TON↔TON swap settlement is same-chain by definition.\n supportsSameChain: true,\n\n supportsRoute(from: Asset, to: Asset): boolean {\n if (isTon(from.chain) && isTon(to.chain)) {\n return cfg.supports(from.chain, to.chain) && trustedContracts.has(from.chain) && sameChainTonReady();\n }\n if (isTon(from.chain) && !isTon(to.chain)) return tonSourceReady(from.chain, to.chain);\n if (!isTon(from.chain) && isTon(to.chain)) return evmSourceReady(from.chain, to.chain);\n return evmToEvmReady(from.chain, to.chain);\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n // Amount-flexible deposits need a static deposit address — orders don't have one.\n if (params.flex) return null;\n if (isTon(params.sourceChain) && isTon(params.destChain)) return await getSwapQuote(params, signal);\n const refuse = (reason: string): null => {\n params.onRefusal?.(`omniston: ${reason}`);\n return null;\n };\n const evmSource = !isTon(params.sourceChain);\n const tonDest = isTon(params.destChain);\n if (!cfg.supports(params.sourceChain, params.destChain)) return refuse(\"route is not an Omniston order corridor\");\n if (!trustedContracts.has(params.sourceChain) || !trustedContracts.has(params.destChain)) {\n return refuse(`no trusted settlement contract configured for ${trustedContracts.has(params.sourceChain) ? params.destChain : params.sourceChain}`);\n }\n if (evmSource) {\n if (!trustedOrderProtocols.has(params.sourceChain)) return refuse(`no trusted EVM order protocol configured for ${params.sourceChain}`);\n if (typeof opts.validateEvmInputPosition !== \"function\" || typeof (tonDest ? opts.validateTonOutputPosition : opts.validateEvmOutputPosition) !== \"function\") {\n return refuse(tonDest\n ? \"EVM→TON needs the EVM input-position and TON output-position validators\"\n : \"EVM→EVM needs the EVM input-position and EVM output-position validators\");\n }\n if (params.dry === false) {\n if (tonDest) {\n try {\n TonAddress.parse(params.destAddress);\n } catch {\n return refuse(\"destination is not a TON address\");\n }\n } else if (!validEvmAddress(params.destAddress)) return refuse(\"destination is not an EVM address\");\n }\n } else if (\n typeof opts.validateTonJettonWallet !== \"function\" ||\n typeof opts.validateTonEscrowPayload !== \"function\" ||\n typeof opts.validateEvmOutputPosition !== \"function\"\n ) return refuse(\"TON→EVM needs the jetton-wallet, escrow-payload and EVM output-position validators\");\n\n const source = ccAsset(params.sourceChain, params.sourceToken);\n const dest = ccAssetByToken(params.destChain, params.destToken);\n if (!source || !dest) return refuse(\"asset is not in the catalog\");\n const inputAsset = toAssetId(params.sourceChain, source);\n const outputAsset = toAssetId(params.destChain, dest);\n if (!inputAsset || !outputAsset) {\n return refuse(`cross-chain orders are token corridors only (no ${!inputAsset ? source.symbol : dest.symbol} native leg)`);\n }\n\n // The resolver only fills the corridor up to ~$1000 a swap (stables 1:1).\n const maxUnits = decimalToUnits(maxUsdText, source.decimals);\n if (!maxUnits || !isPositiveInteger(params.amountIn)) return refuse(\"invalid amount\");\n if (BigInt(params.amountIn) > maxUnits) return refuse(`amount above the ${maxUsdText} USD per-swap cap`);\n\n // Execution and tracking both need the trader's source-chain wallet.\n const trader = params.refundAddress ?? \"\";\n if (!trader && !params.dry) return refuse(`execution quote needs the trader's ${evmSource ? \"EVM\" : \"TON\"} address (refundAddress)`);\n if (evmSource && trader && !validEvmAddress(trader)) return refuse(\"refundAddress is not an EVM address\");\n\n const request: QuoteRequest = {\n inputAsset,\n outputAsset,\n amount: {$case: \"inputUnits\", value: params.amountIn},\n settlementParams: [{params: {$case: \"order\", value: {}}}],\n } as QuoteRequest;\n const integrator = opts.integratorAddress ?? \"\";\n if (hasIntegrator) {\n const pips = opts.integratorFeePips!;\n const address = integrator ? toChainAddress(params.destChain, integrator) : null;\n if (!address) return refuse(\"integrator address is not valid on the destination chain\");\n request.integratorAddress = address;\n request.integratorFeePips = pips;\n }\n\n const omni = await getClient();\n const rfq: RfqOutcome = {updates: 0};\n const q = await awaitQuote(\n omni.requestForQuote(request),\n request,\n signal,\n params.dry === false ? Math.min(quoteSettleMs, EXECUTION_SETTLE_MS) : quoteSettleMs,\n \"order\",\n rfq,\n );\n if (!q) {\n if (signal?.aborted) return null;\n return refuse(\n rfq.error ? `RFQ failed: ${rfq.error}`\n : rfq.rejected ? `resolver quote rejected: ${rfq.rejected}`\n : \"no resolver quoted this route/amount\",\n );\n }\n const orderData = q.settlementData.$case === \"order\" ? q.settlementData.value : null;\n if (!orderData) return refuse(\"resolver answered without order settlement\");\n const srcContract = orderData.srcProtocolContractAddress.chain.value;\n if (evmSource ? !isTrustedOrderProtocol(params.sourceChain, srcContract) : !isTrusted(params.sourceChain, srcContract)) {\n return refuse(evmSource ? `untrusted ${params.sourceChain} order protocol ${srcContract}` : `untrusted TON settlement contract ${srcContract}`);\n }\n if (!orderData.dstProtocolContractAddress || !isTrusted(params.destChain, orderData.dstProtocolContractAddress.chain.value)) {\n return refuse(`untrusted ${params.destChain} settlement contract ${orderData.dstProtocolContractAddress?.chain.value ?? \"(none)\"}`);\n }\n const deadlineMs = orderData.tradeStartDeadline * 1000;\n if (!Number.isFinite(deadlineMs) || deadlineMs <= Date.now()) return refuse(\"quote trade-start deadline already passed\");\n // An execution quote whose deadline cannot outlast signing + inclusion\n // would fund an escrow no resolver will fill.\n if (params.dry === false && deadlineMs - Date.now() < MIN_START_HEADROOM_MS) return refuse(\"quote trade-start deadline too close to execute\");\n\n // The advertised corridors are stable-to-stable. Bound a resolver's\n // optimistic amount before it can dominate the router auction with an\n // impossible quote; settlement remains all-or-refund within this range.\n const inputScaled = BigInt(q.inputUnits) * 10n ** BigInt(dest.decimals);\n const outputScaled = BigInt(q.outputUnits) * 10n ** BigInt(source.decimals);\n if (outputScaled * 2n < inputScaled || outputScaled > inputScaled * 2n) return refuse(\"quoted output is outside 0.5x–2x of the input\");\n\n if (await quoteIdInUse(q.quoteId)) return refuse(\"the platform reused a quote id that already belongs to an order\");\n if (!(await claimBuilt(q.quoteId, {quote: q, at: Date.now(), bound: {trader, dest: params.destAddress, srcChain: params.sourceChain, kind: \"order\"}}))) {\n return refuse(\"the platform reused a quote id that already holds another user's quote\");\n }\n\n // Fees are charged in the OUTPUT asset; the corridor is stables, so units\n // scaled by the dest decimals approximate USD.\n const feeUnits = Number(q.protocolFeeUnits || \"0\") + Number(q.integratorFeeUnits || \"0\");\n const feeUsd = feeUnits / 10 ** dest.decimals;\n\n return {\n provider: \"omniston\",\n intentId: encodeIntent(q.quoteId, trader, params.destAddress, params.sourceChain),\n depositAddress: \"\", // order settlement — no static deposit address\n depositMemo: null,\n sourceAmount: q.inputUnits,\n destAmount: q.outputUnits,\n minDestAmount: q.outputUnits, // HTLC fills at the quoted amount or refunds\n feeUsd: Number.isFinite(feeUsd) ? feeUsd : 0,\n fees: [\n ...(q.protocolFeeUnits && q.protocolFeeUnits !== \"0\" ? [{type: \"protocol\" as const, amount: q.protocolFeeUnits, token: feeToken(dest), included: true}] : []),\n ...(q.integratorFeeUnits && q.integratorFeeUnits !== \"0\" ? [{type: \"affiliate\" as const, amount: q.integratorFeeUnits, token: feeToken(dest), included: true}] : []),\n ],\n etaSeconds: 240,\n reliability: 0.9,\n validUntilMs: Math.min(Date.now() + QUOTE_TTL_MS, deadlineMs),\n };\n },\n\n /**\n * TON-source only: generate the HTLC secret, persist it, build the escrow\n * transfer. The returned tx carries the payload as a serialized CELL\n * (`bodyBoc`, base64) — sending it as a text comment would strand the swap.\n */\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n if (!Number.isFinite(quote.validUntilMs) || quote.validUntilMs <= Date.now()) {\n throw new Error(\"omniston: quote expired — request a fresh quote\");\n }\n const decoded = decodeIntent(quote.intentId);\n if (!decoded) throw new Error(\"omniston: malformed intent id\");\n const cached = await loadBuilt(decoded.quoteId);\n if (!cached) throw new Error(\"omniston: quote expired — request a fresh quote\");\n const ref = requireBinding(decoded, cached, \"buildDeposit\");\n const q = cached.quote;\n if (q.settlementData.$case === \"swap\") return await buildSwapDeposit(ref, q, q.settlementData.value);\n if (q.settlementData.$case !== \"order\" || q.settlementData.value.tradeStartDeadline * 1000 <= Date.now()) {\n throw new Error(\"omniston: quote trade deadline expired — request a fresh quote\");\n }\n\n if (!ref.trader) throw new Error(\"omniston: quote was requested without a refund/source address\");\n const srcCase = q.inputAsset.chain.$case;\n if (srcCase !== \"ton\") return await buildEvmOrder(ref, q, q.settlementData.value, cached.bound);\n const srcChain = ref.srcChain;\n if (!isTon(srcChain)) throw new Error(\"omniston: source chain does not match TON quote\");\n const destCase = q.outputAsset.chain.$case;\n const traderDst = destCase === \"ton\" ? null : {chain: {$case: destCase, value: getAddress(ref.dest)}};\n if (!traderDst) throw new Error(\"omniston: TON-destination orders are not supported\");\n\n const settlement = q.settlementData;\n const hashingFunction = settlement.$case === \"order\" ? settlement.value.htlcHashingFunction : undefined;\n const {secrets, created} = await secretsFor(ref, q, maxExecutions);\n const hashes = secrets.map((s) => hashlock(s, hashingFunction));\n // Clear only what this call created (see buildEvmOrder).\n const forget = async () => { if (created) await clearSecrets(ref.quoteId); };\n\n const owner: ChainAddress = {chain: {$case: \"ton\", value: ref.trader}};\n const omni = await getClient();\n let tx: {messages: EscrowMessage[]};\n try {\n tx = await omni.tonBuildEscrowTransfer({\n quoteId: ref.quoteId,\n ownerSrcAddress: owner,\n transferSrcAddress: owner,\n refundSrcAddress: owner,\n gasExcessAddress: owner,\n traderDstAddress: traderDst as ChainAddress,\n htlcSecrets: {secretMode: {$case: \"provided\", value: {hashes}}},\n });\n } catch (error) {\n await forget();\n throw error;\n }\n const [message, ...rest] = tx.messages;\n if (!message || rest.length > 0) {\n await forget();\n throw new Error(`omniston: expected exactly one escrow message, got ${tx.messages.length}`);\n }\n if (!isPositiveInteger(message.sendAmount) || BigInt(message.sendAmount) > BigInt(maxTonExecutionNano)) {\n await forget();\n throw new Error(\"omniston: resolver TON execution value exceeds the configured safety cap\");\n }\n const expectedProtocol = q.settlementData.value.srcProtocolContractAddress;\n const initialResolver = q.settlementData.value.srcInitialResolverAddress;\n const jettonMaster = assetContract(q.inputAsset);\n if (expectedProtocol.chain.$case !== \"ton\" || initialResolver?.chain.$case !== \"ton\" || !jettonMaster) {\n await forget();\n throw new Error(\"omniston: incomplete TON settlement binding in quote\");\n }\n if (message.jettonWalletStateInit) {\n await forget();\n throw new Error(\"omniston: deploying a resolver-provided jetton wallet is not supported\");\n }\n let walletValid = false;\n try {\n walletValid = opts.validateTonJettonWallet\n ? await opts.validateTonJettonWallet({\n ownerAddress: ref.trader,\n jettonMasterAddress: jettonMaster,\n walletAddress: message.targetAddress,\n })\n : false;\n } catch (error) {\n await forget();\n throw error;\n }\n if (!walletValid) {\n await forget();\n throw new Error(\"omniston: TON jetton wallet was not independently validated\");\n }\n try {\n if (!opts.validateTonEscrowPayload) {\n throw new Error(\"omniston: TON source requires an independent escrow-payload validator\");\n }\n await validateTonEscrowPayload(message, {\n quoteId: ref.quoteId,\n inputUnits: q.inputUnits,\n resolverSendsUnits: q.settlementData.value.resolverSendsUnits,\n srcHtlcSecurityDepositUnits: q.settlementData.value.srcHtlcSecurityDepositUnits ?? \"\",\n protocolAddress: expectedProtocol.chain.value,\n ownerAddress: ref.trader,\n destinationChain: q.outputAsset.chain.$case,\n destinationAddress: ref.dest,\n outputTokenAddress: assetContract(q.outputAsset) ?? \"\",\n initialResolverAddress: initialResolver.chain.value,\n hashes,\n ...(hashingFunction ? {hashingFunction} : {}),\n exclusivityTimeout: q.settlementData.value.exclusivityTimeout ?? 0,\n }, opts.validateTonEscrowPayload);\n } catch (error) {\n await forget();\n throw error;\n }\n\n // Re-save the WHOLE entry with its binding, as the EVM build does: the context disclosure is checked against.\n await saveBuilt(ref.quoteId, {quote: q, at: Date.now(), ...(cached.bound ? {bound: cached.bound} : {})});\n return {\n chain: srcChain,\n to: message.targetAddress,\n value: message.sendAmount, // nanotons (gas + forward), NOT the jetton amount\n bodyBoc: hexToBase64(message.payload),\n };\n },\n\n /**\n * Snapshot the order and use ready phases only to discover candidate EVM\n * escrows. Disclosure follows only after independent finalized on-chain\n * validation; transient failures are retried on the next poll.\n */\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n const decoded = decodeIntent(ref.intentId);\n if (!decoded) throw new Error(\"omniston: malformed intent id\");\n // Swap settlement never discloses anything: tracked from the feed alone.\n if (decoded.kind === \"swap\") return await trackSwap(decoded, ref.sourceTxHash ?? null);\n const trace = traceFor(decoded.quoteId);\n // The secret is released only against the context stored when the quote\n // was minted — never against trader/dest from the caller's intentId\n // (scan F3/F15). Without a cached context (completed, TTL) this is a plain\n // status read of the feed, exactly as before.\n const stored = await loadBuilt(decoded.quoteId);\n let cached: BuiltEntry | undefined;\n let bound: Decoded = decoded;\n if (stored) {\n const result = bindIntent(decoded, stored);\n if (!result.ok && result.reason === \"mismatch\") {\n trace(\"intent-mismatch\", {where: \"trackIntent\", field: result.field});\n throw new Error(`omniston: intent id does not match the quote it was issued for (${result.field})`);\n }\n if (result.ok) {\n if (result.legacy) trace(\"legacy-intent\", {where: \"trackIntent\"});\n cached = stored;\n bound = result.ref;\n } else {\n trace(\"legacy-intent-expired\", {where: \"trackIntent\"});\n }\n }\n const omni = await getClient();\n const order = await awaitOrder(\n omni.orderTrack({\n quoteId: decoded.quoteId,\n traderAddress:\n toChainAddress(bound.srcChain, bound.trader) ??\n ({chain: {$case: \"ton\", value: bound.trader}} as ChainAddress),\n }),\n );\n if (!order) return {state: \"pending\"};\n\n let secretsHex = await store.load(decoded.quoteId);\n if (!secretsHex || cached?.quote.settlementData.$case !== \"order\") trace(\"disclosure-skipped\", {gate: \"context\", secrets: !!secretsHex, cached: !!cached, feedStatus: order.status});\n // The secrets were locked to one order (trader, dest, chain, assets, units): the context they are disclosed\n // against must be that order — never a context rebound under a reused quote id after they were made (scan\n // 2026-10-27 modules, F27).\n if (secretsHex && cached?.quote.settlementData.$case === \"order\") {\n const [lockedTo] = (await store.load(bindKey(decoded.quoteId))) ?? [];\n if (lockedTo !== orderBinding(bound, cached.quote)) {\n trace(\"disclosure-skipped\", {gate: \"binding\", bound: lockedTo !== undefined, feedStatus: order.status});\n secretsHex = undefined;\n }\n }\n if (secretsHex && cached?.quote.settlementData.$case === \"order\") {\n const q = cached.quote;\n const settlement = q.settlementData.value as OrderSettlement;\n const indices = order.executions.map((execution) => execution.index);\n const validIndices = indices.every((index) => Number.isSafeInteger(index) && index >= 0 && index < secretsHex.length) &&\n new Set(indices).size === indices.length;\n const outputTokenAddress = assetContract(q.outputAsset);\n const outputChain = q.outputAsset.chain.$case;\n const outputCaip = caipForChainCase(outputChain);\n const factory = settlement.dstProtocolContractAddress;\n const evmSource = q.inputAsset.chain.$case !== \"ton\";\n const tonDest = outputChain === \"ton\";\n const inputChain = q.inputAsset.chain.$case;\n const inputCaip = caipForChainCase(inputChain);\n const inputTokenAddress = assetContract(q.inputAsset);\n const evmOrder = cached.evmOrder;\n await Promise.all(\n order.executions.map(async (execution) => {\n const i = execution.index;\n const secret = validIndices ? secretsHex[i] : undefined;\n const phase = execution.outputPositionPhase;\n const position = execution.outputPositionAddress;\n const inputPosition = execution.inputPositionAddress;\n if (\n !secret || !validDisclosurePhase(phase) || !position || position.chain.$case !== outputChain ||\n !position.chain.value || !factory || factory.chain.$case !== outputChain || !outputTokenAddress || !outputCaip\n ) { trace(\"disclosure-skipped\", {gate: \"position\", index: i, phase, positionChain: position?.chain.$case, outputChain}); return; }\n if (evmSource\n ? (!evmOrder || !inputCaip || !inputTokenAddress || !inputPosition || inputPosition.chain.$case !== inputChain || !inputPosition.chain.value ||\n !settlement.srcInitialResolverAddress || typeof opts.validateEvmInputPosition !== \"function\" ||\n typeof (tonDest ? opts.validateTonOutputPosition : opts.validateEvmOutputPosition) !== \"function\")\n : typeof opts.validateEvmOutputPosition !== \"function\"\n ) { trace(\"disclosure-skipped\", {gate: \"context-fields\", index: i, evmSource, evmOrder: !!evmOrder, inputPositionChain: inputPosition?.chain.$case}); return; }\n const secretBytes = hexToBytes(secret);\n const expectedHash = hashlock(secretBytes, settlement.htlcHashingFunction);\n if (\n !execution.secretHash || !bytesEqual(execution.secretHash, expectedHash) ||\n execution.inputUnits !== q.inputUnits || execution.outputUnits !== q.outputUnits ||\n execution.resolverSendsUnits !== settlement.resolverSendsUnits\n ) { trace(\"disclosure-skipped\", {gate: \"terms\", index: i, hashMatches: !!execution.secretHash && bytesEqual(execution.secretHash, expectedHash), inputUnits: [execution.inputUnits, q.inputUnits], outputUnits: [execution.outputUnits, q.outputUnits], resolverSendsUnits: [execution.resolverSendsUnits, settlement.resolverSendsUnits]}); return; }\n let verified = false;\n try {\n const evmOutput = () => opts.validateEvmOutputPosition!({\n chain: outputCaip,\n positionAddress: position.chain.value,\n factoryAddress: factory.chain.value,\n quoteTimestamp: q.quoteTimestamp,\n executionIndex: i,\n recipientAddress: bound.dest,\n outputTokenAddress,\n inputUnits: execution.inputUnits,\n outputUnits: execution.outputUnits,\n resolverSendsUnits: execution.resolverSendsUnits,\n srcHtlcSecurityDepositUnits: settlement.srcHtlcSecurityDepositUnits ?? \"\",\n dstSecurityDepositUnits: settlement.dstSecurityDepositUnits ?? \"\",\n protocolFeeUnits: q.protocolFeeUnits ?? \"0\",\n integratorFeeUnits: q.integratorFeeUnits ?? \"0\",\n ...(q.integratorAddress?.chain.value ? {integratorAddress: q.integratorAddress.chain.value} : {}),\n ...(settlement.protocolFeeRecipientAddress?.chain.value ? {protocolFeeRecipientAddress: settlement.protocolFeeRecipientAddress.chain.value} : {}),\n secretHash: expectedHash,\n });\n // EVM source: BOTH positions must be proven before the secret\n // leaves — the trader's full input locked on the source chain for\n // this hashlock, and the destination position (TON or EVM) the\n // trusted factory deployed for this quote, paying the recipient.\n verified = evmSource\n ? await opts.validateEvmInputPosition!({\n chain: inputCaip!,\n positionAddress: inputPosition!.chain.value,\n factoryAddress: evmOrder!.factory,\n orderProtocolAddress: settlement.srcProtocolContractAddress.chain.value,\n ownerAddress: evmOrder!.owner,\n resolverAddress: settlement.srcInitialResolverAddress!.chain.value,\n inputTokenAddress: inputTokenAddress!,\n inputUnits: execution.inputUnits,\n resolverSendsUnits: execution.resolverSendsUnits,\n srcHtlcSecurityDepositUnits: settlement.srcHtlcSecurityDepositUnits ?? \"\",\n quoteTimestamp: q.quoteTimestamp,\n secretHash: expectedHash,\n ...(tonDest ? {} : {\n destinationChainId: evmRef(outputCaip)!,\n destinationTokenAddress: outputTokenAddress,\n dstSecurityDepositUnits: settlement.dstSecurityDepositUnits ?? \"\",\n }),\n }) && (tonDest\n ? await opts.validateTonOutputPosition!({\n positionAddress: position.chain.value,\n protocolAddress: factory.chain.value,\n outputJettonMasterAddress: outputTokenAddress,\n recipientAddress: bound.dest,\n quoteId: decoded.quoteId,\n quoteTimestamp: q.quoteTimestamp,\n inputUnits: execution.inputUnits,\n outputUnits: execution.outputUnits,\n resolverSendsUnits: execution.resolverSendsUnits,\n dstSecurityDepositUnits: settlement.dstSecurityDepositUnits ?? \"\",\n secretHash: expectedHash,\n })\n : await evmOutput())\n : await evmOutput();\n } catch (error) {\n verified = false;\n trace(\"validator-threw\", {index: i, error: error instanceof Error ? error.message : String(error)});\n }\n if (!verified) { trace(\"validator-refused\", {index: i, evmSource, tonDest}); return; }\n await omni\n .orderDiscloseHtlcSecret({quoteId: decoded.quoteId, executionIndex: i, secret: secretBytes})\n .then(async () => {\n trace(\"secret-disclosed\", {index: i});\n // Disclosed = known to the counterparty: never lock a new order to it (scan F6).\n await store.save(disclosedKey(decoded.quoteId), [\"1\"]);\n }, (error) => trace(\"disclose-failed\", {index: i, error: error instanceof Error ? error.message : String(error)})); // retried on the next poll\n }),\n );\n }\n\n const status = mapOrderStatus(order);\n const delivered = order.executions[0]?.outputPositionAddress;\n const outCase = cached?.quote.outputAsset.chain.$case;\n const outCaip = outCase ? caipForChainCase(outCase) : null;\n const outToken = cached ? assetContract(cached.quote.outputAsset) : null;\n if (\n status.state === \"completed\" && opts.locateEvmDelivery && outCase && outCase !== \"ton\" && outCaip && outToken &&\n order.executions.length === 1 && delivered?.chain.$case === outCase && delivered.chain.value\n ) {\n const hash = await opts.locateEvmDelivery({\n chain: outCaip, positionAddress: delivered.chain.value, recipientAddress: bound.dest,\n tokenAddress: outToken, minUnits: order.executions[0]!.outputUnits,\n }).catch(() => null);\n if (hash) status.destTxHash = hash;\n }\n if (\n status.state === \"completed\" && !status.destTxHash && opts.locateTonDelivery && outCase === \"ton\" && outToken &&\n order.executions.length === 1 && delivered?.chain.$case === \"ton\" && delivered.chain.value\n ) {\n const hash = await opts.locateTonDelivery({\n positionAddress: delivered.chain.value, recipientAddress: bound.dest,\n jettonMasterAddress: outToken, minUnits: order.executions[0]!.outputUnits,\n }).catch(() => null);\n if (hash) status.destTxHash = hash;\n }\n // A feed-only CANCELLED/FAILED signal is not on-chain invalidation of a\n // signed order. Retain secrets/context until proven completion or TTL so\n // a late valid output lock can still be completed safely.\n if (status.state === \"completed\") {\n await clearSecrets(decoded.quoteId);\n await quotes.clear(decoded.quoteId);\n }\n return status;\n },\n /** EVM→TON: hand the wallet's EIP-712 signature over the validated order to Omniston. */\n async registerSignedOrder(intentId: string, signature: string): Promise<void> {\n const ref = decodeIntent(intentId);\n if (!ref) throw new Error(\"omniston: malformed intent id\");\n const cached = await loadBuilt(ref.quoteId);\n const order = cached?.evmOrder;\n if (!order) throw new Error(\"omniston: no signed-order context for this quote — build the order again\");\n // Same binding as buildDeposit: the intentId must be the one this order was built for.\n requireBinding(ref, cached!, \"registerSignedOrder\");\n if (!/^0x[0-9a-fA-F]{130}$/.test(signature)) throw new Error(\"omniston: malformed order signature\");\n const td = JSON.parse(order.typedData) as Parameters<typeof encodeTypedMessage>[0];\n const omni = await getClient();\n await omni.orderRegisterSignedOrder({\n quoteId: ref.quoteId,\n ownerSrcAddress: {chain: {$case: order.chainCase, value: order.owner}} as ChainAddress,\n signedOrder: {order: {$case: \"evmV1\", value: {\n encodedOrder: encodeTypedMessage(td),\n signature: hexToBytes(signature),\n orderExtension: hexToBytes(order.orderExtension),\n }}},\n ...(order.serializedOrderDetails ? {serializedOrderDetails: hexToBytes(order.serializedOrderDetails)} : {}),\n });\n },\n\n close(): void {\n clientGeneration += 1;\n if (client && (client !== injectedClient || opts.closeInjectedClient)) {\n if (client.close) client.close();\n else client.transport?.close();\n }\n client = null;\n },\n };\n}\n","/**\n * Activity recognition for Omniston on TON.\n *\n * Same-chain swaps settle through the STON.fi DEX router (the wallet pays TON /\n * a jetton to the router and the output jetton or TON comes back) → `swap`.\n * TON → EVM orders lock the input in the Omniston HTLC escrow (\"Omniston Escrow\n * Minter\", the `srcProtocolContractAddress` of every live quote) → `bridge`;\n * the EVM leg is paid by the resolver and is not recognizable offline.\n * Addresses are compared in raw form, so friendly (EQ…/UQ…) and raw (0:…)\n * notations all match.\n */\nimport {Address} from \"@ton/core\";\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {describeSwapLike} from \"@anywalletkit/protocol-swap2-core/activity\";\n\nexport const OMNISTON_MODULE = \"@anywalletkit/protocol-swap2-omniston\";\n\n/** STON.fi DEX routers (tonapi \"STON.fi DEX\"; v2.2 observed in the test wallet's swaps, v1 kept for older history). */\nexport const STONFI_ROUTERS: readonly string[] = [\n \"EQCS4UEa5UaJLzOyyKieqQOQ2P9M-7kXpkO5HnP3Bv250cN3\",\n \"EQB3ncyBUTjZUA5EnFKR5_EnOMI9V1tTEAAPaiU71gc4TiUt\",\n];\n/** Omniston HTLC escrow on TON (Omniston Escrow Minter) — the `srcProtocolContractAddress` of TON→EVM orders. */\nexport const OMNISTON_ESCROWS: readonly string[] = [\"EQAbWJ3Y1HgIIvcMq1prG1anlDC0T3cZlAU7luPT6LmTpmrZ\"];\n\nfunction raw(address: string | null | undefined): string | null {\n if (!address) return null;\n try {\n return Address.parse(address).toRawString();\n } catch {\n return null;\n }\n}\n\nconst ROUTER_RAW = new Set(STONFI_ROUTERS.map((a) => raw(a)!));\nconst ESCROW_RAW = new Set(OMNISTON_ESCROWS.map((a) => raw(a)!));\n\n/** Every non-own party of the transaction in raw form: the destination contract and each transfer's other side. */\nfunction counterparties(tx: ChainTx, own: Set<string>): string[] {\n const ownRaw = new Set<string>();\n for (const a of own) {\n const r = raw(a);\n if (r) ownRaw.add(r);\n }\n const out = new Set<string>();\n const add = (a: string | null | undefined) => {\n const r = raw(a);\n if (r && !ownRaw.has(r)) out.add(r);\n };\n add(tx.call?.to);\n add(tx.to);\n for (const t of tx.transfers) {\n add(t.from);\n add(t.to);\n }\n return [...out];\n}\n\nexport function describeOmnistonActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n if (!tx.chain.startsWith(\"ton:\")) return null;\n const parties = counterparties(tx, ctx.own);\n const escrow = parties.find((p) => ESCROW_RAW.has(p));\n if (escrow) {\n return describeSwapLike(tx, ctx, {protocol: OMNISTON_MODULE, subtitle: \"Omniston · STON.fi\", kind: \"bridge\", counterparty: tx.call?.to ?? tx.to ?? escrow});\n }\n const router = parties.find((p) => ROUTER_RAW.has(p));\n if (router) {\n return describeSwapLike(tx, ctx, {protocol: OMNISTON_MODULE, subtitle: \"STON.fi · TON\", kind: \"swap\", counterparty: tx.call?.to ?? tx.to ?? router});\n }\n return null;\n}\n","import \"./buffer-global.js\";\nimport {Buffer} from \"buffer\";\nimport {Address, Cell, type Slice} from \"@ton/core\";\n\n/**\n * TON same-chain swap message decoder (scan F11).\n *\n * `tonBuildSwap` returns the body of the one message the trader's wallet\n * signs. The provider's structural checks bind the amount, the attached TON\n * and the contract the message pays into; this module opens the DEX call the\n * body carries and binds what those checks cannot see: who receives the\n * output, where refunds and excesses go, and the on-chain minimum output.\n *\n * Every layout below was decoded from real Omniston builds (fixtures\n * `tests/fixtures/live-ton-swaps-2026-10-22.json`) and cross-checked against\n * the protocols' own SDKs; anything else is refused by name:\n *\n * ```text\n * STON.fi v2 jetton_transfer → router, forward swap#6664de2a; native input\n * as pTON v2 ton_transfer#01f3835d to the router's pTON wallet;\n * multi-hop = cross swap: a hop's receiver is the next router\n * and its custom payload is the next swap#6664de2a.\n * STON.fi v1 jetton_transfer → router, forward swap#25938561; native input\n * as a jetton_transfer to the router's pTON v1 wallet whose\n * destination is the router (STON.fi SDK v1 shape).\n * DeDust v1 jetton_transfer → jetton vault, forward swap#e3a0d482; native\n * vault swap#ea06185d. SwapStep + ^SwapParams.\n * DeDust CPMM v2 native: pay_native#a5a7cbf8 to the pool; jetton:\n * jetton_transfer → pool, forward pay_jetton#cbc33949. Payment\n * payload swap#c442500f + extended payout config.\n * ```\n *\n * The decoder is pure (no network). Facts that need the chain — that an ask\n * wallet is the router's wallet of the quoted output, that a pool trades the\n * quoted pair, that a pTON wallet belongs to the router — are returned as\n * `legs` for the `validateTonSwapLeg` hook (`createOmnistonTonValidators`).\n */\n\nexport const TON_JETTON_TRANSFER_OP = 0x0f8a7ea5;\nconst PTON_V2_TON_TRANSFER_OP = 0x01f3835d;\nconst STONFI_V2_SWAP_OP = 0x6664de2a;\nconst STONFI_V1_SWAP_OP = 0x25938561;\nconst DEDUST_V1_NATIVE_SWAP_OP = 0xea06185d;\nconst DEDUST_V1_JETTON_SWAP_OP = 0xe3a0d482;\nconst DEDUST_V2_PAY_NATIVE_OP = 0xa5a7cbf8;\nconst DEDUST_V2_PAY_JETTON_OP = 0xcbc33949;\nconst DEDUST_V2_SWAP_OP = 0xc442500f;\n\n/** Omniston's `SwapChunk.protocol` names and the layout each one builds. */\nexport const TON_SWAP_PROTOCOL_LAYOUTS: Readonly<Record<string, \"stonfi-v1\" | \"stonfi-v2\" | \"dedust-v1\" | \"dedust-v2\">> = {\n StonFiV1: \"stonfi-v1\",\n StonFiV2: \"stonfi-v2\",\n DeDust: \"dedust-v1\",\n DeDustCPMMV2: \"dedust-v2\",\n};\n\n/** A chain fact the payload depends on; checked by `validateTonSwapLeg`. A\n * jetton is named by its master address; `null` is native GRAM. */\nexport type TonSwapLeg =\n | {\n kind: \"stonfi-router\";\n version: 1 | 2;\n /** The router that executes this hop; null = the owner of `proxyTonWallet`. */\n router: string | null;\n /** Native input: the router's proxy-TON wallet the message pays into. */\n proxyTonWallet?: string;\n /** The router's wallet the hop asks for — must be the router's wallet of `outputJetton`\n * (of a proxy-TON master when the output is native). */\n askWallet: string;\n inputJetton: string | null;\n outputJetton: string | null;\n }\n | {\n kind: \"dedust-pool\";\n version: 1 | 2;\n pool: string;\n inputJetton: string | null;\n outputJetton: string | null;\n };\n\nexport interface TonSwapCheckInput {\n /** The built message's body (BoC hex) and destination. */\n payloadHex: string;\n targetAddress: string;\n /** Value attached to the message, nanoTON. */\n sendAmount: bigint;\n /** The trader's wallet (signs; refunds and excesses return to it). */\n trader: string;\n /** Where the output must land. */\n dest: string;\n /** Quote fields the body must honour. */\n inputUnits: string;\n minOutputAmount: string;\n inputJetton: string | null;\n outputJetton: string | null;\n steps: readonly {protocol: string; inputJetton: string | null | undefined; outputJetton: string | null | undefined}[];\n /** The integrator the quote was requested with: the only referral a body may name. */\n integratorAddress?: string | null;\n}\n\nexport interface TonSwapCheckResult {\n layout: \"stonfi-v1\" | \"stonfi-v2\" | \"dedust-v1\" | \"dedust-v2\";\n /** On-chain minimum of the final hop. */\n minOut: bigint;\n legs: TonSwapLeg[];\n}\n\n/** A refusal with a stable, loggable reason code (never carries secrets). */\nexport class TonSwapPayloadError extends Error {\n constructor(readonly reason: string, detail?: string) {\n super(`omniston: ton-swap-payload ${reason}${detail ? ` (${detail})` : \"\"}`);\n this.name = \"TonSwapPayloadError\";\n }\n}\n\nconst refuse = (reason: string, detail?: string): never => {\n throw new TonSwapPayloadError(reason, detail);\n};\n\nfunction sameAddr(a: Address | null | undefined, b: string | null | undefined): boolean {\n if (!a || !b) return false;\n try {\n return a.equals(Address.parse(b));\n } catch {\n return false;\n }\n}\n\nfunction end(s: Slice, where: string): void {\n if (s.remainingBits !== 0 || s.remainingRefs !== 0) refuse(\"unknown-layout\", `${where}: ${s.remainingBits} bits / ${s.remainingRefs} refs left over`);\n}\n\n/** Either Cell ^Cell forward payload: the rest of this slice or one ref. */\nfunction eitherRef(s: Slice): Slice {\n return s.loadBit() ? s.loadRef().beginParse() : s;\n}\n\nfunction readAddress(s: Slice): Address | null {\n const a = s.loadAddressAny();\n if (a === null) return null;\n if (!(a instanceof Address)) refuse(\"unknown-layout\", \"external address\");\n return a as Address;\n}\n\n/** addr_none means \"the sender\" (DeDust) — the trader's wallet here. */\nfunction isTraderOrNone(a: Address | null, trader: string): boolean {\n return a === null || sameAddr(a, trader);\n}\n\n/** Receiver of the output: exactly the destination, or addr_none (\"the sender\")\n * only when the destination IS the trader. */\nfunction receiverOk(a: Address | null, dest: string, trader: string): boolean {\n if (a === null) {\n try {\n return Address.parse(dest).equals(Address.parse(trader));\n } catch {\n return false;\n }\n }\n return sameAddr(a, dest);\n}\n\nfunction referralOk(address: Address | null, fee: number | null, integrator: string | null | undefined): boolean {\n if (address === null) return true;\n if (fee === 0) return true;\n return !!integrator && sameAddr(address, integrator);\n}\n\ninterface StonFiV2Hop {\n askWallet: Address;\n minOut: bigint;\n receiver: Address | null;\n next: Slice | null;\n}\n\n/** STON.fi v2 swap body; follows cross-swap custom payloads. */\nfunction decodeStonFiV2(s: Slice, ctx: TonSwapCheckInput): StonFiV2Hop[] {\n const hops: StonFiV2Hop[] = [];\n let cur: Slice | null = s;\n for (let depth = 0; cur; depth++) {\n if (depth >= 4) refuse(\"unsupported-ton-route\", \"STON.fi v2 cross-swap deeper than 4 hops\");\n if (cur.loadUint(32) !== STONFI_V2_SWAP_OP) refuse(\"unknown-layout\", `STON.fi v2 hop ${depth} is not swap#6664de2a`);\n const askWallet = readAddress(cur);\n const refund = readAddress(cur);\n const excess = readAddress(cur);\n cur.loadUintBig(64); // tx deadline\n const body = cur.loadRef().beginParse();\n end(cur, \"STON.fi v2 swap\");\n const minOut = body.loadCoins();\n const receiver = readAddress(body);\n const fwdGas = body.loadCoins();\n const custom = body.loadMaybeRef();\n body.loadCoins(); // refund forward gas\n const refundPayload = body.loadMaybeRef();\n const refFee = body.loadUint(16);\n const refAddress = readAddress(body);\n end(body, \"STON.fi v2 cross-swap body\");\n if (!askWallet) refuse(\"unknown-layout\", \"STON.fi v2 swap without an ask wallet\");\n if (!sameAddr(refund, ctx.trader)) refuse(\"refund-not-trader\", `STON.fi v2 hop ${depth}`);\n if (!sameAddr(excess, ctx.trader)) refuse(\"excess-not-trader\", `STON.fi v2 hop ${depth}`);\n if (refundPayload) refuse(\"unknown-layout\", \"STON.fi v2 refund payload\");\n if (!referralOk(refAddress, refFee, ctx.integratorAddress)) refuse(\"referral\", `STON.fi v2 hop ${depth}`);\n if (custom && fwdGas === 0n) refuse(\"unknown-layout\", \"STON.fi v2 custom payload without forward gas\");\n hops.push({askWallet: askWallet!, minOut, receiver, next: custom ? custom.beginParse() : null});\n cur = custom ? custom.beginParse() : null;\n }\n return hops;\n}\n\ninterface DeDustV1Swap {\n pool: Address;\n limit: bigint;\n recipient: Address | null;\n referral: Address | null;\n}\n\n/** DeDust v1 SwapStep (inline) + ^SwapParams. */\nfunction decodeDeDustV1(s: Slice): DeDustV1Swap {\n const pool = readAddress(s);\n if (!pool) refuse(\"unknown-layout\", \"DeDust v1 swap without a pool\");\n if (s.loadUint(1) !== 0) refuse(\"unknown-layout\", \"DeDust v1 swap kind is not given_in\");\n const limit = s.loadCoins();\n if (s.loadMaybeRef()) refuse(\"unsupported-ton-route\", \"DeDust v1 multi-hop (next step)\");\n const params = s.loadRef().beginParse();\n end(s, \"DeDust v1 swap step\");\n params.loadUint(32); // deadline\n const recipient = readAddress(params);\n const referral = readAddress(params);\n params.loadMaybeRef(); // fulfill payload — delivered to the recipient with the output\n params.loadMaybeRef(); // reject payload — delivered back to the sender with the refund\n end(params, \"DeDust v1 swap params\");\n return {pool: pool!, limit, recipient, referral};\n}\n\ninterface DeDustV2Swap {\n minOut: bigint;\n fulfill: Address | null;\n reject: Address | null;\n excessesTo: Address | null;\n}\n\n/** DeDust CPMM v2 payment payload (swap#c442500f) + extended payout config. */\nfunction decodeDeDustV2(payment: Slice, payout: Slice): DeDustV2Swap {\n if (payment.loadUint(32) !== DEDUST_V2_SWAP_OP) refuse(\"unknown-layout\", \"DeDust CPMM v2 payment payload is not swap#c442500f\");\n const minOut = payment.loadCoins();\n payment.loadUint(40); // deadline\n if (payment.loadMaybeRef()) refuse(\"unsupported-ton-route\", \"DeDust CPMM v2 multi-hop (next step)\");\n // Partner / referrer fee configs are not part of an Omniston quote.\n if (payment.loadBit()) refuse(\"referral\", \"DeDust CPMM v2 partner config\");\n if (payment.loadBit()) refuse(\"referral\", \"DeDust CPMM v2 referrer config\");\n end(payment, \"DeDust CPMM v2 swap payload\");\n const options = (): Address | null => {\n const destination = readAddress(payout);\n payout.loadCoins(); // extra gas — bounded by the message value\n payout.loadMaybeRef(); // payload delivered with the payout (to the trader / destination)\n payout.loadBit(); // wrap payload\n return destination;\n };\n const fulfill = options();\n const reject = options();\n const excessesTo = readAddress(payout);\n end(payout, \"DeDust CPMM v2 payout config\");\n return {minOut, fulfill, reject, excessesTo};\n}\n\n/**\n * Decode and check a built TON same-chain swap message. Throws\n * `TonSwapPayloadError` with a reason code on the first violated rule; returns\n * the chain facts (`legs`) still to be confirmed by `validateTonSwapLeg`.\n *\n * Rules (all protocols): one route of single-protocol steps; the body's\n * layout is the one the quoted protocol builds; the DEX call moves exactly the\n * quoted input; the final receiver is the destination; refunds / excesses go\n * to the trader; the final on-chain minimum is ≥ the quote's minOutputAmount;\n * no referral other than the configured integrator; no trailing data.\n */\nexport function checkTonSwapPayload(ctx: TonSwapCheckInput): TonSwapCheckResult {\n if (!/^(?:[0-9a-fA-F]{2})+$/.test(ctx.payloadHex)) refuse(\"malformed\", \"payload hex\");\n const roots = Cell.fromBoc(Buffer.from(ctx.payloadHex, \"hex\"));\n if (roots.length !== 1) refuse(\"malformed\", \"payload must have one root\");\n const steps = ctx.steps;\n if (steps.length === 0) refuse(\"unsupported-ton-route\", \"no route steps\");\n const layouts = steps.map((step) => TON_SWAP_PROTOCOL_LAYOUTS[step.protocol] ?? refuse(\"unsupported-ton-route\", `protocol ${step.protocol}`));\n const layout = layouts[0]!;\n if (layouts.some((l) => l !== layout)) refuse(\"unsupported-ton-route\", `mixed protocols ${steps.map((s) => s.protocol).join(\"+\")}`);\n if (steps.length > 1 && layout !== \"stonfi-v2\") refuse(\"unsupported-ton-route\", `${steps.length}-step ${steps[0]!.protocol} route`);\n // Steps must chain from the quoted input to the quoted output.\n for (let i = 0; i < steps.length; i++) {\n const step = steps[i]!;\n const wantIn = i === 0 ? ctx.inputJetton : steps[i - 1]!.outputJetton;\n const wantOut = i === steps.length - 1 ? ctx.outputJetton : step.outputJetton;\n if (step.inputJetton === undefined || step.outputJetton === undefined) refuse(\"unsupported-ton-route\", `step ${i} without assets`);\n if (!sameJetton(step.inputJetton!, wantIn ?? null) || !sameJetton(step.outputJetton!, wantOut ?? null)) refuse(\"unsupported-ton-route\", `step ${i} assets do not chain`);\n }\n\n const input = BigInt(ctx.inputUnits);\n const quotedMin = BigInt(ctx.minOutputAmount);\n const nativeInput = ctx.inputJetton === null;\n const s = roots[0]!.beginParse();\n const op = s.loadUint(32);\n const legs: TonSwapLeg[] = [];\n const minOk = (minOut: bigint) => {\n if (minOut < quotedMin) refuse(minOut === 0n ? \"min-out-zero\" : \"min-out-below-quote\", `${minOut} < ${quotedMin}`);\n };\n\n // Jetton transfer header: from the trader's jetton wallet (jetton input) or\n // to the router's pTON v1 wallet (STON.fi v1 native input).\n let transfer: null | {destination: Address; forward: Slice; inline: boolean} = null;\n if (op === TON_JETTON_TRANSFER_OP) {\n s.loadUintBig(64);\n const amount = s.loadCoins();\n const destination = readAddress(s);\n const response = readAddress(s);\n if (s.loadMaybeRef()) refuse(\"unknown-layout\", \"jetton transfer custom payload\");\n s.loadCoins(); // forward TON — bounded by the provider's structural checks\n const inline = !s.loadBit();\n const forward = inline ? s : s.loadRef().beginParse();\n if (amount !== input) refuse(\"amount-mismatch\", \"jetton transfer amount\");\n if (!destination) refuse(\"unknown-layout\", \"jetton transfer without a destination\");\n if (!sameAddr(response, ctx.trader)) refuse(\"excess-not-trader\", \"jetton transfer response destination\");\n transfer = {destination: destination!, forward, inline};\n }\n\n let minOut: bigint;\n if (layout === \"stonfi-v2\") {\n let hopsSlice: Slice;\n let router: string | null;\n let proxyTonWallet: string | undefined;\n if (nativeInput) {\n if (op !== PTON_V2_TON_TRANSFER_OP) refuse(\"unknown-layout\", `native STON.fi v2 input op 0x${op.toString(16)}`);\n s.loadUintBig(64);\n const tonAmount = s.loadCoins();\n const refund = readAddress(s);\n hopsSlice = eitherRef(s);\n end(s, \"pTON v2 ton_transfer\");\n if (tonAmount !== input) refuse(\"amount-mismatch\", \"pTON v2 ton_amount\");\n if (!sameAddr(refund, ctx.trader)) refuse(\"refund-not-trader\", \"pTON v2 refund address\");\n router = null;\n proxyTonWallet = ctx.targetAddress;\n } else {\n if (!transfer) refuse(\"unknown-layout\", `jetton-input STON.fi v2 op 0x${op.toString(16)}`);\n if (!transfer!.inline) end(s, \"jetton transfer\");\n hopsSlice = transfer!.forward;\n router = transfer!.destination.toString();\n }\n const hops = decodeStonFiV2(hopsSlice, ctx);\n if (hops.length !== steps.length) refuse(\"unsupported-ton-route\", `${hops.length} STON.fi v2 hops for ${steps.length} quoted steps`);\n hops.forEach((hop, i) => {\n const last = i === hops.length - 1;\n if (last) {\n if (!receiverOk(hop.receiver, ctx.dest, ctx.trader) || hop.receiver === null) refuse(\"receiver-not-destination\", `STON.fi v2 hop ${i}`);\n if (hop.next) refuse(\"unknown-layout\", \"STON.fi v2 final hop carries a custom payload\");\n } else if (!hop.receiver) refuse(\"unknown-layout\", `STON.fi v2 hop ${i} without a receiver`);\n legs.push({\n kind: \"stonfi-router\",\n version: 2,\n router: i === 0 ? router : hops[i - 1]!.receiver!.toString(),\n ...(i === 0 && proxyTonWallet ? {proxyTonWallet} : {}),\n askWallet: hop.askWallet.toString(),\n inputJetton: steps[i]!.inputJetton ?? null,\n outputJetton: steps[i]!.outputJetton ?? null,\n });\n });\n minOut = hops[hops.length - 1]!.minOut;\n } else if (layout === \"stonfi-v1\") {\n if (!transfer) refuse(\"unknown-layout\", `STON.fi v1 op 0x${op.toString(16)}`);\n if (!transfer!.inline) end(s, \"jetton transfer\");\n const f = transfer!.forward;\n if (f.loadUint(32) !== STONFI_V1_SWAP_OP) refuse(\"unknown-layout\", \"STON.fi v1 forward payload is not swap#25938561\");\n const askWallet = readAddress(f);\n minOut = f.loadCoins();\n const to = readAddress(f);\n const referral = f.loadBit() ? readAddress(f) : null;\n end(f, \"STON.fi v1 swap\");\n if (!askWallet) refuse(\"unknown-layout\", \"STON.fi v1 swap without an ask wallet\");\n if (!to || !sameAddr(to, ctx.dest)) refuse(\"receiver-not-destination\", \"STON.fi v1 to_address\");\n if (!referralOk(referral, null, ctx.integratorAddress)) refuse(\"referral\", \"STON.fi v1\");\n // Native input: the message pays the router's pTON v1 wallet, the transfer\n // names the router; jetton input: the transfer goes straight to the router.\n legs.push({\n kind: \"stonfi-router\",\n version: 1,\n router: transfer!.destination.toString(),\n ...(nativeInput ? {proxyTonWallet: ctx.targetAddress} : {}),\n askWallet: askWallet!.toString(),\n inputJetton: ctx.inputJetton,\n outputJetton: ctx.outputJetton,\n });\n } else if (layout === \"dedust-v1\") {\n let swap: DeDustV1Swap;\n if (nativeInput) {\n if (op !== DEDUST_V1_NATIVE_SWAP_OP) refuse(\"unknown-layout\", `native DeDust v1 input op 0x${op.toString(16)}`);\n s.loadUintBig(64);\n const amount = s.loadCoins();\n if (amount !== input) refuse(\"amount-mismatch\", \"DeDust v1 native vault amount\");\n swap = decodeDeDustV1(s);\n } else {\n if (!transfer) refuse(\"unknown-layout\", `jetton-input DeDust v1 op 0x${op.toString(16)}`);\n if (!transfer!.inline) end(s, \"jetton transfer\");\n const f = transfer!.forward;\n if (f.loadUint(32) !== DEDUST_V1_JETTON_SWAP_OP) refuse(\"unknown-layout\", \"DeDust v1 forward payload is not swap#e3a0d482\");\n swap = decodeDeDustV1(f);\n }\n if (!receiverOk(swap.recipient, ctx.dest, ctx.trader)) refuse(\"receiver-not-destination\", \"DeDust v1 recipient\");\n if (!referralOk(swap.referral, null, ctx.integratorAddress)) refuse(\"referral\", \"DeDust v1\");\n minOut = swap.limit;\n legs.push({kind: \"dedust-pool\", version: 1, pool: swap.pool.toString(), inputJetton: ctx.inputJetton, outputJetton: ctx.outputJetton});\n } else {\n let swap: DeDustV2Swap;\n let pool: string;\n if (nativeInput) {\n if (op !== DEDUST_V2_PAY_NATIVE_OP) refuse(\"unknown-layout\", `native DeDust CPMM v2 input op 0x${op.toString(16)}`);\n s.loadUintBig(64);\n const amount = s.loadCoins();\n const payment = s.loadRef().beginParse();\n const payout = s.loadRef().beginParse();\n end(s, \"DeDust CPMM v2 pay_native\");\n if (amount !== input) refuse(\"amount-mismatch\", \"DeDust CPMM v2 pay_native amount\");\n swap = decodeDeDustV2(payment, payout);\n pool = ctx.targetAddress;\n } else {\n if (!transfer) refuse(\"unknown-layout\", `jetton-input DeDust CPMM v2 op 0x${op.toString(16)}`);\n if (!transfer!.inline) end(s, \"jetton transfer\");\n const f = transfer!.forward;\n if (f.loadUint(32) !== DEDUST_V2_PAY_JETTON_OP) refuse(\"unknown-layout\", \"DeDust CPMM v2 forward payload is not pay_jetton#cbc33949\");\n const payment = f.loadRef().beginParse();\n const payout = f.loadRef().beginParse();\n end(f, \"DeDust CPMM v2 pay_jetton\");\n swap = decodeDeDustV2(payment, payout);\n pool = transfer!.destination.toString();\n }\n if (!receiverOk(swap.fulfill, ctx.dest, ctx.trader)) refuse(\"receiver-not-destination\", \"DeDust CPMM v2 fulfill destination\");\n if (!isTraderOrNone(swap.reject, ctx.trader)) refuse(\"refund-not-trader\", \"DeDust CPMM v2 reject destination\");\n if (!isTraderOrNone(swap.excessesTo, ctx.trader)) refuse(\"excess-not-trader\", \"DeDust CPMM v2 excesses\");\n minOut = swap.minOut;\n legs.push({kind: \"dedust-pool\", version: 2, pool, inputJetton: ctx.inputJetton, outputJetton: ctx.outputJetton});\n }\n minOk(minOut);\n return {layout, minOut, legs};\n}\n\nfunction sameJetton(a: string | null, b: string | null): boolean {\n if (a === null || b === null) return a === b;\n try {\n return Address.parse(a).equals(Address.parse(b));\n } catch {\n return false;\n }\n}\n","import \"./buffer-global.js\";\nimport {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {omniston as omnistonCfg} from \"./config.js\";\nimport {omnistonProvider, type OmnistonProviderOptions} from \"./provider.js\";\n\nexport interface OmnistonSwap2Config extends Swap2EngineConfig, OmnistonProviderOptions {}\n\nexport class OmnistonSwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n constructor(account: Swap2Account | undefined, config: OmnistonSwap2Config) {\n super(account, config);\n this.provider = omnistonProvider(config);\n }\n protected override chainSupported(caip2: string): boolean {\n // Network discovery is broad; provider.supportsRoute keeps the currently\n // audited execution direction (TON-source → EVM) fail-closed.\n return omnistonCfg.supportsChain(caip2);\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return this.provider.supportsRoute({chain: fromChain, token: \"\"}, {chain: toChain, token: \"\"});\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AAS;AAAA,UAC/B,gBAAgB,WAAW,MAAM,cAAc;AAAA,QACjD,EAAC,EAAC;AAAA,QACF,GAAI,MAAM,yBAAyB,EAAC,wBAAwB,WAAW,MAAM,sBAAsB,EAAC,IAAI,CAAC;AAAA,MAC3G,CAAC;AAAA,IACH;AAAA,IAEA,QAAc;AACZ,0BAAoB;AACpB,UAAI,WAAW,WAAW,kBAAkB,KAAK,sBAAsB;AACrE,YAAI,OAAO,MAAO,QAAO,MAAM;AAAA,YAC1B,QAAO,WAAW,MAAM;AAAA,MAC/B;AACA,eAAS;AAAA,IACX;AAAA,EACF;AACF;;;AG/2FA,oBAAkC;AAO3B,IAAM,wBAAN,cAAoC,kCAAoB;AAAA,EAC1C;AAAA,EACnB,YAAY,SAAmC,QAA6B;AAC1E,UAAM,SAAS,MAAM;AACrB,SAAK,WAAW,iBAAiB,MAAM;AAAA,EACzC;AAAA,EACmB,eAAe,OAAwB;AAGxD,WAAO,SAAY,cAAc,KAAK;AAAA,EACxC;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,KAAK,SAAS,cAAc,EAAC,OAAO,WAAW,OAAO,GAAE,GAAG,EAAC,OAAO,SAAS,OAAO,GAAE,CAAC;AAAA,EAC/F;AACF;","names":["import_core","import_buffer","import_core","s","minOut","import_core","evmRef","TonAddress","viemHexToBytes","end","hashlock","Address","Cell","TonCell","raw","refuse"]}
|