@anywalletkit/protocol-swap2-usdt0 0.2.1 → 0.4.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/protocol.ts","../src/config.ts","../src/provider.ts","../src/activity.ts"],"sourcesContent":["import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {usdt0 as usdt0Cfg} from \"./config.js\";\nimport {usdt0Provider, type Usdt0ProviderConfig} from \"./provider.js\";\n\nexport interface Usdt0Swap2Config extends Swap2EngineConfig, Usdt0ProviderConfig {}\n\n/** Standalone USDT0 swap2: USDT / USDT0 between the LayerZero OFT deployments in one source transaction. */\nexport class Usdt0Swap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n constructor(account: Swap2Account | undefined, config: Usdt0Swap2Config) {\n super(account, config);\n this.provider = usdt0Provider(config);\n }\n protected override chainSupported(caip2: string): boolean {\n return usdt0Cfg.supportsChain(caip2);\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return usdt0Cfg.supports(fromChain, toChain);\n }\n}\n","// USDT0 — Tether's LayerZero OFT for USDT. Source: docs.usdt0.to\n// (technical-documentation/deployments, read 2026-10-20) — every row below was\n// then re-read on-chain over public RPCs the same day: the OFT's `token()` is\n// the listed token, `endpoint()` is the listed endpoint (and reports the\n// listed eid), `approvalRequired()` is true only for the Ethereum adapter,\n// `sharedDecimals()` = 6 everywhere, and `peers(eid)` are wired between the\n// chains. `oftVersion()` = (0x02e49c2c, 1) on all of them.\n//\n// Only chains the SDK ships (swap2-assets / wallet-evm) are listed. USDT0 is\n// also deployed on Conflux eSpace (1030, eid 30212), Flare (14, 30295),\n// Hedera (295, 30316), Mantle (5000, 30181), Morph (2818, 30322), Rootstock\n// (30, 30333), Stable (988, 30396), Tempo (4217, 30410), plus HyperCore, IOTA\n// and Stellar (non-EVM) — not wallet chains here, so not routable here.\nimport type {RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {evmRef, isEvm} from \"@anywalletkit/protocol-swap2-core/util\";\n\nexport interface Usdt0Chain {\n caip2: string;\n chainId: number;\n /** LayerZero V2 endpoint id. */\n eid: number;\n name: string;\n /** The ERC-20 the user holds: USDT on Ethereum, USDT0 elsewhere (6 decimals everywhere). */\n token: string;\n /**\n * The OFT contract `quoteSend` / `send` are called on. On Ethereum it is the\n * OFT *adapter* that locks USDT (`approvalRequired()` = true, approve the\n * token to it); elsewhere it is the OUpgradeable OFT that burns the caller's\n * USDT0 through the token's mint/burn role — no approval.\n */\n oft: string;\n /** LayerZero V2 EndpointV2 on that chain (`lzReceive` retries of a stored payload go here). */\n endpoint: string;\n /** True on Ethereum: the OFT is a lockbox adapter in front of plain USDT. */\n adapter: boolean;\n}\n\nconst LZ_ENDPOINT_A = \"0x1a44076050125825900e736c501f859c50fE728c\";\nconst LZ_ENDPOINT_B = \"0x6F475642a6e85809B1c36Fa62763669b1b48DD5B\";\n\nconst c = (chainId: number, eid: number, name: string, token: string, oft: string, endpoint: string, adapter = false): Usdt0Chain => ({\n caip2: `eip155:${chainId}`, chainId, eid, name, token, oft, endpoint, adapter,\n});\n\n/** CAIP-2 → USDT0 deployment. */\nexport const USDT0_CHAINS: Readonly<Record<string, Usdt0Chain>> = Object.freeze(Object.fromEntries([\n c(1, 30101, \"Ethereum\", \"0xdAC17F958D2ee523a2206206994597C13D831ec7\", \"0x6C96dE32CEa08842dcc4058c14d3aaAD7Fa41dee\", LZ_ENDPOINT_A, true),\n c(42161, 30110, \"Arbitrum\", \"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9\", \"0x14E4A1B13bf7F943c8ff7C51fb60FA964A298D92\", LZ_ENDPOINT_A),\n c(10, 30111, \"OP Mainnet\", \"0x01bFF41798a0BcF287b996046Ca68b395DbC1071\", \"0xF03b4d9AC1D5d1E7c4cEf54C2A313b9fe051A0aD\", LZ_ENDPOINT_A),\n c(137, 30109, \"Polygon PoS\", \"0xc2132D05D31c914a87C6611C10748AEb04B58e8F\", \"0x6BA10300f0DC58B7a1e4c0e41f5daBb7D7829e13\", LZ_ENDPOINT_A),\n c(999, 30367, \"HyperEVM\", \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\", \"0x904861a24F30EC96ea7CFC3bE9EA4B476d237e98\", \"0x3A73033C0b1407574C76BdBAc67f126f6b4a9AA9\"),\n c(57073, 30339, \"Ink\", \"0x0200C29006150606B650577BBE7B6248F58470c1\", \"0x1cB6De532588fCA4a21B7209DE7C456AF8434A65\", \"0xca29f3A6f966Cb2fc0dE625F8f325c0C46dbE958\"),\n c(80094, 30362, \"Berachain\", \"0x779Ded0c9e1022225f8E0630b35a9b54bE713736\", \"0x3Dc96399109df5ceb2C226664A086140bD0379cB\", LZ_ENDPOINT_B),\n c(130, 30320, \"Unichain\", \"0x9151434b16b9763660705744891fA906F660EcC5\", \"0xc07bE8994D035631c36fb4a89C918CeFB2f03EC3\", LZ_ENDPOINT_B),\n c(1329, 30280, \"Sei\", \"0x9151434b16b9763660705744891fA906F660EcC5\", \"0x56Fe74A2e3b484b921c447357203431a3485CC60\", LZ_ENDPOINT_A),\n c(9745, 30383, \"Plasma\", \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\", \"0x02ca37966753bDdDf11216B73B16C1dE756A7CF9\", LZ_ENDPOINT_B),\n c(143, 30390, \"Monad\", \"0xe7cd86e13AC4309349F30B3435a9d337750fC82D\", \"0x9151434b16b9763660705744891fA906F660EcC5\", LZ_ENDPOINT_B),\n c(4326, 30398, \"MegaETH\", \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\", \"0x9151434b16b9763660705744891fA906F660EcC5\", LZ_ENDPOINT_B),\n c(196, 30274, \"X Layer\", \"0x779Ded0c9e1022225f8E0630b35a9b54bE713736\", \"0x94bcCa6BdfD6a61817aB0E960BfedE4984505554\", LZ_ENDPOINT_A),\n // 2026-10-20 (evm-chains-6 batch): docs.usdt0.to deployments, re-read on-chain (token(), approvalRequired() = false,\n // sharedDecimals() = 6, endpoint(), peers(30110) = the Arbitrum OFT).\n c(5000, 30181, \"Mantle\", \"0x779Ded0c9e1022225f8E0630b35a9b54bE713736\", \"0xcb768e263FB1C62214E7cab4AA8d036D76dc59CC\", LZ_ENDPOINT_A),\n c(2818, 30322, \"Morph\", \"0xe7cd86e13AC4309349F30B3435a9d337750fC82D\", \"0xcb768e263FB1C62214E7cab4AA8d036D76dc59CC\", LZ_ENDPOINT_B),\n c(14, 30295, \"Flare\", \"0xe7cd86e13AC4309349F30B3435a9d337750fC82D\", \"0x567287d2A9829215a37e3B88843d32f9221E7588\", LZ_ENDPOINT_A),\n].map((x) => [x.caip2, x])));\n\n/** LayerZero eid → deployment. */\nexport const USDT0_BY_EID: Readonly<Record<number, Usdt0Chain>> = Object.freeze(\n Object.fromEntries(Object.values(USDT0_CHAINS).map((x) => [x.eid, x])),\n);\n\n/** LayerZero Scan — message status by source transaction hash. */\nexport const LZ_SCAN_API = \"https://scan.layerzero-api.com\";\n\n/** Token symbols the catalog uses for the same asset across chains. */\nexport const USDT0_SYMBOLS: readonly string[] = Object.freeze([\"USDT0\", \"USDT\", \"USD₮0\", \"USD₮\"]);\n\nexport const usdt0 = {\n supportsChain(chain: string): boolean {\n return isEvm(chain) && !!USDT0_CHAINS[`eip155:${evmRef(chain)}`];\n },\n supports(from: string, to: string): boolean {\n return from !== to && this.supportsChain(from) && this.supportsChain(to);\n },\n};\n\n/**\n * The USDT0 OFT a send calls on a chain, and the adapter it approves where one locks USDT (Ethereum) —\n * the app's pins for `remoteProvider({name: \"usdt0\", baseUrl, ...usdt0Pins})` (scan 2026-10-27 modules, F8/F16).\n */\nexport const usdt0Pins: RemotePins = Object.freeze({\n callTargets: (chain: string): readonly string[] => { const c = usdt0ChainFor(chain); return c ? [c.oft] : []; },\n spenders: (chain: string): readonly string[] => { const c = usdt0ChainFor(chain); return c?.adapter ? [c.oft] : []; },\n});\nfunction usdt0ChainFor(chain: string): Usdt0Chain | undefined {\n return Object.prototype.hasOwnProperty.call(USDT0_CHAINS, chain) ? USDT0_CHAINS[chain] : undefined;\n}\n","import {createPublicClient, encodeFunctionData, fallback, getAddress, http, isAddress, pad, parseAbi, type Hex} from \"viem\";\nimport {describeUsdt0Activity} from \"./activity.js\";\nimport {ccAsset} from \"@anywalletkit/swap2-assets\";\nimport {redactUrls, timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentState, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {LZ_SCAN_API, USDT0_BY_EID, USDT0_CHAINS, USDT0_SYMBOLS, usdt0 as usdt0Cfg, type Usdt0Chain} from \"./config.js\";\n\n/**\n * USDT0 — Tether's USDT as a LayerZero OFT. ONE source transaction:\n * `send(SendParam, MessagingFee, refund)` on the chain's OFT with the\n * LayerZero messaging fee as `msg.value`; LayerZero's DVNs verify and the\n * executor delivers on the destination (mint of USDT0, or unlock of USDT out\n * of the Ethereum adapter). No second user transaction in the normal case.\n *\n * - Quote = two `eth_call`s on the source OFT: `quoteOFT` for the limits,\n * protocol fees and the amount that really arrives after dust removal\n * (shared decimals = 6, so none today), then `quoteSend` for the native\n * fee with `minAmountLD` pinned to that received amount — the contract\n * reverts rather than deliver less. Both are sealed into the quote.\n * - `enforcedOptions` on every deployment already carry the executor gas\n * (type-3 options, lzReceive gas 80 000, read on-chain 2026-10-20), so\n * `extraOptions` stays empty; LayerZero Scan confirms deliveries ran on it.\n * - Ethereum locks USDT in an adapter (`approvalRequired()` = true →\n * `approvalAddress`); every other chain's OFT burns the caller's USDT0\n * itself (`approvalRequired()` = false → no approval at all).\n * - Every address in `config.ts` is re-read on-chain before the first quote\n * on a chain (`token()`, `approvalRequired()`) and per pair (`peers(dstEid)`\n * must be the destination OFT) — a mismatch refuses the route.\n * - Status: LayerZero Scan by source hash. DELIVERED carries the destination\n * hash; PAYLOAD_STORED (delivery reverted on the destination, funds safe)\n * becomes \"action-required\" with a `buildClaim` that retries\n * `EndpointV2.lzReceive` — anyone may call it, so the user can.\n */\n\nconst OFT_ABI = parseAbi([\n \"struct SendParam { uint32 dstEid; bytes32 to; uint256 amountLD; uint256 minAmountLD; bytes extraOptions; bytes composeMsg; bytes oftCmd; }\",\n \"struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; }\",\n \"struct OFTLimit { uint256 minAmountLD; uint256 maxAmountLD; }\",\n \"struct OFTFeeDetail { int256 feeAmountLD; string description; }\",\n \"struct OFTReceipt { uint256 amountSentLD; uint256 amountReceivedLD; }\",\n \"struct MessagingReceipt { bytes32 guid; uint64 nonce; MessagingFee fee; }\",\n \"function quoteSend(SendParam s, bool payInLzToken) view returns (MessagingFee)\",\n \"function quoteOFT(SendParam s) view returns (OFTLimit, OFTFeeDetail[], OFTReceipt)\",\n \"function send(SendParam s, MessagingFee fee, address refundAddress) payable returns (MessagingReceipt, OFTReceipt)\",\n \"function token() view returns (address)\",\n \"function approvalRequired() view returns (bool)\",\n \"function peers(uint32 eid) view returns (bytes32)\",\n]);\nconst ENDPOINT_ABI = parseAbi([\n \"struct Origin { uint32 srcEid; bytes32 sender; uint64 nonce; }\",\n \"function lzReceive(Origin origin, address receiver, bytes32 guid, bytes message, bytes extraData) payable\",\n]);\n\nconst EVM_PLACEHOLDER = \"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045\";\nconst DEFAULT_QUOTE_TTL_MS = 60_000;\nconst RPC_TIMEOUT_MS = 12_000;\nconst SCAN_TIMEOUT_MS = 12_000;\n/** A direct `send` used ~330k gas on Arbitrum and on the Ethereum adapter (2026-10-20 receipts). */\nconst GAS_SEND = \"450000\";\n/**\n * The LayerZero fee is quoted at quote time but paid at send time, and it moves\n * with source and destination gas (live: +1.7 % within a minute on Ethereum).\n * The sealed `msg.value` carries this headroom; EndpointV2 charges the current\n * fee and refunds the surplus to `refundAddress` (the trader) in the same\n * transaction, so the headroom costs nothing — it only avoids a re-quote.\n */\nconst FEE_HEADROOM_BPS = 2_500n;\n/** `lzReceive` retry of a stored payload: a mint plus the endpoint bookkeeping. */\nconst GAS_CLAIM = \"300000\";\nconst ZERO_B32 = `0x${\"00\".repeat(32)}` as Hex;\n\nexport interface Usdt0ProviderConfig {\n enabled?: boolean;\n /**\n * JSON-RPC URL(s) per CAIP-2 chain. REQUIRED for every chain the provider\n * should quote from: the fee and the received amount come from the OFT\n * itself. The destination RPC is optional (used for the stored-payload retry).\n */\n rpcUrls?: Readonly<Record<string, string | readonly string[]>>;\n /** LayerZero Scan base (default https://scan.layerzero-api.com). */\n scanUrl?: string;\n /** Local lifetime of a quote (default 60 s; the sealed fee is re-checked at preflight). */\n quoteTtlMs?: number;\n /** Injectable for tests (also used by the RPC transport). */\n fetchImpl?: typeof fetch;\n}\n\ninterface ScanMessage {\n pathway?: {srcEid?: number; dstEid?: number; sender?: {address?: string}; receiver?: {address?: string}; nonce?: number};\n source?: {status?: string; tx?: {txHash?: string; payload?: string; options?: {lzReceive?: {gas?: string; value?: string}}}};\n destination?: {status?: string; tx?: {txHash?: string}};\n guid?: string;\n status?: {name?: string; message?: string};\n}\n\nconst same = (a: string | undefined | null, b: string) => !!a && a.toLowerCase() === b.toLowerCase();\nconst isHexData = (v: unknown): v is Hex => typeof v === \"string\" && /^0x(?:[0-9a-fA-F]{2})*$/.test(v);\n\n/** Does the catalog symbol on `chain` name this deployment's token? (USDT on Ethereum/Polygon, USDT0 elsewhere.) */\nfunction tokenMatches(chain: Usdt0Chain, symbolOrAddress: string): boolean {\n if (symbolOrAddress.startsWith(\"0x\")) return same(symbolOrAddress, chain.token);\n if (!USDT0_SYMBOLS.includes(symbolOrAddress.toUpperCase().replace(\"USD₮\", \"USDT\"))) return false;\n const known = ccAsset(chain.caip2, symbolOrAddress);\n // A symbol the catalog binds to another contract (OP's legacy bridged USDT) is not the OFT token.\n return !known || same(known.contract ?? \"\", chain.token);\n}\n\n/**\n * A refusal / preflight error that may reach a client: an RPC transport failure\n * becomes a fixed reason (viem's HTTP / timeout errors carry `URL: …`, and a keyed\n * endpoint's key sits in that path — scan 2026-10-23 F8); anything else loses its URLs.\n */\nfunction rpcSafeReason(err: unknown, chainName: string): string {\n const e = err as {name?: string; shortMessage?: string; message?: string} | undefined;\n const text = `${e?.shortMessage ?? \"\"}\\n${e?.message ?? String(err)}`;\n if (/HttpRequestError|TimeoutError|RpcRequestError|WebSocketRequestError/.test(String(e?.name)) || /\\bURL: |HTTP request failed|request timed out|took too long to respond/i.test(text)) {\n return `usdt0: RPC for ${chainName} unavailable — try again`;\n }\n return redactUrls(err instanceof Error ? err.message : String(err));\n}\n\nexport function usdt0Provider(config: Usdt0ProviderConfig = {}): CrossChainProvider {\n config = Object.freeze({...config});\n const scan = (config.scanUrl ?? LZ_SCAN_API).replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(scan)) throw new Error(\"usdt0: scanUrl must use http or https\");\n const quoteTtlMs = config.quoteTtlMs ?? DEFAULT_QUOTE_TTL_MS;\n if (!Number.isInteger(quoteTtlMs) || quoteTtlMs <= 0 || quoteTtlMs > 300_000) throw new Error(\"usdt0: quoteTtlMs must be an integer between 1 and 300000\");\n const rpcUrls = Object.freeze({...(config.rpcUrls ?? {})});\n const doFetch: typeof fetch = (input, init) => (config.fetchImpl ?? fetch)(input, init);\n\n const client = (caip2: string) => {\n const raw = rpcUrls[caip2];\n const urls = typeof raw === \"string\" ? [raw] : [...(raw ?? [])];\n if (urls.length === 0) return null;\n const opts = {timeout: RPC_TIMEOUT_MS, ...(config.fetchImpl ? {fetchFn: config.fetchImpl} : {})} as never;\n return createPublicClient({transport: urls.length === 1 ? http(urls[0], opts) : fallback(urls.map((u) => http(u, opts))), ccipRead: false});\n };\n\n /** Once per chain: the OFT really is the OFT of the listed token with the listed approval mode. */\n const verified = new Map<string, Promise<void>>();\n function verifyChain(chain: Usdt0Chain): Promise<void> {\n let p = verified.get(chain.caip2);\n if (!p) {\n p = (async () => {\n const c = client(chain.caip2);\n if (!c) throw new Error(`usdt0: no RPC for ${chain.caip2}`);\n const [token, approval] = await Promise.all([\n c.readContract({address: getAddress(chain.oft), abi: OFT_ABI, functionName: \"token\"}),\n c.readContract({address: getAddress(chain.oft), abi: OFT_ABI, functionName: \"approvalRequired\"}),\n ]);\n if (!same(token, chain.token)) throw new Error(`usdt0: OFT ${chain.oft} on ${chain.name} reports token ${token}, expected ${chain.token}`);\n if (approval !== chain.adapter) throw new Error(`usdt0: OFT ${chain.oft} on ${chain.name} reports approvalRequired=${String(approval)}, expected ${String(chain.adapter)}`);\n })();\n p.catch(() => verified.delete(chain.caip2));\n verified.set(chain.caip2, p);\n }\n return p;\n }\n\n /** Once per pair: the source OFT's peer for the destination eid is the destination OFT. */\n const peers = new Map<string, Promise<void>>();\n function verifyPeer(src: Usdt0Chain, dst: Usdt0Chain): Promise<void> {\n const key = `${src.eid}>${dst.eid}`;\n let p = peers.get(key);\n if (!p) {\n p = (async () => {\n const c = client(src.caip2);\n if (!c) throw new Error(`usdt0: no RPC for ${src.caip2}`);\n const peer = await c.readContract({address: getAddress(src.oft), abi: OFT_ABI, functionName: \"peers\", args: [dst.eid]});\n if (!same(peer, pad(getAddress(dst.oft), {size: 32}))) throw new Error(`usdt0: ${src.name} OFT has no peer for ${dst.name} (eid ${dst.eid}) — route not wired`);\n })();\n p.catch(() => peers.delete(key));\n peers.set(key, p);\n }\n return p;\n }\n\n function parseIntent(intentId: string): {src: Usdt0Chain; dst: Usdt0Chain} | null {\n const [tag, s, d] = intentId.split(\":\");\n if (tag !== \"usdt0\") return null;\n const src = USDT0_BY_EID[Number(s)];\n const dst = USDT0_BY_EID[Number(d)];\n return src && dst && src !== dst ? {src, dst} : null;\n }\n\n const sendParam = (dstEid: number, recipient: string, amountLD: bigint, minAmountLD: bigint) => ({\n dstEid, to: pad(getAddress(recipient), {size: 32}), amountLD, minAmountLD, extraOptions: \"0x\" as Hex, composeMsg: \"0x\" as Hex, oftCmd: \"0x\" as Hex,\n });\n\n /** The LayerZero message of a source transaction on this route, or null while Scan has not indexed it. */\n async function scanMessage(src: Usdt0Chain, dst: Usdt0Chain, sourceTxHash: string): Promise<ScanMessage | null | \"foreign\"> {\n const res = await doFetch(`${scan}/v1/messages/tx/${encodeURIComponent(sourceTxHash)}`, {headers: {accept: \"application/json\"}, signal: timeoutSignal(SCAN_TIMEOUT_MS)});\n if (res.status === 404) return null;\n if (!res.ok) throw new Error(`usdt0: LayerZero Scan → ${res.status}`);\n const body = (await res.json()) as {data?: ScanMessage[]};\n const list = Array.isArray(body?.data) ? body.data : [];\n if (list.length === 0) return null;\n const m = list.find((x) => x.pathway?.srcEid === src.eid && x.pathway?.dstEid === dst.eid && same(x.pathway?.sender?.address, src.oft));\n return m ?? \"foreign\";\n }\n\n return {\n name: \"usdt0\",\n describeActivity: describeUsdt0Activity,\n enabled: () => config.enabled ?? true,\n supportsChain: (chain: string) => usdt0Cfg.supportsChain(chain) && client(chain) !== null,\n supportsChainPair: (from: string, to: string) => usdt0Cfg.supports(from, to) && client(from) !== null,\n supportsRoute(from: Asset, to: Asset): boolean {\n const src = USDT0_CHAINS[from.chain];\n const dst = USDT0_CHAINS[to.chain];\n if (!src || !dst || src === dst || client(from.chain) === null) return false;\n return tokenMatches(src, from.token) && tokenMatches(dst, to.token);\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (reason: string) => { params.onRefusal?.(reason); return null; };\n if (params.flex) return refuse(\"the amount is sealed into the calldata (no flexible deposits)\");\n const src = USDT0_CHAINS[params.sourceChain];\n const dst = USDT0_CHAINS[params.destChain];\n if (!src || !dst) return refuse(\"USDT0 is not deployed on this chain\");\n if (src === dst) return refuse(\"same-chain transfers are not a bridge\");\n if (!tokenMatches(src, params.sourceToken)) return refuse(`source token ${params.sourceToken} is not USDT0 (${src.token}) on ${src.name}`);\n if (!tokenMatches(dst, params.destToken)) return refuse(`destination token ${params.destToken} is not USDT0 (${dst.token}) on ${dst.name}`);\n if (!/^\\d+$/.test(params.amountIn)) return refuse(\"amount must be a base-unit integer\");\n const amount = BigInt(params.amountIn);\n if (amount <= 0n) return refuse(\"amount must be positive\");\n // The placeholder prices a dry quote; a live one without addresses would send there (round 3, H8).\n const dry = params.dry !== false;\n const recipient = params.destAddress || (dry ? EVM_PLACEHOLDER : \"\");\n if (!recipient) return refuse(\"a live quote needs a recipient\");\n if (!isAddress(recipient)) return refuse(\"destination must be an EVM address\");\n const refund = params.refundAddress || (dry ? EVM_PLACEHOLDER : \"\");\n if (!refund) return refuse(\"a live quote needs a refund address\");\n if (!isAddress(refund)) return refuse(\"refund address must be an EVM address\");\n const c = client(src.caip2);\n if (!c) return refuse(`no RPC configured for ${src.caip2}`);\n\n try {\n await Promise.all([verifyChain(src), verifyPeer(src, dst)]);\n const probe = sendParam(dst.eid, recipient, amount, 0n);\n const [limit, feeDetails, receipt] = await c.readContract({address: getAddress(src.oft), abi: OFT_ABI, functionName: \"quoteOFT\", args: [probe]});\n if (amount < limit.minAmountLD) return refuse(`amount ${amount} is below the OFT minimum ${limit.minAmountLD}`);\n if (amount > limit.maxAmountLD) return refuse(`amount ${amount} exceeds the OFT maximum ${limit.maxAmountLD}`);\n const received = receipt.amountReceivedLD;\n if (received <= 0n) return refuse(\"amount is below the OFT dust threshold — nothing would arrive\");\n if (received > amount) return refuse(\"OFT reports more received than sent — refusing\");\n if (params.minAmountOut !== undefined && received < BigInt(params.minAmountOut)) return refuse(`received ${received} is below the caller's floor ${params.minAmountOut}`);\n const sp = sendParam(dst.eid, recipient, amount, received);\n const fee = await c.readContract({address: getAddress(src.oft), abi: OFT_ABI, functionName: \"quoteSend\", args: [sp, false]});\n if (fee.lzTokenFee !== 0n) return refuse(\"OFT asks for a fee in LZ token — unsupported\");\n // Sealed with headroom: OAppSender requires msg.value == MessagingFee.nativeFee, the\n // endpoint refunds whatever the current fee does not use to `refund`.\n const nativeFee = fee.nativeFee + (fee.nativeFee * FEE_HEADROOM_BPS) / 10_000n;\n const data = encodeFunctionData({abi: OFT_ABI, functionName: \"send\", args: [sp, {nativeFee, lzTokenFee: 0n}, getAddress(refund)]});\n const protocolFees = feeDetails\n .filter((f) => f.feeAmountLD > 0n)\n .map((f) => ({type: \"protocol\" as const, amount: f.feeAmountLD.toString(), token: src.token, included: true, description: f.description || \"OFT fee\"}));\n const feeUsd = protocolFees.reduce((a, f) => a + Number(f.amount) / 1e6, 0);\n // Ethereum sources wait for 60 confirmations before the DVNs attest (~15 min live); L2 sources land in a few minutes.\n const eta = src.chainId === 1 ? 1000 : 240;\n return {\n provider: \"usdt0\",\n intentId: `usdt0:${src.eid}:${dst.eid}`,\n depositAddress: \"\",\n depositMemo: null,\n txRequest: {\n to: src.oft,\n data,\n value: nativeFee.toString(),\n chainId: src.chainId,\n gasLimit: GAS_SEND,\n ...(src.adapter ? {approvalAddress: src.oft} : {}),\n ...(nativeFee > 0n ? {nativeFee: nativeFee.toString()} : {}),\n },\n sourceAmount: amount.toString(),\n destAmount: received.toString(),\n minDestAmount: received.toString(),\n feeUsd,\n fees: protocolFees,\n etaSeconds: eta,\n reliability: 0.98,\n validUntilMs: Date.now() + quoteTtlMs,\n providerData: {\n srcEid: String(src.eid), dstEid: String(dst.eid), oft: src.oft, token: src.token, recipient: getAddress(recipient), refundAddress: getAddress(refund),\n amountLD: amount.toString(), minAmountLD: received.toString(), nativeFee: nativeFee.toString(),\n },\n };\n } catch (err) {\n return refuse(rpcSafeReason(err, src.name));\n }\n },\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n const parsed = parseIntent(quote.intentId);\n if (!tx || !parsed) throw new Error(\"swap2: USDT0 quote has no transaction request\");\n return {\n chain: parsed.src.caip2,\n to: tx.to ?? \"\",\n value: tx.value ?? \"0\",\n ...(tx.data ? {data: tx.data} : {}),\n ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}),\n ...(tx.gasLimit ? {gasLimit: tx.gasLimit} : {}),\n ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {}),\n };\n },\n\n /**\n * Right before signing: the target is the source OFT, the peer is still the\n * destination OFT, and the CURRENT LayerZero fee still fits the sealed\n * `msg.value` (quote + headroom) — the endpoint reverts a send that\n * underpays, so a fee past the headroom means re-quote rather than a\n * wasted broadcast.\n */\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n const parsed = parseIntent(quote.intentId);\n if (!parsed) throw new Error(\"usdt0: malformed intent id\");\n const {src, dst} = parsed;\n if (!same(tx.to, src.oft)) throw new Error(`usdt0: deposit target ${tx.to} is not the ${src.name} OFT`);\n const pd = quote.providerData ?? {};\n if (!/^\\d+$/.test(pd.amountLD ?? \"\") || !/^\\d+$/.test(pd.minAmountLD ?? \"\") || !/^\\d+$/.test(pd.nativeFee ?? \"\") || !isAddress(pd.recipient ?? \"\")) {\n throw new Error(\"usdt0: quote carries no sealed send parameters\");\n }\n const c = client(src.caip2);\n if (!c) throw new Error(`usdt0: no RPC for ${src.caip2}`);\n const sp = sendParam(dst.eid, pd.recipient!, BigInt(pd.amountLD!), BigInt(pd.minAmountLD!));\n let fee: {nativeFee: bigint};\n try {\n await Promise.all([verifyChain(src), verifyPeer(src, dst)]);\n fee = await c.readContract({address: getAddress(src.oft), abi: OFT_ABI, functionName: \"quoteSend\", args: [sp, false]});\n } catch (err) {\n throw new Error(rpcSafeReason(err, src.name));\n }\n const sealed = BigInt(pd.nativeFee!);\n if (fee.nativeFee > sealed) throw new Error(`usdt0: LayerZero fee rose to ${fee.nativeFee} above the sealed ${sealed} (quote + ${FEE_HEADROOM_BPS / 100n} % headroom) — re-quote`);\n if (BigInt(tx.value) !== sealed) throw new Error(`usdt0: transaction value ${tx.value} is not the quoted fee ${sealed}`);\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n const parsed = parseIntent(ref.intentId);\n if (!parsed) return {state: \"failed\"};\n const {src, dst} = parsed;\n if (!ref.sourceTxHash) return {state: \"pending\"};\n try {\n const m = await scanMessage(src, dst, ref.sourceTxHash);\n if (m === null) return {state: \"pending\", depositReceived: false};\n if (m === \"foreign\") return {state: \"failed\"}; // the hash carries a LayerZero message, but not ours\n const name = (m.status?.name ?? \"\").toUpperCase();\n const destHash = m.destination?.tx?.txHash;\n if (name === \"DELIVERED\") return {state: \"completed\", depositReceived: true, ...(destHash ? {destTxHash: destHash} : ref.destTxHash ? {destTxHash: ref.destTxHash} : {})};\n if (name === \"PAYLOAD_STORED\") return {state: \"action-required\", depositReceived: true, claim: {chain: dst.caip2, ready: true}};\n if ([\"FAILED\", \"APPLICATION_BURNED\", \"APPLICATION_SKIPPED\", \"UNRESOLVABLE_COMMAND\", \"MALFORMED_COMMAND\"].includes(name)) return {state: \"failed\", depositReceived: true};\n // INFLIGHT, CONFIRMING, BLOCKED (an earlier nonce on the pathway is stuck — LayerZero clears it), or anything new.\n return {state: \"pending\", depositReceived: true};\n } catch {\n return {state: \"pending\"};\n }\n },\n\n /**\n * A delivery that reverted on the destination (PAYLOAD_STORED — out of\n * executor gas, paused token) is retried by anyone through the endpoint:\n * `lzReceive(origin, receiver, guid, message, extraData)` with the exact\n * packet LayerZero Scan recorded. Null while nothing is stored.\n */\n async buildClaim(ref: IntentRef): Promise<UnsignedTx | null> {\n const parsed = parseIntent(ref.intentId);\n if (!parsed || !ref.sourceTxHash) return null;\n const {src, dst} = parsed;\n const m = await scanMessage(src, dst, ref.sourceTxHash);\n if (!m || m === \"foreign\" || (m.status?.name ?? \"\").toUpperCase() !== \"PAYLOAD_STORED\") return null;\n const nonce = m.pathway?.nonce;\n const guid = m.guid;\n const message = m.source?.tx?.payload;\n if (!Number.isInteger(nonce) || !isHexData(guid) || guid.length !== 66 || !isHexData(message) || message.length <= 2) {\n throw new Error(\"usdt0: LayerZero Scan has no complete packet for the stored payload\");\n }\n if (!same(m.pathway?.receiver?.address, dst.oft)) throw new Error(\"usdt0: stored payload is addressed to another receiver\");\n const valueRaw = m.source?.tx?.options?.lzReceive?.value ?? \"0\";\n const value = /^\\d+$/.test(valueRaw) ? valueRaw : \"0\";\n return {\n chain: dst.caip2,\n to: dst.endpoint,\n value,\n data: encodeFunctionData({\n abi: ENDPOINT_ABI,\n functionName: \"lzReceive\",\n args: [{srcEid: src.eid, sender: pad(getAddress(src.oft), {size: 32}), nonce: BigInt(nonce as number)}, getAddress(dst.oft), guid, message, \"0x\"],\n }),\n chainId: dst.chainId,\n gasLimit: GAS_CLAIM,\n };\n },\n };\n}\n\n/** Exported for tests and diagnostics: the LayerZero Scan status → swap2 state mapping. */\nexport const USDT0_STATUS_MAP: Readonly<Record<string, IntentState>> = Object.freeze({\n INFLIGHT: \"pending\", CONFIRMING: \"pending\", BLOCKED: \"pending\",\n DELIVERED: \"completed\", PAYLOAD_STORED: \"action-required\",\n FAILED: \"failed\", APPLICATION_BURNED: \"failed\", APPLICATION_SKIPPED: \"failed\", UNRESOLVABLE_COMMAND: \"failed\", MALFORMED_COMMAND: \"failed\",\n});\n\nexport {ZERO_B32 as USDT0_ZERO_PEER};\n","/**\n * Activity recognition for USDT0 on every chain in `config.ts`:\n * - `send(...)` on the chain's OFT is our source leg (\"Bridged USDT0\", or\n * \"Bridged USDT\" on Ethereum where the adapter locks plain USDT);\n * - the inbound leg is the executor's delivery — the user signs nothing, so\n * it is recognized by its effect: the chain's USDT0 minted to the owner\n * (from the zero address), or USDT released by the Ethereum adapter to the\n * owner, inside a transaction that did NOT call the token itself (a plain\n * transfer is not a bridge);\n * - `lzReceive` on the LayerZero endpoint is the owner's own retry of a\n * stored payload (`claimSwap2`).\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {calledContract, chainLabel, describeSwapLike, matchesCall} from \"@anywalletkit/protocol-swap2-core/activity\";\nimport {decodeFunctionData, parseAbi, type Hex} from \"viem\";\nimport {USDT0_BY_EID, USDT0_CHAINS, type Usdt0Chain} from \"./config.js\";\n\nconst SEND_ABI = parseAbi([\n \"struct SendParam { uint32 dstEid; bytes32 to; uint256 amountLD; uint256 minAmountLD; bytes extraOptions; bytes composeMsg; bytes oftCmd; }\",\n \"struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; }\",\n \"function send(SendParam sp, MessagingFee fee, address refundAddress)\",\n]);\n\nexport const USDT0_MODULE = \"@anywalletkit/protocol-swap2-usdt0\";\n\n/** send((uint32,bytes32,uint256,uint256,bytes,bytes,bytes),(uint256,uint256),address) — IOFT */\nexport const USDT0_SEND = \"0xc7c7f5b3\";\n/** lzReceive((uint32,bytes32,uint64),address,bytes32,bytes,bytes) — EndpointV2 */\nexport const LZ_RECEIVE = \"0x0c0c389e\";\n\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\n\n/** The symbol the catalog uses on each deployment: USDT where the OFT wraps Tether's USDT, USDT0 elsewhere. */\nfunction symbolFor(chain: Usdt0Chain): string {\n return chain.adapter || [42161, 10, 137].includes(chain.chainId) ? \"USDT\" : \"USDT0\";\n}\n\n/** `send(SendParam, …)` → the destination deployment (dstEid is the first word of the tuple), null when the calldata is absent or foreign. */\nfunction sendDestination(tx: ChainTx): Usdt0Chain | null {\n const data = tx.call?.data;\n if (!data || data.length < 10 + 64 * 2) return null;\n try {\n const [sp] = decodeFunctionData({abi: SEND_ABI, data: data as Hex}).args as unknown as [{dstEid: number}];\n return USDT0_BY_EID[sp.dstEid] ?? null;\n } catch {\n return null;\n }\n}\nconst lc = (a: string) => a.toLowerCase();\n\nexport function describeUsdt0Activity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n const chain = USDT0_CHAINS[tx.chain];\n if (!chain) return null;\n const subtitle = `USDT0 · ${chainLabel(tx.chain)}`;\n if (matchesCall(tx, [chain.oft], [USDT0_SEND])) {\n // The native value is the LayerZero messaging fee (plus the headroom the\n // endpoint refunds), not an asset the owner swapped away: it rides in `fee`\n // next to the gas, and the title names both ends when the calldata says\n // where the tokens go.\n const dst = sendDestination(tx);\n const item = describeSwapLike(tx, ctx, {protocol: USDT0_MODULE, subtitle, kind: \"bridge\", outVerb: \"Bridged\"});\n if (!item) return null;\n const native = item.assetsOut.filter((a) => a.token === null).reduce((sum, a) => sum + a.amount, 0n);\n item.assetsOut = item.assetsOut.filter((a) => a.token !== null);\n if (native > 0n) item.fee = (item.fee ?? 0n) + native;\n const srcSym = item.assetsOut[0]?.symbol ?? symbolFor(chain);\n if (dst) {\n item.title = `Bridged ${srcSym} → ${symbolFor(dst)}`;\n item.subtitle = `USDT0 · ${chainLabel(tx.chain)} → ${dst.name}`;\n } else item.title = `Bridged ${srcSym}`;\n return item;\n }\n if (matchesCall(tx, [chain.endpoint], [LZ_RECEIVE])) {\n return describeSwapLike(tx, ctx, {protocol: USDT0_MODULE, subtitle, kind: \"bridge\", inSuffix: \"via LayerZero\"});\n }\n // Delivery by the LayerZero executor: the token moves out of nowhere (mint)\n // or out of the adapter into the owner, and the call target is not the token.\n const called = calledContract(tx);\n if (called && called === lc(chain.token)) return null;\n const own = new Set([...ctx.own].map(lc));\n const origin = chain.adapter ? lc(chain.oft) : ZERO;\n const delivered = tx.transfers.some((t) => t.token !== null && lc(t.token) === lc(chain.token) && lc(t.from) === origin && own.has(lc(t.to)));\n if (!delivered || own.has(lc(tx.from))) return null;\n return describeSwapLike(tx, ctx, {protocol: USDT0_MODULE, subtitle, kind: \"bridge\", inSuffix: \"via LayerZero\", counterparty: chain.oft});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAkC;;;ACclC,kBAA4B;AAuB5B,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AAEtB,IAAM,IAAI,CAAC,SAAiB,KAAa,MAAc,OAAe,KAAa,UAAkB,UAAU,WAAuB;AAAA,EACpI,OAAO,UAAU,OAAO;AAAA,EAAI;AAAA,EAAS;AAAA,EAAK;AAAA,EAAM;AAAA,EAAO;AAAA,EAAK;AAAA,EAAU;AACxE;AAG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;AAAA,QACA,UAAM,iCAAmB;AAAA,UACvB,KAAK;AAAA,UACL,cAAc;AAAA,UACd,MAAM,CAAC,EAAC,QAAQ,IAAI,KAAK,YAAQ,sBAAI,yBAAW,IAAI,GAAG,GAAG,EAAC,MAAM,GAAE,CAAC,GAAG,OAAO,OAAO,KAAe,EAAC,OAAG,yBAAW,IAAI,GAAG,GAAG,MAAM,SAAS,IAAI;AAAA,QAClJ,CAAC;AAAA,QACD,SAAS,IAAI;AAAA,QACb,UAAU;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF;AAGO,IAAM,mBAA0D,OAAO,OAAO;AAAA,EACnF,UAAU;AAAA,EAAW,YAAY;AAAA,EAAW,SAAS;AAAA,EACrD,WAAW;AAAA,EAAa,gBAAgB;AAAA,EACxC,QAAQ;AAAA,EAAU,oBAAoB;AAAA,EAAU,qBAAqB;AAAA,EAAU,sBAAsB;AAAA,EAAU,mBAAmB;AACpI,CAAC;;;AFzYM,IAAM,qBAAN,cAAiC,kCAAoB;AAAA,EACvC;AAAA,EACnB,YAAY,SAAmC,QAA0B;AACvE,UAAM,SAAS,MAAM;AACrB,SAAK,WAAW,cAAc,MAAM;AAAA,EACtC;AAAA,EACmB,eAAe,OAAwB;AACxD,WAAO,MAAS,cAAc,KAAK;AAAA,EACrC;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,MAAS,SAAS,WAAW,OAAO;AAAA,EAC7C;AACF;","names":["c","import_viem","import_util","c"]}
1
+ {"version":3,"sources":["../src/protocol.ts","../src/config.ts","../src/provider.ts","../src/activity.ts"],"sourcesContent":["import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {usdt0 as usdt0Cfg} from \"./config.js\";\nimport {usdt0Provider, type Usdt0ProviderConfig} from \"./provider.js\";\n\nexport interface Usdt0Swap2Config extends Swap2EngineConfig, Usdt0ProviderConfig {}\n\n/** Standalone USDT0 swap2: USDT / USDT0 between the LayerZero OFT deployments in one source transaction. */\nexport class Usdt0Swap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n constructor(account: Swap2Account | undefined, config: Usdt0Swap2Config) {\n super(account, config);\n this.provider = usdt0Provider(config);\n }\n protected override chainSupported(caip2: string): boolean {\n return usdt0Cfg.supportsChain(caip2);\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return usdt0Cfg.supports(fromChain, toChain);\n }\n}\n","// USDT0 — Tether's LayerZero OFT for USDT. Source: docs.usdt0.to\n// (technical-documentation/deployments, read 2026-10-20) — every row below was\n// then re-read on-chain over public RPCs the same day: the OFT's `token()` is\n// the listed token, `endpoint()` is the listed endpoint (and reports the\n// listed eid), `approvalRequired()` is true only for the Ethereum adapter,\n// `sharedDecimals()` = 6 everywhere, and `peers(eid)` are wired between the\n// chains. `oftVersion()` = (0x02e49c2c, 1) on all of them.\n//\n// Only chains the SDK ships (swap2-assets / wallet-evm) are listed. USDT0 is\n// also deployed on Conflux eSpace (1030, eid 30212), Flare (14, 30295),\n// Hedera (295, 30316), Mantle (5000, 30181), Morph (2818, 30322), Rootstock\n// (30, 30333), Stable (988, 30396), Tempo (4217, 30410), plus HyperCore, IOTA\n// and Stellar (non-EVM) — not wallet chains here, so not routable here.\nimport {decodeFunctionData, getAddress, isAddress, pad, parseAbi, type Hex} from \"viem\";\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {evmRef, isEvm} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {ccAsset} from \"@anywalletkit/swap2-assets\";\n\nexport interface Usdt0Chain {\n caip2: string;\n chainId: number;\n /** LayerZero V2 endpoint id. */\n eid: number;\n name: string;\n /** The ERC-20 the user holds: USDT on Ethereum, USDT0 elsewhere (6 decimals everywhere). */\n token: string;\n /**\n * The OFT contract `quoteSend` / `send` are called on. On Ethereum it is the\n * OFT *adapter* that locks USDT (`approvalRequired()` = true, approve the\n * token to it); elsewhere it is the OUpgradeable OFT that burns the caller's\n * USDT0 through the token's mint/burn role — no approval.\n */\n oft: string;\n /** LayerZero V2 EndpointV2 on that chain (`lzReceive` retries of a stored payload go here). */\n endpoint: string;\n /** True on Ethereum: the OFT is a lockbox adapter in front of plain USDT. */\n adapter: boolean;\n}\n\nconst LZ_ENDPOINT_A = \"0x1a44076050125825900e736c501f859c50fE728c\";\nconst LZ_ENDPOINT_B = \"0x6F475642a6e85809B1c36Fa62763669b1b48DD5B\";\n\nconst c = (chainId: number, eid: number, name: string, token: string, oft: string, endpoint: string, adapter = false): Usdt0Chain => ({\n caip2: `eip155:${chainId}`, chainId, eid, name, token, oft, endpoint, adapter,\n});\n\n/** CAIP-2 → USDT0 deployment. */\nexport const USDT0_CHAINS: Readonly<Record<string, Usdt0Chain>> = Object.freeze(Object.fromEntries([\n c(1, 30101, \"Ethereum\", \"0xdAC17F958D2ee523a2206206994597C13D831ec7\", \"0x6C96dE32CEa08842dcc4058c14d3aaAD7Fa41dee\", LZ_ENDPOINT_A, true),\n c(42161, 30110, \"Arbitrum\", \"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9\", \"0x14E4A1B13bf7F943c8ff7C51fb60FA964A298D92\", LZ_ENDPOINT_A),\n c(10, 30111, \"OP Mainnet\", \"0x01bFF41798a0BcF287b996046Ca68b395DbC1071\", \"0xF03b4d9AC1D5d1E7c4cEf54C2A313b9fe051A0aD\", LZ_ENDPOINT_A),\n c(137, 30109, \"Polygon PoS\", \"0xc2132D05D31c914a87C6611C10748AEb04B58e8F\", \"0x6BA10300f0DC58B7a1e4c0e41f5daBb7D7829e13\", LZ_ENDPOINT_A),\n c(999, 30367, \"HyperEVM\", \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\", \"0x904861a24F30EC96ea7CFC3bE9EA4B476d237e98\", \"0x3A73033C0b1407574C76BdBAc67f126f6b4a9AA9\"),\n c(57073, 30339, \"Ink\", \"0x0200C29006150606B650577BBE7B6248F58470c1\", \"0x1cB6De532588fCA4a21B7209DE7C456AF8434A65\", \"0xca29f3A6f966Cb2fc0dE625F8f325c0C46dbE958\"),\n c(80094, 30362, \"Berachain\", \"0x779Ded0c9e1022225f8E0630b35a9b54bE713736\", \"0x3Dc96399109df5ceb2C226664A086140bD0379cB\", LZ_ENDPOINT_B),\n c(130, 30320, \"Unichain\", \"0x9151434b16b9763660705744891fA906F660EcC5\", \"0xc07bE8994D035631c36fb4a89C918CeFB2f03EC3\", LZ_ENDPOINT_B),\n c(1329, 30280, \"Sei\", \"0x9151434b16b9763660705744891fA906F660EcC5\", \"0x56Fe74A2e3b484b921c447357203431a3485CC60\", LZ_ENDPOINT_A),\n c(9745, 30383, \"Plasma\", \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\", \"0x02ca37966753bDdDf11216B73B16C1dE756A7CF9\", LZ_ENDPOINT_B),\n c(143, 30390, \"Monad\", \"0xe7cd86e13AC4309349F30B3435a9d337750fC82D\", \"0x9151434b16b9763660705744891fA906F660EcC5\", LZ_ENDPOINT_B),\n c(4326, 30398, \"MegaETH\", \"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb\", \"0x9151434b16b9763660705744891fA906F660EcC5\", LZ_ENDPOINT_B),\n c(196, 30274, \"X Layer\", \"0x779Ded0c9e1022225f8E0630b35a9b54bE713736\", \"0x94bcCa6BdfD6a61817aB0E960BfedE4984505554\", LZ_ENDPOINT_A),\n // 2026-10-20 (evm-chains-6 batch): docs.usdt0.to deployments, re-read on-chain (token(), approvalRequired() = false,\n // sharedDecimals() = 6, endpoint(), peers(30110) = the Arbitrum OFT).\n c(5000, 30181, \"Mantle\", \"0x779Ded0c9e1022225f8E0630b35a9b54bE713736\", \"0xcb768e263FB1C62214E7cab4AA8d036D76dc59CC\", LZ_ENDPOINT_A),\n c(2818, 30322, \"Morph\", \"0xe7cd86e13AC4309349F30B3435a9d337750fC82D\", \"0xcb768e263FB1C62214E7cab4AA8d036D76dc59CC\", LZ_ENDPOINT_B),\n c(14, 30295, \"Flare\", \"0xe7cd86e13AC4309349F30B3435a9d337750fC82D\", \"0x567287d2A9829215a37e3B88843d32f9221E7588\", LZ_ENDPOINT_A),\n].map((x) => [x.caip2, x])));\n\n/** LayerZero eid → deployment. */\nexport const USDT0_BY_EID: Readonly<Record<number, Usdt0Chain>> = Object.freeze(\n Object.fromEntries(Object.values(USDT0_CHAINS).map((x) => [x.eid, x])),\n);\n\n/** LayerZero Scan — message status by source transaction hash. */\nexport const LZ_SCAN_API = \"https://scan.layerzero-api.com\";\n\n/** Token symbols the catalog uses for the same asset across chains. */\nexport const USDT0_SYMBOLS: readonly string[] = Object.freeze([\"USDT0\", \"USDT\", \"USD₮0\", \"USD₮\"]);\n\nexport const usdt0 = {\n supportsChain(chain: string): boolean {\n return isEvm(chain) && !!USDT0_CHAINS[`eip155:${evmRef(chain)}`];\n },\n supports(from: string, to: string): boolean {\n return from !== to && this.supportsChain(from) && this.supportsChain(to);\n },\n};\n\nconst OFT_SEND_ABI = parseAbi([\n \"struct SendParam { uint32 dstEid; bytes32 to; uint256 amountLD; uint256 minAmountLD; bytes extraOptions; bytes composeMsg; bytes oftCmd; }\",\n \"struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; }\",\n \"function send(SendParam s, MessagingFee fee, address refundAddress) payable\",\n]);\n\n/**\n * Does `symbolOrAddress` name this deployment's token on `chain`? The contract itself, or a USDT / USDT0 symbol the\n * catalog does not bind to another contract (OP's legacy bridged USDT is not the OFT token). The provider and\n * {@link usdt0VerifyQuote} both check the request with it.\n */\nexport function tokenMatches(chain: Usdt0Chain, symbolOrAddress: string): boolean {\n const same = (a: string | undefined | null, b: string) => !!a && a.toLowerCase() === b.toLowerCase();\n if (symbolOrAddress.startsWith(\"0x\")) return same(symbolOrAddress, chain.token);\n if (!USDT0_SYMBOLS.includes(symbolOrAddress.toUpperCase().replace(\"USD₮\", \"USDT\"))) return false;\n const known = ccAsset(chain.caip2, symbolOrAddress);\n return !known || same(known.contract ?? \"\", chain.token);\n}\n\n/**\n * A remote USDT0 quote's `send`, decoded on the device against the app's own request (scan 2026-10-30, F3): exactly\n * `send(SendParam, MessagingFee, refund)` on the source OFT; the destination chain's eid; the recipient as `to`; the\n * input as `amountLD`; a `minAmountLD` no larger than the input that guarantees the quoted minimum and the caller's\n * floor; empty `extraOptions`, `composeMsg` and `oftCmd` (what the provider sends); no LZ-token fee; the trader as\n * refund; `msg.value` = the declared native fee = the call's `nativeFee`; the adapter as spender on Ethereum only.\n * The reason it fails, or null. The engine's native-fee ceiling bounds the fee itself.\n */\nexport function usdt0VerifyQuote(params: QuoteParams, quote: Quote): string | null {\n const src = usdt0ChainFor(params.sourceChain);\n const dst = usdt0ChainFor(params.destChain);\n if (!src || !dst || src === dst) return \"not a USDT0 route between two deployments\";\n // The OFT burns or locks its own token whatever the request named, so both sides are bound here (reaudit 2026-10-30, #1).\n if (!tokenMatches(src, params.sourceToken)) return `source token ${params.sourceToken} is not USDT0 (${src.token}) on ${src.name}`;\n if (!tokenMatches(dst, params.destToken)) return `destination token ${params.destToken} is not USDT0 (${dst.token}) on ${dst.name}`;\n const tx = quote.txRequest;\n if (!tx?.data || !tx.to || tx.serializedTx !== undefined) return \"the quote carries no OFT call\";\n if (tx.to.toLowerCase() !== src.oft.toLowerCase()) return `the call targets ${tx.to}, not the ${src.name} OFT`;\n if (tx.chainId !== undefined && tx.chainId !== src.chainId) return `the call is for chain ${tx.chainId}, not ${src.chainId}`;\n if (src.adapter ? !tx.approvalAddress || tx.approvalAddress.toLowerCase() !== src.oft.toLowerCase() : tx.approvalAddress !== undefined) {\n return src.adapter ? \"the Ethereum send approves another spender than the adapter\" : \"an OFT send needs no approval\";\n }\n let sp: {dstEid: number; to: Hex; amountLD: bigint; minAmountLD: bigint; extraOptions: Hex; composeMsg: Hex; oftCmd: Hex};\n let fee: {nativeFee: bigint; lzTokenFee: bigint};\n let refund: string;\n try {\n const d = decodeFunctionData({abi: OFT_SEND_ABI, data: tx.data as Hex});\n [sp, fee, refund] = d.args as unknown as [typeof sp, typeof fee, string];\n } catch {\n return \"the call is not send(SendParam, MessagingFee, refund)\";\n }\n let amountIn: bigint, floor: bigint, value: bigint;\n try {\n amountIn = BigInt(params.amountIn);\n floor = BigInt(quote.minDestAmount);\n if (params.minAmountOut !== undefined && BigInt(params.minAmountOut) > floor) floor = BigInt(params.minAmountOut);\n value = BigInt(tx.value ?? \"0\");\n } catch {\n return \"the request does not name amounts\";\n }\n if (sp.dstEid !== dst.eid) return `the send goes to eid ${sp.dstEid}, not ${dst.name} (${dst.eid})`;\n if (sp.amountLD !== amountIn || BigInt(quote.sourceAmount) !== amountIn) return `the send moves ${sp.amountLD}, not the ${amountIn} input`;\n if (sp.minAmountLD > sp.amountLD || sp.minAmountLD <= 0n || sp.minAmountLD < floor) return `the send's minAmountLD ${sp.minAmountLD} is below the ${floor} minimum`;\n if (sp.extraOptions !== \"0x\" || sp.composeMsg !== \"0x\" || sp.oftCmd !== \"0x\") return \"the send carries options, a compose message or an OFT command\";\n // A dry quote without addresses prices the provider's placeholders; it is never built (the engine re-quotes live).\n const live = params.dry === false;\n if (params.destAddress || live) {\n if (!isAddress(params.destAddress)) return \"the recipient is not an EVM address\";\n if (sp.to.toLowerCase() !== pad(getAddress(params.destAddress), {size: 32}).toLowerCase()) return `the send delivers to ${sp.to}, not the recipient`;\n }\n if (params.refundAddress || live) {\n if (!isAddress(params.refundAddress ?? \"\")) return \"the refund address is not an EVM address\";\n if (getAddress(refund) !== getAddress(params.refundAddress!)) return `the send refunds ${refund}, not the trader`;\n }\n if (fee.lzTokenFee !== 0n) return \"the send pays an LZ-token fee\";\n if (value !== fee.nativeFee || (tx.nativeFee ?? \"0\") !== fee.nativeFee.toString()) return \"msg.value is not the declared native fee of the send\";\n if (quote.intentId.replace(/~[0-9a-f]{32}$/, \"\") !== `usdt0:${src.eid}:${dst.eid}`) return \"the intent id does not name this send\";\n return null;\n}\n\n/**\n * The contracts a USDT0 claim may call on `chain`: its LayerZero EndpointV2 (`lzReceive`, retrying a stored\n * payload). Empty for a chain USDT0 is not listed on.\n */\nexport function usdt0ClaimTargets(chain: string): readonly string[] {\n const c = usdt0ChainFor(chain);\n return c ? [c.endpoint] : [];\n}\n\n/**\n * The USDT0 OFT a send calls on a chain, the adapter it approves where one locks USDT (Ethereum), the endpoint\n * a stored-payload claim calls, and {@link usdt0VerifyQuote} — the app's pins for\n * `remoteProvider({name: \"usdt0\", baseUrl, ...usdt0Pins})` (scan 2026-10-27 modules, F8/F16; the send's\n * arguments since scan 2026-10-30, F3).\n */\nexport const usdt0Pins: RemotePins & {claimTargets(chain: string): readonly string[]} = Object.freeze({\n callTargets: (chain: string): readonly string[] => { const c = usdt0ChainFor(chain); return c ? [c.oft] : []; },\n spenders: (chain: string): readonly string[] => { const c = usdt0ChainFor(chain); return c?.adapter ? [c.oft] : []; },\n claimTargets: usdt0ClaimTargets,\n verifyQuote: usdt0VerifyQuote,\n});\nfunction usdt0ChainFor(chain: string): Usdt0Chain | undefined {\n return Object.prototype.hasOwnProperty.call(USDT0_CHAINS, chain) ? USDT0_CHAINS[chain] : undefined;\n}\n","import {createPublicClient, encodeFunctionData, fallback, getAddress, http, isAddress, pad, parseAbi, type Hex} from \"viem\";\nimport {describeUsdt0Activity} from \"./activity.js\";\nimport {ccAsset} from \"@anywalletkit/swap2-assets\";\nimport {redactUrls, timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentState, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {LZ_SCAN_API, USDT0_BY_EID, USDT0_CHAINS, tokenMatches, usdt0ClaimTargets, usdt0 as usdt0Cfg, type Usdt0Chain} from \"./config.js\";\n\n/**\n * USDT0 — Tether's USDT as a LayerZero OFT. ONE source transaction:\n * `send(SendParam, MessagingFee, refund)` on the chain's OFT with the\n * LayerZero messaging fee as `msg.value`; LayerZero's DVNs verify and the\n * executor delivers on the destination (mint of USDT0, or unlock of USDT out\n * of the Ethereum adapter). No second user transaction in the normal case.\n *\n * - Quote = two `eth_call`s on the source OFT: `quoteOFT` for the limits,\n * protocol fees and the amount that really arrives after dust removal\n * (shared decimals = 6, so none today), then `quoteSend` for the native\n * fee with `minAmountLD` pinned to that received amount — the contract\n * reverts rather than deliver less. Both are sealed into the quote.\n * - `enforcedOptions` on every deployment already carry the executor gas\n * (type-3 options, lzReceive gas 80 000, read on-chain 2026-10-20), so\n * `extraOptions` stays empty; LayerZero Scan confirms deliveries ran on it.\n * - Ethereum locks USDT in an adapter (`approvalRequired()` = true →\n * `approvalAddress`); every other chain's OFT burns the caller's USDT0\n * itself (`approvalRequired()` = false → no approval at all).\n * - Every address in `config.ts` is re-read on-chain before the first quote\n * on a chain (`token()`, `approvalRequired()`) and per pair (`peers(dstEid)`\n * must be the destination OFT) — a mismatch refuses the route.\n * - Status: LayerZero Scan by source hash. DELIVERED carries the destination\n * hash; PAYLOAD_STORED (delivery reverted on the destination, funds safe)\n * becomes \"action-required\" with a `buildClaim` that retries\n * `EndpointV2.lzReceive` — anyone may call it, so the user can.\n */\n\nconst OFT_ABI = parseAbi([\n \"struct SendParam { uint32 dstEid; bytes32 to; uint256 amountLD; uint256 minAmountLD; bytes extraOptions; bytes composeMsg; bytes oftCmd; }\",\n \"struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; }\",\n \"struct OFTLimit { uint256 minAmountLD; uint256 maxAmountLD; }\",\n \"struct OFTFeeDetail { int256 feeAmountLD; string description; }\",\n \"struct OFTReceipt { uint256 amountSentLD; uint256 amountReceivedLD; }\",\n \"struct MessagingReceipt { bytes32 guid; uint64 nonce; MessagingFee fee; }\",\n \"function quoteSend(SendParam s, bool payInLzToken) view returns (MessagingFee)\",\n \"function quoteOFT(SendParam s) view returns (OFTLimit, OFTFeeDetail[], OFTReceipt)\",\n \"function send(SendParam s, MessagingFee fee, address refundAddress) payable returns (MessagingReceipt, OFTReceipt)\",\n \"function token() view returns (address)\",\n \"function approvalRequired() view returns (bool)\",\n \"function peers(uint32 eid) view returns (bytes32)\",\n]);\nconst ENDPOINT_ABI = parseAbi([\n \"struct Origin { uint32 srcEid; bytes32 sender; uint64 nonce; }\",\n \"function lzReceive(Origin origin, address receiver, bytes32 guid, bytes message, bytes extraData) payable\",\n]);\n\nconst EVM_PLACEHOLDER = \"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045\";\nconst DEFAULT_QUOTE_TTL_MS = 60_000;\nconst RPC_TIMEOUT_MS = 12_000;\nconst SCAN_TIMEOUT_MS = 12_000;\n/** A direct `send` used ~330k gas on Arbitrum and on the Ethereum adapter (2026-10-20 receipts). */\nconst GAS_SEND = \"450000\";\n/**\n * The LayerZero fee is quoted at quote time but paid at send time, and it moves\n * with source and destination gas (live: +1.7 % within a minute on Ethereum).\n * The sealed `msg.value` carries this headroom; EndpointV2 charges the current\n * fee and refunds the surplus to `refundAddress` (the trader) in the same\n * transaction, so the headroom costs nothing — it only avoids a re-quote.\n */\nconst FEE_HEADROOM_BPS = 2_500n;\n/** `lzReceive` retry of a stored payload: a mint plus the endpoint bookkeeping. */\nconst GAS_CLAIM = \"300000\";\nconst ZERO_B32 = `0x${\"00\".repeat(32)}` as Hex;\n\nexport interface Usdt0ProviderConfig {\n enabled?: boolean;\n /**\n * JSON-RPC URL(s) per CAIP-2 chain. REQUIRED for every chain the provider\n * should quote from: the fee and the received amount come from the OFT\n * itself. The destination RPC is optional (used for the stored-payload retry).\n */\n rpcUrls?: Readonly<Record<string, string | readonly string[]>>;\n /** LayerZero Scan base (default https://scan.layerzero-api.com). */\n scanUrl?: string;\n /** Local lifetime of a quote (default 60 s; the sealed fee is re-checked at preflight). */\n quoteTtlMs?: number;\n /** Injectable for tests (also used by the RPC transport). */\n fetchImpl?: typeof fetch;\n}\n\ninterface ScanMessage {\n pathway?: {srcEid?: number; dstEid?: number; sender?: {address?: string}; receiver?: {address?: string}; nonce?: number};\n source?: {status?: string; tx?: {txHash?: string; payload?: string; options?: {lzReceive?: {gas?: string; value?: string}}}};\n destination?: {status?: string; tx?: {txHash?: string}};\n guid?: string;\n status?: {name?: string; message?: string};\n}\n\nconst same = (a: string | undefined | null, b: string) => !!a && a.toLowerCase() === b.toLowerCase();\nconst isHexData = (v: unknown): v is Hex => typeof v === \"string\" && /^0x(?:[0-9a-fA-F]{2})*$/.test(v);\n\n\n/**\n * A refusal / preflight error that may reach a client: an RPC transport failure\n * becomes a fixed reason (viem's HTTP / timeout errors carry `URL: …`, and a keyed\n * endpoint's key sits in that path — scan 2026-10-23 F8); anything else loses its URLs.\n */\nfunction rpcSafeReason(err: unknown, chainName: string): string {\n const e = err as {name?: string; shortMessage?: string; message?: string} | undefined;\n const text = `${e?.shortMessage ?? \"\"}\\n${e?.message ?? String(err)}`;\n if (/HttpRequestError|TimeoutError|RpcRequestError|WebSocketRequestError/.test(String(e?.name)) || /\\bURL: |HTTP request failed|request timed out|took too long to respond/i.test(text)) {\n return `usdt0: RPC for ${chainName} unavailable — try again`;\n }\n return redactUrls(err instanceof Error ? err.message : String(err));\n}\n\nexport function usdt0Provider(config: Usdt0ProviderConfig = {}): CrossChainProvider {\n config = Object.freeze({...config});\n const scan = (config.scanUrl ?? LZ_SCAN_API).replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(scan)) throw new Error(\"usdt0: scanUrl must use http or https\");\n const quoteTtlMs = config.quoteTtlMs ?? DEFAULT_QUOTE_TTL_MS;\n if (!Number.isInteger(quoteTtlMs) || quoteTtlMs <= 0 || quoteTtlMs > 300_000) throw new Error(\"usdt0: quoteTtlMs must be an integer between 1 and 300000\");\n const rpcUrls = Object.freeze({...(config.rpcUrls ?? {})});\n const doFetch: typeof fetch = (input, init) => (config.fetchImpl ?? fetch)(input, init);\n\n const client = (caip2: string) => {\n const raw = rpcUrls[caip2];\n const urls = typeof raw === \"string\" ? [raw] : [...(raw ?? [])];\n if (urls.length === 0) return null;\n const opts = {timeout: RPC_TIMEOUT_MS, ...(config.fetchImpl ? {fetchFn: config.fetchImpl} : {})} as never;\n return createPublicClient({transport: urls.length === 1 ? http(urls[0], opts) : fallback(urls.map((u) => http(u, opts))), ccipRead: false});\n };\n\n /** Once per chain: the OFT really is the OFT of the listed token with the listed approval mode. */\n const verified = new Map<string, Promise<void>>();\n function verifyChain(chain: Usdt0Chain): Promise<void> {\n let p = verified.get(chain.caip2);\n if (!p) {\n p = (async () => {\n const c = client(chain.caip2);\n if (!c) throw new Error(`usdt0: no RPC for ${chain.caip2}`);\n const [token, approval] = await Promise.all([\n c.readContract({address: getAddress(chain.oft), abi: OFT_ABI, functionName: \"token\"}),\n c.readContract({address: getAddress(chain.oft), abi: OFT_ABI, functionName: \"approvalRequired\"}),\n ]);\n if (!same(token, chain.token)) throw new Error(`usdt0: OFT ${chain.oft} on ${chain.name} reports token ${token}, expected ${chain.token}`);\n if (approval !== chain.adapter) throw new Error(`usdt0: OFT ${chain.oft} on ${chain.name} reports approvalRequired=${String(approval)}, expected ${String(chain.adapter)}`);\n })();\n p.catch(() => verified.delete(chain.caip2));\n verified.set(chain.caip2, p);\n }\n return p;\n }\n\n /** Once per pair: the source OFT's peer for the destination eid is the destination OFT. */\n const peers = new Map<string, Promise<void>>();\n function verifyPeer(src: Usdt0Chain, dst: Usdt0Chain): Promise<void> {\n const key = `${src.eid}>${dst.eid}`;\n let p = peers.get(key);\n if (!p) {\n p = (async () => {\n const c = client(src.caip2);\n if (!c) throw new Error(`usdt0: no RPC for ${src.caip2}`);\n const peer = await c.readContract({address: getAddress(src.oft), abi: OFT_ABI, functionName: \"peers\", args: [dst.eid]});\n if (!same(peer, pad(getAddress(dst.oft), {size: 32}))) throw new Error(`usdt0: ${src.name} OFT has no peer for ${dst.name} (eid ${dst.eid}) — route not wired`);\n })();\n p.catch(() => peers.delete(key));\n peers.set(key, p);\n }\n return p;\n }\n\n function parseIntent(intentId: string): {src: Usdt0Chain; dst: Usdt0Chain} | null {\n const [tag, s, d] = intentId.split(\":\");\n if (tag !== \"usdt0\") return null;\n const src = USDT0_BY_EID[Number(s)];\n const dst = USDT0_BY_EID[Number(d)];\n return src && dst && src !== dst ? {src, dst} : null;\n }\n\n const sendParam = (dstEid: number, recipient: string, amountLD: bigint, minAmountLD: bigint) => ({\n dstEid, to: pad(getAddress(recipient), {size: 32}), amountLD, minAmountLD, extraOptions: \"0x\" as Hex, composeMsg: \"0x\" as Hex, oftCmd: \"0x\" as Hex,\n });\n\n /** The LayerZero message of a source transaction on this route, or null while Scan has not indexed it. */\n async function scanMessage(src: Usdt0Chain, dst: Usdt0Chain, sourceTxHash: string): Promise<ScanMessage | null | \"foreign\"> {\n const res = await doFetch(`${scan}/v1/messages/tx/${encodeURIComponent(sourceTxHash)}`, {headers: {accept: \"application/json\"}, signal: timeoutSignal(SCAN_TIMEOUT_MS)});\n if (res.status === 404) return null;\n if (!res.ok) throw new Error(`usdt0: LayerZero Scan → ${res.status}`);\n const body = (await res.json()) as {data?: ScanMessage[]};\n const list = Array.isArray(body?.data) ? body.data : [];\n if (list.length === 0) return null;\n const m = list.find((x) => x.pathway?.srcEid === src.eid && x.pathway?.dstEid === dst.eid && same(x.pathway?.sender?.address, src.oft));\n return m ?? \"foreign\";\n }\n\n return {\n name: \"usdt0\",\n describeActivity: describeUsdt0Activity,\n claimTargets: usdt0ClaimTargets,\n enabled: () => config.enabled ?? true,\n supportsChain: (chain: string) => usdt0Cfg.supportsChain(chain) && client(chain) !== null,\n supportsChainPair: (from: string, to: string) => usdt0Cfg.supports(from, to) && client(from) !== null,\n supportsRoute(from: Asset, to: Asset): boolean {\n const src = USDT0_CHAINS[from.chain];\n const dst = USDT0_CHAINS[to.chain];\n if (!src || !dst || src === dst || client(from.chain) === null) return false;\n return tokenMatches(src, from.token) && tokenMatches(dst, to.token);\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (reason: string) => { params.onRefusal?.(reason); return null; };\n if (params.flex) return refuse(\"the amount is sealed into the calldata (no flexible deposits)\");\n const src = USDT0_CHAINS[params.sourceChain];\n const dst = USDT0_CHAINS[params.destChain];\n if (!src || !dst) return refuse(\"USDT0 is not deployed on this chain\");\n if (src === dst) return refuse(\"same-chain transfers are not a bridge\");\n if (!tokenMatches(src, params.sourceToken)) return refuse(`source token ${params.sourceToken} is not USDT0 (${src.token}) on ${src.name}`);\n if (!tokenMatches(dst, params.destToken)) return refuse(`destination token ${params.destToken} is not USDT0 (${dst.token}) on ${dst.name}`);\n if (!/^\\d+$/.test(params.amountIn)) return refuse(\"amount must be a base-unit integer\");\n const amount = BigInt(params.amountIn);\n if (amount <= 0n) return refuse(\"amount must be positive\");\n // The placeholder prices a dry quote; a live one without addresses would send there (round 3, H8).\n const dry = params.dry !== false;\n const recipient = params.destAddress || (dry ? EVM_PLACEHOLDER : \"\");\n if (!recipient) return refuse(\"a live quote needs a recipient\");\n if (!isAddress(recipient)) return refuse(\"destination must be an EVM address\");\n const refund = params.refundAddress || (dry ? EVM_PLACEHOLDER : \"\");\n if (!refund) return refuse(\"a live quote needs a refund address\");\n if (!isAddress(refund)) return refuse(\"refund address must be an EVM address\");\n const c = client(src.caip2);\n if (!c) return refuse(`no RPC configured for ${src.caip2}`);\n\n try {\n await Promise.all([verifyChain(src), verifyPeer(src, dst)]);\n const probe = sendParam(dst.eid, recipient, amount, 0n);\n const [limit, feeDetails, receipt] = await c.readContract({address: getAddress(src.oft), abi: OFT_ABI, functionName: \"quoteOFT\", args: [probe]});\n if (amount < limit.minAmountLD) return refuse(`amount ${amount} is below the OFT minimum ${limit.minAmountLD}`);\n if (amount > limit.maxAmountLD) return refuse(`amount ${amount} exceeds the OFT maximum ${limit.maxAmountLD}`);\n const received = receipt.amountReceivedLD;\n if (received <= 0n) return refuse(\"amount is below the OFT dust threshold — nothing would arrive\");\n if (received > amount) return refuse(\"OFT reports more received than sent — refusing\");\n if (params.minAmountOut !== undefined && received < BigInt(params.minAmountOut)) return refuse(`received ${received} is below the caller's floor ${params.minAmountOut}`);\n const sp = sendParam(dst.eid, recipient, amount, received);\n const fee = await c.readContract({address: getAddress(src.oft), abi: OFT_ABI, functionName: \"quoteSend\", args: [sp, false]});\n if (fee.lzTokenFee !== 0n) return refuse(\"OFT asks for a fee in LZ token — unsupported\");\n // Sealed with headroom: OAppSender requires msg.value == MessagingFee.nativeFee, the\n // endpoint refunds whatever the current fee does not use to `refund`.\n const nativeFee = fee.nativeFee + (fee.nativeFee * FEE_HEADROOM_BPS) / 10_000n;\n const data = encodeFunctionData({abi: OFT_ABI, functionName: \"send\", args: [sp, {nativeFee, lzTokenFee: 0n}, getAddress(refund)]});\n const protocolFees = feeDetails\n .filter((f) => f.feeAmountLD > 0n)\n .map((f) => ({type: \"protocol\" as const, amount: f.feeAmountLD.toString(), token: src.token, included: true, description: f.description || \"OFT fee\"}));\n const feeUsd = protocolFees.reduce((a, f) => a + Number(f.amount) / 1e6, 0);\n // Ethereum sources wait for 60 confirmations before the DVNs attest (~15 min live); L2 sources land in a few minutes.\n const eta = src.chainId === 1 ? 1000 : 240;\n return {\n provider: \"usdt0\",\n intentId: `usdt0:${src.eid}:${dst.eid}`,\n depositAddress: \"\",\n depositMemo: null,\n txRequest: {\n to: src.oft,\n data,\n value: nativeFee.toString(),\n chainId: src.chainId,\n gasLimit: GAS_SEND,\n ...(src.adapter ? {approvalAddress: src.oft} : {}),\n ...(nativeFee > 0n ? {nativeFee: nativeFee.toString()} : {}),\n },\n sourceAmount: amount.toString(),\n destAmount: received.toString(),\n minDestAmount: received.toString(),\n feeUsd,\n fees: protocolFees,\n etaSeconds: eta,\n reliability: 0.98,\n validUntilMs: Date.now() + quoteTtlMs,\n providerData: {\n srcEid: String(src.eid), dstEid: String(dst.eid), oft: src.oft, token: src.token, recipient: getAddress(recipient), refundAddress: getAddress(refund),\n amountLD: amount.toString(), minAmountLD: received.toString(), nativeFee: nativeFee.toString(),\n },\n };\n } catch (err) {\n return refuse(rpcSafeReason(err, src.name));\n }\n },\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n const parsed = parseIntent(quote.intentId);\n if (!tx || !parsed) throw new Error(\"swap2: USDT0 quote has no transaction request\");\n return {\n chain: parsed.src.caip2,\n to: tx.to ?? \"\",\n value: tx.value ?? \"0\",\n ...(tx.data ? {data: tx.data} : {}),\n ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}),\n ...(tx.gasLimit ? {gasLimit: tx.gasLimit} : {}),\n ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {}),\n };\n },\n\n /**\n * Right before signing: the target is the source OFT, the peer is still the\n * destination OFT, and the CURRENT LayerZero fee still fits the sealed\n * `msg.value` (quote + headroom) — the endpoint reverts a send that\n * underpays, so a fee past the headroom means re-quote rather than a\n * wasted broadcast.\n */\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n const parsed = parseIntent(quote.intentId);\n if (!parsed) throw new Error(\"usdt0: malformed intent id\");\n const {src, dst} = parsed;\n if (!same(tx.to, src.oft)) throw new Error(`usdt0: deposit target ${tx.to} is not the ${src.name} OFT`);\n const pd = quote.providerData ?? {};\n if (!/^\\d+$/.test(pd.amountLD ?? \"\") || !/^\\d+$/.test(pd.minAmountLD ?? \"\") || !/^\\d+$/.test(pd.nativeFee ?? \"\") || !isAddress(pd.recipient ?? \"\")) {\n throw new Error(\"usdt0: quote carries no sealed send parameters\");\n }\n const c = client(src.caip2);\n if (!c) throw new Error(`usdt0: no RPC for ${src.caip2}`);\n const sp = sendParam(dst.eid, pd.recipient!, BigInt(pd.amountLD!), BigInt(pd.minAmountLD!));\n let fee: {nativeFee: bigint};\n try {\n await Promise.all([verifyChain(src), verifyPeer(src, dst)]);\n fee = await c.readContract({address: getAddress(src.oft), abi: OFT_ABI, functionName: \"quoteSend\", args: [sp, false]});\n } catch (err) {\n throw new Error(rpcSafeReason(err, src.name));\n }\n const sealed = BigInt(pd.nativeFee!);\n if (fee.nativeFee > sealed) throw new Error(`usdt0: LayerZero fee rose to ${fee.nativeFee} above the sealed ${sealed} (quote + ${FEE_HEADROOM_BPS / 100n} % headroom) — re-quote`);\n if (BigInt(tx.value) !== sealed) throw new Error(`usdt0: transaction value ${tx.value} is not the quoted fee ${sealed}`);\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n const parsed = parseIntent(ref.intentId);\n if (!parsed) return {state: \"failed\"};\n const {src, dst} = parsed;\n if (!ref.sourceTxHash) return {state: \"pending\"};\n try {\n const m = await scanMessage(src, dst, ref.sourceTxHash);\n if (m === null) return {state: \"pending\", depositReceived: false};\n if (m === \"foreign\") return {state: \"failed\"}; // the hash carries a LayerZero message, but not ours\n const name = (m.status?.name ?? \"\").toUpperCase();\n const destHash = m.destination?.tx?.txHash;\n if (name === \"DELIVERED\") return {state: \"completed\", depositReceived: true, ...(destHash ? {destTxHash: destHash} : ref.destTxHash ? {destTxHash: ref.destTxHash} : {})};\n if (name === \"PAYLOAD_STORED\") return {state: \"action-required\", depositReceived: true, claim: {chain: dst.caip2, ready: true}};\n if ([\"FAILED\", \"APPLICATION_BURNED\", \"APPLICATION_SKIPPED\", \"UNRESOLVABLE_COMMAND\", \"MALFORMED_COMMAND\"].includes(name)) return {state: \"failed\", depositReceived: true};\n // INFLIGHT, CONFIRMING, BLOCKED (an earlier nonce on the pathway is stuck — LayerZero clears it), or anything new.\n return {state: \"pending\", depositReceived: true};\n } catch {\n return {state: \"pending\"};\n }\n },\n\n /**\n * A delivery that reverted on the destination (PAYLOAD_STORED — out of\n * executor gas, paused token) is retried by anyone through the endpoint:\n * `lzReceive(origin, receiver, guid, message, extraData)` with the exact\n * packet LayerZero Scan recorded. Null while nothing is stored.\n */\n async buildClaim(ref: IntentRef): Promise<UnsignedTx | null> {\n const parsed = parseIntent(ref.intentId);\n if (!parsed || !ref.sourceTxHash) return null;\n const {src, dst} = parsed;\n const m = await scanMessage(src, dst, ref.sourceTxHash);\n if (!m || m === \"foreign\" || (m.status?.name ?? \"\").toUpperCase() !== \"PAYLOAD_STORED\") return null;\n const nonce = m.pathway?.nonce;\n const guid = m.guid;\n const message = m.source?.tx?.payload;\n if (!Number.isInteger(nonce) || !isHexData(guid) || guid.length !== 66 || !isHexData(message) || message.length <= 2) {\n throw new Error(\"usdt0: LayerZero Scan has no complete packet for the stored payload\");\n }\n if (!same(m.pathway?.receiver?.address, dst.oft)) throw new Error(\"usdt0: stored payload is addressed to another receiver\");\n const valueRaw = m.source?.tx?.options?.lzReceive?.value ?? \"0\";\n const value = /^\\d+$/.test(valueRaw) ? valueRaw : \"0\";\n return {\n chain: dst.caip2,\n to: dst.endpoint,\n value,\n data: encodeFunctionData({\n abi: ENDPOINT_ABI,\n functionName: \"lzReceive\",\n args: [{srcEid: src.eid, sender: pad(getAddress(src.oft), {size: 32}), nonce: BigInt(nonce as number)}, getAddress(dst.oft), guid, message, \"0x\"],\n }),\n chainId: dst.chainId,\n gasLimit: GAS_CLAIM,\n };\n },\n };\n}\n\n/** Exported for tests and diagnostics: the LayerZero Scan status → swap2 state mapping. */\nexport const USDT0_STATUS_MAP: Readonly<Record<string, IntentState>> = Object.freeze({\n INFLIGHT: \"pending\", CONFIRMING: \"pending\", BLOCKED: \"pending\",\n DELIVERED: \"completed\", PAYLOAD_STORED: \"action-required\",\n FAILED: \"failed\", APPLICATION_BURNED: \"failed\", APPLICATION_SKIPPED: \"failed\", UNRESOLVABLE_COMMAND: \"failed\", MALFORMED_COMMAND: \"failed\",\n});\n\nexport {ZERO_B32 as USDT0_ZERO_PEER};\n","/**\n * Activity recognition for USDT0 on every chain in `config.ts`:\n * - `send(...)` on the chain's OFT is our source leg (\"Bridged USDT0\", or\n * \"Bridged USDT\" on Ethereum where the adapter locks plain USDT);\n * - the inbound leg is the executor's delivery — the user signs nothing, so\n * it is recognized by its effect: the chain's USDT0 minted to the owner\n * (from the zero address), or USDT released by the Ethereum adapter to the\n * owner, inside a transaction that did NOT call the token itself (a plain\n * transfer is not a bridge);\n * - `lzReceive` on the LayerZero endpoint is the owner's own retry of a\n * stored payload (`claimSwap2`).\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {calledContract, chainLabel, describeSwapLike, matchesCall} from \"@anywalletkit/protocol-swap2-core/activity\";\nimport {decodeFunctionData, parseAbi, type Hex} from \"viem\";\nimport {USDT0_BY_EID, USDT0_CHAINS, type Usdt0Chain} from \"./config.js\";\n\nconst SEND_ABI = parseAbi([\n \"struct SendParam { uint32 dstEid; bytes32 to; uint256 amountLD; uint256 minAmountLD; bytes extraOptions; bytes composeMsg; bytes oftCmd; }\",\n \"struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; }\",\n \"function send(SendParam sp, MessagingFee fee, address refundAddress)\",\n]);\n\nexport const USDT0_MODULE = \"@anywalletkit/protocol-swap2-usdt0\";\n\n/** send((uint32,bytes32,uint256,uint256,bytes,bytes,bytes),(uint256,uint256),address) — IOFT */\nexport const USDT0_SEND = \"0xc7c7f5b3\";\n/** lzReceive((uint32,bytes32,uint64),address,bytes32,bytes,bytes) — EndpointV2 */\nexport const LZ_RECEIVE = \"0x0c0c389e\";\n\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\n\n/** The symbol the catalog uses on each deployment: USDT where the OFT wraps Tether's USDT, USDT0 elsewhere. */\nfunction symbolFor(chain: Usdt0Chain): string {\n return chain.adapter || [42161, 10, 137].includes(chain.chainId) ? \"USDT\" : \"USDT0\";\n}\n\n/** `send(SendParam, …)` → the destination deployment (dstEid is the first word of the tuple), null when the calldata is absent or foreign. */\nfunction sendDestination(tx: ChainTx): Usdt0Chain | null {\n const data = tx.call?.data;\n if (!data || data.length < 10 + 64 * 2) return null;\n try {\n const [sp] = decodeFunctionData({abi: SEND_ABI, data: data as Hex}).args as unknown as [{dstEid: number}];\n return USDT0_BY_EID[sp.dstEid] ?? null;\n } catch {\n return null;\n }\n}\nconst lc = (a: string) => a.toLowerCase();\n\nexport function describeUsdt0Activity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n const chain = USDT0_CHAINS[tx.chain];\n if (!chain) return null;\n const subtitle = `USDT0 · ${chainLabel(tx.chain)}`;\n if (matchesCall(tx, [chain.oft], [USDT0_SEND])) {\n // The native value is the LayerZero messaging fee (plus the headroom the\n // endpoint refunds), not an asset the owner swapped away: it rides in `fee`\n // next to the gas, and the title names both ends when the calldata says\n // where the tokens go.\n const dst = sendDestination(tx);\n const item = describeSwapLike(tx, ctx, {protocol: USDT0_MODULE, subtitle, kind: \"bridge\", outVerb: \"Bridged\"});\n if (!item) return null;\n const native = item.assetsOut.filter((a) => a.token === null).reduce((sum, a) => sum + a.amount, 0n);\n item.assetsOut = item.assetsOut.filter((a) => a.token !== null);\n if (native > 0n) item.fee = (item.fee ?? 0n) + native;\n const srcSym = item.assetsOut[0]?.symbol ?? symbolFor(chain);\n if (dst) {\n item.title = `Bridged ${srcSym} → ${symbolFor(dst)}`;\n item.subtitle = `USDT0 · ${chainLabel(tx.chain)} → ${dst.name}`;\n } else item.title = `Bridged ${srcSym}`;\n return item;\n }\n if (matchesCall(tx, [chain.endpoint], [LZ_RECEIVE])) {\n return describeSwapLike(tx, ctx, {protocol: USDT0_MODULE, subtitle, kind: \"bridge\", inSuffix: \"via LayerZero\"});\n }\n // Delivery by the LayerZero executor: the token moves out of nowhere (mint)\n // or out of the adapter into the owner, and the call target is not the token.\n const called = calledContract(tx);\n if (called && called === lc(chain.token)) return null;\n const own = new Set([...ctx.own].map(lc));\n const origin = chain.adapter ? lc(chain.oft) : ZERO;\n const delivered = tx.transfers.some((t) => t.token !== null && lc(t.token) === lc(chain.token) && lc(t.from) === origin && own.has(lc(t.to)));\n if (!delivered || own.has(lc(tx.from))) return null;\n return describeSwapLike(tx, ctx, {protocol: USDT0_MODULE, subtitle, kind: \"bridge\", inSuffix: \"via LayerZero\", counterparty: chain.oft});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAkC;;;ACalC,kBAAiF;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AACrB,SAAK,WAAW,cAAc,MAAM;AAAA,EACtC;AAAA,EACmB,eAAe,OAAwB;AACxD,WAAO,MAAS,cAAc,KAAK;AAAA,EACrC;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,MAAS,SAAS,WAAW,OAAO;AAAA,EAC7C;AACF;","names":["same","c","import_viem","import_viem","import_swap2_assets","import_util","c"]}
package/dist/protocol.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  Usdt0Swap2Protocol
3
- } from "./chunk-DDUVPDD6.js";
4
- import "./chunk-COIPAOOA.js";
5
- import "./chunk-DGMQ563D.js";
6
- import "./chunk-7YL2Y3QA.js";
3
+ } from "./chunk-TPBH2Z3B.js";
4
+ import "./chunk-QSOGG65J.js";
5
+ import "./chunk-PUDGFJJG.js";
6
+ import "./chunk-M5SCA7EC.js";
7
7
  export {
8
8
  Usdt0Swap2Protocol
9
9
  };
