@anywalletkit/protocol-swap2-chainflip 0.4.5 → 0.4.7

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anywalletkit/protocol-swap2-chainflip",
3
- "version": "0.4.5",
3
+ "version": "0.4.7",
4
4
  "description": "Chainflip vault swaps for the swap2 engine: native BTC / ETH / SOL / TRX and USDC / USDT across Ethereum, Arbitrum, Solana, Tron and Bitcoin through Chainflip's public backend (its own broker, 0 bps, no account). Sources in this release: Ethereum, Arbitrum and Tron (a plain USDT transfer to the Vault with the swap in the note — no approval, no 3.4 USDT channel fee). Every byte the encoder returns is decoded and checked before signing; fill-or-kill refunds to the sender.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://docs.anywallet.tech",
@@ -62,16 +62,16 @@
62
62
  "@noble/hashes": "^2.4.0",
63
63
  "@scure/base": "^2.4.0",
64
64
  "viem": "^2.57.2",
65
- "@anywalletkit/protocol-swap2-core": "0.10.3"
65
+ "@anywalletkit/protocol-swap2-core": "0.12.0"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "@anywalletkit/core": "0.8.0"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@types/node": "^22",
72
- "vitest": "^5.0.3",
73
- "@anywalletkit/protocol-swap2-router": "0.5.4",
72
+ "vitest": "^5.1.0",
74
73
  "@anywalletkit/conformance": "0.5.1",
74
+ "@anywalletkit/protocol-swap2-router": "0.6.0",
75
75
  "@anywalletkit/core": "0.8.0"
76
76
  },
