@anywalletkit/protocol-swap2-fynd 0.2.12 → 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/dist/index.cjs CHANGED
@@ -23,6 +23,7 @@ __export(src_exports, {
23
23
  FYND_CHAINS: () => FYND_CHAINS,
24
24
  FYND_DEFAULT_EXCLUDED_PROTOCOLS: () => FYND_DEFAULT_EXCLUDED_PROTOCOLS,
25
25
  FYND_MODULE: () => FYND_MODULE,
26
+ FYND_PREVIOUS_ROUTERS: () => FYND_PREVIOUS_ROUTERS,
26
27
  FyndSwap2Protocol: () => FyndSwap2Protocol,
27
28
  FyndTransactionError: () => FyndTransactionError,
28
29
  ROUTER_NATIVE: () => ROUTER_NATIVE,
@@ -31,6 +32,7 @@ __export(src_exports, {
31
32
  checkFyndTransaction: () => checkFyndTransaction,
32
33
  default: () => FyndSwap2Protocol,
33
34
  describeFyndActivity: () => describeFyndActivity,
35
+ fyndNativeSwaps: () => fyndNativeSwaps,
34
36
  fyndPins: () => fyndPins,
35
37
  fyndProvider: () => fyndProvider,
36
38
  fyndVerifyQuote: () => fyndVerifyQuote
@@ -49,16 +51,22 @@ var import_util2 = require("@anywalletkit/protocol-swap2-core/util");
49
51
  // src/router.ts
50
52
  var import_util = require("@anywalletkit/protocol-swap2-core/util");
51
53
  var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
54
+ var import_swap2_assets = require("@anywalletkit/swap2-assets");
52
55
  var import_viem = require("viem");
53
56
  var FYND_CHAINS = Object.freeze({
54
- 1: { slug: "ethereum", name: "Ethereum", router: "0x1644D2477f809cc2C71bCCFd6Dc9497E3F83210d" },
55
- 8453: { slug: "base", name: "Base", router: "0xAbA5B53b03eAfaD1C5fc8BD5Fc765fC85Bb3de67" },
56
- 42161: { slug: "arbitrum", name: "Arbitrum", router: "0x924F147c50eA59f5180a26031A8b65B2aA1e81Cd" },
57
- 56: { slug: "bsc", name: "BNB Smart Chain", router: "0x7f3D12BBaFb8955E51B3ab9588b34c8ad95BDA4e" },
58
- 137: { slug: "polygon", name: "Polygon", router: "0xbd4e6011F03355C2A377Fd9Af939322A7d0A1bC1" },
59
- 130: { slug: "unichain", name: "Unichain", router: "0xCba5574597Ad00EA250Fd106DAB4Fc7461949635" },
60
- 4663: { slug: "robinhood", name: "Robinhood Chain", router: "0x09215a470bD585E59EB3F4B612fBD2678131fF9e" }
57
+ 1: { slug: "ethereum", name: "Ethereum", router: "0xe41c726421007e133a59365432fE886a73B45126" },
58
+ 8453: { slug: "base", name: "Base", router: "0xd374c00614f95492D816b5957E3797ce3f0c445C" },
59
+ 42161: { slug: "arbitrum", name: "Arbitrum", router: "0x1B82e8C16Ce8E17535C9B6b8AD107f61b0b192B5" },
60
+ 56: { slug: "bsc", name: "BNB Smart Chain", router: "0xEe7eCe626064BDA1c6aFDb8A281afe44Eabd3242" },
61
+ 137: { slug: "polygon", name: "Polygon", router: "0x4dB0B661dc706f7e09e54273028B22f61f8F94C2" },
62
+ 130: { slug: "unichain", name: "Unichain", router: "0x556dff14e4A42259ebCE4fa087323c1047e9a55A" },
63
+ 4663: { slug: "robinhood", name: "Robinhood Chain", router: "0x6F460540B03651d2Ad0ec28f777e4A0480A756a5" },
64
+ 5042: { slug: "arc", name: "Arc", router: "0x52A1BC20F2B78461D7a03c32f6c7388D4587980f" },
65
+ 99901: { slug: "elysium", name: "Elysium", router: "0x643577F3b0cB8CE1b1b73C6E872b907aCACD2662" }
61
66
  });
67
+ function fyndNativeSwaps(chainId) {
68
+ return !!(0, import_swap2_assets.ccAssetByToken)(`eip155:${chainId}`, ZERO);
69
+ }
62
70
  var ROUTER_NATIVE = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
63
71
  var ZERO = "0x0000000000000000000000000000000000000000";
64
72
  var PARAMS = "uint256 amountIn, address tokenIn, address tokenOut, uint256 expectedAmountOut, uint256 minAmountOut";
@@ -103,6 +111,9 @@ function checkFyndTransaction(tx, expected) {
103
111
  if (!chain) throw fail(`chain ${expected.chainId} has no pinned Tycho router`, "unsupported_pair");
104
112
  if (!sameAddress(tx.to, chain.router)) throw fail(`the transaction targets ${/^0x[0-9a-fA-F]{40}$/.test(tx.to) ? tx.to : "something that is not an address"}, not the Tycho router on ${chain.name}`, "vault_mismatch");
105
113
  if (sameAddress(expected.receiver, ZERO) || sameAddress(expected.receiver, chain.router)) throw fail("invalid receiver", "recipient_mismatch");
114
+ if ((sameAddress(routerToken(expected.tokenIn), ROUTER_NATIVE) || sameAddress(routerToken(expected.tokenOut), ROUTER_NATIVE)) && !fyndNativeSwaps(expected.chainId)) {
115
+ throw fail(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, "unsupported_pair");
116
+ }
106
117
  if (expected.amountIn <= 0n || expected.minAmountOut <= 0n || expected.minAmountOut > expected.expectedAmountOut) {
107
118
  throw fail("invalid quote amounts", "price_check_failed");
108
119
  }
@@ -173,11 +184,21 @@ function fyndRouterFor(chain) {
173
184
 
174
185
  // src/activity.ts
175
186
  var FYND_MODULE = "@anywalletkit/protocol-swap2-fynd";
187
+ var FYND_PREVIOUS_ROUTERS = Object.freeze({
188
+ 1: Object.freeze(["0x1644D2477f809cc2C71bCCFd6Dc9497E3F83210d"]),
189
+ 8453: Object.freeze(["0xAbA5B53b03eAfaD1C5fc8BD5Fc765fC85Bb3de67"]),
190
+ 42161: Object.freeze(["0x924F147c50eA59f5180a26031A8b65B2aA1e81Cd"]),
191
+ 56: Object.freeze(["0x7f3D12BBaFb8955E51B3ab9588b34c8ad95BDA4e"]),
192
+ 137: Object.freeze(["0xbd4e6011F03355C2A377Fd9Af939322A7d0A1bC1"]),
193
+ 130: Object.freeze(["0xCba5574597Ad00EA250Fd106DAB4Fc7461949635"]),
194
+ 4663: Object.freeze(["0x09215a470bD585E59EB3F4B612fBD2678131fF9e"])
195
+ });
176
196
  function describeFyndActivity(tx, ctx) {
177
197
  if (!(0, import_util2.isEvm)(tx.chain)) return null;
178
- const chain = FYND_CHAINS[(0, import_util2.evmRef)(tx.chain)];
198
+ const id = (0, import_util2.evmRef)(tx.chain);
199
+ const chain = FYND_CHAINS[id];
179
200
  if (!chain) return null;
180
- if (!(0, import_activity.matchesCall)(tx, [chain.router], TYCHO_ROUTER_SELECTORS)) return null;
201
+ if (!(0, import_activity.matchesCall)(tx, [chain.router, ...FYND_PREVIOUS_ROUTERS[id] ?? []], TYCHO_ROUTER_SELECTORS)) return null;
181
202
  return (0, import_activity.describeSwapLike)(tx, ctx, { protocol: FYND_MODULE, subtitle: `Fynd \xB7 ${(0, import_activity.chainLabel)(tx.chain)}`, kind: "swap" });
182
203
  }
183
204
 
@@ -335,6 +356,9 @@ function fyndProvider(config) {
335
356
  if (!nativeOut && !/^0x[0-9a-fA-F]{40}$/.test(params.destToken)) return refuse("destination token must be an EVM address", "unsupported_pair");
336
357
  const tokenOut = nativeOut ? ZERO2 : (0, import_viem2.getAddress)(params.destToken);
337
358
  if (tokenIn === tokenOut) return refuse("same token in and out", "unsupported_pair");
359
+ if ((tokenIn === ZERO2 || tokenOut === ZERO2 || tokenOut === (0, import_viem2.getAddress)(ROUTER_NATIVE)) && !fyndNativeSwaps(chainId)) {
360
+ return refuse(`the native coin on ${FYND_CHAINS[chainId].name} is not a catalog asset here; swap its ERC-20 instead`, "unsupported_pair");
361
+ }
338
362
  if (!/^0x[0-9a-fA-F]{40}$/.test(params.destAddress)) return refuse("recipient must be an EVM address", "recipient_mismatch");
339
363
  const receiver = (0, import_viem2.getAddress)(params.destAddress);
340
364
  const sender = (0, import_viem2.getAddress)(params.refundAddress && /^0x[0-9a-fA-F]{40}$/.test(params.refundAddress) ? params.refundAddress : params.destAddress);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/provider.ts","../src/activity.ts","../src/router.ts","../src/protocol.ts"],"sourcesContent":["export * from \"./provider.js\";\nexport * from \"./router.js\";\nexport {FyndSwap2Protocol} from \"./protocol.js\";\nexport {FyndSwap2Protocol as default} from \"./protocol.js\";\nexport * from \"./activity.js\";\nexport type { FyndSwap2Config } from \"./protocol.js\"\n","import {decodeErrorResult, decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\nimport {evmRef, isEvm, timeoutSignal, sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {httpRefusal, refusal, refusalOf, withReason, type Swap2RefusalInfo, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {describeFyndActivity} from \"./activity.js\";\nimport {FYND_CHAINS, ROUTER_NATIVE, TYCHO_ROUTER_ABI, checkFyndTransaction} from \"./router.js\";\n\n/**\n * Fynd — Propeller Heads' DEX aggregator (docs.fynd.xyz) as a same-chain\n * swap2 provider: exact-input swaps on Ethereum, Base, Arbitrum, BNB Chain,\n * Polygon, Unichain and Robinhood Chain, priced over the pools Tycho indexes\n * and settled through TychoRouterV3.\n *\n * Fynd outputs are licensed under the Fynd License: a swap built from a Fynd\n * quote must settle through the Tycho router with its fees intact — which is\n * the only transaction this provider builds (see README).\n *\n * Two backends: the hosted API (`apiKey` — keep it on a server, behind\n * `remoteProvider`) or your own `fynd serve` per chain (`selfHosted`).\n */\n\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\nconst DEFAULT_BASE_URL = \"https://fynd-api.propellerheads.xyz\";\nconst DEFAULT_SLIPPAGE_BPS = 50;\n/** A Fynd quote is priced at one block; the router enforces the minimum, the engine re-checks this TTL before broadcast. */\nconst DEFAULT_TTL_MS = 30_000;\n/**\n * Liquidity families left out of routing by default. 2026-10-24 on the hosted\n * API: every Ethereum route through `uniswap_v4_hooks` was quoted ~0.6–1 %\n * above the market and reverted when simulated (4 of 4 native-in pairs,\n * also USDT → USDC), while the same pairs without it executed (8 of 8 across\n * Ethereum, Base and Arbitrum). Override with `excludeProtocols`.\n */\nexport const FYND_DEFAULT_EXCLUDED_PROTOCOLS: readonly string[] = Object.freeze([\"uniswap_v4_hooks\"]);\nconst QUOTE_FAILURES: Readonly<Record<string, string>> = {\n no_route_found: \"no route for this pair\",\n insufficient_liquidity: \"not enough liquidity for this amount\",\n timeout: \"the solver timed out\",\n not_ready: \"the solver is still syncing\",\n price_check_failed: \"the price guard rejected the route\",\n encoding_failed: \"could not encode the swap (fees + slippage leave nothing)\",\n};\n/** The refusal reason of each solver failure in {@link QUOTE_FAILURES}; another status stays unclassified. */\nconst QUOTE_FAILURE_REASONS: Readonly<Record<string, Swap2RefusalReason>> = {\n no_route_found: \"no_route\",\n insufficient_liquidity: \"insufficient_liquidity\",\n timeout: \"upstream_unavailable\",\n not_ready: \"stale_node\",\n price_check_failed: \"price_check_failed\",\n encoding_failed: \"amount_too_small\",\n};\nconst quoteFailureReason = (status: unknown): Swap2RefusalReason | undefined =>\n typeof status === \"string\" && Object.prototype.hasOwnProperty.call(QUOTE_FAILURE_REASONS, status) ? QUOTE_FAILURE_REASONS[status] : undefined;\n\nexport interface FyndProviderConfig {\n enabled?: boolean;\n /** Hosted API key (raw `Authorization` value). Server-side only. */\n apiKey?: string;\n /** Hosted API base URL; requests go to `{baseUrl}/v1/{chain}/quote`. */\n baseUrl?: string;\n /** Your own Fynd servers per EVM chain id; requests go to `{url}/v1/quote`, no key. Takes precedence over the hosted API for that chain. */\n selfHosted?: Readonly<Record<number, string>>;\n /** JSON-RPC endpoints per chain id: pre-broadcast simulation and receipts. Optional. */\n rpcUrls?: Readonly<Record<number, readonly string[]>>;\n defaultSlippageBps?: number;\n quoteTtlMs?: number;\n timeoutMs?: number;\n /** Protocol names or family prefixes ending in \":\" Fynd must not route through. Default {@link FYND_DEFAULT_EXCLUDED_PROTOCOLS}. */\n excludeProtocols?: readonly string[];\n}\n\ninterface FyndOrderQuote {\n status?: string;\n amount_in?: string;\n amount_out?: string;\n gas_estimate?: string;\n price_impact_bps?: number | null;\n route?: {swaps?: {protocol?: string}[]};\n fee_breakdown?: {router_fee?: string; client_fee?: string; max_slippage?: string; min_amount_received?: string};\n transaction?: {to?: string; value?: string; data?: string};\n}\n\n/**\n * The router's custom errors a preflight revert is read against (TychoRouterV3.sol, TransferManager.sol in\n * github.com/propeller-heads/tycho crates/tycho-execution). Only `TychoRouter__NegativeSlippage` — the final\n * output under `minAmountOut` — means the price moved; the others are named as they are.\n */\nconst ROUTER_ERRORS = parseAbi([\n \"error TychoRouter__NegativeSlippage(uint256 amount, uint256 minAmount)\",\n \"error TychoRouter__FeesExceedOutput(uint256 totalFees, uint256 actualAmountOut)\",\n \"error TychoRouter__NegativeOutputDelta(int256 amount)\",\n \"error TychoRouter__MsgValueDoesNotMatchAmountIn(uint256 msgValue, uint256 amountIn)\",\n \"error TychoRouter__AmountOutZero()\",\n \"error TychoRouter__ZeroInput()\",\n \"error TychoRouter__EmptySwaps()\",\n \"error TransferManager__ExceededTransferFromAllowance(uint256 allowedAmount, uint256 amountAttempted)\",\n]);\nconst ERC20_READS = parseAbi([\"function balanceOf(address) view returns (uint256)\", \"function allowance(address, address) view returns (uint256)\"]);\n\n/** The revert data an RPC error carries (`error.data`, a nested `data.data`, or hex in the message), at most 4 KB of it. */\nfunction revertData(e: unknown): Hex | null {\n const err = e as {data?: unknown; message?: unknown};\n const nested = err.data && typeof err.data === \"object\" ? (err.data as {data?: unknown}).data : undefined;\n for (const v of [err.data, nested]) if (typeof v === \"string\" && /^0x(?:[0-9a-fA-F]{2}){4,4096}$/.test(v)) return v as Hex;\n const inMessage = typeof err.message === \"string\" ? /0x(?:[0-9a-fA-F]{2}){4,4096}/.exec(err.message.slice(0, 9000)) : null;\n return inMessage ? (inMessage[0] as Hex) : null;\n}\n\n/** The decoded router error (or `Error(string)` / `Panic`) behind a revert, or null when it is none of them. */\nfunction routerRevert(e: unknown): {name: string; args: readonly unknown[]} | null {\n const data = revertData(e);\n if (data) {\n try {\n const r = decodeErrorResult({abi: ROUTER_ERRORS, data});\n return {name: r.errorName, args: r.args ?? []};\n } catch {\n // not one of the router's errors\n }\n }\n // Some RPCs name the error in the message instead of returning its data.\n const message = e instanceof Error ? e.message.slice(0, 2000) : \"\";\n return /\\bTychoRouter__NegativeSlippage\\b/.test(message) ? {name: \"TychoRouter__NegativeSlippage\", args: []} : null;\n}\n\nconst uint = (v: unknown): bigint | null => (typeof v === \"string\" && /^\\d+$/.test(v) ? BigInt(v) : null);\n/** A protocol name from the API as it may appear in a refusal or the quote: at most 40 characters (scan 2026-10-27 modules, F34). */\nconst protocolName = (p: string): string => (p.length > 40 ? `${p.slice(0, 40)}…` : p);\n/** Hex or an address, compared without case (length first: the client's side may be a megabyte). */\nconst sameText = (a: string, b: string): boolean => a.length === b.length && a.toLowerCase() === b.toLowerCase();\nconst sameAmount = (a: string, b: string): boolean => /^\\d{1,80}$/.test(a) && /^\\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);\n\nexport function fyndProvider(config: FyndProviderConfig): CrossChainProvider {\n const baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;\n const ttl = config.quoteTtlMs ?? DEFAULT_TTL_MS;\n const timeoutMs = config.timeoutMs ?? 10_000;\n const excluded = [...(config.excludeProtocols ?? FYND_DEFAULT_EXCLUDED_PROTOCOLS)];\n const isExcluded = (protocol: string) => excluded.some((x) => (x.endsWith(\":\") ? protocol.startsWith(x) : protocol === x));\n\n const endpoint = (chainId: number): {url: string; headers: Record<string, string>} | null => {\n const chain = FYND_CHAINS[chainId];\n if (!chain) return null;\n const own = config.selfHosted?.[chainId];\n if (own) return {url: `${own.replace(/\\/+$/, \"\")}/v1/quote`, headers: {}};\n if (!config.apiKey) return null;\n return {url: `${baseUrl}/v1/${chain.slug}/quote`, headers: {authorization: config.apiKey}};\n };\n const chainIdOf = (caip2: string): number | null => {\n if (!isEvm(caip2)) return null;\n const id = evmRef(caip2);\n return endpoint(id) ? id : null;\n };\n\n async function rpc(chainId: number, method: string, params: unknown[]): Promise<unknown> {\n let lastErr: unknown;\n for (const url of config.rpcUrls?.[chainId] ?? []) {\n try {\n const res = await fetch(url, {method: \"POST\", headers: {\"content-type\": \"application/json\"}, body: JSON.stringify({jsonrpc: \"2.0\", id: 1, method, params}), signal: timeoutSignal(12_000)});\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status}`);\n const info = httpRefusal(res.status, res.headers?.get?.(\"retry-after\"));\n throw info ? withReason(error, info) : error;\n }\n const body = (await res.json()) as {result?: unknown; error?: {message?: string; data?: unknown}};\n if (body.error) throw Object.assign(new Error(body.error.message ?? \"rpc error\"), {rpc: true, data: body.error.data});\n return body.result ?? null;\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) throw e;\n lastErr = e;\n }\n }\n // Every endpoint failed: the last one's own classification (a 429, a rejected key), else unavailable.\n throw withReason(new Error(`fynd: no RPC answered on chain ${chainId} (${lastErr instanceof Error ? lastErr.message : String(lastErr)})`), refusalOf(lastErr) ?? \"upstream_unavailable\");\n }\n\n /**\n * Why the quoted swap reverts for `sender` now, as the refusal the wallet shows. The price moved only when the\n * router says so (`TychoRouter__NegativeSlippage`); otherwise the input side is read first — a balance under the\n * amount, or an approval the RPC does not see yet, reverts before any pool is touched — and anything else is\n * named neutrally with the revert's reason. The price is `price_check_failed`; the rest reverted in simulation.\n */\n async function revertReason(chainId: number, sender: string, quoted: NonNullable<Quote[\"txRequest\"]>, e: unknown): Promise<Error> {\n const revert = routerRevert(e);\n if (revert?.name === \"TychoRouter__NegativeSlippage\") {\n const [out, min] = revert.args as readonly bigint[];\n const pays = typeof out === \"bigint\" && typeof min === \"bigint\" ? ` — the route now pays ${out}, under your minimum ${min}` : \"\";\n return refusal(\"price_check_failed\", `fynd: the price moved past your minimum${pays}. Nothing was sent; refresh the quote.`);\n }\n const short = await inputShortfall(chainId, sender, quoted).catch(() => null);\n if (short) return refusal(\"simulation_failed\", short);\n const why = revert\n ? revert.name === \"Error\" && typeof revert.args[0] === \"string\" ? revert.args[0].slice(0, 120) : `${revert.name}${revert.args.length ? `(${revert.args.map(String).join(\", \").slice(0, 100)})` : \"\"}`\n : e instanceof Error ? e.message.slice(0, 120) : \"revert\";\n return refusal(\"simulation_failed\", `fynd: the swap would revert now (${why}). Nothing was sent; refresh the quote.`);\n }\n\n /** The wallet's side of a revert: the input balance under the amount, or (ERC-20) the router's allowance under it. Null when both cover it. */\n async function inputShortfall(chainId: number, sender: string, quoted: NonNullable<Quote[\"txRequest\"]>): Promise<string | null> {\n const call = decodeFunctionData({abi: TYCHO_ROUTER_ABI, data: quoted.data as Hex});\n const [amountIn, tokenIn] = call.args;\n const word = (v: unknown): bigint | null => (typeof v === \"string\" && /^0x[0-9a-fA-F]{1,64}$/.test(v) ? BigInt(v) : null);\n if (getAddress(tokenIn) === getAddress(ROUTER_NATIVE)) {\n const value = BigInt(quoted.value ?? \"0\");\n const balance = word(await rpc(chainId, \"eth_getBalance\", [sender, \"latest\"]));\n if (balance !== null && balance < value) return `fynd: the wallet's balance is below the amount (${balance} < ${value}). Nothing was sent.`;\n return null;\n }\n const spender = getAddress(quoted.approvalAddress ?? quoted.to ?? \"\");\n const read = (data: Hex) => rpc(chainId, \"eth_call\", [{to: tokenIn, data}, \"latest\"]);\n const [balance, allowance] = (await Promise.all([\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"balanceOf\", args: [sender as Hex]})),\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"allowance\", args: [sender as Hex, spender]})),\n ])).map(word);\n if (balance != null && balance < amountIn) return `fynd: the wallet's balance is below the amount (${balance} < ${amountIn}). Nothing was sent.`;\n if (allowance != null && allowance < amountIn) return \"fynd: the token approval is not visible on-chain yet. Nothing was sent; try again in a moment.\";\n return null;\n }\n\n return {\n name: \"fynd\",\n describeActivity: describeFyndActivity,\n supportsSameChain: true,\n enabled: () => config.enabled ?? true,\n supportsChain: (caip2: string) => chainIdOf(caip2) !== null,\n supportsChainPair: (from: string, to: string) => from === to && chainIdOf(from) !== null,\n supportsRoute: (from: Asset, to: Asset) => from.chain === to.chain && chainIdOf(from.chain) !== null,\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (why: string, info?: Swap2RefusalReason | Swap2RefusalInfo): null => {\n params.onRefusal?.(`fynd: ${why}`, typeof info === \"string\" ? {reason: info} : info);\n return null;\n };\n if (params.flex) return refuse(\"amount-flexible deposits are not supported\", \"unsupported_pair\");\n if (params.sourceChain !== params.destChain) return refuse(\"same-chain swaps only\", \"unsupported_pair\");\n const chainId = chainIdOf(params.sourceChain);\n if (chainId === null) return refuse(`Fynd is not configured for ${params.sourceChain}`, \"unsupported_pair\");\n const ep = endpoint(chainId)!;\n const src = sourceAssetOf(params);\n if (!src) return refuse(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n const tokenIn = src.contract ? getAddress(src.contract) : ZERO;\n const nativeOut = /^0x0+$/.test(params.destToken);\n if (!nativeOut && !/^0x[0-9a-fA-F]{40}$/.test(params.destToken)) return refuse(\"destination token must be an EVM address\", \"unsupported_pair\");\n const tokenOut = nativeOut ? ZERO : getAddress(params.destToken);\n if (tokenIn === tokenOut) return refuse(\"same token in and out\", \"unsupported_pair\");\n if (!/^0x[0-9a-fA-F]{40}$/.test(params.destAddress)) return refuse(\"recipient must be an EVM address\", \"recipient_mismatch\");\n const receiver = getAddress(params.destAddress);\n const sender = getAddress(params.refundAddress && /^0x[0-9a-fA-F]{40}$/.test(params.refundAddress) ? params.refundAddress : params.destAddress);\n let amountIn: bigint;\n try {\n amountIn = BigInt(params.amountIn);\n } catch {\n return refuse(\"amount is not an integer\");\n }\n if (amountIn <= 0n) return refuse(\"amount must be positive\");\n const bps = params.slippageBps ?? slippageDefault;\n if (!Number.isInteger(bps) || bps <= 0 || bps >= 10_000) return refuse(\"invalid slippage\", \"price_check_failed\");\n\n const body = {\n orders: [{token_in: tokenIn, token_out: tokenOut, amount: amountIn.toString(), side: \"sell\", sender, receiver}],\n options: {\n timeout_ms: Math.min(timeoutMs, 8_000),\n encoding_options: {slippage: (bps / 10_000).toString(), transfer_type: \"transfer_from\"},\n ...(excluded.length ? {route_filter: {exclude_protocols: excluded}} : {}),\n },\n };\n let res: Response;\n try {\n res = await fetch(ep.url, {method: \"POST\", headers: {\"content-type\": \"application/json\", ...ep.headers}, body: JSON.stringify(body), signal: signal ?? timeoutSignal(timeoutMs)});\n } catch (e) {\n // The network or this module's own timeout; the caller's abort is not the API's failure.\n return refuse(`API unreachable (${e instanceof Error ? e.name : \"error\"})`, signal?.aborted ? undefined : \"upstream_unavailable\");\n }\n if (res.status === 401 || res.status === 403) return refuse(`API key rejected (HTTP ${res.status})`, httpRefusal(res.status));\n if (res.status === 429) return refuse(\"rate limited (HTTP 429)\", httpRefusal(res.status, res.headers?.get?.(\"retry-after\")));\n if (res.status === 422) return refuse(\"no route for this pair\", \"no_route\");\n // 408 / 425 / 5xx: unavailable; another 4xx says nothing without the body (a 404 is a misconfigured URL).\n if (!res.ok) return refuse(`API answered HTTP ${res.status}`, httpRefusal(res.status, res.headers?.get?.(\"retry-after\")));\n let parsed: {orders?: FyndOrderQuote[]};\n try {\n parsed = (await res.json()) as {orders?: FyndOrderQuote[]};\n } catch {\n // The body failed to read or parse; the caller aborting mid-read is not the API's failure.\n return refuse(\"malformed API response\", signal?.aborted ? undefined : \"upstream_unavailable\");\n }\n if (!Array.isArray(parsed.orders) || parsed.orders.length !== 1) return refuse(\"malformed API response (order count)\", \"upstream_unavailable\");\n const q = parsed.orders[0]!;\n if (q.status !== \"success\") return refuse(QUOTE_FAILURES[q.status ?? \"\"] ?? `quote status ${String(q.status).slice(0, 40)}`, quoteFailureReason(q.status));\n\n const quotedIn = uint(q.amount_in);\n const gross = uint(q.amount_out);\n const routerFee = uint(q.fee_breakdown?.router_fee);\n const clientFee = uint(q.fee_breakdown?.client_fee);\n const maxSlippage = uint(q.fee_breakdown?.max_slippage);\n const minOut = uint(q.fee_breakdown?.min_amount_received);\n const value = uint(q.transaction?.value ?? \"\");\n if (quotedIn === null || gross === null || routerFee === null || clientFee === null || maxSlippage === null || minOut === null || value === null) {\n return refuse(\"malformed quote amounts\", \"upstream_unavailable\");\n }\n if (quotedIn !== amountIn) return refuse(`quoted ${quotedIn}, not the requested ${amountIn}`, \"price_check_failed\");\n if (clientFee !== 0n) return refuse(\"the quote carries a client fee\", \"policy_refused\");\n if (routerFee + clientFee + maxSlippage + minOut !== gross) return refuse(\"fee breakdown does not add up to the output\", \"price_check_failed\");\n if (params.minAmountOut !== undefined && minOut < BigInt(params.minAmountOut)) return refuse(`floor breach (min=${minOut} < floor=${params.minAmountOut})`, \"price_check_failed\");\n const tx = {to: q.transaction?.to ?? \"\", value, data: q.transaction?.data ?? \"\"};\n try {\n checkFyndTransaction(tx, {chainId, tokenIn, tokenOut, amountIn, receiver, expectedAmountOut: gross, minAmountOut: minOut});\n } catch (e) {\n return refuse(e instanceof Error ? e.message.replace(/^fynd: /, \"\") : String(e), refusalOf(e));\n }\n const allProtocols = [...new Set((q.route?.swaps ?? []).map((s) => s.protocol).filter((p): p is string => typeof p === \"string\"))];\n const banned = allProtocols.find(isExcluded);\n if (banned) return refuse(`the route goes through ${protocolName(banned)}, which this wallet excludes`, \"policy_refused\");\n // Native input needs no allowance: the exact transaction can be executed\n // against the latest block right now, so a route that would revert never\n // enters the auction. (ERC-20 input is simulated in preflightDeposit,\n // once the approval exists.)\n if (tokenIn === ZERO && config.rpcUrls?.[chainId]?.length) {\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: tx.to, data: tx.data, value: `0x${value.toString(16)}`}, \"latest\", {[sender]: {balance: `0x${(value + 10n ** 18n).toString(16)}`}}]);\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) return refuse(`the route does not execute on-chain right now (simulation reverted via ${allProtocols.slice(0, 6).map(protocolName).join(\", \") || \"?\"})`, \"simulation_failed\");\n // no RPC answered: the router still enforces the minimum\n }\n }\n const gas = uint(q.gas_estimate) ?? 0n;\n const protocols = allProtocols.slice(0, 6).map(protocolName);\n return {\n provider: \"fynd\",\n intentId: `fynd:${chainId}`,\n depositAddress: \"\",\n depositMemo: null,\n txRequest: {\n to: getAddress(tx.to),\n data: tx.data,\n value: value.toString(),\n chainId,\n // the router's own overhead on top of Fynd's route estimate\n gasLimit: ((gas * 13n) / 10n + 80_000n).toString(),\n ...(tokenIn === ZERO ? {} : {approvalAddress: getAddress(tx.to)}),\n },\n sourceAmount: amountIn.toString(),\n // what the receiver gets at the quoted price: gross minus the router fee\n destAmount: (gross - routerFee).toString(),\n minDestAmount: minOut.toString(),\n feeUsd: 0,\n etaSeconds: 15,\n reliability: 0.96,\n validUntilMs: Date.now() + ttl,\n providerData: {\n minOut: minOut.toString(),\n sender,\n routerFee: routerFee.toString(),\n gross: gross.toString(),\n protocols: protocols.join(\",\"),\n ...(typeof q.price_impact_bps === \"number\" ? {priceImpactBps: String(q.price_impact_bps)} : {}),\n },\n };\n },\n\n /**\n * Simulate the exact transaction at the latest block (allowance already in place); refuse when it would revert,\n * with the reason ({@link revertReason}: price, balance, approval, or the revert as it is).\n * Only the quote's own transaction is simulated: behind a backend `tx` is the client's and only the quote is\n * sealed, so a client's call (any target, a megabyte of calldata) never reaches this RPC (scan 2026-10-27 modules, F24).\n */\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n const chainId = Number(quote.intentId.split(\":\")[1]);\n const sender = quote.providerData?.sender;\n if (!FYND_CHAINS[chainId] || !config.rpcUrls?.[chainId]?.length || !tx.data || !sender) return;\n const quoted = quote.txRequest;\n if (!quoted?.to || !quoted.data || !sameText(tx.to, quoted.to) || !sameText(tx.data, quoted.data) || !sameAmount(tx.value || \"0\", quoted.value ?? \"0\")) {\n throw refusal(\"policy_refused\", \"fynd: the transaction is not the quoted swap. Nothing was sent; refresh the quote.\");\n }\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? \"0\").toString(16)}`}, \"latest\"]);\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) throw await revertReason(chainId, sender, quoted, e);\n // no RPC answered: leave it to the router's own minimum\n }\n },\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n if (!tx?.to || !tx.data) throw refusal(\"policy_refused\", \"swap2: Fynd quote has no transaction request\");\n return {chain: \"\", to: tx.to, value: tx.value ?? \"0\", data: tx.data, ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}), ...(tx.gasLimit ? {gasLimit: tx.gasLimit} : {}), ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {})};\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n if (!ref.sourceTxHash) return {state: \"pending\"};\n const chainId = Number(ref.intentId.split(\":\")[1]);\n if (!FYND_CHAINS[chainId] || !config.rpcUrls?.[chainId]?.length) return {state: \"pending\"};\n try {\n const receipt = (await rpc(chainId, \"eth_getTransactionReceipt\", [ref.sourceTxHash])) as {status?: string} | null;\n if (!receipt) return {state: \"pending\"};\n return receipt.status === \"0x1\" ? {state: \"completed\", destTxHash: ref.sourceTxHash} : {state: \"failed\"};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n","/**\n * Activity recognition for Fynd: a swap entry point of the pinned\n * TychoRouterV3 on a chain the module serves → `swap`, \"Swapped A → B\" from\n * the owner's net transfers.\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {chainLabel, describeSwapLike, matchesCall} from \"@anywalletkit/protocol-swap2-core/activity\";\nimport {evmRef, isEvm} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {FYND_CHAINS, TYCHO_ROUTER_SELECTORS} from \"./router.js\";\n\nexport const FYND_MODULE = \"@anywalletkit/protocol-swap2-fynd\";\n\nexport function describeFyndActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n if (!isEvm(tx.chain)) return null;\n const chain = FYND_CHAINS[evmRef(tx.chain)];\n if (!chain) return null;\n if (!matchesCall(tx, [chain.router], TYCHO_ROUTER_SELECTORS)) return null;\n return describeSwapLike(tx, ctx, {protocol: FYND_MODULE, subtitle: `Fynd · ${chainLabel(tx.chain)}`, kind: \"swap\"});\n}\n","/**\n * TychoRouterV3 — the only contract a Fynd quote may settle through (Fynd\n * License §3: every settlement of a Fynd output goes through the router in\n * Propeller Heads' registry). This file pins the router per chain and checks\n * Fynd's encoded transaction against the request before anything is approved\n * or sent: right contract, right method, the exact input, the requested\n * tokens, the user as receiver, the quoted output and minimum, and no client\n * fee. The route inside `swaps` is opaque and is not inspected here — the\n * router itself reverts below `minAmountOut`.\n */\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {refusalNotes, refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {decodeFunctionData, getAddress, parseAbi, toFunctionSelector, type Hex} from \"viem\";\n\n/** Router registry: github.com/propeller-heads/tycho crates/tycho-execution/config/deployment_registry.json (TychoRouterV3, effective 2026-09-01). */\nexport const FYND_CHAINS: Readonly<Record<number, {slug: string; name: string; router: `0x${string}`}>> = Object.freeze({\n 1: {slug: \"ethereum\", name: \"Ethereum\", router: \"0x1644D2477f809cc2C71bCCFd6Dc9497E3F83210d\"},\n 8453: {slug: \"base\", name: \"Base\", router: \"0xAbA5B53b03eAfaD1C5fc8BD5Fc765fC85Bb3de67\"},\n 42161: {slug: \"arbitrum\", name: \"Arbitrum\", router: \"0x924F147c50eA59f5180a26031A8b65B2aA1e81Cd\"},\n 56: {slug: \"bsc\", name: \"BNB Smart Chain\", router: \"0x7f3D12BBaFb8955E51B3ab9588b34c8ad95BDA4e\"},\n 137: {slug: \"polygon\", name: \"Polygon\", router: \"0xbd4e6011F03355C2A377Fd9Af939322A7d0A1bC1\"},\n 130: {slug: \"unichain\", name: \"Unichain\", router: \"0xCba5574597Ad00EA250Fd106DAB4Fc7461949635\"},\n 4663: {slug: \"robinhood\", name: \"Robinhood Chain\", router: \"0x09215a470bD585E59EB3F4B612fBD2678131fF9e\"},\n});\n\n/** The router's native-coin sentinel (lib/NativeETH.sol); Fynd's API uses the zero address instead. */\nexport const ROUTER_NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\n\nconst PARAMS = \"uint256 amountIn, address tokenIn, address tokenOut, uint256 expectedAmountOut, uint256 minAmountOut\";\nconst FEE = \"(uint32 clientFeeBps, address clientFeeReceiver, uint256 maxClientContribution, uint256 deadline, bytes clientSignature) clientFeeParams\";\nconst PERMIT = \"((address token, uint160 amount, uint48 expiration, uint48 nonce) details, address spender, uint256 sigDeadline) permitSingle, bytes signature\";\n\n/** The three entry points a wallet swap uses (plain `transferFrom` from the user). */\nexport const TYCHO_ROUTER_ABI = parseAbi([\n `function singleSwap(${PARAMS}, address receiver, ${FEE}, bytes swapData) payable returns (uint256)`,\n `function sequentialSwap(${PARAMS}, address receiver, ${FEE}, bytes swaps) payable returns (uint256)`,\n `function splitSwap(${PARAMS}, uint256 nTokens, address receiver, ${FEE}, bytes swaps) payable returns (uint256)`,\n]);\n\n/** Every swap entry point of the router (Permit2 and vault variants included) — for recognizing history. */\nexport const TYCHO_ROUTER_SELECTORS: ReadonlySet<string> = new Set(\n [\n `singleSwap(${PARAMS}, address receiver, ${FEE}, bytes swapData)`,\n `sequentialSwap(${PARAMS}, address receiver, ${FEE}, bytes swaps)`,\n `splitSwap(${PARAMS}, uint256 nTokens, address receiver, ${FEE}, bytes swaps)`,\n `singleSwapUsingVault(${PARAMS}, address receiver, ${FEE}, bytes swapData)`,\n `sequentialSwapUsingVault(${PARAMS}, address receiver, ${FEE}, bytes swaps)`,\n `splitSwapUsingVault(${PARAMS}, uint256 nTokens, address receiver, ${FEE}, bytes swaps)`,\n `singleSwapPermit2(${PARAMS}, address receiver, ${FEE}, ${PERMIT}, bytes swapData)`,\n `sequentialSwapPermit2(${PARAMS}, address receiver, ${FEE}, ${PERMIT}, bytes swaps)`,\n `splitSwapPermit2(${PARAMS}, uint256 nTokens, address receiver, ${FEE}, ${PERMIT}, bytes swaps)`,\n ].map((sig) => toFunctionSelector(`function ${sig}`)),\n);\n\nexport class FyndTransactionError extends Error {\n constructor(message: string) {\n super(`fynd: ${message}`);\n this.name = \"FyndTransactionError\";\n }\n}\n/** A {@link FyndTransactionError} tagged with its refusal reason (class, name and text unchanged). */\nconst fail = (message: string, reason: Swap2RefusalReason): FyndTransactionError => withReason(new FyndTransactionError(message), reason);\n/** The reasons of the texts {@link fyndVerifyQuote} returned, for `fyndPins.reasonOf`. */\nconst notes = refusalNotes();\n\nexport interface ExpectedSwap {\n chainId: number;\n /** ERC-20 address, or the zero address for the native coin. */\n tokenIn: string;\n tokenOut: string;\n amountIn: bigint;\n receiver: string;\n /** Fynd's gross `amount_out` (before the router fee and slippage). */\n expectedAmountOut: bigint;\n /** Fynd's `min_amount_received` — what the router enforces on-chain. */\n minAmountOut: bigint;\n}\n\nexport interface EncodedTx {\n to: string;\n value: bigint;\n data: string;\n}\n\nconst sameAddress = (a: string, b: string) => {\n try {\n return getAddress(a) === getAddress(b);\n } catch {\n return false;\n }\n};\nconst routerToken = (t: string) => (sameAddress(t, ZERO) ? ROUTER_NATIVE : t);\n\n/** Refuses (throws {@link FyndTransactionError}) unless `tx` is exactly the swap the wallet asked for. */\nexport function checkFyndTransaction(tx: EncodedTx, expected: ExpectedSwap): {method: \"singleSwap\" | \"sequentialSwap\" | \"splitSwap\"} {\n const chain = FYND_CHAINS[expected.chainId];\n if (!chain) throw fail(`chain ${expected.chainId} has no pinned Tycho router`, \"unsupported_pair\");\n // `tx.to` is the API's: named in the refusal only when it is an address (scan 2026-10-27 modules, F34).\n if (!sameAddress(tx.to, chain.router)) throw fail(`the transaction targets ${/^0x[0-9a-fA-F]{40}$/.test(tx.to) ? tx.to : \"something that is not an address\"}, not the Tycho router on ${chain.name}`, \"vault_mismatch\");\n if (sameAddress(expected.receiver, ZERO) || sameAddress(expected.receiver, chain.router)) throw fail(\"invalid receiver\", \"recipient_mismatch\");\n if (expected.amountIn <= 0n || expected.minAmountOut <= 0n || expected.minAmountOut > expected.expectedAmountOut) {\n throw fail(\"invalid quote amounts\", \"price_check_failed\");\n }\n const nativeIn = sameAddress(expected.tokenIn, ZERO);\n if (tx.value !== (nativeIn ? expected.amountIn : 0n)) throw fail(\"native value does not match the input\", \"price_check_failed\");\n if (!/^0x(?:[0-9a-fA-F]{2}){4,}$/.test(tx.data)) throw fail(\"malformed calldata\", \"policy_refused\");\n\n let call: ReturnType<typeof decodeFunctionData<typeof TYCHO_ROUTER_ABI>>;\n try {\n call = decodeFunctionData({abi: TYCHO_ROUTER_ABI, data: tx.data as Hex});\n } catch {\n throw fail(\"not a plain singleSwap / sequentialSwap / splitSwap call (Permit2 and vault variants are not used)\", \"policy_refused\");\n }\n const a = call.args;\n const [amountIn, tokenIn, tokenOut, expectedAmountOut, minAmountOut] = a;\n const isSplit = call.functionName === \"splitSwap\";\n const receiver = (isSplit ? a[6] : a[5]) as string;\n const fee = (isSplit ? a[7] : a[6]) as {clientFeeBps: number; clientFeeReceiver: string; maxClientContribution: bigint; deadline: bigint; clientSignature: string};\n const swaps = (isSplit ? a[8] : a[7]) as string;\n if (amountIn !== expected.amountIn) throw fail(`calldata spends ${amountIn}, not ${expected.amountIn}`, \"price_check_failed\");\n if (!sameAddress(tokenIn, routerToken(expected.tokenIn)) || !sameAddress(tokenOut, routerToken(expected.tokenOut))) {\n throw fail(\"calldata swaps other tokens than requested\", \"policy_refused\");\n }\n if (!sameAddress(receiver, expected.receiver)) throw fail(`calldata pays ${receiver}, not ${expected.receiver}`, \"recipient_mismatch\");\n if (expectedAmountOut !== expected.expectedAmountOut || minAmountOut !== expected.minAmountOut) {\n throw fail(\"calldata amounts do not match the quote\", \"price_check_failed\");\n }\n if (fee.clientFeeBps !== 0 || fee.maxClientContribution !== 0n || !sameAddress(fee.clientFeeReceiver, ZERO)) {\n throw fail(\"calldata carries client-fee parameters — this module charges none\", \"policy_refused\");\n }\n if (swaps === \"0x\" || (isSplit && (a[5] as bigint) < 2n)) throw fail(\"empty or invalid route\", \"policy_refused\");\n return {method: call.functionName};\n}\n\n/**\n * {@link checkFyndTransaction} on a remote quote, against the request this app sent: the pinned\n * router, one chain, the exact input, the requested tokens, the app's recipient, the quoted minimum and\n * no client fee. The reason it fails, or null.\n */\nexport function fyndVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n // Fynd swaps on one chain; a source-chain swap must not answer a cross-chain request (reaudit 2026-10-30, #3).\n if (params.sourceChain !== params.destChain) return notes.note(\"same-chain swaps only\", \"unsupported_pair\");\n try {\n const chainId = /^eip155:[0-9]+$/.test(params.sourceChain) ? Number(params.sourceChain.slice(7)) : NaN;\n const src = sourceAssetOf(params);\n if (!src) return notes.note(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n const tx = quote.txRequest;\n if (!tx?.to || !tx.data) return notes.note(\"the quote carries no router transaction\", \"policy_refused\");\n checkFyndTransaction({to: tx.to, data: tx.data, value: BigInt(tx.value ?? \"0\")}, {\n chainId,\n tokenIn: src.contract ? getAddress(src.contract) : ZERO,\n tokenOut: /^0x0+$/.test(params.destToken) ? ZERO : getAddress(params.destToken),\n amountIn: BigInt(params.amountIn),\n receiver: getAddress(params.destAddress),\n expectedAmountOut: BigInt(quote.providerData?.gross ?? \"0\"),\n minAmountOut: BigInt(quote.minDestAmount),\n });\n return null;\n } catch (e) {\n const text = e instanceof Error ? e.message.replace(/^fynd: /, \"\") : String(e);\n // checkFyndTransaction's refusals are classified; a request or quote that does not parse is not.\n const info = refusalOf(e);\n return info ? notes.note(text, info) : text;\n }\n}\n\n/**\n * The Tycho router a Fynd swap calls and approves on a chain, and {@link fyndVerifyQuote} — the\n * app's side of `remoteProvider({name: \"fynd\", baseUrl, ...fyndPins})`, so a backend's quote is\n * checked against these routers and the app's own request, never against itself (scan 2026-10-27\n * modules, F9). `reasonOf` classifies the texts `fyndVerifyQuote` returned, so the remote stub's refusal carries a reason.\n */\nexport const fyndPins: RemotePins = Object.freeze({\n callTargets: (chain: string): readonly string[] => fyndRouterFor(chain),\n spenders: (chain: string): readonly string[] => fyndRouterFor(chain),\n verifyQuote: fyndVerifyQuote,\n reasonOf: (refusal: string) => notes.reasonOf(refusal),\n});\nfunction fyndRouterFor(chain: string): readonly string[] {\n const id = /^eip155:[0-9]+$/.test(chain) ? Number(chain.slice(7)) : NaN;\n const c = Object.prototype.hasOwnProperty.call(FYND_CHAINS, id) ? FYND_CHAINS[id] : undefined;\n return c ? [c.router] : [];\n}\n","import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {evmRef, isEvm} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {fyndProvider, type FyndProviderConfig} from \"./provider.js\";\nimport {FYND_CHAINS} from \"./router.js\";\n\nexport interface FyndSwap2Config extends Swap2EngineConfig, FyndProviderConfig {}\n\n/** Fynd as a standalone swap2 protocol (same-chain swaps on one account). */\nexport class FyndSwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n private readonly _fynd: FyndProviderConfig;\n constructor(account: Swap2Account | undefined, config: FyndSwap2Config) {\n super(account, config);\n this.provider = fyndProvider(config);\n this._fynd = config;\n }\n protected override chainSupported(caip2: string): boolean {\n if (!isEvm(caip2)) return false;\n const id = evmRef(caip2);\n return !!FYND_CHAINS[id] && (!!this._fynd.selfHosted?.[id] || !!this._fynd.apiKey);\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return fromChain === toChain && this.chainSupported(fromChain);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AS;AAAA,EAC/D;AACF;","names":["import_viem","import_util","import_errors","import_util","refusal","ZERO","balance","import_util"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/provider.ts","../src/activity.ts","../src/router.ts","../src/protocol.ts"],"sourcesContent":["export * from \"./provider.js\";\nexport * from \"./router.js\";\nexport {FyndSwap2Protocol} from \"./protocol.js\";\nexport {FyndSwap2Protocol as default} from \"./protocol.js\";\nexport * from \"./activity.js\";\nexport type { FyndSwap2Config } from \"./protocol.js\"\n","import {decodeErrorResult, decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\nimport {evmRef, isEvm, timeoutSignal, sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {httpRefusal, refusal, refusalOf, withReason, type Swap2RefusalInfo, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {describeFyndActivity} from \"./activity.js\";\nimport {FYND_CHAINS, ROUTER_NATIVE, TYCHO_ROUTER_ABI, checkFyndTransaction, fyndNativeSwaps} from \"./router.js\";\n\n/**\n * Fynd — Propeller Heads' DEX aggregator (docs.fynd.xyz) as a same-chain\n * swap2 provider: exact-input swaps on Ethereum, Base, Arbitrum, BNB Chain,\n * Polygon, Unichain, Robinhood Chain, Arc and Elysium, priced over the pools\n * Tycho indexes and settled through TychoRouterV3.\n *\n * Fynd outputs are licensed under the Fynd License: a swap built from a Fynd\n * quote must settle through the Tycho router with its fees intact — which is\n * the only transaction this provider builds (see README).\n *\n * Two backends: the hosted API (`apiKey` — keep it on a server, behind\n * `remoteProvider`) or your own `fynd serve` per chain (`selfHosted`).\n */\n\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\nconst DEFAULT_BASE_URL = \"https://fynd-api.propellerheads.xyz\";\nconst DEFAULT_SLIPPAGE_BPS = 50;\n/** A Fynd quote is priced at one block; the router enforces the minimum, the engine re-checks this TTL before broadcast. */\nconst DEFAULT_TTL_MS = 30_000;\n/**\n * Liquidity families left out of routing by default. 2026-10-24 on the hosted\n * API: every Ethereum route through `uniswap_v4_hooks` was quoted ~0.6–1 %\n * above the market and reverted when simulated (4 of 4 native-in pairs,\n * also USDT → USDC), while the same pairs without it executed (8 of 8 across\n * Ethereum, Base and Arbitrum). Override with `excludeProtocols`.\n */\nexport const FYND_DEFAULT_EXCLUDED_PROTOCOLS: readonly string[] = Object.freeze([\"uniswap_v4_hooks\"]);\nconst QUOTE_FAILURES: Readonly<Record<string, string>> = {\n no_route_found: \"no route for this pair\",\n insufficient_liquidity: \"not enough liquidity for this amount\",\n timeout: \"the solver timed out\",\n not_ready: \"the solver is still syncing\",\n price_check_failed: \"the price guard rejected the route\",\n encoding_failed: \"could not encode the swap (fees + slippage leave nothing)\",\n};\n/** The refusal reason of each solver failure in {@link QUOTE_FAILURES}; another status stays unclassified. */\nconst QUOTE_FAILURE_REASONS: Readonly<Record<string, Swap2RefusalReason>> = {\n no_route_found: \"no_route\",\n insufficient_liquidity: \"insufficient_liquidity\",\n timeout: \"upstream_unavailable\",\n not_ready: \"stale_node\",\n price_check_failed: \"price_check_failed\",\n encoding_failed: \"amount_too_small\",\n};\nconst quoteFailureReason = (status: unknown): Swap2RefusalReason | undefined =>\n typeof status === \"string\" && Object.prototype.hasOwnProperty.call(QUOTE_FAILURE_REASONS, status) ? QUOTE_FAILURE_REASONS[status] : undefined;\n\nexport interface FyndProviderConfig {\n enabled?: boolean;\n /** Hosted API key (raw `Authorization` value). Server-side only. */\n apiKey?: string;\n /** Hosted API base URL; requests go to `{baseUrl}/v1/{chain}/quote`. */\n baseUrl?: string;\n /** Your own Fynd servers per EVM chain id; requests go to `{url}/v1/quote`, no key. Takes precedence over the hosted API for that chain. */\n selfHosted?: Readonly<Record<number, string>>;\n /** JSON-RPC endpoints per chain id: pre-broadcast simulation and receipts. Optional. */\n rpcUrls?: Readonly<Record<number, readonly string[]>>;\n defaultSlippageBps?: number;\n quoteTtlMs?: number;\n timeoutMs?: number;\n /** Protocol names or family prefixes ending in \":\" Fynd must not route through. Default {@link FYND_DEFAULT_EXCLUDED_PROTOCOLS}. */\n excludeProtocols?: readonly string[];\n}\n\ninterface FyndOrderQuote {\n status?: string;\n amount_in?: string;\n amount_out?: string;\n gas_estimate?: string;\n price_impact_bps?: number | null;\n route?: {swaps?: {protocol?: string}[]};\n fee_breakdown?: {router_fee?: string; client_fee?: string; max_slippage?: string; min_amount_received?: string};\n transaction?: {to?: string; value?: string; data?: string};\n}\n\n/**\n * The router's custom errors a preflight revert is read against (TychoRouterV3.sol, TransferManager.sol in\n * github.com/propeller-heads/tycho crates/tycho-execution). Only `TychoRouter__NegativeSlippage` — the final\n * output under `minAmountOut` — means the price moved; the others are named as they are.\n */\nconst ROUTER_ERRORS = parseAbi([\n \"error TychoRouter__NegativeSlippage(uint256 amount, uint256 minAmount)\",\n \"error TychoRouter__FeesExceedOutput(uint256 totalFees, uint256 actualAmountOut)\",\n \"error TychoRouter__NegativeOutputDelta(int256 amount)\",\n \"error TychoRouter__MsgValueDoesNotMatchAmountIn(uint256 msgValue, uint256 amountIn)\",\n \"error TychoRouter__AmountOutZero()\",\n \"error TychoRouter__ZeroInput()\",\n \"error TychoRouter__EmptySwaps()\",\n \"error TransferManager__ExceededTransferFromAllowance(uint256 allowedAmount, uint256 amountAttempted)\",\n]);\nconst ERC20_READS = parseAbi([\"function balanceOf(address) view returns (uint256)\", \"function allowance(address, address) view returns (uint256)\"]);\n\n/** The revert data an RPC error carries (`error.data`, a nested `data.data`, or hex in the message), at most 4 KB of it. */\nfunction revertData(e: unknown): Hex | null {\n const err = e as {data?: unknown; message?: unknown};\n const nested = err.data && typeof err.data === \"object\" ? (err.data as {data?: unknown}).data : undefined;\n for (const v of [err.data, nested]) if (typeof v === \"string\" && /^0x(?:[0-9a-fA-F]{2}){4,4096}$/.test(v)) return v as Hex;\n const inMessage = typeof err.message === \"string\" ? /0x(?:[0-9a-fA-F]{2}){4,4096}/.exec(err.message.slice(0, 9000)) : null;\n return inMessage ? (inMessage[0] as Hex) : null;\n}\n\n/** The decoded router error (or `Error(string)` / `Panic`) behind a revert, or null when it is none of them. */\nfunction routerRevert(e: unknown): {name: string; args: readonly unknown[]} | null {\n const data = revertData(e);\n if (data) {\n try {\n const r = decodeErrorResult({abi: ROUTER_ERRORS, data});\n return {name: r.errorName, args: r.args ?? []};\n } catch {\n // not one of the router's errors\n }\n }\n // Some RPCs name the error in the message instead of returning its data.\n const message = e instanceof Error ? e.message.slice(0, 2000) : \"\";\n return /\\bTychoRouter__NegativeSlippage\\b/.test(message) ? {name: \"TychoRouter__NegativeSlippage\", args: []} : null;\n}\n\nconst uint = (v: unknown): bigint | null => (typeof v === \"string\" && /^\\d+$/.test(v) ? BigInt(v) : null);\n/** A protocol name from the API as it may appear in a refusal or the quote: at most 40 characters (scan 2026-10-27 modules, F34). */\nconst protocolName = (p: string): string => (p.length > 40 ? `${p.slice(0, 40)}…` : p);\n/** Hex or an address, compared without case (length first: the client's side may be a megabyte). */\nconst sameText = (a: string, b: string): boolean => a.length === b.length && a.toLowerCase() === b.toLowerCase();\nconst sameAmount = (a: string, b: string): boolean => /^\\d{1,80}$/.test(a) && /^\\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);\n\nexport function fyndProvider(config: FyndProviderConfig): CrossChainProvider {\n const baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;\n const ttl = config.quoteTtlMs ?? DEFAULT_TTL_MS;\n const timeoutMs = config.timeoutMs ?? 10_000;\n const excluded = [...(config.excludeProtocols ?? FYND_DEFAULT_EXCLUDED_PROTOCOLS)];\n const isExcluded = (protocol: string) => excluded.some((x) => (x.endsWith(\":\") ? protocol.startsWith(x) : protocol === x));\n\n const endpoint = (chainId: number): {url: string; headers: Record<string, string>} | null => {\n const chain = FYND_CHAINS[chainId];\n if (!chain) return null;\n const own = config.selfHosted?.[chainId];\n if (own) return {url: `${own.replace(/\\/+$/, \"\")}/v1/quote`, headers: {}};\n if (!config.apiKey) return null;\n return {url: `${baseUrl}/v1/${chain.slug}/quote`, headers: {authorization: config.apiKey}};\n };\n const chainIdOf = (caip2: string): number | null => {\n if (!isEvm(caip2)) return null;\n const id = evmRef(caip2);\n return endpoint(id) ? id : null;\n };\n\n async function rpc(chainId: number, method: string, params: unknown[]): Promise<unknown> {\n let lastErr: unknown;\n for (const url of config.rpcUrls?.[chainId] ?? []) {\n try {\n const res = await fetch(url, {method: \"POST\", headers: {\"content-type\": \"application/json\"}, body: JSON.stringify({jsonrpc: \"2.0\", id: 1, method, params}), signal: timeoutSignal(12_000)});\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status}`);\n const info = httpRefusal(res.status, res.headers?.get?.(\"retry-after\"));\n throw info ? withReason(error, info) : error;\n }\n const body = (await res.json()) as {result?: unknown; error?: {message?: string; data?: unknown}};\n if (body.error) throw Object.assign(new Error(body.error.message ?? \"rpc error\"), {rpc: true, data: body.error.data});\n return body.result ?? null;\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) throw e;\n lastErr = e;\n }\n }\n // Every endpoint failed: the last one's own classification (a 429, a rejected key), else unavailable.\n throw withReason(new Error(`fynd: no RPC answered on chain ${chainId} (${lastErr instanceof Error ? lastErr.message : String(lastErr)})`), refusalOf(lastErr) ?? \"upstream_unavailable\");\n }\n\n /**\n * Why the quoted swap reverts for `sender` now, as the refusal the wallet shows. The price moved only when the\n * router says so (`TychoRouter__NegativeSlippage`); otherwise the input side is read first — a balance under the\n * amount, or an approval the RPC does not see yet, reverts before any pool is touched — and anything else is\n * named neutrally with the revert's reason. The price is `price_check_failed`; the rest reverted in simulation.\n */\n async function revertReason(chainId: number, sender: string, quoted: NonNullable<Quote[\"txRequest\"]>, e: unknown): Promise<Error> {\n const revert = routerRevert(e);\n if (revert?.name === \"TychoRouter__NegativeSlippage\") {\n const [out, min] = revert.args as readonly bigint[];\n const pays = typeof out === \"bigint\" && typeof min === \"bigint\" ? ` — the route now pays ${out}, under your minimum ${min}` : \"\";\n return refusal(\"price_check_failed\", `fynd: the price moved past your minimum${pays}. Nothing was sent; refresh the quote.`);\n }\n const short = await inputShortfall(chainId, sender, quoted).catch(() => null);\n if (short) return refusal(\"simulation_failed\", short);\n const why = revert\n ? revert.name === \"Error\" && typeof revert.args[0] === \"string\" ? revert.args[0].slice(0, 120) : `${revert.name}${revert.args.length ? `(${revert.args.map(String).join(\", \").slice(0, 100)})` : \"\"}`\n : e instanceof Error ? e.message.slice(0, 120) : \"revert\";\n return refusal(\"simulation_failed\", `fynd: the swap would revert now (${why}). Nothing was sent; refresh the quote.`);\n }\n\n /** The wallet's side of a revert: the input balance under the amount, or (ERC-20) the router's allowance under it. Null when both cover it. */\n async function inputShortfall(chainId: number, sender: string, quoted: NonNullable<Quote[\"txRequest\"]>): Promise<string | null> {\n const call = decodeFunctionData({abi: TYCHO_ROUTER_ABI, data: quoted.data as Hex});\n const [amountIn, tokenIn] = call.args;\n const word = (v: unknown): bigint | null => (typeof v === \"string\" && /^0x[0-9a-fA-F]{1,64}$/.test(v) ? BigInt(v) : null);\n if (getAddress(tokenIn) === getAddress(ROUTER_NATIVE)) {\n const value = BigInt(quoted.value ?? \"0\");\n const balance = word(await rpc(chainId, \"eth_getBalance\", [sender, \"latest\"]));\n if (balance !== null && balance < value) return `fynd: the wallet's balance is below the amount (${balance} < ${value}). Nothing was sent.`;\n return null;\n }\n const spender = getAddress(quoted.approvalAddress ?? quoted.to ?? \"\");\n const read = (data: Hex) => rpc(chainId, \"eth_call\", [{to: tokenIn, data}, \"latest\"]);\n const [balance, allowance] = (await Promise.all([\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"balanceOf\", args: [sender as Hex]})),\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"allowance\", args: [sender as Hex, spender]})),\n ])).map(word);\n if (balance != null && balance < amountIn) return `fynd: the wallet's balance is below the amount (${balance} < ${amountIn}). Nothing was sent.`;\n if (allowance != null && allowance < amountIn) return \"fynd: the token approval is not visible on-chain yet. Nothing was sent; try again in a moment.\";\n return null;\n }\n\n return {\n name: \"fynd\",\n describeActivity: describeFyndActivity,\n supportsSameChain: true,\n enabled: () => config.enabled ?? true,\n supportsChain: (caip2: string) => chainIdOf(caip2) !== null,\n supportsChainPair: (from: string, to: string) => from === to && chainIdOf(from) !== null,\n supportsRoute: (from: Asset, to: Asset) => from.chain === to.chain && chainIdOf(from.chain) !== null,\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (why: string, info?: Swap2RefusalReason | Swap2RefusalInfo): null => {\n params.onRefusal?.(`fynd: ${why}`, typeof info === \"string\" ? {reason: info} : info);\n return null;\n };\n if (params.flex) return refuse(\"amount-flexible deposits are not supported\", \"unsupported_pair\");\n if (params.sourceChain !== params.destChain) return refuse(\"same-chain swaps only\", \"unsupported_pair\");\n const chainId = chainIdOf(params.sourceChain);\n if (chainId === null) return refuse(`Fynd is not configured for ${params.sourceChain}`, \"unsupported_pair\");\n const ep = endpoint(chainId)!;\n const src = sourceAssetOf(params);\n if (!src) return refuse(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n const tokenIn = src.contract ? getAddress(src.contract) : ZERO;\n const nativeOut = /^0x0+$/.test(params.destToken);\n if (!nativeOut && !/^0x[0-9a-fA-F]{40}$/.test(params.destToken)) return refuse(\"destination token must be an EVM address\", \"unsupported_pair\");\n const tokenOut = nativeOut ? ZERO : getAddress(params.destToken);\n if (tokenIn === tokenOut) return refuse(\"same token in and out\", \"unsupported_pair\");\n // Arc: the native coin is USDC in 18-decimal units, which the catalog does not list (see fyndNativeSwaps).\n if ((tokenIn === ZERO || tokenOut === ZERO || tokenOut === getAddress(ROUTER_NATIVE)) && !fyndNativeSwaps(chainId)) {\n return refuse(`the native coin on ${FYND_CHAINS[chainId]!.name} is not a catalog asset here; swap its ERC-20 instead`, \"unsupported_pair\");\n }\n if (!/^0x[0-9a-fA-F]{40}$/.test(params.destAddress)) return refuse(\"recipient must be an EVM address\", \"recipient_mismatch\");\n const receiver = getAddress(params.destAddress);\n const sender = getAddress(params.refundAddress && /^0x[0-9a-fA-F]{40}$/.test(params.refundAddress) ? params.refundAddress : params.destAddress);\n let amountIn: bigint;\n try {\n amountIn = BigInt(params.amountIn);\n } catch {\n return refuse(\"amount is not an integer\");\n }\n if (amountIn <= 0n) return refuse(\"amount must be positive\");\n const bps = params.slippageBps ?? slippageDefault;\n if (!Number.isInteger(bps) || bps <= 0 || bps >= 10_000) return refuse(\"invalid slippage\", \"price_check_failed\");\n\n const body = {\n orders: [{token_in: tokenIn, token_out: tokenOut, amount: amountIn.toString(), side: \"sell\", sender, receiver}],\n options: {\n timeout_ms: Math.min(timeoutMs, 8_000),\n encoding_options: {slippage: (bps / 10_000).toString(), transfer_type: \"transfer_from\"},\n ...(excluded.length ? {route_filter: {exclude_protocols: excluded}} : {}),\n },\n };\n let res: Response;\n try {\n res = await fetch(ep.url, {method: \"POST\", headers: {\"content-type\": \"application/json\", ...ep.headers}, body: JSON.stringify(body), signal: signal ?? timeoutSignal(timeoutMs)});\n } catch (e) {\n // The network or this module's own timeout; the caller's abort is not the API's failure.\n return refuse(`API unreachable (${e instanceof Error ? e.name : \"error\"})`, signal?.aborted ? undefined : \"upstream_unavailable\");\n }\n if (res.status === 401 || res.status === 403) return refuse(`API key rejected (HTTP ${res.status})`, httpRefusal(res.status));\n if (res.status === 429) return refuse(\"rate limited (HTTP 429)\", httpRefusal(res.status, res.headers?.get?.(\"retry-after\")));\n if (res.status === 422) return refuse(\"no route for this pair\", \"no_route\");\n // 408 / 425 / 5xx: unavailable; another 4xx says nothing without the body (a 404 is a misconfigured URL).\n if (!res.ok) return refuse(`API answered HTTP ${res.status}`, httpRefusal(res.status, res.headers?.get?.(\"retry-after\")));\n let parsed: {orders?: FyndOrderQuote[]};\n try {\n parsed = (await res.json()) as {orders?: FyndOrderQuote[]};\n } catch {\n // The body failed to read or parse; the caller aborting mid-read is not the API's failure.\n return refuse(\"malformed API response\", signal?.aborted ? undefined : \"upstream_unavailable\");\n }\n if (!Array.isArray(parsed.orders) || parsed.orders.length !== 1) return refuse(\"malformed API response (order count)\", \"upstream_unavailable\");\n const q = parsed.orders[0]!;\n if (q.status !== \"success\") return refuse(QUOTE_FAILURES[q.status ?? \"\"] ?? `quote status ${String(q.status).slice(0, 40)}`, quoteFailureReason(q.status));\n\n const quotedIn = uint(q.amount_in);\n const gross = uint(q.amount_out);\n const routerFee = uint(q.fee_breakdown?.router_fee);\n const clientFee = uint(q.fee_breakdown?.client_fee);\n const maxSlippage = uint(q.fee_breakdown?.max_slippage);\n const minOut = uint(q.fee_breakdown?.min_amount_received);\n const value = uint(q.transaction?.value ?? \"\");\n if (quotedIn === null || gross === null || routerFee === null || clientFee === null || maxSlippage === null || minOut === null || value === null) {\n return refuse(\"malformed quote amounts\", \"upstream_unavailable\");\n }\n if (quotedIn !== amountIn) return refuse(`quoted ${quotedIn}, not the requested ${amountIn}`, \"price_check_failed\");\n if (clientFee !== 0n) return refuse(\"the quote carries a client fee\", \"policy_refused\");\n if (routerFee + clientFee + maxSlippage + minOut !== gross) return refuse(\"fee breakdown does not add up to the output\", \"price_check_failed\");\n if (params.minAmountOut !== undefined && minOut < BigInt(params.minAmountOut)) return refuse(`floor breach (min=${minOut} < floor=${params.minAmountOut})`, \"price_check_failed\");\n const tx = {to: q.transaction?.to ?? \"\", value, data: q.transaction?.data ?? \"\"};\n try {\n checkFyndTransaction(tx, {chainId, tokenIn, tokenOut, amountIn, receiver, expectedAmountOut: gross, minAmountOut: minOut});\n } catch (e) {\n return refuse(e instanceof Error ? e.message.replace(/^fynd: /, \"\") : String(e), refusalOf(e));\n }\n const allProtocols = [...new Set((q.route?.swaps ?? []).map((s) => s.protocol).filter((p): p is string => typeof p === \"string\"))];\n const banned = allProtocols.find(isExcluded);\n if (banned) return refuse(`the route goes through ${protocolName(banned)}, which this wallet excludes`, \"policy_refused\");\n // Native input needs no allowance: the exact transaction can be executed\n // against the latest block right now, so a route that would revert never\n // enters the auction. (ERC-20 input is simulated in preflightDeposit,\n // once the approval exists.)\n if (tokenIn === ZERO && config.rpcUrls?.[chainId]?.length) {\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: tx.to, data: tx.data, value: `0x${value.toString(16)}`}, \"latest\", {[sender]: {balance: `0x${(value + 10n ** 18n).toString(16)}`}}]);\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) return refuse(`the route does not execute on-chain right now (simulation reverted via ${allProtocols.slice(0, 6).map(protocolName).join(\", \") || \"?\"})`, \"simulation_failed\");\n // no RPC answered: the router still enforces the minimum\n }\n }\n const gas = uint(q.gas_estimate) ?? 0n;\n const protocols = allProtocols.slice(0, 6).map(protocolName);\n return {\n provider: \"fynd\",\n intentId: `fynd:${chainId}`,\n depositAddress: \"\",\n depositMemo: null,\n txRequest: {\n to: getAddress(tx.to),\n data: tx.data,\n value: value.toString(),\n chainId,\n // the router's own overhead on top of Fynd's route estimate\n gasLimit: ((gas * 13n) / 10n + 80_000n).toString(),\n ...(tokenIn === ZERO ? {} : {approvalAddress: getAddress(tx.to)}),\n },\n sourceAmount: amountIn.toString(),\n // what the receiver gets at the quoted price: gross minus the router fee\n destAmount: (gross - routerFee).toString(),\n minDestAmount: minOut.toString(),\n feeUsd: 0,\n etaSeconds: 15,\n reliability: 0.96,\n validUntilMs: Date.now() + ttl,\n providerData: {\n minOut: minOut.toString(),\n sender,\n routerFee: routerFee.toString(),\n gross: gross.toString(),\n protocols: protocols.join(\",\"),\n ...(typeof q.price_impact_bps === \"number\" ? {priceImpactBps: String(q.price_impact_bps)} : {}),\n },\n };\n },\n\n /**\n * Simulate the exact transaction at the latest block (allowance already in place); refuse when it would revert,\n * with the reason ({@link revertReason}: price, balance, approval, or the revert as it is).\n * Only the quote's own transaction is simulated: behind a backend `tx` is the client's and only the quote is\n * sealed, so a client's call (any target, a megabyte of calldata) never reaches this RPC (scan 2026-10-27 modules, F24).\n */\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n const chainId = Number(quote.intentId.split(\":\")[1]);\n const sender = quote.providerData?.sender;\n if (!FYND_CHAINS[chainId] || !config.rpcUrls?.[chainId]?.length || !tx.data || !sender) return;\n const quoted = quote.txRequest;\n if (!quoted?.to || !quoted.data || !sameText(tx.to, quoted.to) || !sameText(tx.data, quoted.data) || !sameAmount(tx.value || \"0\", quoted.value ?? \"0\")) {\n throw refusal(\"policy_refused\", \"fynd: the transaction is not the quoted swap. Nothing was sent; refresh the quote.\");\n }\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? \"0\").toString(16)}`}, \"latest\"]);\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) throw await revertReason(chainId, sender, quoted, e);\n // no RPC answered: leave it to the router's own minimum\n }\n },\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n if (!tx?.to || !tx.data) throw refusal(\"policy_refused\", \"swap2: Fynd quote has no transaction request\");\n return {chain: \"\", to: tx.to, value: tx.value ?? \"0\", data: tx.data, ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}), ...(tx.gasLimit ? {gasLimit: tx.gasLimit} : {}), ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {})};\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n if (!ref.sourceTxHash) return {state: \"pending\"};\n const chainId = Number(ref.intentId.split(\":\")[1]);\n if (!FYND_CHAINS[chainId] || !config.rpcUrls?.[chainId]?.length) return {state: \"pending\"};\n try {\n const receipt = (await rpc(chainId, \"eth_getTransactionReceipt\", [ref.sourceTxHash])) as {status?: string} | null;\n if (!receipt) return {state: \"pending\"};\n return receipt.status === \"0x1\" ? {state: \"completed\", destTxHash: ref.sourceTxHash} : {state: \"failed\"};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n","/**\n * Activity recognition for Fynd: a swap entry point of TychoRouterV3 on a\n * chain the module serves → `swap`, \"Swapped A → B\" from the owner's net\n * transfers. The active router and the routers it replaced both count, so\n * swaps made before a redeploy keep their label.\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {chainLabel, describeSwapLike, matchesCall} from \"@anywalletkit/protocol-swap2-core/activity\";\nimport {evmRef, isEvm} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {FYND_CHAINS, TYCHO_ROUTER_SELECTORS} from \"./router.js\";\n\nexport const FYND_MODULE = \"@anywalletkit/protocol-swap2-fynd\";\n\n/**\n * TychoRouterV3 deployments the registry listed before the active one, per chain — for reading\n * history only. Never a call target or a spender: quotes and approvals accept only `FYND_CHAINS`\n * (Fynd License §3). These were effective 2026-09-01, paused 2026-11-16 and replaced the same day\n * (registry commit 8aab890).\n */\nexport const FYND_PREVIOUS_ROUTERS: Readonly<Record<number, readonly `0x${string}`[]>> = Object.freeze({\n 1: Object.freeze([\"0x1644D2477f809cc2C71bCCFd6Dc9497E3F83210d\"] as const),\n 8453: Object.freeze([\"0xAbA5B53b03eAfaD1C5fc8BD5Fc765fC85Bb3de67\"] as const),\n 42161: Object.freeze([\"0x924F147c50eA59f5180a26031A8b65B2aA1e81Cd\"] as const),\n 56: Object.freeze([\"0x7f3D12BBaFb8955E51B3ab9588b34c8ad95BDA4e\"] as const),\n 137: Object.freeze([\"0xbd4e6011F03355C2A377Fd9Af939322A7d0A1bC1\"] as const),\n 130: Object.freeze([\"0xCba5574597Ad00EA250Fd106DAB4Fc7461949635\"] as const),\n 4663: Object.freeze([\"0x09215a470bD585E59EB3F4B612fBD2678131fF9e\"] as const),\n});\n\nexport function describeFyndActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n if (!isEvm(tx.chain)) return null;\n const id = evmRef(tx.chain);\n const chain = FYND_CHAINS[id];\n if (!chain) return null;\n if (!matchesCall(tx, [chain.router, ...(FYND_PREVIOUS_ROUTERS[id] ?? [])], TYCHO_ROUTER_SELECTORS)) return null;\n return describeSwapLike(tx, ctx, {protocol: FYND_MODULE, subtitle: `Fynd · ${chainLabel(tx.chain)}`, kind: \"swap\"});\n}\n","/**\n * TychoRouterV3 — the only contract a Fynd quote may settle through (Fynd\n * License §3: every settlement of a Fynd output goes through the router in\n * Propeller Heads' registry). This file pins the router per chain and checks\n * Fynd's encoded transaction against the request before anything is approved\n * or sent: right contract, right method, the exact input, the requested\n * tokens, the user as receiver, the quoted output and minimum, and no client\n * fee. The route inside `swaps` is opaque and is not inspected here — the\n * router itself reverts below `minAmountOut`.\n */\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {refusalNotes, refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {ccAssetByToken} from \"@anywalletkit/swap2-assets\";\nimport {decodeFunctionData, getAddress, parseAbi, toFunctionSelector, type Hex} from \"viem\";\n\n/**\n * The active TychoRouterV3 per chain — github.com/propeller-heads/tycho\n * crates/tycho-execution/config/deployment_registry.json. Propeller Heads paused\n * every earlier router on 2026-11-16 (a router-vault vulnerability; this module\n * never uses the vault) and redeployed TychoRouterV3 on every chain the same day\n * (registry commit 8aab890). Quotes and approvals accept only these; the paused\n * routers are known to activity.ts alone, to read past swaps. Arc and Elysium\n * joined after that redeploy (the registry's `arc` and `elysium`, the hosted\n * API's `/v1/arc` and `/v1/elysium`); this module never pinned their paused\n * routers, so history knows none.\n */\nexport const FYND_CHAINS: Readonly<Record<number, {slug: string; name: string; router: `0x${string}`}>> = Object.freeze({\n 1: {slug: \"ethereum\", name: \"Ethereum\", router: \"0xe41c726421007e133a59365432fE886a73B45126\"},\n 8453: {slug: \"base\", name: \"Base\", router: \"0xd374c00614f95492D816b5957E3797ce3f0c445C\"},\n 42161: {slug: \"arbitrum\", name: \"Arbitrum\", router: \"0x1B82e8C16Ce8E17535C9B6b8AD107f61b0b192B5\"},\n 56: {slug: \"bsc\", name: \"BNB Smart Chain\", router: \"0xEe7eCe626064BDA1c6aFDb8A281afe44Eabd3242\"},\n 137: {slug: \"polygon\", name: \"Polygon\", router: \"0x4dB0B661dc706f7e09e54273028B22f61f8F94C2\"},\n 130: {slug: \"unichain\", name: \"Unichain\", router: \"0x556dff14e4A42259ebCE4fa087323c1047e9a55A\"},\n 4663: {slug: \"robinhood\", name: \"Robinhood Chain\", router: \"0x6F460540B03651d2Ad0ec28f777e4A0480A756a5\"},\n 5042: {slug: \"arc\", name: \"Arc\", router: \"0x52A1BC20F2B78461D7a03c32f6c7388D4587980f\"},\n 99901: {slug: \"elysium\", name: \"Elysium\", router: \"0x643577F3b0cB8CE1b1b73C6E872b907aCACD2662\"},\n});\n\n/**\n * Whether a swap may take or pay the chain's native coin: only where the token catalog lists one.\n * Arc's gas token is USDC with 18-decimal native accounting, and the catalog lists USDC only through\n * its 6-decimal ERC-20 interface (0x3600…) — every venue addresses it that way. Fynd prices a native\n * leg on Arc in the 18-decimal units (2026-11-17: 10 USDC in = `value` 10^19), so a native swap there\n * would carry amounts 10^12 off the catalog's USDC; it is refused, and the ERC-20 swaps instead.\n */\nexport function fyndNativeSwaps(chainId: number): boolean {\n return !!ccAssetByToken(`eip155:${chainId}`, ZERO);\n}\n\n/** The router's native-coin sentinel (lib/NativeETH.sol); Fynd's API uses the zero address instead. */\nexport const ROUTER_NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\n\nconst PARAMS = \"uint256 amountIn, address tokenIn, address tokenOut, uint256 expectedAmountOut, uint256 minAmountOut\";\nconst FEE = \"(uint32 clientFeeBps, address clientFeeReceiver, uint256 maxClientContribution, uint256 deadline, bytes clientSignature) clientFeeParams\";\nconst PERMIT = \"((address token, uint160 amount, uint48 expiration, uint48 nonce) details, address spender, uint256 sigDeadline) permitSingle, bytes signature\";\n\n/** The three entry points a wallet swap uses (plain `transferFrom` from the user). */\nexport const TYCHO_ROUTER_ABI = parseAbi([\n `function singleSwap(${PARAMS}, address receiver, ${FEE}, bytes swapData) payable returns (uint256)`,\n `function sequentialSwap(${PARAMS}, address receiver, ${FEE}, bytes swaps) payable returns (uint256)`,\n `function splitSwap(${PARAMS}, uint256 nTokens, address receiver, ${FEE}, bytes swaps) payable returns (uint256)`,\n]);\n\n/** Every swap entry point of the router (Permit2 and vault variants included) — for recognizing history. */\nexport const TYCHO_ROUTER_SELECTORS: ReadonlySet<string> = new Set(\n [\n `singleSwap(${PARAMS}, address receiver, ${FEE}, bytes swapData)`,\n `sequentialSwap(${PARAMS}, address receiver, ${FEE}, bytes swaps)`,\n `splitSwap(${PARAMS}, uint256 nTokens, address receiver, ${FEE}, bytes swaps)`,\n `singleSwapUsingVault(${PARAMS}, address receiver, ${FEE}, bytes swapData)`,\n `sequentialSwapUsingVault(${PARAMS}, address receiver, ${FEE}, bytes swaps)`,\n `splitSwapUsingVault(${PARAMS}, uint256 nTokens, address receiver, ${FEE}, bytes swaps)`,\n `singleSwapPermit2(${PARAMS}, address receiver, ${FEE}, ${PERMIT}, bytes swapData)`,\n `sequentialSwapPermit2(${PARAMS}, address receiver, ${FEE}, ${PERMIT}, bytes swaps)`,\n `splitSwapPermit2(${PARAMS}, uint256 nTokens, address receiver, ${FEE}, ${PERMIT}, bytes swaps)`,\n ].map((sig) => toFunctionSelector(`function ${sig}`)),\n);\n\nexport class FyndTransactionError extends Error {\n constructor(message: string) {\n super(`fynd: ${message}`);\n this.name = \"FyndTransactionError\";\n }\n}\n/** A {@link FyndTransactionError} tagged with its refusal reason (class, name and text unchanged). */\nconst fail = (message: string, reason: Swap2RefusalReason): FyndTransactionError => withReason(new FyndTransactionError(message), reason);\n/** The reasons of the texts {@link fyndVerifyQuote} returned, for `fyndPins.reasonOf`. */\nconst notes = refusalNotes();\n\nexport interface ExpectedSwap {\n chainId: number;\n /** ERC-20 address, or the zero address for the native coin. */\n tokenIn: string;\n tokenOut: string;\n amountIn: bigint;\n receiver: string;\n /** Fynd's gross `amount_out` (before the router fee and slippage). */\n expectedAmountOut: bigint;\n /** Fynd's `min_amount_received` — what the router enforces on-chain. */\n minAmountOut: bigint;\n}\n\nexport interface EncodedTx {\n to: string;\n value: bigint;\n data: string;\n}\n\nconst sameAddress = (a: string, b: string) => {\n try {\n return getAddress(a) === getAddress(b);\n } catch {\n return false;\n }\n};\nconst routerToken = (t: string) => (sameAddress(t, ZERO) ? ROUTER_NATIVE : t);\n\n/** Refuses (throws {@link FyndTransactionError}) unless `tx` is exactly the swap the wallet asked for. */\nexport function checkFyndTransaction(tx: EncodedTx, expected: ExpectedSwap): {method: \"singleSwap\" | \"sequentialSwap\" | \"splitSwap\"} {\n const chain = FYND_CHAINS[expected.chainId];\n if (!chain) throw fail(`chain ${expected.chainId} has no pinned Tycho router`, \"unsupported_pair\");\n // `tx.to` is the API's: named in the refusal only when it is an address (scan 2026-10-27 modules, F34).\n if (!sameAddress(tx.to, chain.router)) throw fail(`the transaction targets ${/^0x[0-9a-fA-F]{40}$/.test(tx.to) ? tx.to : \"something that is not an address\"}, not the Tycho router on ${chain.name}`, \"vault_mismatch\");\n if (sameAddress(expected.receiver, ZERO) || sameAddress(expected.receiver, chain.router)) throw fail(\"invalid receiver\", \"recipient_mismatch\");\n if ((sameAddress(routerToken(expected.tokenIn), ROUTER_NATIVE) || sameAddress(routerToken(expected.tokenOut), ROUTER_NATIVE)) && !fyndNativeSwaps(expected.chainId)) {\n throw fail(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, \"unsupported_pair\");\n }\n if (expected.amountIn <= 0n || expected.minAmountOut <= 0n || expected.minAmountOut > expected.expectedAmountOut) {\n throw fail(\"invalid quote amounts\", \"price_check_failed\");\n }\n const nativeIn = sameAddress(expected.tokenIn, ZERO);\n if (tx.value !== (nativeIn ? expected.amountIn : 0n)) throw fail(\"native value does not match the input\", \"price_check_failed\");\n if (!/^0x(?:[0-9a-fA-F]{2}){4,}$/.test(tx.data)) throw fail(\"malformed calldata\", \"policy_refused\");\n\n let call: ReturnType<typeof decodeFunctionData<typeof TYCHO_ROUTER_ABI>>;\n try {\n call = decodeFunctionData({abi: TYCHO_ROUTER_ABI, data: tx.data as Hex});\n } catch {\n throw fail(\"not a plain singleSwap / sequentialSwap / splitSwap call (Permit2 and vault variants are not used)\", \"policy_refused\");\n }\n const a = call.args;\n const [amountIn, tokenIn, tokenOut, expectedAmountOut, minAmountOut] = a;\n const isSplit = call.functionName === \"splitSwap\";\n const receiver = (isSplit ? a[6] : a[5]) as string;\n const fee = (isSplit ? a[7] : a[6]) as {clientFeeBps: number; clientFeeReceiver: string; maxClientContribution: bigint; deadline: bigint; clientSignature: string};\n const swaps = (isSplit ? a[8] : a[7]) as string;\n if (amountIn !== expected.amountIn) throw fail(`calldata spends ${amountIn}, not ${expected.amountIn}`, \"price_check_failed\");\n if (!sameAddress(tokenIn, routerToken(expected.tokenIn)) || !sameAddress(tokenOut, routerToken(expected.tokenOut))) {\n throw fail(\"calldata swaps other tokens than requested\", \"policy_refused\");\n }\n if (!sameAddress(receiver, expected.receiver)) throw fail(`calldata pays ${receiver}, not ${expected.receiver}`, \"recipient_mismatch\");\n if (expectedAmountOut !== expected.expectedAmountOut || minAmountOut !== expected.minAmountOut) {\n throw fail(\"calldata amounts do not match the quote\", \"price_check_failed\");\n }\n if (fee.clientFeeBps !== 0 || fee.maxClientContribution !== 0n || !sameAddress(fee.clientFeeReceiver, ZERO)) {\n throw fail(\"calldata carries client-fee parameters — this module charges none\", \"policy_refused\");\n }\n if (swaps === \"0x\" || (isSplit && (a[5] as bigint) < 2n)) throw fail(\"empty or invalid route\", \"policy_refused\");\n return {method: call.functionName};\n}\n\n/**\n * {@link checkFyndTransaction} on a remote quote, against the request this app sent: the pinned\n * router, one chain, the exact input, the requested tokens, the app's recipient, the quoted minimum and\n * no client fee. The reason it fails, or null.\n */\nexport function fyndVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n // Fynd swaps on one chain; a source-chain swap must not answer a cross-chain request (reaudit 2026-10-30, #3).\n if (params.sourceChain !== params.destChain) return notes.note(\"same-chain swaps only\", \"unsupported_pair\");\n try {\n const chainId = /^eip155:[0-9]+$/.test(params.sourceChain) ? Number(params.sourceChain.slice(7)) : NaN;\n const src = sourceAssetOf(params);\n if (!src) return notes.note(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n const tx = quote.txRequest;\n if (!tx?.to || !tx.data) return notes.note(\"the quote carries no router transaction\", \"policy_refused\");\n checkFyndTransaction({to: tx.to, data: tx.data, value: BigInt(tx.value ?? \"0\")}, {\n chainId,\n tokenIn: src.contract ? getAddress(src.contract) : ZERO,\n tokenOut: /^0x0+$/.test(params.destToken) ? ZERO : getAddress(params.destToken),\n amountIn: BigInt(params.amountIn),\n receiver: getAddress(params.destAddress),\n expectedAmountOut: BigInt(quote.providerData?.gross ?? \"0\"),\n minAmountOut: BigInt(quote.minDestAmount),\n });\n return null;\n } catch (e) {\n const text = e instanceof Error ? e.message.replace(/^fynd: /, \"\") : String(e);\n // checkFyndTransaction's refusals are classified; a request or quote that does not parse is not.\n const info = refusalOf(e);\n return info ? notes.note(text, info) : text;\n }\n}\n\n/**\n * The Tycho router a Fynd swap calls and approves on a chain, and {@link fyndVerifyQuote} — the\n * app's side of `remoteProvider({name: \"fynd\", baseUrl, ...fyndPins})`, so a backend's quote is\n * checked against these routers and the app's own request, never against itself (scan 2026-10-27\n * modules, F9). `reasonOf` classifies the texts `fyndVerifyQuote` returned, so the remote stub's refusal carries a reason.\n */\nexport const fyndPins: RemotePins = Object.freeze({\n callTargets: (chain: string): readonly string[] => fyndRouterFor(chain),\n spenders: (chain: string): readonly string[] => fyndRouterFor(chain),\n verifyQuote: fyndVerifyQuote,\n reasonOf: (refusal: string) => notes.reasonOf(refusal),\n});\nfunction fyndRouterFor(chain: string): readonly string[] {\n const id = /^eip155:[0-9]+$/.test(chain) ? Number(chain.slice(7)) : NaN;\n const c = Object.prototype.hasOwnProperty.call(FYND_CHAINS, id) ? FYND_CHAINS[id] : undefined;\n return c ? [c.router] : [];\n}\n","import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {evmRef, isEvm} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {fyndProvider, type FyndProviderConfig} from \"./provider.js\";\nimport {FYND_CHAINS} from \"./router.js\";\n\nexport interface FyndSwap2Config extends Swap2EngineConfig, FyndProviderConfig {}\n\n/** Fynd as a standalone swap2 protocol (same-chain swaps on one account). */\nexport class FyndSwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n private readonly _fynd: FyndProviderConfig;\n constructor(account: Swap2Account | undefined, config: FyndSwap2Config) {\n super(account, config);\n this.provider = fyndProvider(config);\n this._fynd = config;\n }\n protected override chainSupported(caip2: string): boolean {\n if (!isEvm(caip2)) return false;\n const id = evmRef(caip2);\n return !!FYND_CHAINS[id] && (!!this._fynd.selfHosted?.[id] || !!this._fynd.apiKey);\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return fromChain === toChain && this.chainSupported(fromChain);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAAwG;AACxG,IAAAC,eAA0D;AAC1D,IAAAC,iBAA0G;;;ACK1G,sBAAwD;AACxD,IAAAC,eAA4B;;;ACG5B,kBAA4B;AAC5B,oBAA2E;AAC3E,0BAA6B;AAC7B,kBAAqF;AAa9E,IAAM,cAA6F,OAAO,OAAO;AAAA,EACtH,GAAG,EAAC,MAAM,YAAY,MAAM,YAAY,QAAQ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BAA6B,CAAC,IAAI,YAAY,CAAC;AACnF,YAAI,CAAC,QAAS,QAAO,EAAC,OAAO,UAAS;AACtC,eAAO,QAAQ,WAAW,QAAQ,EAAC,OAAO,aAAa,YAAY,IAAI,aAAY,IAAI,EAAC,OAAO,SAAQ;AAAA,MACzG,QAAQ;AACN,eAAO,EAAC,OAAO,UAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;;;AGnZA,oBAAkC;AAElC,IAAAE,eAA4B;AAOrB,IAAM,oBAAN,cAAgC,kCAAoB;AAAA,EACtC;AAAA,EACF;AAAA,EACjB,YAAY,SAAmC,QAAyB;AACtE,UAAM,SAAS,MAAM;AACrB,SAAK,WAAW,aAAa,MAAM;AACnC,SAAK,QAAQ;AAAA,EACf;AAAA,EACmB,eAAe,OAAwB;AACxD,QAAI,KAAC,oBAAM,KAAK,EAAG,QAAO;AAC1B,UAAM,SAAK,qBAAO,KAAK;AACvB,WAAO,CAAC,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC,KAAK,MAAM,aAAa,EAAE,KAAK,CAAC,CAAC,KAAK,MAAM;AAAA,EAC7E;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,cAAc,WAAW,KAAK,eAAe,SAAS;AAAA,EAC/D;AACF;","names":["import_viem","import_util","import_errors","import_util","refusal","ZERO","balance","import_util"]}
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { FYND_DEFAULT_EXCLUDED_PROTOCOLS, FyndProviderConfig, fyndProvider } from './provider.cjs';
2
- export { EncodedTx, ExpectedSwap, FYND_CHAINS, FyndTransactionError, ROUTER_NATIVE, TYCHO_ROUTER_ABI, TYCHO_ROUTER_SELECTORS, checkFyndTransaction, fyndPins, fyndVerifyQuote } from './router.cjs';
2
+ export { EncodedTx, ExpectedSwap, FYND_CHAINS, FyndTransactionError, ROUTER_NATIVE, TYCHO_ROUTER_ABI, TYCHO_ROUTER_SELECTORS, checkFyndTransaction, fyndNativeSwaps, fyndPins, fyndVerifyQuote } from './router.cjs';
3
3
  export { FyndSwap2Config, FyndSwap2Protocol, FyndSwap2Protocol as default } from './protocol.cjs';
4
- export { FYND_MODULE, describeFyndActivity } from './activity.cjs';
4
+ export { FYND_MODULE, FYND_PREVIOUS_ROUTERS, describeFyndActivity } from './activity.cjs';
5
5
  import '@anywalletkit/protocol-swap2-core/types';
6
6
  import '@anywalletkit/protocol-swap2-core/swap2/single';
7
7
  import '@anywalletkit/protocol-swap2-core/swap2/base';
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { FYND_DEFAULT_EXCLUDED_PROTOCOLS, FyndProviderConfig, fyndProvider } from './provider.js';
2
- export { EncodedTx, ExpectedSwap, FYND_CHAINS, FyndTransactionError, ROUTER_NATIVE, TYCHO_ROUTER_ABI, TYCHO_ROUTER_SELECTORS, checkFyndTransaction, fyndPins, fyndVerifyQuote } from './router.js';
2
+ export { EncodedTx, ExpectedSwap, FYND_CHAINS, FyndTransactionError, ROUTER_NATIVE, TYCHO_ROUTER_ABI, TYCHO_ROUTER_SELECTORS, checkFyndTransaction, fyndNativeSwaps, fyndPins, fyndVerifyQuote } from './router.js';
3
3
  export { FyndSwap2Config, FyndSwap2Protocol, FyndSwap2Protocol as default } from './protocol.js';
4
- export { FYND_MODULE, describeFyndActivity } from './activity.js';
4
+ export { FYND_MODULE, FYND_PREVIOUS_ROUTERS, describeFyndActivity } from './activity.js';
5
5
  import '@anywalletkit/protocol-swap2-core/types';
6
6
  import '@anywalletkit/protocol-swap2-core/swap2/single';
7
7
  import '@anywalletkit/protocol-swap2-core/swap2/base';
package/dist/index.js CHANGED
@@ -1,14 +1,15 @@
1
1
  import {
2
2
  FyndSwap2Protocol
3
- } from "./chunk-FTBFWSOY.js";
3
+ } from "./chunk-GOHYCHZV.js";
4
4
  import {
5
5
  FYND_DEFAULT_EXCLUDED_PROTOCOLS,
6
6
  fyndProvider
7
- } from "./chunk-6AQCGGUZ.js";
7
+ } from "./chunk-AGCJEZYO.js";
8
8
  import {
9
9
  FYND_MODULE,
10
+ FYND_PREVIOUS_ROUTERS,
10
11
  describeFyndActivity
11
- } from "./chunk-O47NHTKT.js";
12
+ } from "./chunk-VXRMH634.js";
12
13
  import {
13
14
  FYND_CHAINS,
14
15
  FyndTransactionError,
@@ -16,13 +17,15 @@ import {
16
17
  TYCHO_ROUTER_ABI,
17
18
  TYCHO_ROUTER_SELECTORS,
18
19
  checkFyndTransaction,
20
+ fyndNativeSwaps,
19
21
  fyndPins,
20
22
  fyndVerifyQuote
21
- } from "./chunk-6WSGOEAI.js";
23
+ } from "./chunk-DFBL7TBQ.js";
22
24
  export {
23
25
  FYND_CHAINS,
24
26
  FYND_DEFAULT_EXCLUDED_PROTOCOLS,
25
27
  FYND_MODULE,
28
+ FYND_PREVIOUS_ROUTERS,
26
29
  FyndSwap2Protocol,
27
30
  FyndTransactionError,
28
31
  ROUTER_NATIVE,
@@ -31,6 +34,7 @@ export {
31
34
  checkFyndTransaction,
32
35
  FyndSwap2Protocol as default,
33
36
  describeFyndActivity,
37
+ fyndNativeSwaps,
34
38
  fyndPins,
35
39
  fyndProvider,
36
40
  fyndVerifyQuote
package/dist/protocol.cjs CHANGED
@@ -38,16 +38,22 @@ var import_util2 = require("@anywalletkit/protocol-swap2-core/util");
38
38
  // src/router.ts
39
39
  var import_util = require("@anywalletkit/protocol-swap2-core/util");
40
40
  var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
41
+ var import_swap2_assets = require("@anywalletkit/swap2-assets");
41
42
  var import_viem = require("viem");
42
43
  var FYND_CHAINS = Object.freeze({
43
- 1: { slug: "ethereum", name: "Ethereum", router: "0x1644D2477f809cc2C71bCCFd6Dc9497E3F83210d" },
44
- 8453: { slug: "base", name: "Base", router: "0xAbA5B53b03eAfaD1C5fc8BD5Fc765fC85Bb3de67" },
45
- 42161: { slug: "arbitrum", name: "Arbitrum", router: "0x924F147c50eA59f5180a26031A8b65B2aA1e81Cd" },
46
- 56: { slug: "bsc", name: "BNB Smart Chain", router: "0x7f3D12BBaFb8955E51B3ab9588b34c8ad95BDA4e" },
47
- 137: { slug: "polygon", name: "Polygon", router: "0xbd4e6011F03355C2A377Fd9Af939322A7d0A1bC1" },
48
- 130: { slug: "unichain", name: "Unichain", router: "0xCba5574597Ad00EA250Fd106DAB4Fc7461949635" },
49
- 4663: { slug: "robinhood", name: "Robinhood Chain", router: "0x09215a470bD585E59EB3F4B612fBD2678131fF9e" }
44
+ 1: { slug: "ethereum", name: "Ethereum", router: "0xe41c726421007e133a59365432fE886a73B45126" },
45
+ 8453: { slug: "base", name: "Base", router: "0xd374c00614f95492D816b5957E3797ce3f0c445C" },
46
+ 42161: { slug: "arbitrum", name: "Arbitrum", router: "0x1B82e8C16Ce8E17535C9B6b8AD107f61b0b192B5" },
47
+ 56: { slug: "bsc", name: "BNB Smart Chain", router: "0xEe7eCe626064BDA1c6aFDb8A281afe44Eabd3242" },
48
+ 137: { slug: "polygon", name: "Polygon", router: "0x4dB0B661dc706f7e09e54273028B22f61f8F94C2" },
49
+ 130: { slug: "unichain", name: "Unichain", router: "0x556dff14e4A42259ebCE4fa087323c1047e9a55A" },
50
+ 4663: { slug: "robinhood", name: "Robinhood Chain", router: "0x6F460540B03651d2Ad0ec28f777e4A0480A756a5" },
51
+ 5042: { slug: "arc", name: "Arc", router: "0x52A1BC20F2B78461D7a03c32f6c7388D4587980f" },
52
+ 99901: { slug: "elysium", name: "Elysium", router: "0x643577F3b0cB8CE1b1b73C6E872b907aCACD2662" }
50
53
  });
54
+ function fyndNativeSwaps(chainId) {
55
+ return !!(0, import_swap2_assets.ccAssetByToken)(`eip155:${chainId}`, ZERO);
56
+ }
51
57
  var ROUTER_NATIVE = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
52
58
  var ZERO = "0x0000000000000000000000000000000000000000";
53
59
  var PARAMS = "uint256 amountIn, address tokenIn, address tokenOut, uint256 expectedAmountOut, uint256 minAmountOut";
@@ -92,6 +98,9 @@ function checkFyndTransaction(tx, expected) {
92
98
  if (!chain) throw fail(`chain ${expected.chainId} has no pinned Tycho router`, "unsupported_pair");
93
99
  if (!sameAddress(tx.to, chain.router)) throw fail(`the transaction targets ${/^0x[0-9a-fA-F]{40}$/.test(tx.to) ? tx.to : "something that is not an address"}, not the Tycho router on ${chain.name}`, "vault_mismatch");
94
100
  if (sameAddress(expected.receiver, ZERO) || sameAddress(expected.receiver, chain.router)) throw fail("invalid receiver", "recipient_mismatch");
101
+ if ((sameAddress(routerToken(expected.tokenIn), ROUTER_NATIVE) || sameAddress(routerToken(expected.tokenOut), ROUTER_NATIVE)) && !fyndNativeSwaps(expected.chainId)) {
102
+ throw fail(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, "unsupported_pair");
103
+ }
95
104
  if (expected.amountIn <= 0n || expected.minAmountOut <= 0n || expected.minAmountOut > expected.expectedAmountOut) {
96
105
  throw fail("invalid quote amounts", "price_check_failed");
97
106
  }
@@ -162,11 +171,21 @@ function fyndRouterFor(chain) {
162
171
 
163
172
  // src/activity.ts
164
173
  var FYND_MODULE = "@anywalletkit/protocol-swap2-fynd";
174
+ var FYND_PREVIOUS_ROUTERS = Object.freeze({
175
+ 1: Object.freeze(["0x1644D2477f809cc2C71bCCFd6Dc9497E3F83210d"]),
176
+ 8453: Object.freeze(["0xAbA5B53b03eAfaD1C5fc8BD5Fc765fC85Bb3de67"]),
177
+ 42161: Object.freeze(["0x924F147c50eA59f5180a26031A8b65B2aA1e81Cd"]),
178
+ 56: Object.freeze(["0x7f3D12BBaFb8955E51B3ab9588b34c8ad95BDA4e"]),
179
+ 137: Object.freeze(["0xbd4e6011F03355C2A377Fd9Af939322A7d0A1bC1"]),
180
+ 130: Object.freeze(["0xCba5574597Ad00EA250Fd106DAB4Fc7461949635"]),
181
+ 4663: Object.freeze(["0x09215a470bD585E59EB3F4B612fBD2678131fF9e"])
182
+ });
165
183
  function describeFyndActivity(tx, ctx) {
166
184
  if (!(0, import_util2.isEvm)(tx.chain)) return null;
167
- const chain = FYND_CHAINS[(0, import_util2.evmRef)(tx.chain)];
185
+ const id = (0, import_util2.evmRef)(tx.chain);
186
+ const chain = FYND_CHAINS[id];
168
187
  if (!chain) return null;
169
- if (!(0, import_activity.matchesCall)(tx, [chain.router], TYCHO_ROUTER_SELECTORS)) return null;
188
+ if (!(0, import_activity.matchesCall)(tx, [chain.router, ...FYND_PREVIOUS_ROUTERS[id] ?? []], TYCHO_ROUTER_SELECTORS)) return null;
170
189
  return (0, import_activity.describeSwapLike)(tx, ctx, { protocol: FYND_MODULE, subtitle: `Fynd \xB7 ${(0, import_activity.chainLabel)(tx.chain)}`, kind: "swap" });
171
190
  }
172
191
 
@@ -324,6 +343,9 @@ function fyndProvider(config) {
324
343
  if (!nativeOut && !/^0x[0-9a-fA-F]{40}$/.test(params.destToken)) return refuse("destination token must be an EVM address", "unsupported_pair");
325
344
  const tokenOut = nativeOut ? ZERO2 : (0, import_viem2.getAddress)(params.destToken);
326
345
  if (tokenIn === tokenOut) return refuse("same token in and out", "unsupported_pair");
346
+ if ((tokenIn === ZERO2 || tokenOut === ZERO2 || tokenOut === (0, import_viem2.getAddress)(ROUTER_NATIVE)) && !fyndNativeSwaps(chainId)) {
347
+ return refuse(`the native coin on ${FYND_CHAINS[chainId].name} is not a catalog asset here; swap its ERC-20 instead`, "unsupported_pair");
348
+ }
327
349
  if (!/^0x[0-9a-fA-F]{40}$/.test(params.destAddress)) return refuse("recipient must be an EVM address", "recipient_mismatch");
328
350
  const receiver = (0, import_viem2.getAddress)(params.destAddress);
329
351
  const sender = (0, import_viem2.getAddress)(params.refundAddress && /^0x[0-9a-fA-F]{40}$/.test(params.refundAddress) ? params.refundAddress : params.destAddress);