package/dist/provider.cjs CHANGED
@@ -25,14 +25,16 @@ __export(provider_exports, {
25
25
  usdt0Provider: () => usdt0Provider
26
26
  });
27
27
  module.exports = __toCommonJS(provider_exports);
28
- var import_viem2 = require("viem");
28
+ var import_viem3 = require("viem");
29
29
 
30
30
  // src/activity.ts
31
31
  var import_activity = require("@anywalletkit/protocol-swap2-core/activity");
32
- var import_viem = require("viem");
32
+ var import_viem2 = require("viem");
33
33
 
34
34
  // src/config.ts
35
+ var import_viem = require("viem");
35
36
  var import_util = require("@anywalletkit/protocol-swap2-core/util");
37
+ var import_swap2_assets = require("@anywalletkit/swap2-assets");
36
38
  var LZ_ENDPOINT_A = "0x1a44076050125825900e736c501f859c50fE728c";
37
39
  var LZ_ENDPOINT_B = "0x6F475642a6e85809B1c36Fa62763669b1b48DD5B";
38
40
  var c = (chainId, eid, name, token, oft, endpoint, adapter = false) => ({
@@ -78,6 +80,71 @@ var usdt0 = {
78
80
  return from !== to && this.supportsChain(from) && this.supportsChain(to);
79
81
  }
80
82
  };
83
+ var OFT_SEND_ABI = (0, import_viem.parseAbi)([
84
+ "struct SendParam { uint32 dstEid; bytes32 to; uint256 amountLD; uint256 minAmountLD; bytes extraOptions; bytes composeMsg; bytes oftCmd; }",
85
+ "struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; }",
86
+ "function send(SendParam s, MessagingFee fee, address refundAddress) payable"
87
+ ]);
88
+ function tokenMatches(chain, symbolOrAddress) {
89
+ const same2 = (a, b) => !!a && a.toLowerCase() === b.toLowerCase();
90
+ if (symbolOrAddress.startsWith("0x")) return same2(symbolOrAddress, chain.token);
91
+ if (!USDT0_SYMBOLS.includes(symbolOrAddress.toUpperCase().replace("USD\u20AE", "USDT"))) return false;
92
+ const known = (0, import_swap2_assets.ccAsset)(chain.caip2, symbolOrAddress);
93
+ return !known || same2(known.contract ?? "", chain.token);
94
+ }
95
+ function usdt0VerifyQuote(params, quote) {
96
+ const src = usdt0ChainFor(params.sourceChain);
97
+ const dst = usdt0ChainFor(params.destChain);
98
+ if (!src || !dst || src === dst) return "not a USDT0 route between two deployments";
99
+ if (!tokenMatches(src, params.sourceToken)) return `source token ${params.sourceToken} is not USDT0 (${src.token}) on ${src.name}`;
100
+ if (!tokenMatches(dst, params.destToken)) return `destination token ${params.destToken} is not USDT0 (${dst.token}) on ${dst.name}`;
101
+ const tx = quote.txRequest;
102
+ if (!tx?.data || !tx.to || tx.serializedTx !== void 0) return "the quote carries no OFT call";
103
+ if (tx.to.toLowerCase() !== src.oft.toLowerCase()) return `the call targets ${tx.to}, not the ${src.name} OFT`;
104
+ if (tx.chainId !== void 0 && tx.chainId !== src.chainId) return `the call is for chain ${tx.chainId}, not ${src.chainId}`;
105
+ if (src.adapter ? !tx.approvalAddress || tx.approvalAddress.toLowerCase() !== src.oft.toLowerCase() : tx.approvalAddress !== void 0) {
106
+ return src.adapter ? "the Ethereum send approves another spender than the adapter" : "an OFT send needs no approval";
107
+ }
108
+ let sp;
109
+ let fee;
110
+ let refund;
111
+ try {
112
+ const d = (0, import_viem.decodeFunctionData)({ abi: OFT_SEND_ABI, data: tx.data });
113
+ [sp, fee, refund] = d.args;
114
+ } catch {
115
+ return "the call is not send(SendParam, MessagingFee, refund)";
116
+ }
117
+ let amountIn, floor, value;
118
+ try {
119
+ amountIn = BigInt(params.amountIn);
120
+ floor = BigInt(quote.minDestAmount);
121
+ if (params.minAmountOut !== void 0 && BigInt(params.minAmountOut) > floor) floor = BigInt(params.minAmountOut);
122
+ value = BigInt(tx.value ?? "0");
123
+ } catch {
124
+ return "the request does not name amounts";
125
+ }
126
+ if (sp.dstEid !== dst.eid) return `the send goes to eid ${sp.dstEid}, not ${dst.name} (${dst.eid})`;
127
+ if (sp.amountLD !== amountIn || BigInt(quote.sourceAmount) !== amountIn) return `the send moves ${sp.amountLD}, not the ${amountIn} input`;
128
+ if (sp.minAmountLD > sp.amountLD || sp.minAmountLD <= 0n || sp.minAmountLD < floor) return `the send's minAmountLD ${sp.minAmountLD} is below the ${floor} minimum`;
129
+ if (sp.extraOptions !== "0x" || sp.composeMsg !== "0x" || sp.oftCmd !== "0x") return "the send carries options, a compose message or an OFT command";
130
+ const live = params.dry === false;
131
+ if (params.destAddress || live) {
132
+ if (!(0, import_viem.isAddress)(params.destAddress)) return "the recipient is not an EVM address";
133
+ if (sp.to.toLowerCase() !== (0, import_viem.pad)((0, import_viem.getAddress)(params.destAddress), { size: 32 }).toLowerCase()) return `the send delivers to ${sp.to}, not the recipient`;
134
+ }
135
+ if (params.refundAddress || live) {
136
+ if (!(0, import_viem.isAddress)(params.refundAddress ?? "")) return "the refund address is not an EVM address";
137
+ if ((0, import_viem.getAddress)(refund) !== (0, import_viem.getAddress)(params.refundAddress)) return `the send refunds ${refund}, not the trader`;
138
+ }
139
+ if (fee.lzTokenFee !== 0n) return "the send pays an LZ-token fee";
140
+ if (value !== fee.nativeFee || (tx.nativeFee ?? "0") !== fee.nativeFee.toString()) return "msg.value is not the declared native fee of the send";
141
+ if (quote.intentId.replace(/~[0-9a-f]{32}$/, "") !== `usdt0:${src.eid}:${dst.eid}`) return "the intent id does not name this send";
142
+ return null;
143
+ }
144
+ function usdt0ClaimTargets(chain) {
145
+ const c2 = usdt0ChainFor(chain);
146
+ return c2 ? [c2.endpoint] : [];
147
+ }
81
148
  var usdt0Pins = Object.freeze({
82
149
  callTargets: (chain) => {
83
150
  const c2 = usdt0ChainFor(chain);
@@ -86,14 +153,16 @@ var usdt0Pins = Object.freeze({
86
153
  spenders: (chain) => {
87
154
  const c2 = usdt0ChainFor(chain);
88
155
  return c2?.adapter ? [c2.oft] : [];
89
- }
156
+ },
157
+ claimTargets: usdt0ClaimTargets,
158
+ verifyQuote: usdt0VerifyQuote
90
159
  });
91
160
  function usdt0ChainFor(chain) {
92
161
  return Object.prototype.hasOwnProperty.call(USDT0_CHAINS, chain) ? USDT0_CHAINS[chain] : void 0;
93
162
  }
94
163
 
95
164
  // src/activity.ts
96
- var SEND_ABI = (0, import_viem.parseAbi)([
165
+ var SEND_ABI = (0, import_viem2.parseAbi)([
97
166
  "struct SendParam { uint32 dstEid; bytes32 to; uint256 amountLD; uint256 minAmountLD; bytes extraOptions; bytes composeMsg; bytes oftCmd; }",
98
167
  "struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; }",
99
168
  "function send(SendParam sp, MessagingFee fee, address refundAddress)"
@@ -109,7 +178,7 @@ function sendDestination(tx) {
109
178
  const data = tx.call?.data;
110
179
  if (!data || data.length < 10 + 64 * 2) return null;
111
180
  try {
112
- const [sp] = (0, import_viem.decodeFunctionData)({ abi: SEND_ABI, data }).args;
181
+ const [sp] = (0, import_viem2.decodeFunctionData)({ abi: SEND_ABI, data }).args;
113
182
  return USDT0_BY_EID[sp.dstEid] ?? null;
114
183
  } catch {
115
184
  return null;
@@ -147,9 +216,9 @@ function describeUsdt0Activity(tx, ctx) {
147
216
  }
148
217
 
149
218
  // src/provider.ts
150
- var import_swap2_assets = require("@anywalletkit/swap2-assets");
219
+ var import_swap2_assets2 = require("@anywalletkit/swap2-assets");
151
220
  var import_util2 = require("@anywalletkit/protocol-swap2-core/util");
152
- var OFT_ABI = (0, import_viem2.parseAbi)([
221
+ var OFT_ABI = (0, import_viem3.parseAbi)([
153
222
  "struct SendParam { uint32 dstEid; bytes32 to; uint256 amountLD; uint256 minAmountLD; bytes extraOptions; bytes composeMsg; bytes oftCmd; }",
154
223
  "struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; }",
155
224
  "struct OFTLimit { uint256 minAmountLD; uint256 maxAmountLD; }",
@@ -163,7 +232,7 @@ var OFT_ABI = (0, import_viem2.parseAbi)([
163
232
  "function approvalRequired() view returns (bool)",
164
233
  "function peers(uint32 eid) view returns (bytes32)"
165
234
  ]);
166
- var ENDPOINT_ABI = (0, import_viem2.parseAbi)([
235
+ var ENDPOINT_ABI = (0, import_viem3.parseAbi)([
167
236
  "struct Origin { uint32 srcEid; bytes32 sender; uint64 nonce; }",
168
237
  "function lzReceive(Origin origin, address receiver, bytes32 guid, bytes message, bytes extraData) payable"
169
238
  ]);
@@ -177,12 +246,6 @@ var GAS_CLAIM = "300000";
177
246
  var ZERO_B32 = `0x${"00".repeat(32)}`;
178
247
  var same = (a, b) => !!a && a.toLowerCase() === b.toLowerCase();
179
248
  var isHexData = (v) => typeof v === "string" && /^0x(?:[0-9a-fA-F]{2})*$/.test(v);
180
- function tokenMatches(chain, symbolOrAddress) {
181
- if (symbolOrAddress.startsWith("0x")) return same(symbolOrAddress, chain.token);
182
- if (!USDT0_SYMBOLS.includes(symbolOrAddress.toUpperCase().replace("USD\u20AE", "USDT"))) return false;
183
- const known = (0, import_swap2_assets.ccAsset)(chain.caip2, symbolOrAddress);
184
- return !known || same(known.contract ?? "", chain.token);
185
- }
186
249
  function rpcSafeReason(err, chainName) {
187
250
  const e = err;
188
251
  const text = `${e?.shortMessage ?? ""}
@@ -205,7 +268,7 @@ function usdt0Provider(config = {}) {
205
268
  const urls = typeof raw === "string" ? [raw] : [...raw ?? []];
206
269
  if (urls.length === 0) return null;
207
270
  const opts = { timeout: RPC_TIMEOUT_MS, ...config.fetchImpl ? { fetchFn: config.fetchImpl } : {} };
208
- return (0, import_viem2.createPublicClient)({ transport: urls.length === 1 ? (0, import_viem2.http)(urls[0], opts) : (0, import_viem2.fallback)(urls.map((u) => (0, import_viem2.http)(u, opts))), ccipRead: false });
271
+ return (0, import_viem3.createPublicClient)({ transport: urls.length === 1 ? (0, import_viem3.http)(urls[0], opts) : (0, import_viem3.fallback)(urls.map((u) => (0, import_viem3.http)(u, opts))), ccipRead: false });
209
272
  };
210
273
  const verified = /* @__PURE__ */ new Map();
211
274
  function verifyChain(chain) {
@@ -215,8 +278,8 @@ function usdt0Provider(config = {}) {
215
278
  const c2 = client(chain.caip2);
216
279
  if (!c2) throw new Error(`usdt0: no RPC for ${chain.caip2}`);
217
280
  const [token, approval] = await Promise.all([
218
- c2.readContract({ address: (0, import_viem2.getAddress)(chain.oft), abi: OFT_ABI, functionName: "token" }),
219
- c2.readContract({ address: (0, import_viem2.getAddress)(chain.oft), abi: OFT_ABI, functionName: "approvalRequired" })
281
+ c2.readContract({ address: (0, import_viem3.getAddress)(chain.oft), abi: OFT_ABI, functionName: "token" }),
282
+ c2.readContract({ address: (0, import_viem3.getAddress)(chain.oft), abi: OFT_ABI, functionName: "approvalRequired" })
220
283
  ]);
221
284
  if (!same(token, chain.token)) throw new Error(`usdt0: OFT ${chain.oft} on ${chain.name} reports token ${token}, expected ${chain.token}`);
222
285
  if (approval !== chain.adapter) throw new Error(`usdt0: OFT ${chain.oft} on ${chain.name} reports approvalRequired=${String(approval)}, expected ${String(chain.adapter)}`);
@@ -234,8 +297,8 @@ function usdt0Provider(config = {}) {
234
297
  p = (async () => {
235
298
  const c2 = client(src.caip2);
236
299
  if (!c2) throw new Error(`usdt0: no RPC for ${src.caip2}`);
237
- const peer = await c2.readContract({ address: (0, import_viem2.getAddress)(src.oft), abi: OFT_ABI, functionName: "peers", args: [dst.eid] });
238
- if (!same(peer, (0, import_viem2.pad)((0, import_viem2.getAddress)(dst.oft), { size: 32 }))) throw new Error(`usdt0: ${src.name} OFT has no peer for ${dst.name} (eid ${dst.eid}) \u2014 route not wired`);
300
+ const peer = await c2.readContract({ address: (0, import_viem3.getAddress)(src.oft), abi: OFT_ABI, functionName: "peers", args: [dst.eid] });
301
+ if (!same(peer, (0, import_viem3.pad)((0, import_viem3.getAddress)(dst.oft), { size: 32 }))) throw new Error(`usdt0: ${src.name} OFT has no peer for ${dst.name} (eid ${dst.eid}) \u2014 route not wired`);
239
302
  })();
240
303
  p.catch(() => peers.delete(key));
241
304
  peers.set(key, p);
@@ -251,7 +314,7 @@ function usdt0Provider(config = {}) {
251
314
  }
252
315
  const sendParam = (dstEid, recipient, amountLD, minAmountLD) => ({
253
316
  dstEid,
254
- to: (0, import_viem2.pad)((0, import_viem2.getAddress)(recipient), { size: 32 }),
317
+ to: (0, import_viem3.pad)((0, import_viem3.getAddress)(recipient), { size: 32 }),
255
318
  amountLD,
256
319
  minAmountLD,
257
320
  extraOptions: "0x",
@@ -271,6 +334,7 @@ function usdt0Provider(config = {}) {
271
334
  return {
272
335
  name: "usdt0",
273
336
  describeActivity: describeUsdt0Activity,
337
+ claimTargets: usdt0ClaimTargets,
274
338
  enabled: () => config.enabled ?? true,
275
339
  supportsChain: (chain) => usdt0.supportsChain(chain) && client(chain) !== null,
276
340
  supportsChainPair: (from, to) => usdt0.supports(from, to) && client(from) !== null,
@@ -298,16 +362,16 @@ function usdt0Provider(config = {}) {
298
362
  const dry = params.dry !== false;
299
363
  const recipient = params.destAddress || (dry ? EVM_PLACEHOLDER : "");
300
364
  if (!recipient) return refuse("a live quote needs a recipient");
301
- if (!(0, import_viem2.isAddress)(recipient)) return refuse("destination must be an EVM address");
365
+ if (!(0, import_viem3.isAddress)(recipient)) return refuse("destination must be an EVM address");
302
366
  const refund = params.refundAddress || (dry ? EVM_PLACEHOLDER : "");
303
367
  if (!refund) return refuse("a live quote needs a refund address");
304
- if (!(0, import_viem2.isAddress)(refund)) return refuse("refund address must be an EVM address");
368
+ if (!(0, import_viem3.isAddress)(refund)) return refuse("refund address must be an EVM address");
305
369
  const c2 = client(src.caip2);
306
370
  if (!c2) return refuse(`no RPC configured for ${src.caip2}`);
307
371
  try {
308
372
  await Promise.all([verifyChain(src), verifyPeer(src, dst)]);
309
373
  const probe = sendParam(dst.eid, recipient, amount, 0n);
310
- const [limit, feeDetails, receipt] = await c2.readContract({ address: (0, import_viem2.getAddress)(src.oft), abi: OFT_ABI, functionName: "quoteOFT", args: [probe] });
374
+ const [limit, feeDetails, receipt] = await c2.readContract({ address: (0, import_viem3.getAddress)(src.oft), abi: OFT_ABI, functionName: "quoteOFT", args: [probe] });
311
375
  if (amount < limit.minAmountLD) return refuse(`amount ${amount} is below the OFT minimum ${limit.minAmountLD}`);
312
376
  if (amount > limit.maxAmountLD) return refuse(`amount ${amount} exceeds the OFT maximum ${limit.maxAmountLD}`);
313
377
  const received = receipt.amountReceivedLD;
@@ -315,10 +379,10 @@ function usdt0Provider(config = {}) {
315
379
  if (received > amount) return refuse("OFT reports more received than sent \u2014 refusing");
316
380
  if (params.minAmountOut !== void 0 && received < BigInt(params.minAmountOut)) return refuse(`received ${received} is below the caller's floor ${params.minAmountOut}`);
317
381
  const sp = sendParam(dst.eid, recipient, amount, received);
318
- const fee = await c2.readContract({ address: (0, import_viem2.getAddress)(src.oft), abi: OFT_ABI, functionName: "quoteSend", args: [sp, false] });
382
+ const fee = await c2.readContract({ address: (0, import_viem3.getAddress)(src.oft), abi: OFT_ABI, functionName: "quoteSend", args: [sp, false] });
319
383
  if (fee.lzTokenFee !== 0n) return refuse("OFT asks for a fee in LZ token \u2014 unsupported");
320
384
  const nativeFee = fee.nativeFee + fee.nativeFee * FEE_HEADROOM_BPS / 10000n;
321
- const data = (0, import_viem2.encodeFunctionData)({ abi: OFT_ABI, functionName: "send", args: [sp, { nativeFee, lzTokenFee: 0n }, (0, import_viem2.getAddress)(refund)] });
385
+ const data = (0, import_viem3.encodeFunctionData)({ abi: OFT_ABI, functionName: "send", args: [sp, { nativeFee, lzTokenFee: 0n }, (0, import_viem3.getAddress)(refund)] });
322
386
  const protocolFees = feeDetails.filter((f) => f.feeAmountLD > 0n).map((f) => ({ type: "protocol", amount: f.feeAmountLD.toString(), token: src.token, included: true, description: f.description || "OFT fee" }));
323
387
  const feeUsd = protocolFees.reduce((a, f) => a + Number(f.amount) / 1e6, 0);
324
388
  const eta = src.chainId === 1 ? 1e3 : 240;
@@ -349,8 +413,8 @@ function usdt0Provider(config = {}) {
349
413
  dstEid: String(dst.eid),
350
414
  oft: src.oft,
351
415
  token: src.token,
352
- recipient: (0, import_viem2.getAddress)(recipient),
353
- refundAddress: (0, import_viem2.getAddress)(refund),
416
+ recipient: (0, import_viem3.getAddress)(recipient),
417
+ refundAddress: (0, import_viem3.getAddress)(refund),
354
418
  amountLD: amount.toString(),
355
419
  minAmountLD: received.toString(),
356
420
  nativeFee: nativeFee.toString()
@@ -387,7 +451,7 @@ function usdt0Provider(config = {}) {
387
451
  const { src, dst } = parsed;
388
452
  if (!same(tx.to, src.oft)) throw new Error(`usdt0: deposit target ${tx.to} is not the ${src.name} OFT`);
389
453
  const pd = quote.providerData ?? {};
390
- if (!/^\d+$/.test(pd.amountLD ?? "") || !/^\d+$/.test(pd.minAmountLD ?? "") || !/^\d+$/.test(pd.nativeFee ?? "") || !(0, import_viem2.isAddress)(pd.recipient ?? "")) {
454
+ if (!/^\d+$/.test(pd.amountLD ?? "") || !/^\d+$/.test(pd.minAmountLD ?? "") || !/^\d+$/.test(pd.nativeFee ?? "") || !(0, import_viem3.isAddress)(pd.recipient ?? "")) {
391
455
  throw new Error("usdt0: quote carries no sealed send parameters");
392
456
  }
393
457
  const c2 = client(src.caip2);
@@ -396,7 +460,7 @@ function usdt0Provider(config = {}) {
396
460
  let fee;
397
461
  try {
398
462
  await Promise.all([verifyChain(src), verifyPeer(src, dst)]);
399
- fee = await c2.readContract({ address: (0, import_viem2.getAddress)(src.oft), abi: OFT_ABI, functionName: "quoteSend", args: [sp, false] });
463
+ fee = await c2.readContract({ address: (0, import_viem3.getAddress)(src.oft), abi: OFT_ABI, functionName: "quoteSend", args: [sp, false] });
400
464
  } catch (err) {
401
465
  throw new Error(rpcSafeReason(err, src.name));
402
466
  }
@@ -448,10 +512,10 @@ function usdt0Provider(config = {}) {
448
512
  chain: dst.caip2,
449
513
  to: dst.endpoint,
450
514
  value,
451
- data: (0, import_viem2.encodeFunctionData)({
515
+ data: (0, import_viem3.encodeFunctionData)({
452
516
  abi: ENDPOINT_ABI,
453
517
  functionName: "lzReceive",
454
- args: [{ srcEid: src.eid, sender: (0, import_viem2.pad)((0, import_viem2.getAddress)(src.oft), { size: 32 }), nonce: BigInt(nonce) }, (0, import_viem2.getAddress)(dst.oft), guid, message, "0x"]
518
+ args: [{ srcEid: src.eid, sender: (0, import_viem3.pad)((0, import_viem3.getAddress)(src.oft), { size: 32 }), nonce: BigInt(nonce) }, (0, import_viem3.getAddress)(dst.oft), guid, message, "0x"]
455
519
  }),
456
520
  chainId: dst.chainId,
457
521
  gasLimit: GAS_CLAIM