77
77
  "keywords": [
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/config.ts"],"sourcesContent":["/**\n * Chainflip (JIT-AMM state chain) — chains, assets and contracts as the public backend and the vault encodings name them.\n * Asset ids, chain ids and decimals are the protocol's own (`cf_environment` / networkInfo, verified 2026-10-20); the\n * contract addresses are Chainflip's mainnet deployments (docs mainnet-addresses, confirmed by live encodings).\n *\n * Only VAULT SWAPS are offered: the donor signs a transaction whose every Chainflip parameter (destination, minimum price,\n * refund address) is decoded and checked locally before signing — no off-chain deposit channel to trust, and on Tron no\n * 3.4 USDT ingress fee. Sources: EVM (Ethereum, Arbitrum) and Tron in this release; Solana / Bitcoin vault swaps need an\n * instruction / OP_RETURN builder and come next. Destinations: every live chain.\n */\nimport type {Quote, QuoteParams, RemotePins, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {decodeEvmVaultCall, decodeTronNote, destAddressBytes, fromHex, minOutOf, sameBytes, type CfParameters} from \"./codec.js\";\n\nexport type CfChain = \"Ethereum\" | \"Bitcoin\" | \"Arbitrum\" | \"Solana\" | \"Tron\";\n\nexport interface CfAsset {\n chain: CfChain;\n /** the API's asset symbol */\n asset: string;\n /** the u32 asset id inside vault encodings */\n id: number;\n decimals: number;\n /** token contract / mint on its chain, null for the native coin */\n token: string | null;\n /** smallest deposit the state chain accepts (base units) */\n minDeposit: bigint;\n}\n\n/**\n * CAIP-2 → Chainflip chain: `id` = the ForeignChain number an EVM vault call names (`dstChain`), `addrTag` = the\n * EncodedAddress variant a Tron note names (Eth 0, Dot 1, Btc 2, Arb 3, Sol 4, Hub 5, Tron 6) — two different enums.\n */\nexport const CF_CHAINS: Readonly<Record<string, {name: CfChain; id: number; addrTag: number}>> = {\n \"eip155:1\": {name: \"Ethereum\", id: 1, addrTag: 0},\n \"bitcoin:mainnet\": {name: \"Bitcoin\", id: 3, addrTag: 2},\n \"eip155:42161\": {name: \"Arbitrum\", id: 4, addrTag: 3},\n \"solana:mainnet\": {name: \"Solana\", id: 5, addrTag: 4},\n \"tron:728126428\": {name: \"Tron\", id: 7, addrTag: 6},\n};\n\nexport const CF_ASSETS: readonly CfAsset[] = [\n {chain: \"Ethereum\", asset: \"ETH\", id: 1, decimals: 18, token: null, minDeposit: 10n ** 16n},\n {chain: \"Ethereum\", asset: \"USDC\", id: 3, decimals: 6, token: \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\", minDeposit: 20_000_000n},\n {chain: \"Ethereum\", asset: \"USDT\", id: 8, decimals: 6, token: \"0xdAC17F958D2ee523a2206206994597C13D831ec7\", minDeposit: 20_000_000n},\n {chain: \"Ethereum\", asset: \"WBTC\", id: 14, decimals: 8, token: \"0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599\", minDeposit: 40_000n},\n {chain: \"Bitcoin\", asset: \"BTC\", id: 5, decimals: 8, token: null, minDeposit: 40_000n},\n {chain: \"Arbitrum\", asset: \"ETH\", id: 6, decimals: 18, token: null, minDeposit: 3_900_000_000_000_000n},\n {chain: \"Arbitrum\", asset: \"USDC\", id: 7, decimals: 6, token: \"0xaf88d065e77c8cC2239327C5EDb3A432268e5831\", minDeposit: 10_000_000n},\n {chain: \"Arbitrum\", asset: \"USDT\", id: 15, decimals: 6, token: \"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9\", minDeposit: 10_000_000n},\n {chain: \"Solana\", asset: \"SOL\", id: 9, decimals: 9, token: null, minDeposit: 68_000_000n},\n {chain: \"Solana\", asset: \"USDC\", id: 10, decimals: 6, token: \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\", minDeposit: 10_000_000n},\n {chain: \"Solana\", asset: \"USDT\", id: 16, decimals: 6, token: \"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB\", minDeposit: 10_000_000n},\n {chain: \"Tron\", asset: \"TRX\", id: 17, decimals: 6, token: null, minDeposit: 30_000_000n},\n {chain: \"Tron\", asset: \"USDT\", id: 18, decimals: 6, token: \"TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t\", minDeposit: 10_000_000n},\n];\n\n/** Vault contracts that receive vault swaps (the deposit transaction's target). */\nexport const CF_VAULTS: Readonly<Record<string, string>> = {\n \"eip155:1\": \"0xF5e10380213880111522dd0efD3dbb45b9f62Bcc\",\n \"eip155:42161\": \"0x79001a5e762f3bEFC8e5871b42F6734e00498920\",\n \"tron:728126428\": \"TEcDijvKSXcfWT7S6rd44H5vNgufm7Y4XC\",\n};\n\n/** Sources this release signs (vault swaps the engine can execute and the verifier can decode). */\nexport const CF_SOURCE_CHAINS = new Set([\"eip155:1\", \"eip155:42161\", \"tron:728126428\"]);\n\nexport const CF_API_DEFAULT = \"https://chainflip-swap.chainflip.io\";\n\nconst sameToken = (chain: string, a: string, b: string) => (chain.startsWith(\"eip155:\") ? a.toLowerCase() === b.toLowerCase() : a === b);\nconst NATIVE = new Set([\"\", \"native\", \"0x0000000000000000000000000000000000000000\"]);\n\n/** The Chainflip asset for a CAIP-2 chain + token (contract / mint, a native marker, or the asset symbol). */\nexport function cfAsset(chain: string, token: string): CfAsset | undefined {\n const c = CF_CHAINS[chain];\n if (!c) return undefined;\n const on = CF_ASSETS.filter((a) => a.chain === c.name);\n if (NATIVE.has(token.toLowerCase())) return on.find((a) => a.token === null);\n return on.find((a) => (a.token !== null && sameToken(chain, a.token, token)) || a.asset === token.toUpperCase());\n}\n\nexport const chainflip = {\n supportsChain: (chain: string) => !!CF_CHAINS[chain],\n supports: (from: string, to: string) => CF_SOURCE_CHAINS.has(from) && !!CF_CHAINS[to] && from !== to,\n};\n\n/**\n * The provider's own decode of a vault swap, run on the client against the app's request (scan 2026-10-28, F9): an\n * EVM source is a vault call (`xSwapNative` / `xSwapToken`) on the pinned Vault, a Tron source a send to the pinned\n * Tron Vault whose note carries the swap; either way the destination chain, asset and address, the source token and\n * amount, the refund address and a minimum price that guarantees the quoted minimum must be the app's, with no DCA,\n * boost, broker fee or affiliates. The reason it fails, or null.\n */\nexport function chainflipVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n try {\n const src = cfAsset(params.sourceChain, params.sourceToken);\n const dst = cfAsset(params.destChain, params.destToken);\n const dstChain = CF_CHAINS[params.destChain];\n const vault = Object.prototype.hasOwnProperty.call(CF_VAULTS, params.sourceChain) ? CF_VAULTS[params.sourceChain] : undefined;\n if (!src || !dst || !dstChain || !vault || !CF_SOURCE_CHAINS.has(params.sourceChain)) return \"not a vault swap this release signs\";\n // A dry quote lists a route and pays nobody; execution re-quotes live.\n if (!quote.txRequest && !quote.depositAddress) return null;\n if (!params.refundAddress) return \"a live quote needs the refund address\";\n const amountIn = BigInt(params.amountIn);\n const dest = destAddressBytes(params.destChain, params.destAddress);\n const refund = destAddressBytes(params.sourceChain, params.refundAddress);\n const checkParams = (p: CfParameters): string | null => {\n if (!sameBytes(fromHex(p.refundAddress), refund)) return \"the refund address is not the sender\";\n if (minOutOf(amountIn, p.minPriceX128) < BigInt(quote.minDestAmount)) return \"the minimum price does not guarantee the quoted minimum\";\n if (p.dca !== null || p.boostFeeBps !== 0 || p.broker.feeBps !== 0 || p.affiliates.length) return \"DCA, boost, a broker fee or affiliates\";\n return null;\n };\n if (params.sourceChain.startsWith(\"eip155:\")) {\n const tx = quote.txRequest;\n if (quote.depositAddress || !tx?.data || tx.serializedTx !== undefined) return \"an EVM vault swap is a vault call, not a deposit\";\n if (!tx.to || tx.to.toLowerCase() !== vault.toLowerCase()) return `the call targets ${tx.to}, not the Vault`;\n const v = decodeEvmVaultCall(tx.data);\n if (v.dstChain !== dstChain.id || v.dstToken !== dst.id || !sameBytes(v.dstAddress, dest)) return \"the vault call names another destination\";\n if (src.token === null) {\n if (!v.native || BigInt(tx.value ?? \"0\") !== amountIn || tx.approvalAddress) return \"the native vault call moves another amount\";\n } else if (v.native || v.srcToken?.toLowerCase() !== src.token.toLowerCase() || v.amount !== amountIn || BigInt(tx.value ?? \"0\") !== 0n ||\n tx.approvalAddress?.toLowerCase() !== vault.toLowerCase()) {\n return \"the token vault call moves another token or amount\";\n }\n return checkParams(v.params);\n }\n // Tron: the deposit is a send of the input to the Vault, the swap riding in the note.\n if (quote.txRequest || quote.depositAddress !== vault || !quote.depositMemo) return \"a Tron vault swap is a send to the Tron Vault with its note\";\n const n = decodeTronNote(quote.depositMemo);\n if (n.outputAsset !== dst.id || n.destTag !== dstChain.addrTag || !sameBytes(n.destAddress, dest)) return \"the note names another destination\";\n return checkParams(n.params);\n } catch (e) {\n return `the vault swap does not decode (${(e instanceof Error ? e.message : String(e)).slice(0, 120)})`;\n }\n}\n\n/**\n * The Chainflip Vault a vault swap calls and approves on an EVM chain ({@link CF_VAULTS}), and\n * {@link chainflipVerifyQuote} — the app's pins for `remoteProvider({name: \"chainflip\", baseUrl, ...chainflipPins})`\n * (scan 2026-10-27 modules, F8/F16). A Tron vault swap is a send to the Tron Vault the verifier pins, so the stub is\n * opened to that deposit route (`depositAddressRoutes`, scan 2026-10-28 F9); its note must ride as hex bytes.\n */\nexport const chainflipPins: RemotePins = Object.freeze({\n callTargets: (chain: string): readonly string[] => chainflipVaultFor(chain),\n spenders: (chain: string): readonly string[] => chainflipVaultFor(chain),\n verifyQuote: chainflipVerifyQuote,\n verifyBuild: (quote: Quote, tx: UnsignedTx): string | null =>\n quote.depositMemo && tx.memoEncoding !== \"hex\" ? \"the Tron note is not sent as hex bytes\" : null,\n depositAddressRoutes: true,\n});\nfunction chainflipVaultFor(chain: string): readonly string[] {\n const vault = chain.startsWith(\"eip155:\") && Object.prototype.hasOwnProperty.call(CF_VAULTS, chain) ? CF_VAULTS[chain] : undefined;\n return vault ? [vault] : [];\n}\n"],"mappings":";;;;;;;;;;AAgCO,IAAM,YAAoF;AAAA,EAC/F,YAAY,EAAC,MAAM,YAAY,IAAI,GAAG,SAAS,EAAC;AAAA,EAChD,mBAAmB,EAAC,MAAM,WAAW,IAAI,GAAG,SAAS,EAAC;AAAA,EACtD,gBAAgB,EAAC,MAAM,YAAY,IAAI,GAAG,SAAS,EAAC;AAAA,EACpD,kBAAkB,EAAC,MAAM,UAAU,IAAI,GAAG,SAAS,EAAC;AAAA,EACpD,kBAAkB,EAAC,MAAM,QAAQ,IAAI,GAAG,SAAS,EAAC;AACpD;AAEO,IAAM,YAAgC;AAAA,EAC3C,EAAC,OAAO,YAAY,OAAO,OAAO,IAAI,GAAG,UAAU,IAAI,OAAO,MAAM,YAA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AEA,QAAI,MAAM,aAAa,MAAM,mBAAmB,SAAS,CAAC,MAAM,YAAa,QAAO;AACpF,UAAM,IAAI,eAAe,MAAM,WAAW;AAC1C,QAAI,EAAE,gBAAgB,IAAI,MAAM,EAAE,YAAY,SAAS,WAAW,CAAC,UAAU,EAAE,aAAa,IAAI,EAAG,QAAO;AAC1G,WAAO,YAAY,EAAE,MAAM;AAAA,EAC7B,SAAS,GAAG;AACV,WAAO,oCAAoC,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,GAAG,MAAM,GAAG,GAAG,CAAC;AAAA,EACtG;AACF;AAQO,IAAM,gBAA4B,OAAO,OAAO;AAAA,EACrD,aAAa,CAAC,UAAqC,kBAAkB,KAAK;AAAA,EAC1E,UAAU,CAAC,UAAqC,kBAAkB,KAAK;AAAA,EACvE,aAAa;AAAA,EACb,aAAa,CAAC,OAAc,OAC1B,MAAM,eAAe,GAAG,iBAAiB,QAAQ,2CAA2C;AAAA,EAC9F,sBAAsB;AACxB,CAAC;AACD,SAAS,kBAAkB,OAAkC;AAC3D,QAAM,QAAQ,MAAM,WAAW,SAAS,KAAK,OAAO,UAAU,eAAe,KAAK,WAAW,KAAK,IAAI,UAAU,KAAK,IAAI;AACzH,SAAO,QAAQ,CAAC,KAAK,IAAI,CAAC;AAC5B;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/provider.ts"],"sourcesContent":["/**\n * Chainflip provider — VAULT SWAPS through the public backend (chainflip-swap.chainflip.io), Chainflip's own broker at\n * 0 bps, no account or key:\n * quote GET /v2/quote?isVaultSwap=true → expected output, fees, ETA, recommended slippage\n * encode POST /api/encodeVaultSwapData → EVM vault calldata / Tron TRC-20 transfer + note (live quotes only)\n * status GET /v2/swaps/{source tx hash} → RECEIVING … COMPLETED | FAILED, egress / refund tx refs\n * The encoder runs on a server we do not control, so every byte it returns is decoded here and checked against the\n * request before the quote is handed out: vault address, source token and amount, destination chain / asset / address,\n * refund address, the minimum price (it must guarantee our minimum), no boost / DCA / CCM / affiliates, broker fee 0.\n * Fill-or-kill is always on: a price below the minimum after the retry window refunds to the source address.\n */\nimport {describeChainflipActivity} from \"./activity.js\";\nimport {CF_API_DEFAULT, CF_CHAINS, CF_VAULTS, cfAsset, chainflip as cfg} from \"./config.js\";\nimport {decodeEvmVaultCall, decodeTronNote, destAddressBytes, fromHex, minOutOf, minPriceX128For, sameBytes, tronToBytes, type CfParameters} from \"./codec.js\";\nimport {timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {decodeFunctionData, parseAbi, type Hex} from \"viem\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\n\nconst QUOTE_TTL_MS = 60_000;\n/** 50 state-chain blocks ≈ 5 min of retries before a fill-or-kill refund (the backend's recommendation). */\nconst RETRY_BLOCKS = 50;\nconst MAX_RETRY_BLOCKS = 600;\nconst ERC20 = parseAbi([\"function transfer(address to, uint256 amount) returns (bool)\"]);\n\nexport interface ChainflipProviderConfig {\n enabled?: boolean;\n /** Backend base URL (default the public chainflip-swap.chainflip.io). */\n apiUrl?: string;\n /** Live-price (oracle) slippage guard in bps; null turns it off. Default: the quote's recommendation. */\n maxOraclePriceSlippageBps?: number | null;\n}\n\ninterface CfQuote {\n type?: string;\n egressAmount?: string;\n depositAmount?: string;\n estimatedDurationSeconds?: number;\n recommendedSlippageTolerancePercent?: number;\n recommendedLivePriceSlippageTolerancePercent?: number;\n includedFees?: {type: string; chain: string; asset: string; amount: string}[];\n lowLiquidityWarning?: boolean;\n}\n\n/** The intent id: `cfvault:<source chain>` — vault swaps are tracked by their source transaction. */\nconst INTENT_PREFIX = \"cfvault:\";\n\nexport function chainflipProvider(config: ChainflipProviderConfig = {}): CrossChainProvider {\n config = Object.freeze({...config});\n const base = new URL(config.apiUrl ?? CF_API_DEFAULT).toString().replace(/\\/$/, \"\");\n\n /** One GET/POST with a single back-off on 429 (the backend sits behind a rate-limiting CDN). */\n const call = async (path: string, init: RequestInit = {}, signal?: AbortSignal): Promise<{ok: boolean; status: number; body: unknown}> => {\n for (let attempt = 0; ; attempt++) {\n const res = await fetch(`${base}${path}`, {...init, headers: {accept: \"application/json\", ...(init.body ? {\"content-type\": \"application/json\"} : {}), ...(init.headers ?? {})}, signal: signal ?? timeoutSignal(12_000)});\n const body = await res.json().catch(() => null);\n if (res.status === 429 && attempt === 0 && !signal?.aborted) { await new Promise((r) => setTimeout(r, 1200)); continue; }\n return {ok: res.ok, status: res.status, body};\n }\n };\n\n /** Everything the encoder returned must say exactly what we asked; any difference refuses the quote. */\n const checkParams = (p: CfParameters, want: {refund: Uint8Array; minPriceX128: bigint; oracle: number | null}): string | null => {\n if (!sameBytes(fromHex(p.refundAddress), want.refund)) return `refund address ${p.refundAddress} is not the sender`;\n if (p.minPriceX128 < want.minPriceX128) return \"minimum price is below the one requested\";\n if (p.retryDurationBlocks > MAX_RETRY_BLOCKS) return `retry window ${p.retryDurationBlocks} blocks is too long`;\n if (p.maxOraclePriceSlippageBps !== want.oracle) return \"oracle slippage guard differs from the request\";\n if (p.dca !== null) return \"unexpected DCA parameters\";\n if (p.boostFeeBps !== 0) return \"unexpected boost fee\";\n if (p.broker.feeBps !== 0) return `broker takes ${p.broker.feeBps} bps`;\n if (p.affiliates.length) return \"unexpected affiliates\";\n return null;\n };\n\n return {\n name: \"chainflip\",\n describeActivity: describeChainflipActivity,\n enabled: () => config.enabled ?? true,\n supportsChain: (chain: string) => cfg.supportsChain(chain),\n supportsChainPair: (from: string, to: string) => cfg.supports(from, to),\n supportsRoute(from: Asset, to: Asset): boolean {\n if (!cfg.supports(from.chain, to.chain)) return false;\n const a = cfAsset(from.chain, from.token), b = cfAsset(to.chain, to.token);\n return !!a && !!b && a.id !== b.id;\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const dry = params.dry !== false;\n const refuse = (reason: string): null => {\n params.onRefusal?.(`chainflip: ${reason}`);\n return null;\n };\n if (!cfg.supports(params.sourceChain, params.destChain)) return refuse(`no vault swap ${params.sourceChain} → ${params.destChain}`);\n const src = cfAsset(params.sourceChain, params.sourceToken);\n const dst = cfAsset(params.destChain, params.destToken);\n if (!src || !dst) return refuse(`asset not listed (${params.sourceToken} on ${params.sourceChain} → ${params.destToken} on ${params.destChain})`);\n const amountIn = BigInt(params.amountIn);\n if (amountIn < src.minDeposit) return refuse(`below the minimum deposit (${src.minDeposit} ${src.asset})`);\n let destBytes: Uint8Array;\n try { destBytes = destAddressBytes(params.destChain, params.destAddress); } catch (e) { return refuse((e as Error).message); }\n\n const qs = new URLSearchParams({amount: params.amountIn, srcChain: src.chain, srcAsset: src.asset, destChain: dst.chain, destAsset: dst.asset, isVaultSwap: \"true\", isOnChain: \"false\", dcaV2Enabled: \"false\"});\n let q: CfQuote | undefined;\n try {\n const r = await call(`/v2/quote?${qs.toString()}`, {}, signal);\n if (!r.ok) return refuse(`quote ${r.status}: ${String((r.body as {message?: string} | null)?.message ?? \"\").slice(0, 160)}`);\n q = (r.body as CfQuote[] | null)?.find((x) => x.type === \"REGULAR\") ?? (r.body as CfQuote[] | null)?.[0];\n } catch (e) { return refuse(`quote failed: ${(e as Error).message.slice(0, 160)}`); }\n if (!q?.egressAmount || !/^\\d+$/.test(q.egressAmount)) return refuse(\"quote without an egress amount\");\n if (q.type && q.type !== \"REGULAR\") return refuse(`${q.type} quotes are not supported`);\n const expected = BigInt(q.egressAmount);\n // Minimum: the expected output less the slippage (the caller's, else the backend's advice), or the\n // caller's floor. A caller who names both is held to both — the engine checks the quote against\n // each (execution sends a floor under the listed quote AND the slippage the list was quoted at).\n const slipBps = params.slippageBps ?? Math.round((q.recommendedSlippageTolerancePercent ?? 1) * 100);\n const byTolerance = (expected * BigInt(10_000 - Math.min(9_999, Math.max(0, slipBps)))) / 10_000n;\n const callerFloor = params.minAmountOut !== undefined ? BigInt(params.minAmountOut) : undefined;\n const minOut = callerFloor === undefined ? byTolerance\n : params.slippageBps !== undefined && byTolerance > callerFloor ? byTolerance : callerFloor;\n if (minOut > expected) return refuse(`floor ${minOut} above the expected output ${expected}`);\n const minPriceX128 = minPriceX128For(amountIn, minOut);\n const guaranteed = minOutOf(amountIn, minPriceX128);\n const oracle = config.maxOraclePriceSlippageBps !== undefined ? config.maxOraclePriceSlippageBps\n : q.recommendedLivePriceSlippageTolerancePercent !== undefined ? Math.round(q.recommendedLivePriceSlippageTolerancePercent * 100) : null;\n const fees = (q.includedFees ?? []).map((f) => ({type: (f.type === \"NETWORK\" ? \"protocol\" : f.type === \"BROKER\" ? \"affiliate\" : \"network\") as \"network\" | \"protocol\" | \"affiliate\", amount: f.amount, token: `${f.chain}:${f.asset}`, included: true, description: `Chainflip ${f.type.toLowerCase()} fee`}));\n const stableUsd = (f: {asset: string; amount: string}) => (f.asset === \"USDC\" || f.asset === \"USDT\" ? Number(f.amount) / 1e6 : 0);\n const common = {\n provider: \"chainflip\",\n sourceAmount: params.amountIn,\n destAmount: q.egressAmount,\n minDestAmount: guaranteed.toString(),\n feeUsd: (q.includedFees ?? []).reduce((s, f) => s + stableUsd(f), 0),\n fees,\n etaSeconds: Math.round(q.estimatedDurationSeconds ?? 180),\n reliability: q.lowLiquidityWarning ? 0.75 : 0.9,\n validUntilMs: Date.now() + QUOTE_TTL_MS,\n };\n if (dry) return {...common, intentId: `dry:${crypto.randomUUID()}`, depositAddress: \"\", depositMemo: null};\n\n if (!params.refundAddress) return refuse(\"live quote without a refund address\");\n let refund: Uint8Array;\n try { refund = destAddressBytes(params.sourceChain, params.refundAddress); } catch (e) { return refuse(`refund address: ${(e as Error).message}`); }\n const body = {\n srcAsset: {chain: src.chain, asset: src.asset}, destAsset: {chain: dst.chain, asset: dst.asset},\n srcAddress: params.refundAddress, destAddress: params.destAddress, amount: params.amountIn,\n fillOrKillParams: {retryDurationBlocks: RETRY_BLOCKS, refundAddress: params.refundAddress, minPriceX128: minPriceX128.toString(), maxOraclePriceSlippage: oracle},\n commissionBps: 0,\n };\n let enc: {to?: string; calldata?: string; value?: string; note?: string; sourceTokenAddress?: string; chain?: string};\n try {\n const r = await call(\"/api/encodeVaultSwapData\", {method: \"POST\", body: JSON.stringify(body)}, signal);\n if (!r.ok) return refuse(`encode ${r.status}: ${String((r.body as {message?: string} | null)?.message ?? \"\").slice(0, 160)}`);\n enc = (r.body ?? {}) as typeof enc;\n } catch (e) { return refuse(`encode failed: ${(e as Error).message.slice(0, 160)}`); }\n const want = {refund, minPriceX128, oracle};\n const vault = CF_VAULTS[params.sourceChain]!;\n const dstChain = CF_CHAINS[params.destChain]!;\n\n try {\n if (params.sourceChain.startsWith(\"eip155:\")) {\n if (!enc.to || enc.to.toLowerCase() !== vault.toLowerCase()) return refuse(`encoder targets ${enc.to}, not the ${src.chain} Vault`);\n const v = decodeEvmVaultCall(enc.calldata ?? \"0x\");\n if (v.dstChain !== dstChain.id || v.dstToken !== dst.id || !sameBytes(v.dstAddress, destBytes)) return refuse(\"encoded destination differs from the request\");\n if (src.token === null) {\n if (!v.native || BigInt(enc.value ?? \"0\") !== amountIn) return refuse(\"native vault call with a different amount\");\n } else if (v.native || v.srcToken?.toLowerCase() !== src.token.toLowerCase() || v.amount !== amountIn || BigInt(enc.value ?? \"0\") !== 0n) {\n return refuse(\"token vault call with a different token or amount\");\n }\n const bad = checkParams(v.params, want);\n if (bad) return refuse(bad);\n return {\n ...common,\n intentId: `${INTENT_PREFIX}${params.sourceChain}`,\n depositAddress: \"\",\n depositMemo: null,\n txRequest: {to: vault, data: enc.calldata!, value: src.token === null ? params.amountIn : \"0\", chainId: Number(params.sourceChain.slice(7)), ...(src.token ? {approvalAddress: vault} : {})},\n providerData: {kind: \"evm\", srcAsset: String(src.id), dstAsset: String(dst.id)},\n };\n }\n // Tron: the deposit IS a plain transfer to the Vault; the swap parameters ride in the transaction note.\n if (enc.to !== vault) return refuse(`encoder targets ${enc.to}, not the Tron Vault`);\n if (!enc.note) return refuse(\"Tron vault swap without a note\");\n if (src.token !== null) {\n if (enc.sourceTokenAddress !== src.token) return refuse(`source token ${enc.sourceTokenAddress} is not ${src.asset}`);\n const t = decodeFunctionData({abi: ERC20, data: (enc.calldata ?? \"0x\") as Hex});\n if (!sameBytes(fromHex(String(t.args[0])), tronToBytes(vault)) || t.args[1] !== amountIn) return refuse(\"TRC-20 transfer is not the amount to the Vault\");\n }\n const n = decodeTronNote(enc.note);\n if (n.outputAsset !== dst.id || n.destTag !== dstChain.addrTag || !sameBytes(n.destAddress, destBytes)) return refuse(\"note names another destination\");\n const bad = checkParams(n.params, want);\n if (bad) return refuse(bad);\n return {\n ...common,\n intentId: `${INTENT_PREFIX}${params.sourceChain}`,\n depositAddress: vault,\n depositMemo: enc.note,\n providerData: {kind: \"tron\", memoEncoding: \"hex\", srcAsset: String(src.id), dstAsset: String(dst.id)},\n };\n } catch (e) {\n return refuse(`encoder output does not decode: ${(e as Error).message.slice(0, 160)}`);\n }\n },\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n if (quote.providerData?.kind === \"evm\") {\n const tx = quote.txRequest;\n if (!tx?.to || !tx.data) throw new Error(\"chainflip: quote has no vault call\");\n return {chain: \"\", to: tx.to, value: tx.value ?? \"0\", data: tx.data, ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}), ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {})};\n }\n if (quote.providerData?.kind === \"tron\") {\n if (!quote.depositAddress || !quote.depositMemo) throw new Error(\"chainflip: Tron quote without vault or note\");\n return {chain: \"\", to: quote.depositAddress, value: quote.sourceAmount, memo: quote.depositMemo, memoEncoding: \"hex\"};\n }\n throw new Error(\"chainflip: not a live vault-swap quote\");\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n if (!ref.sourceTxHash) return {state: \"pending\"};\n const id = ref.intentId.startsWith(`${INTENT_PREFIX}tron:`) ? ref.sourceTxHash.replace(/^0x/, \"\") : ref.sourceTxHash;\n try {\n const r = await call(`/v2/swaps/${encodeURIComponent(id)}`);\n if (r.status === 404) return {state: \"pending\"}; // not witnessed yet\n if (!r.ok) return {state: \"pending\"};\n const s = (r.body ?? {}) as {state?: string; swapEgress?: {txRef?: string}; refundEgress?: {txRef?: string}; fallbackEgress?: {txRef?: string}; deposit?: {txRef?: string}};\n const egress = s.swapEgress?.txRef;\n const refunded = !!(s.refundEgress || s.fallbackEgress);\n if (s.state === \"COMPLETED\" || (s.state === \"SENT\" && egress)) {\n // Fill-or-kill: only a refund went out → refunded; swapped in part and refunded the rest → partial (round 3, M26).\n if (!s.swapEgress && refunded) return {state: \"refunded\", depositReceived: true};\n if (s.swapEgress && refunded) return {state: \"partial\", depositReceived: true, ...(egress ? {destTxHash: egress} : {})};\n return {state: \"completed\", depositReceived: true, ...(egress ? {destTxHash: egress} : {})};\n }\n if (s.state === \"FAILED\") return s.refundEgress || s.fallbackEgress ? {state: \"refunded\", depositReceived: true} : {state: \"failed\", depositReceived: true};\n const received = s.state === \"RECEIVING\" || s.state === \"SWAPPING\" || s.state === \"SENDING\" || s.state === \"SENT\";\n return {state: \"pending\", depositReceived: received};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAcA,SAAQ,qBAAoB;AAC5B,SAAQ,oBAAoB,gBAAyB;AAGrD,IAAM,eAAe;AAErB,IAAM,eAAe;AACrB,IAAM,mBAAmB;AACzB,IAAM,QAAQ,SAAS,CAAC,8DAA8D,CAAC;AAsBvF,IAAM,gBAAgB;AAEf,SAAS,kBAAkB,SAAkC,CAAC,GAAuB;AAC1F,WAAS,OAAO,OAAO,EAAC,GAAG,OAAM,CAAC;AAClC,QAAM,OAAO,IAAI,IAAI,OAAO,UAAU,cAAc,EAAE,SAAS,EAAE,QAAQ,OAAO,EAAE;AAGlF,QAAM,OAAO,OAAO,MAAc,OAAoB,CAAC,GAAG,WAAgF;AACxI,aAAS,UAAU,KAAK,WAAW;AACjC,YAAM,MAAM,MAAM,MAAM,GAAG,IAAI,G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