@anywalletkit/protocol-swap2-near-intents 0.3.4 → 0.3.6

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/index.ts","../src/config.ts","../src/activity.ts","../src/provider.ts","../src/protocol.ts"],"sourcesContent":["export * from \"./config.js\";\nexport * from \"./provider.js\";\nexport {NearIntentsSwap2Protocol} from \"./protocol.js\";\nexport {NearIntentsSwap2Protocol as default} from \"./protocol.js\";\nexport * from \"./activity.js\";\nexport type { NearIntentsSwap2Config } from \"./protocol.js\"\n","import type {RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {namespace} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {ccChain} from \"@anywalletkit/swap2-assets\";\n\n// ── NEAR Intents (1Click) — core, broadest coverage ─────────────────────────\nconst NEAR_INTENTS_NS = new Set([\n \"eip155\", \"solana\", \"tron\", \"bitcoin\", \"near\", \"sui\", \"ton\", \"zcash\",\n \"litecoin\", \"doge\", \"xrp\", \"bch\", \"cardano\", \"stellar\", \"aptos\",\n]);\n\n/**\n * Corridors the APP has paused (caip2 → why), passed in through the provider\n * config: a venue-side degradation (1Click's HOT omni-bridge assets answering\n * \"not available\" for days) is an operational switch, not SDK knowledge — the\n * wallet flips an env var and lifts it the same way when the venue recovers.\n */\nexport type NearIntentsSuspendedChains = Readonly<Record<string, string>>;\n\n/** Why a chain is refused up front, or null when 1Click can serve it. */\nexport function nearIntentsChainRefusal(chain: string, suspended: NearIntentsSuspendedChains = {}): string | null {\n if (!NEAR_INTENTS_NS.has(namespace(chain))) return `1Click does not serve ${chain}`;\n const why = suspended[chain];\n if (why) return `1Click corridor paused by the app: ${chain} — ${why}`;\n // A chain the catalog knows but carries no 1Click asset id for (World Chain,\n // Sei, Ink, Plume, X Layer, Unichain, MegaETH, Linea, Sonic, …) is LI.FI /\n // CCTP territory: the eip155 namespace alone used to claim it, and every\n // quote then died as \"unknown asset\" (2026-10-16 funded run).\n const listed = ccChain(chain)?.assets.some((a) => a.assetId.length > 0) ?? false;\n return listed ? null : `1Click does not list ${chain}`;\n}\n\nexport const nearIntents = {\n enabled: () => true,\n // Routes between any pair of 1Click-listed chains. 1Click is a NEAR-intents\n // solver network — it settles non-EVM↔non-EVM directly (BTC→Solana, Tron→\n // Base …), so this pre-filter must NOT require an EVM leg (the old \"vault\n // leg is always EVM\" assumption of the off-ramp flow silently blocked those\n // swap routes). A chain counts as listed when the shared catalog carries at\n // least one 1Click asset id for it and it is not suspended above; `getQuote`\n // is the real per-pair check and fail-closes (returns null, naming why) for\n // any pair 1Click can't actually route.\n // 2026-08 sweep: 1Click added LTC/DOGE/XRP/BCH/ADA/XLM/APT (+ the EVM\n // additions Avalanche/Scroll/Berachain, covered by the catalog ids).\n supportsChain(chain: string): boolean {\n return nearIntentsChainRefusal(chain) === null;\n },\n supports(from: string, to: string): boolean {\n return this.supportsChain(from) && this.supportsChain(to);\n },\n};\n\n/**\n * The app's side of a remote NEAR Intents stub: `remoteProvider({name: \"near_intents\", baseUrl, ...nearIntentsPins})`.\n * Every 1Click route is a send to a deposit address minted per quote, so nothing can be pinned ahead: the stub calls\n * no contract and approves no spender, and is opened to deposit-address routes (scan 2026-10-28, F9). The deposit\n * address is your backend's word — run the backend you trust.\n */\nexport const nearIntentsPins: RemotePins = Object.freeze({\n callTargets: (): readonly string[] => [],\n spenders: (): readonly string[] => [],\n depositAddressRoutes: true,\n});\n","/**\n * Activity recognition for NEAR Intents (1Click).\n *\n * The source leg on EVM / TON / Solana / Tron / BTC is a plain transfer to a\n * one-time 1Click deposit address, and the destination leg is a plain transfer\n * from a solver / bridge account that changes per swap — neither carries a\n * stable on-chain marker, so they are NOT recognizable offline. The kit's\n * intent journal (the `intentId` returned by `swap2()`) ties those legs back to\n * the swap; this hook only answers for the legs that do have a fixed\n * counterparty: on NEAR itself, deposits into and withdrawals out of the\n * `intents.near` verifier contract (NEP-141 `ft_transfer_call` / `ft_withdraw`).\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {describeSwapLike} from \"@anywalletkit/protocol-swap2-core/activity\";\n\nexport const NEAR_INTENTS_MODULE = \"@anywalletkit/protocol-swap2-near-intents\";\n\n/** The NEAR Intents verifier / settlement contract. */\nexport const NEAR_INTENTS_CONTRACT = \"intents.near\";\n\nexport function describeNearIntentsActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n if (!tx.chain.startsWith(\"near:\")) return null;\n const isOwn = (a: string) => ctx.own.has(a);\n const touches = tx.transfers.some((t) => (t.from === NEAR_INTENTS_CONTRACT && isOwn(t.to)) || (t.to === NEAR_INTENTS_CONTRACT && isOwn(t.from)));\n if (!touches) return null;\n return describeSwapLike(tx, ctx, {\n protocol: NEAR_INTENTS_MODULE,\n subtitle: \"NEAR Intents\",\n kind: \"bridge\",\n counterparty: NEAR_INTENTS_CONTRACT,\n inSuffix: \"via NEAR Intents\",\n });\n}\n","import {nearIntents as cfg, nearIntentsChainRefusal, type NearIntentsSuspendedChains} from \"./config.js\";\nimport {describeNearIntentsActivity} from \"./activity.js\";\nimport {namespace, timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {CC_DEST, ccAsset, ccAssetByToken, ccChain} from \"@anywalletkit/swap2-assets\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\n\n/**\n * NEAR Intents (1Click) provider — the core route, broadest coverage:\n * dry quote → pricing preview; live quote → depositAddress the user funds\n * from any wallet; status polled by depositAddress.\n * Runs server-side, so the partner JWT stays here (no proxy needed). Defensive:\n * any API error yields a null quote so the provider drops out of that round.\n */\n\nconst ONE_CLICK_DEFAULT = \"https://1click.chaindefuser.com/v0\";\nconst QUOTE_TTL_MS = 55_000;\n\n/** intentId durably carries both status lookup keys (memo is quote-specific). */\nconst INTENT_PREFIX = \"near1click:\";\n\nfunction encodeIntent(depositAddress: string, depositMemo: string | null): string {\n return `${INTENT_PREFIX}${encodeURIComponent(depositAddress)}|${encodeURIComponent(depositMemo ?? \"\")}`;\n}\n\nfunction decodeIntent(intentId: string): {depositAddress: string; depositMemo?: string} {\n try {\n if (!intentId.startsWith(INTENT_PREFIX)) throw new Error(\"unsupported id version\");\n const raw = intentId.slice(INTENT_PREFIX.length);\n const parts = raw.split(\"|\");\n if (parts.length !== 2 || !parts[0]) throw new Error(\"invalid id shape\");\n const depositAddress = decodeURIComponent(parts[0]);\n const memo = decodeURIComponent(parts[1] ?? \"\");\n if (!depositAddress) throw new Error(\"empty deposit address\");\n return {depositAddress, ...(memo ? {depositMemo: memo} : {})};\n } catch {\n throw new Error(\"near-intents: malformed intent id\");\n }\n}\n\nfunction authHeaders(jwtOverride?: string): Record<string, string> {\n const h: Record<string, string> = {\"content-type\": \"application/json\", accept: \"application/json\"};\n const jwt = jwtOverride;\n if (jwt) h.authorization = `Bearer ${jwt}`;\n return h;\n}\n\n/** Our integrator fee, injected server-side when a recipient is configured. */\nfunction appFees(recipient?: string, bps?: number): {recipient: string; fee: number}[] | undefined {\n return recipient !== undefined && bps !== undefined ? [{recipient, fee: bps}] : undefined;\n}\n\n/**\n * Per-source deposit + refund config. Every live default keeps failed-swap\n * ownership on the caller's source-chain address.\n */\nfunction depositConfig(_sourceChain: string, refundAddress: string, _dry: boolean) {\n // Every source refunds to the caller's own source-chain address (Zcash\n // included — a t-address placeholder serves dry quotes since 2026-10-18).\n // Never redirect failed swaps to an integrator-owned NEAR account.\n return {depositType: \"ORIGIN_CHAIN\", refundType: \"ORIGIN_CHAIN\", refundTo: refundAddress};\n}\n\n/** Placeholder sender/recipient for dry quotes (1Click requires the fields). */\nconst PLACEHOLDER: Record<string, string> = {\n bitcoin: \"bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq\",\n ton: \"UQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJKZ\",\n // NOT a token mint: with the USDC mint here, every dry quote whose ORIGIN\n // was Solana USDC answered 500 \"Internal server error\" (2026-10-09) — a\n // refund \"to the asset's own mint\" trips 1Click. The incinerator is a\n // plain, valid system address.\n solana: \"1nc1nerator11111111111111111111111111111111\",\n tron: \"TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9\",\n // NEAR refunds go to an account id; the registrar account always exists.\n near: \"near\",\n // A live transparent address (exchange hot wallet); dry quotes only.\n zcash: \"t1KfwsnwJeNRVjQGBDZhwKskpQbih2qx5Ua\",\n eip155: \"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045\",\n};\n\nfunction placeholderFor(chain: string): string {\n return PLACEHOLDER[chain.split(\":\")[0] ?? \"\"] ?? PLACEHOLDER.eip155!;\n}\n\nfunction deadlineIn(minutes: number): string {\n return new Date(Date.now() + minutes * 60_000).toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\n}\n\n/**\n * dest asset id for ANY chain in the catalog (inbound → Ethereum, or the step-2\n * off-ramp → any supported chain). Falls back to the Ethereum omft pattern for\n * a mainnet ERC-20 that isn't in the curated catalog.\n */\nfunction destAssetId(destChain: string, destToken: string): string | null {\n const asset = ccAssetByToken(destChain, destToken);\n if (asset) return asset.assetId;\n if (destChain === CC_DEST.caip2 && /^0x[0-9a-fA-F]{40}$/.test(destToken)) {\n return `nep141:eth-${destToken.toLowerCase()}.omft.near`;\n }\n return null;\n}\n\ntype OneClickQuote = {\n quote?: Record<string, unknown>;\n correlationId?: string;\n error?: string;\n message?: string;\n};\n\n/** 1Click returns tx hashes either as strings or {hash, explorerUrl}. */\nfunction txHashOf(entry: unknown): string | null {\n if (!entry) return null;\n if (typeof entry === \"string\") return entry;\n const h = (entry as {hash?: string}).hash;\n return typeof h === \"string\" ? h : null;\n}\n\n/** `units / 10^decimals` as an exact decimal string (no float on the way, so no Hermes bigint trap). */\nfunction unitsText(units: string, decimals: number): string {\n const digits = units.replace(/^0+(?=\\d)/, \"\").padStart(decimals + 1, \"0\");\n const whole = digits.slice(0, digits.length - decimals);\n const frac = digits.slice(digits.length - decimals).replace(/0+$/, \"\");\n return frac ? `${whole}.${frac}` : whole;\n}\n\n/**\n * 1Click's amount floors, as a stable text an app can show the user. Two wordings, both HTTP 400:\n * - \"Temporary swap limits: minimum swap amount is $1,000\" — the USD floors 1Click announces in its\n * changelog (2026-09-09: $1,000 on BNB Chain and other chains; 2026-09-14: $100 from Tron), seen\n * live 2026-11-04 on Base USDC → BSC USDT and Tron USDT → Base USDC;\n * - \"Amount is too low for bridge, try at least 150000\" — a floor in the ORIGIN asset's base units\n * (live 2026-11-04: Base USDC → Arbitrum answers it below 150000 and quotes at exactly 150000).\n * Only digits are taken from 1Click's text; anything else is not a known floor and returns null.\n */\nfunction minimumRefusal(message: string, origin: {symbol: string; decimals: number}): string | null {\n const usd = /minimum swap amount is \\$([\\d,.]+)/i.exec(message)?.[1]?.replace(/[.,]+$/, \"\");\n if (usd && /\\d/.test(usd)) return `near_intents: below the 1Click minimum ($${usd})`;\n const units = /amount is too low for bridge, try at least (\\d{1,78})\\b/i.exec(message)?.[1];\n if (units) return `near_intents: below the 1Click minimum (at least ${unitsText(units, origin.decimals)} ${origin.symbol})`;\n return null;\n}\n\n/** Explicit constructor configuration; no deployment environment is read. */\nexport interface NearIntentsProviderConfig {\n enabled?: boolean;\n apiUrl?: string;\n jwt?: string;\n feeRecipient?: string;\n feeBps?: number;\n /** Corridors the app has paused (caip2 → reason): refused up front, by name, until the app lifts them. */\n suspendedChains?: NearIntentsSuspendedChains;\n /**\n * Where 1Click credits the output. `DESTINATION_CHAIN` (default) withdraws to\n * `destAddress` on `destChain`. `INTENTS` credits the NEAR Intents account\n * `destAddress` inside intents.near — the account a near.com user holds — with\n * no withdrawal: the asset stays there as the intents token. In this mode\n * `destChain` must be the NEAR chain (`near:mainnet`), and `destToken` may be\n * the intents token id itself (`nep141:…` / `nep245:…`).\n * `CONFIDENTIAL_INTENTS` credits the same account's Confidential Intents\n * balance (where near.com keeps funds); 1Click settles it with a signed\n * transfer intent and serves it to partners only, so it requires `jwt`.\n */\n recipientType?: \"DESTINATION_CHAIN\" | \"INTENTS\" | \"CONFIDENTIAL_INTENTS\";\n}\n\n/** NEAR account id rules (intents.near accounts include implicit hex and 0x ids). */\nconst NEAR_ACCOUNT_ID = /^(?=.{2,64}$)(([a-z\\d]+[-_])*[a-z\\d]+\\.)*([a-z\\d]+[-_])*[a-z\\d]+$/;\nconst INTENTS_TOKEN_ID = /^nep(141|245):\\S+$/;\n\n/**\n * An intents.near account someone can sign for: a named account (`alice.near`), an\n * implicit ed25519 id (64 hex) or an implicit EVM-style id (`0x` + 40 hex). Any other\n * dot-less id passes the NEAR syntax but is a pasted chain address (`bc1q…`, a padded\n * `0x…`), credited to an account no key controls.\n */\nfunction intentsAccountId(id: string): boolean {\n if (!NEAR_ACCOUNT_ID.test(id)) return false;\n return id.includes(\".\") || /^[0-9a-f]{64}$/.test(id) || /^0x[0-9a-f]{40}$/.test(id);\n}\n\nexport function nearIntentsProvider(config: NearIntentsProviderConfig = {}): CrossChainProvider {\n config = Object.freeze({...config});\n const parsedApiUrl = new URL(config.apiUrl ?? ONE_CLICK_DEFAULT);\n if (parsedApiUrl.protocol !== \"https:\" && parsedApiUrl.protocol !== \"http:\") {\n throw new Error(\"near-intents: apiUrl must use http or https\");\n }\n const apiBase = parsedApiUrl.toString().replace(/\\/$/, \"\");\n const recipientType = config.recipientType ?? \"DESTINATION_CHAIN\";\n if (recipientType !== \"DESTINATION_CHAIN\" && recipientType !== \"INTENTS\" && recipientType !== \"CONFIDENTIAL_INTENTS\") {\n throw new Error(\"near-intents: recipientType must be DESTINATION_CHAIN, INTENTS or CONFIDENTIAL_INTENTS\");\n }\n if (recipientType === \"CONFIDENTIAL_INTENTS\" && !config.jwt) {\n throw new Error(\"near-intents: CONFIDENTIAL_INTENTS delivery is partner-only and needs a 1Click jwt\");\n }\n /** Output credited inside NEAR Intents (public or confidential), never withdrawn to a chain. */\n const intents = recipientType !== \"DESTINATION_CHAIN\";\n /**\n * An intents credit lands in the intents.near contract on NEAR, whatever token it is, so\n * only a NEAR destChain names it truthfully: a review of \"USDC on Base to 0x…\" must not\n * be a credit that never reaches Base.\n */\n const intentsDestOk = (destChain: string): boolean => !intents || namespace(destChain) === \"near\";\n /** The 1Click destination asset: an intents token id passes through in INTENTS mode. */\n const destinationAsset = (destChain: string, destToken: string): string | null =>\n intents && INTENTS_TOKEN_ID.test(destToken) ? destToken : destAssetId(destChain, destToken);\n const hasRecipient = config.feeRecipient !== undefined;\n const hasBps = config.feeBps !== undefined;\n if (hasRecipient !== hasBps) throw new Error(\"near-intents: feeRecipient and feeBps must be configured together\");\n if (hasRecipient && (!config.feeRecipient!.trim() || !Number.isInteger(config.feeBps) || config.feeBps! <= 0 || config.feeBps! > 10_000)) {\n throw new Error(\"near-intents: fee config requires a recipient and feeBps between 1 and 10000\");\n }\n return {\n name: \"near_intents\",\n describeActivity: describeNearIntentsActivity,\n enabled: () => config.enabled ?? true,\n\n // Capability discovery comes from the provider itself, so it can run alone\n // or inside the optional aggregator without a central capability table.\n supportsChain: (chain: string) => cfg.supportsChain(chain),\n supportsChainPair: (fromChain: string, toChain: string) => cfg.supports(fromChain, toChain) && intentsDestOk(toChain),\n supportsRoute(from: Asset, to: Asset): boolean {\n // Chain-level gate first (namespace, catalog listing, hand-suspended\n // corridors such as TON while the HOT bridge is dark) …\n if (!cfg.supports(from.chain, to.chain) || !intentsDestOk(to.chain)) return false;\n // … then only pairs present in the curated catalog are offered — and only\n // those with a 1Click asset id (LI.FI-only tokens carry an empty assetId).\n // Both ends: a destination 1Click doesn't list (Unichain, MegaETH, …)\n // answered \"unknown asset\" on every quote (589 of the 2026-10-10 matrix).\n const asset = ccAsset(from.chain, from.token);\n return !!ccChain(from.chain) && !!asset?.assetId && !!destinationAsset(to.chain, to.token);\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n // Every refusal below names itself: on the server these lines are the\n // only visibility into WHY a live quote returned null (the wire answer\n // is just `null`), and \"no route\" bugs hide in exactly that silence.\n // `shown`, when given, is the user-presentable text the caller hands on (a router rejection,\n // the server's {noQuote}); the log line keeps the debug suffix either way.\n const refuse = (reason: string, shown?: string): null => {\n const detail = `${reason} [dry=${params.dry !== false} ${params.sourceChain}->${params.destChain} amount=${params.amountIn}]`;\n // Caller fields and 1Click text are untrusted: no control characters in server logs.\n console.warn(`near-intents: no quote — ${detail.replace(/[\\u0000-\\u001f\\u007f]/g, \" \")}`);\n params.onRefusal?.(shown ?? detail);\n return null;\n };\n // Up-front, named refusals — no wire call for a corridor 1Click cannot\n // serve: a chain outside its list / suspended by hand, or a token the\n // catalog carries without a 1Click asset id (\"1Click does not list …\").\n const paused = config.suspendedChains ?? {};\n // An output credited inside intents.near never touches the destination\n // chain, so only the source corridor can be paused for it.\n const rawIntentsDest = intents && INTENTS_TOKEN_ID.test(params.destToken);\n const chainRefusal = nearIntentsChainRefusal(params.sourceChain, paused)\n ?? (rawIntentsDest ? null : nearIntentsChainRefusal(params.destChain, paused));\n if (chainRefusal) return refuse(chainRefusal);\n if (!intentsDestOk(params.destChain)) return refuse(`${recipientType} credits intents.near: destChain must be a NEAR chain, not ${params.destChain}`);\n if (intents && !intentsAccountId(params.destAddress)) {\n return refuse(`${recipientType} recipient must be a NEAR Intents account id`);\n }\n const origin = ccAsset(params.sourceChain, params.sourceToken);\n if (!origin?.assetId) return refuse(`1Click does not list ${params.sourceChain} ${params.sourceToken}`);\n const destination = destinationAsset(params.destChain, params.destToken);\n if (!destination) return refuse(`1Click does not list ${params.destChain} ${params.destToken}`);\n const dry = params.dry !== false;\n // A live quote derives the deposit address from the refund config —\n // never create one without a real refund destination.\n const refund = params.refundAddress ?? (dry ? placeholderFor(params.sourceChain) : \"\");\n const dcfg = depositConfig(params.sourceChain, refund, dry);\n if (!dry && !dcfg.refundTo) return refuse(\"live quote without a refund address\");\n\n const requestedDeadline = deadlineIn(60);\n const body: Record<string, unknown> = {\n dry,\n // FLEX_INPUT (exchange flow): the address accepts any amount; amountIn\n // is just the pricing notional. Verified against the live API.\n swapType: params.flex ? \"FLEX_INPUT\" : \"EXACT_INPUT\",\n slippageTolerance: params.slippageBps ?? 100,\n originAsset: origin.assetId,\n depositType: dcfg.depositType,\n destinationAsset: destination,\n amount: params.amountIn,\n refundTo: dcfg.refundTo,\n refundType: dcfg.refundType,\n recipient: params.destAddress,\n recipientType,\n deadline: requestedDeadline,\n };\n const fees = appFees(config.feeRecipient, config.feeBps);\n if (fees) body.appFees = fees;\n\n try {\n // 1Click's solver auction flaps: the same body can answer 400 \"No\n // liquidity available\" and 201 seconds apart (observed live on\n // TON USDT -> ETH). A transient flap on the EXECUTION quote would\n // surface as a terminal \"no route\" right after a successful display\n // quote, so ride through it: up to two retries on liquidity flaps,\n // 5xx and network errors. Real rejections (bad address, unknown\n // asset) still fail on the first answer.\n let res: Response | null = null;\n let data: OneClickQuote = {};\n for (let attempt = 0; ; attempt++) {\n try {\n res = await fetch(`${apiBase}/quote`, {\n method: \"POST\",\n headers: authHeaders(config.jwt),\n body: JSON.stringify(body),\n signal: signal ?? timeoutSignal(12_000),\n });\n data = (await res.json().catch(() => ({}))) as OneClickQuote;\n } catch (err) {\n if (attempt >= 2 || signal?.aborted) throw err;\n res = null;\n }\n if (res?.ok) break;\n const flaky =\n res === null ||\n res.status >= 500 ||\n (res.status === 400 && /no liquidity/i.test(String(data.message ?? \"\")));\n if (!flaky || attempt >= 2 || signal?.aborted) break;\n await new Promise((resolve) => setTimeout(resolve, 500 * (attempt + 1)));\n }\n if (!res?.ok) {\n const message = String(data.message ?? \"\").slice(0, 200);\n // A known amount floor goes out as a stable, presentable reason; any other answer keeps the raw text.\n const below = res?.status === 400 ? minimumRefusal(message, origin) : null;\n return refuse(`1Click ${res?.status ?? \"network error\"}: ${message}`, below ?? undefined);\n }\n const q = (data.quote ?? {}) as Record<string, unknown>;\n\n const depositAddress = typeof q.depositAddress === \"string\" ? q.depositAddress : \"\";\n if (!dry && !depositAddress) return refuse(\"live quote came back without a deposit address\");\n const inUsd = Number.parseFloat(String(q.amountInUsd ?? \"0\"));\n const outUsd = Number.parseFloat(String(q.amountOutUsd ?? \"0\"));\n const parsedDeadline = Date.parse(String(q.deadline ?? \"\"));\n if (!dry && (!Number.isFinite(parsedDeadline) || parsedDeadline <= Date.now())) return refuse(`unusable deadline ${String(q.deadline)}`);\n const deadline = Number.isFinite(parsedDeadline) && parsedDeadline > Date.now()\n ? Math.min(parsedDeadline, Date.now() + QUOTE_TTL_MS)\n : Date.now() + QUOTE_TTL_MS;\n\n if (q.amountIn !== undefined && String(q.amountIn) !== params.amountIn) return refuse(`amountIn mismatch (${String(q.amountIn)} vs ${params.amountIn})`);\n\n // amountOut is optimistic, not a guaranteed floor. Live execution must\n // not fabricate a minimum when the provider omits it.\n if (q.minAmountOut === undefined || q.minAmountOut === null) return refuse(\"quote has no minAmountOut\");\n const minDestAmount = String(q.minAmountOut);\n if (params.minAmountOut !== undefined && BigInt(minDestAmount) < BigInt(params.minAmountOut)) return refuse(`floor breach (min=${minDestAmount} < floor=${params.minAmountOut})`);\n const depositMemo =\n (typeof q.depositMemo === \"string\" && q.depositMemo) ||\n (typeof q.memo === \"string\" && q.memo) ||\n null;\n return {\n provider: \"near_intents\",\n intentId: depositAddress ? encodeIntent(depositAddress, depositMemo) : `dry:${crypto.randomUUID()}`,\n depositAddress,\n depositMemo,\n sourceAmount: params.amountIn,\n destAmount: String(q.amountOut ?? \"0\"),\n minDestAmount,\n feeUsd: Math.max(0, inUsd - outUsd),\n etaSeconds: Number(q.timeEstimate ?? 60),\n reliability: 0.95,\n validUntilMs: deadline,\n };\n } catch (err) {\n return refuse(`threw: ${err instanceof Error ? err.message.slice(0, 200) : String(err).slice(0, 200)}`);\n }\n },\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n return {\n chain: \"\",\n to: quote.depositAddress,\n value: quote.sourceAmount,\n ...(quote.depositMemo ? {memo: quote.depositMemo} : {}),\n };\n },\n\n async notifyDeposit(intentId: string, txHash: string): Promise<void> {\n const {depositAddress} = decodeIntent(intentId);\n const res = await fetch(`${apiBase}/deposit/submit`, {\n method: \"POST\",\n headers: authHeaders(config.jwt),\n body: JSON.stringify({depositAddress, txHash}),\n signal: timeoutSignal(12_000),\n });\n if (!res.ok) throw new Error(`near-intents: deposit notification failed (${res.status})`);\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n const {depositAddress, depositMemo} = decodeIntent(ref.intentId);\n // Durable retry: BaseSwap2Protocol embeds the source hash in the swap2\n // id. If the post-broadcast notify failed, every status poll retries it.\n if (ref.sourceTxHash) {\n await this.notifyDeposit?.(ref.intentId, ref.sourceTxHash).catch(() => {});\n }\n try {\n const query = new URLSearchParams({depositAddress});\n if (depositMemo) query.set(\"depositMemo\", depositMemo);\n const res = await fetch(\n `${apiBase}/status?${query.toString()}`,\n {headers: authHeaders(config.jwt), signal: timeoutSignal(12_000)},\n );\n if (!res.ok) return {state: \"pending\"};\n const s = (await res.json()) as {\n status?: string;\n swapDetails?: {destinationChainTxHashes?: unknown[]};\n };\n const map: Record<string, IntentStatus[\"state\"]> = {\n PENDING_DEPOSIT: \"pending\",\n KNOWN_DEPOSIT_TX: \"pending\",\n INCOMPLETE_DEPOSIT: \"pending\",\n PROCESSING: \"pending\",\n SUCCESS: \"completed\",\n FAILED: \"failed\",\n REFUNDED: \"refunded\",\n };\n const state = map[s.status ?? \"PENDING_DEPOSIT\"] ?? \"pending\";\n // KNOWN_DEPOSIT_TX: 1Click has the deposit tx (submitted, not yet\n // credited). Counted as received so a caller with no source hash of\n // its own does not expire a swap that is already on its way.\n const depositReceived = s.status === \"KNOWN_DEPOSIT_TX\" || s.status === \"PROCESSING\" || s.status === \"INCOMPLETE_DEPOSIT\";\n const destTx = txHashOf(s.swapDetails?.destinationChainTxHashes?.[0]);\n return {state, depositReceived, ...(destTx ? {destTxHash: destTx} : {})};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n","import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {nearIntents as nearIntentsCfg} from \"./config.js\";\nimport {nearIntentsProvider, type NearIntentsProviderConfig} from \"./provider.js\";\n\nexport interface NearIntentsSwap2Config extends Swap2EngineConfig, NearIntentsProviderConfig {}\n\nexport class NearIntentsSwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n constructor(account: Swap2Account | undefined, config: NearIntentsSwap2Config) {\n super(account, config);\n this.provider = nearIntentsProvider(config);\n }\n protected override chainSupported(caip2: string): boolean {\n return nearIntentsCfg.supports(caip2, \"eip155:1\") || nearIntentsCfg.supports(\"eip155:1\", caip2);\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return nearIntentsCfg.supports(fromChain, toChain);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,kBAAwB;AACxB,0BAAsB;AAGtB,IAAM,kBAAkB,oBAAI,IAAI;AAAA,EAC9B;AAAA,EAAU;AAAA,EAAU;AAAA,EAAQ;AAAA,EAAW;AAAA,EAAQ;AAAA,EAAO;AAAA,EAAO;AAAA,EAC7D;AAAA,EAAY;AAAA,EAAQ;AAAA,EAAO;AAAA,EAAO;AAAA,EAAW;AAAA,EAAW;AAC1D,CAAC;AAWM,SAAS,wBAAwB,OAAe,YAAwC,CAAC,GAAkB;AAChH,MAAI,CAAC,gBAAgB,QAAI,uBAAU,KAAK,CAAC,EAAG,QAAO,yBAAyB,KAAK;AACjF,QAAM,MAAM,UAAU,KAAK;AAC3B,MAAI,IAAK,QAAO,sCAAsC,KAAK,WAAM,GAAG;AAKpE,QAAM,aAAS,6BAAQ,KAAK,GAAG,OAAO,KAAK,CAAC,MAAM,EAAE,QAAQ,SAAS,CA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AM,IAAI,CAAC,EAAE;AAAA,MACzE,QAAQ;AACN,eAAO,EAAC,OAAO,UAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;;;AC3aA,oBAAkC;AAO3B,IAAM,2BAAN,cAAuC,kCAAoB;AAAA,EAC7C;AAAA,EACnB,YAAY,SAAmC,QAAgC;AAC7E,UAAM,SAAS,MAAM;AACrB,SAAK,WAAW,oBAAoB,MAAM;AAAA,EAC5C;AAAA,EACmB,eAAe,OAAwB;AACxD,WAAO,YAAe,SAAS,OAAO,UAAU,KAAK,YAAe,SAAS,YAAY,KAAK;AAAA,EAChG;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,YAAe,SAAS,WAAW,OAAO;AAAA,EACnD;AACF;","names":["import_util","import_swap2_assets"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/config.ts","../src/refusals.ts","../src/activity.ts","../src/provider.ts","../src/protocol.ts"],"sourcesContent":["export * from \"./config.js\";\nexport * from \"./provider.js\";\nexport {NearIntentsSwap2Protocol} from \"./protocol.js\";\nexport {NearIntentsSwap2Protocol as default} from \"./protocol.js\";\nexport * from \"./activity.js\";\nexport type { NearIntentsSwap2Config } from \"./protocol.js\"\n","import type {RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {namespace} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {ccChain} from \"@anywalletkit/swap2-assets\";\nimport {note} from \"./refusals.js\";\n\n// ── NEAR Intents (1Click) — core, broadest coverage ─────────────────────────\nconst NEAR_INTENTS_NS = new Set([\n \"eip155\", \"solana\", \"tron\", \"bitcoin\", \"near\", \"sui\", \"ton\", \"zcash\",\n \"litecoin\", \"doge\", \"xrp\", \"bch\", \"cardano\", \"stellar\", \"aptos\",\n]);\n\n/**\n * Corridors the APP has paused (caip2 → why), passed in through the provider\n * config: a venue-side degradation (1Click's HOT omni-bridge assets answering\n * \"not available\" for days) is an operational switch, not SDK knowledge — the\n * wallet flips an env var and lifts it the same way when the venue recovers.\n */\nexport type NearIntentsSuspendedChains = Readonly<Record<string, string>>;\n\n/** Why a chain is refused up front, or null when 1Click can serve it. */\nexport function nearIntentsChainRefusal(chain: string, suspended: NearIntentsSuspendedChains = {}): string | null {\n if (!NEAR_INTENTS_NS.has(namespace(chain))) return note(`1Click does not serve ${chain}`, \"unsupported_pair\");\n const why = suspended[chain];\n // The app's own switch (a disabled provider, for one corridor): its policy, whatever made it pause the corridor.\n if (why) return note(`1Click corridor paused by the app: ${chain} — ${why}`, \"policy_refused\");\n // A chain the catalog knows but carries no 1Click asset id for (World Chain,\n // Sei, Ink, Plume, X Layer, Unichain, MegaETH, Linea, Sonic, …) is LI.FI /\n // CCTP territory: the eip155 namespace alone used to claim it, and every\n // quote then died as \"unknown asset\" (2026-10-16 funded run).\n const listed = ccChain(chain)?.assets.some((a) => a.assetId.length > 0) ?? false;\n return listed ? null : note(`1Click does not list ${chain}`, \"unsupported_pair\");\n}\n\nexport const nearIntents = {\n enabled: () => true,\n // Routes between any pair of 1Click-listed chains. 1Click is a NEAR-intents\n // solver network — it settles non-EVM↔non-EVM directly (BTC→Solana, Tron→\n // Base …), so this pre-filter must NOT require an EVM leg (the old \"vault\n // leg is always EVM\" assumption of the off-ramp flow silently blocked those\n // swap routes). A chain counts as listed when the shared catalog carries at\n // least one 1Click asset id for it and it is not suspended above; `getQuote`\n // is the real per-pair check and fail-closes (returns null, naming why) for\n // any pair 1Click can't actually route.\n // 2026-08 sweep: 1Click added LTC/DOGE/XRP/BCH/ADA/XLM/APT (+ the EVM\n // additions Avalanche/Scroll/Berachain, covered by the catalog ids).\n supportsChain(chain: string): boolean {\n return nearIntentsChainRefusal(chain) === null;\n },\n supports(from: string, to: string): boolean {\n return this.supportsChain(from) && this.supportsChain(to);\n },\n};\n\n/**\n * The app's side of a remote NEAR Intents stub: `remoteProvider({name: \"near_intents\", baseUrl, ...nearIntentsPins})`.\n * Every 1Click route is a send to a deposit address minted per quote, so nothing can be pinned ahead: the stub calls\n * no contract and approves no spender, and is opened to deposit-address routes (scan 2026-10-28, F9). The deposit\n * address is your backend's word — run the backend you trust.\n */\nexport const nearIntentsPins: RemotePins = Object.freeze({\n callTargets: (): readonly string[] => [],\n spenders: (): readonly string[] => [],\n depositAddressRoutes: true,\n});\n","import {refusalNotes} from \"@anywalletkit/protocol-swap2-core/errors\";\n\n/**\n * The reasons of the texts this package returns as strings (`nearIntentsChainRefusal`): `note` hands a text back\n * unchanged and remembers its reason, `reasonOf` reads it back for the provider's refusal. Bounded; a text always\n * gets the same reason.\n */\nconst notes = refusalNotes();\n\nexport const note = notes.note;\nexport const reasonOf = notes.reasonOf;\n","/**\n * Activity recognition for NEAR Intents (1Click).\n *\n * The source leg on EVM / TON / Solana / Tron / BTC is a plain transfer to a\n * one-time 1Click deposit address, and the destination leg is a plain transfer\n * from a solver / bridge account that changes per swap — neither carries a\n * stable on-chain marker, so they are NOT recognizable offline. The kit's\n * intent journal (the `intentId` returned by `swap2()`) ties those legs back to\n * the swap; this hook only answers for the legs that do have a fixed\n * counterparty: on NEAR itself, deposits into and withdrawals out of the\n * `intents.near` verifier contract (NEP-141 `ft_transfer_call` / `ft_withdraw`).\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {describeSwapLike} from \"@anywalletkit/protocol-swap2-core/activity\";\n\nexport const NEAR_INTENTS_MODULE = \"@anywalletkit/protocol-swap2-near-intents\";\n\n/** The NEAR Intents verifier / settlement contract. */\nexport const NEAR_INTENTS_CONTRACT = \"intents.near\";\n\nexport function describeNearIntentsActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n if (!tx.chain.startsWith(\"near:\")) return null;\n const isOwn = (a: string) => ctx.own.has(a);\n const touches = tx.transfers.some((t) => (t.from === NEAR_INTENTS_CONTRACT && isOwn(t.to)) || (t.to === NEAR_INTENTS_CONTRACT && isOwn(t.from)));\n if (!touches) return null;\n return describeSwapLike(tx, ctx, {\n protocol: NEAR_INTENTS_MODULE,\n subtitle: \"NEAR Intents\",\n kind: \"bridge\",\n counterparty: NEAR_INTENTS_CONTRACT,\n inSuffix: \"via NEAR Intents\",\n });\n}\n","import {nearIntents as cfg, nearIntentsChainRefusal, type NearIntentsSuspendedChains} from \"./config.js\";\nimport {describeNearIntentsActivity} from \"./activity.js\";\nimport {namespace, timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {CC_DEST, ccAsset, ccAssetByToken, ccChain} from \"@anywalletkit/swap2-assets\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {httpRefusal, parseRetryAfter, refusalOf, withReason, type Swap2RefusalInfo, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {reasonOf} from \"./refusals.js\";\n\n/**\n * NEAR Intents (1Click) provider — the core route, broadest coverage:\n * dry quote → pricing preview; live quote → depositAddress the user funds\n * from any wallet; status polled by depositAddress.\n * Runs server-side, so the partner JWT stays here (no proxy needed). Defensive:\n * any API error yields a null quote so the provider drops out of that round.\n */\n\nconst ONE_CLICK_DEFAULT = \"https://1click.chaindefuser.com/v0\";\nconst QUOTE_TTL_MS = 55_000;\n\n/** intentId durably carries both status lookup keys (memo is quote-specific). */\nconst INTENT_PREFIX = \"near1click:\";\n\nfunction encodeIntent(depositAddress: string, depositMemo: string | null): string {\n return `${INTENT_PREFIX}${encodeURIComponent(depositAddress)}|${encodeURIComponent(depositMemo ?? \"\")}`;\n}\n\nfunction decodeIntent(intentId: string): {depositAddress: string; depositMemo?: string} {\n try {\n if (!intentId.startsWith(INTENT_PREFIX)) throw new Error(\"unsupported id version\");\n const raw = intentId.slice(INTENT_PREFIX.length);\n const parts = raw.split(\"|\");\n if (parts.length !== 2 || !parts[0]) throw new Error(\"invalid id shape\");\n const depositAddress = decodeURIComponent(parts[0]);\n const memo = decodeURIComponent(parts[1] ?? \"\");\n if (!depositAddress) throw new Error(\"empty deposit address\");\n return {depositAddress, ...(memo ? {depositMemo: memo} : {})};\n } catch {\n throw new Error(\"near-intents: malformed intent id\");\n }\n}\n\nfunction authHeaders(jwtOverride?: string): Record<string, string> {\n const h: Record<string, string> = {\"content-type\": \"application/json\", accept: \"application/json\"};\n const jwt = jwtOverride;\n if (jwt) h.authorization = `Bearer ${jwt}`;\n return h;\n}\n\n/** Our integrator fee, injected server-side when a recipient is configured. */\nfunction appFees(recipient?: string, bps?: number): {recipient: string; fee: number}[] | undefined {\n return recipient !== undefined && bps !== undefined ? [{recipient, fee: bps}] : undefined;\n}\n\n/**\n * Per-source deposit + refund config. Every live default keeps failed-swap\n * ownership on the caller's source-chain address.\n */\nfunction depositConfig(_sourceChain: string, refundAddress: string, _dry: boolean) {\n // Every source refunds to the caller's own source-chain address (Zcash\n // included — a t-address placeholder serves dry quotes since 2026-10-18).\n // Never redirect failed swaps to an integrator-owned NEAR account.\n return {depositType: \"ORIGIN_CHAIN\", refundType: \"ORIGIN_CHAIN\", refundTo: refundAddress};\n}\n\n/** Placeholder sender/recipient for dry quotes (1Click requires the fields). */\nconst PLACEHOLDER: Record<string, string> = {\n bitcoin: \"bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq\",\n ton: \"UQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJKZ\",\n // NOT a token mint: with the USDC mint here, every dry quote whose ORIGIN\n // was Solana USDC answered 500 \"Internal server error\" (2026-10-09) — a\n // refund \"to the asset's own mint\" trips 1Click. The incinerator is a\n // plain, valid system address.\n solana: \"1nc1nerator11111111111111111111111111111111\",\n tron: \"TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9\",\n // NEAR refunds go to an account id; the registrar account always exists.\n near: \"near\",\n // A live transparent address (exchange hot wallet); dry quotes only.\n zcash: \"t1KfwsnwJeNRVjQGBDZhwKskpQbih2qx5Ua\",\n eip155: \"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045\",\n};\n\nfunction placeholderFor(chain: string): string {\n return PLACEHOLDER[chain.split(\":\")[0] ?? \"\"] ?? PLACEHOLDER.eip155!;\n}\n\nfunction deadlineIn(minutes: number): string {\n return new Date(Date.now() + minutes * 60_000).toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\n}\n\n/**\n * dest asset id for ANY chain in the catalog (inbound → Ethereum, or the step-2\n * off-ramp → any supported chain). Falls back to the Ethereum omft pattern for\n * a mainnet ERC-20 that isn't in the curated catalog.\n */\nfunction destAssetId(destChain: string, destToken: string): string | null {\n const asset = ccAssetByToken(destChain, destToken);\n if (asset) return asset.assetId;\n if (destChain === CC_DEST.caip2 && /^0x[0-9a-fA-F]{40}$/.test(destToken)) {\n return `nep141:eth-${destToken.toLowerCase()}.omft.near`;\n }\n return null;\n}\n\ntype OneClickQuote = {\n quote?: Record<string, unknown>;\n correlationId?: string;\n error?: string;\n message?: string;\n};\n\n/** 1Click returns tx hashes either as strings or {hash, explorerUrl}. */\nfunction txHashOf(entry: unknown): string | null {\n if (!entry) return null;\n if (typeof entry === \"string\") return entry;\n const h = (entry as {hash?: string}).hash;\n return typeof h === \"string\" ? h : null;\n}\n\n/** `units / 10^decimals` as an exact decimal string (no float on the way, so no Hermes bigint trap). */\nfunction unitsText(units: string, decimals: number): string {\n const digits = units.replace(/^0+(?=\\d)/, \"\").padStart(decimals + 1, \"0\");\n const whole = digits.slice(0, digits.length - decimals);\n const frac = digits.slice(digits.length - decimals).replace(/0+$/, \"\");\n return frac ? `${whole}.${frac}` : whole;\n}\n\n/**\n * 1Click's amount floors, as a stable text an app can show the user. Two wordings, both HTTP 400:\n * - \"Temporary swap limits: minimum swap amount is $1,000\" — the USD floors 1Click announces in its\n * changelog (2026-09-09: $1,000 on BNB Chain and other chains; 2026-09-14: $100 from Tron), seen\n * live 2026-11-04 on Base USDC → BSC USDT and Tron USDT → Base USDC;\n * - \"Amount is too low for bridge, try at least 150000\" — a floor in the ORIGIN asset's base units\n * (live 2026-11-04: Base USDC → Arbitrum answers it below 150000 and quotes at exactly 150000).\n * Only digits are taken from 1Click's text; anything else is not a known floor and returns null.\n */\nfunction minimumRefusal(message: string, origin: {symbol: string; decimals: number}): string | null {\n const usd = /minimum swap amount is \\$([\\d,.]+)/i.exec(message)?.[1]?.replace(/[.,]+$/, \"\");\n if (usd && /\\d/.test(usd)) return `near_intents: below the 1Click minimum ($${usd})`;\n const units = /amount is too low for bridge, try at least (\\d{1,78})\\b/i.exec(message)?.[1];\n if (units) return `near_intents: below the 1Click minimum (at least ${unitsText(units, origin.decimals)} ${origin.symbol})`;\n return null;\n}\n\n/** 1Click's error messages that name one reason (its error answers carry a message, no code). */\nconst ONE_CLICK_MESSAGE_REASONS: readonly (readonly [RegExp, Swap2RefusalReason])[] = [\n [/no liquidity|insufficient liquidity|not enough liquidity/i, \"insufficient_liquidity\"],\n [/minimum swap amount|amount is too (?:low|small)|below the minimum/i, \"amount_too_small\"],\n [/maximum swap amount|amount is too (?:high|large)|above the maximum/i, \"amount_too_large\"],\n [/rate limit|too many requests/i, \"rate_limited\"],\n [/invalid (?:recipient|refund)|(?:recipient|refund)\\w* (?:address )?is (?:not valid|invalid)/i, \"recipient_mismatch\"],\n [/paused|halted|maintenance|suspended/i, \"chain_halted\"],\n [/unknown asset|not supported|unsupported|not available|is not valid/i, \"unsupported_pair\"],\n [/no quote|no route|failed to get quote/i, \"no_route\"],\n];\n\n/** What a message may still name on a 408 / 425 / 5xx: a passing condition, never a verdict on the pair or the route. */\nconst ONE_CLICK_TRANSIENT_REASONS: ReadonlySet<Swap2RefusalReason> = new Set([\"insufficient_liquidity\", \"rate_limited\", \"chain_halted\"]);\n\n/**\n * Why 1Click answered a quote with an error status (or never answered): 429 (with Retry-After) and 401 / 403 by\n * their status; 408 / 425 / 5xx as `upstream_unavailable` unless the message names a passing condition (liquidity,\n * throttling, a halt), since a failing 1Click says nothing about the pair or the route; any other status by what\n * its message says, else 1Click declining to route the request (`no_route`). No answer at all is `upstream_unavailable`.\n */\nfunction oneClickRefusal(status: number | undefined, retryAfter: string | null | undefined, message: string): Swap2RefusalInfo {\n if (status === undefined) return {reason: \"upstream_unavailable\"};\n const http = httpRefusal(status, retryAfter);\n if (http && http.reason !== \"upstream_unavailable\") return http;\n const byMessage = ONE_CLICK_MESSAGE_REASONS.find(([pattern]) => pattern.test(message))?.[1];\n if (http && !(byMessage !== undefined && ONE_CLICK_TRANSIENT_REASONS.has(byMessage))) return http;\n if (byMessage === \"rate_limited\") {\n const wait = parseRetryAfter(retryAfter);\n return {reason: byMessage, httpStatus: status, ...(wait !== undefined ? {retryAfterMs: wait} : {})};\n }\n if (byMessage) return {reason: byMessage};\n return {reason: \"no_route\"};\n}\n\n/** Explicit constructor configuration; no deployment environment is read. */\nexport interface NearIntentsProviderConfig {\n enabled?: boolean;\n apiUrl?: string;\n jwt?: string;\n feeRecipient?: string;\n feeBps?: number;\n /** Corridors the app has paused (caip2 → reason): refused up front, by name, until the app lifts them. */\n suspendedChains?: NearIntentsSuspendedChains;\n /**\n * Where 1Click credits the output. `DESTINATION_CHAIN` (default) withdraws to\n * `destAddress` on `destChain`. `INTENTS` credits the NEAR Intents account\n * `destAddress` inside intents.near — the account a near.com user holds — with\n * no withdrawal: the asset stays there as the intents token. In this mode\n * `destChain` must be the NEAR chain (`near:mainnet`), and `destToken` may be\n * the intents token id itself (`nep141:…` / `nep245:…`).\n * `CONFIDENTIAL_INTENTS` credits the same account's Confidential Intents\n * balance (where near.com keeps funds); 1Click settles it with a signed\n * transfer intent and serves it to partners only, so it requires `jwt`.\n */\n recipientType?: \"DESTINATION_CHAIN\" | \"INTENTS\" | \"CONFIDENTIAL_INTENTS\";\n}\n\n/** NEAR account id rules (intents.near accounts include implicit hex and 0x ids). */\nconst NEAR_ACCOUNT_ID = /^(?=.{2,64}$)(([a-z\\d]+[-_])*[a-z\\d]+\\.)*([a-z\\d]+[-_])*[a-z\\d]+$/;\nconst INTENTS_TOKEN_ID = /^nep(141|245):\\S+$/;\n\n/**\n * An intents.near account someone can sign for: a named account (`alice.near`), an\n * implicit ed25519 id (64 hex) or an implicit EVM-style id (`0x` + 40 hex). Any other\n * dot-less id passes the NEAR syntax but is a pasted chain address (`bc1q…`, a padded\n * `0x…`), credited to an account no key controls.\n */\nfunction intentsAccountId(id: string): boolean {\n if (!NEAR_ACCOUNT_ID.test(id)) return false;\n return id.includes(\".\") || /^[0-9a-f]{64}$/.test(id) || /^0x[0-9a-f]{40}$/.test(id);\n}\n\nexport function nearIntentsProvider(config: NearIntentsProviderConfig = {}): CrossChainProvider {\n config = Object.freeze({...config});\n const parsedApiUrl = new URL(config.apiUrl ?? ONE_CLICK_DEFAULT);\n if (parsedApiUrl.protocol !== \"https:\" && parsedApiUrl.protocol !== \"http:\") {\n throw new Error(\"near-intents: apiUrl must use http or https\");\n }\n const apiBase = parsedApiUrl.toString().replace(/\\/$/, \"\");\n const recipientType = config.recipientType ?? \"DESTINATION_CHAIN\";\n if (recipientType !== \"DESTINATION_CHAIN\" && recipientType !== \"INTENTS\" && recipientType !== \"CONFIDENTIAL_INTENTS\") {\n throw new Error(\"near-intents: recipientType must be DESTINATION_CHAIN, INTENTS or CONFIDENTIAL_INTENTS\");\n }\n if (recipientType === \"CONFIDENTIAL_INTENTS\" && !config.jwt) {\n throw new Error(\"near-intents: CONFIDENTIAL_INTENTS delivery is partner-only and needs a 1Click jwt\");\n }\n /** Output credited inside NEAR Intents (public or confidential), never withdrawn to a chain. */\n const intents = recipientType !== \"DESTINATION_CHAIN\";\n /**\n * An intents credit lands in the intents.near contract on NEAR, whatever token it is, so\n * only a NEAR destChain names it truthfully: a review of \"USDC on Base to 0x…\" must not\n * be a credit that never reaches Base.\n */\n const intentsDestOk = (destChain: string): boolean => !intents || namespace(destChain) === \"near\";\n /** The 1Click destination asset: an intents token id passes through in INTENTS mode. */\n const destinationAsset = (destChain: string, destToken: string): string | null =>\n intents && INTENTS_TOKEN_ID.test(destToken) ? destToken : destAssetId(destChain, destToken);\n const hasRecipient = config.feeRecipient !== undefined;\n const hasBps = config.feeBps !== undefined;\n if (hasRecipient !== hasBps) throw new Error(\"near-intents: feeRecipient and feeBps must be configured together\");\n if (hasRecipient && (!config.feeRecipient!.trim() || !Number.isInteger(config.feeBps) || config.feeBps! <= 0 || config.feeBps! > 10_000)) {\n throw new Error(\"near-intents: fee config requires a recipient and feeBps between 1 and 10000\");\n }\n return {\n name: \"near_intents\",\n describeActivity: describeNearIntentsActivity,\n enabled: () => config.enabled ?? true,\n\n // Capability discovery comes from the provider itself, so it can run alone\n // or inside the optional aggregator without a central capability table.\n supportsChain: (chain: string) => cfg.supportsChain(chain),\n supportsChainPair: (fromChain: string, toChain: string) => cfg.supports(fromChain, toChain) && intentsDestOk(toChain),\n supportsRoute(from: Asset, to: Asset): boolean {\n // Chain-level gate first (namespace, catalog listing, hand-suspended\n // corridors such as TON while the HOT bridge is dark) …\n if (!cfg.supports(from.chain, to.chain) || !intentsDestOk(to.chain)) return false;\n // … then only pairs present in the curated catalog are offered — and only\n // those with a 1Click asset id (LI.FI-only tokens carry an empty assetId).\n // Both ends: a destination 1Click doesn't list (Unichain, MegaETH, …)\n // answered \"unknown asset\" on every quote (589 of the 2026-10-10 matrix).\n const asset = ccAsset(from.chain, from.token);\n return !!ccChain(from.chain) && !!asset?.assetId && !!destinationAsset(to.chain, to.token);\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n // Every refusal below names itself: on the server these lines are the\n // only visibility into WHY a live quote returned null (the wire answer\n // is just `null`), and \"no route\" bugs hide in exactly that silence.\n // `shown`, when given, is the user-presentable text the caller hands on (a router rejection,\n // the server's {noQuote}); the log line keeps the debug suffix either way.\n // `why` classifies the refusal (see Swap2RefusalReason); the text is the same with or without it.\n const refuse = (reason: string, shown?: string, why?: Swap2RefusalReason | Swap2RefusalInfo): null => {\n const detail = `${reason} [dry=${params.dry !== false} ${params.sourceChain}->${params.destChain} amount=${params.amountIn}]`;\n // Caller fields and 1Click text are untrusted: no control characters in server logs.\n console.warn(`near-intents: no quote — ${detail.replace(/[\\u0000-\\u001f\\u007f]/g, \" \")}`);\n const info = typeof why === \"string\" ? {reason: why} : why;\n if (info) params.onRefusal?.(shown ?? detail, info);\n else params.onRefusal?.(shown ?? detail);\n return null;\n };\n // Up-front, named refusals — no wire call for a corridor 1Click cannot\n // serve: a chain outside its list / suspended by hand, or a token the\n // catalog carries without a 1Click asset id (\"1Click does not list …\").\n const paused = config.suspendedChains ?? {};\n // An output credited inside intents.near never touches the destination\n // chain, so only the source corridor can be paused for it.\n const rawIntentsDest = intents && INTENTS_TOKEN_ID.test(params.destToken);\n const chainRefusal = nearIntentsChainRefusal(params.sourceChain, paused)\n ?? (rawIntentsDest ? null : nearIntentsChainRefusal(params.destChain, paused));\n if (chainRefusal) return refuse(chainRefusal, undefined, reasonOf(chainRefusal));\n if (!intentsDestOk(params.destChain)) return refuse(`${recipientType} credits intents.near: destChain must be a NEAR chain, not ${params.destChain}`, undefined, \"unsupported_pair\");\n if (intents && !intentsAccountId(params.destAddress)) {\n return refuse(`${recipientType} recipient must be a NEAR Intents account id`, undefined, \"recipient_mismatch\");\n }\n const origin = ccAsset(params.sourceChain, params.sourceToken);\n if (!origin?.assetId) return refuse(`1Click does not list ${params.sourceChain} ${params.sourceToken}`, undefined, \"unsupported_pair\");\n const destination = destinationAsset(params.destChain, params.destToken);\n if (!destination) return refuse(`1Click does not list ${params.destChain} ${params.destToken}`, undefined, \"unsupported_pair\");\n const dry = params.dry !== false;\n // A live quote derives the deposit address from the refund config —\n // never create one without a real refund destination.\n const refund = params.refundAddress ?? (dry ? placeholderFor(params.sourceChain) : \"\");\n const dcfg = depositConfig(params.sourceChain, refund, dry);\n if (!dry && !dcfg.refundTo) return refuse(\"live quote without a refund address\");\n\n const requestedDeadline = deadlineIn(60);\n const body: Record<string, unknown> = {\n dry,\n // FLEX_INPUT (exchange flow): the address accepts any amount; amountIn\n // is just the pricing notional. Verified against the live API.\n swapType: params.flex ? \"FLEX_INPUT\" : \"EXACT_INPUT\",\n slippageTolerance: params.slippageBps ?? 100,\n originAsset: origin.assetId,\n depositType: dcfg.depositType,\n destinationAsset: destination,\n amount: params.amountIn,\n refundTo: dcfg.refundTo,\n refundType: dcfg.refundType,\n recipient: params.destAddress,\n recipientType,\n deadline: requestedDeadline,\n };\n const fees = appFees(config.feeRecipient, config.feeBps);\n if (fees) body.appFees = fees;\n\n try {\n // 1Click's solver auction flaps: the same body can answer 400 \"No\n // liquidity available\" and 201 seconds apart (observed live on\n // TON USDT -> ETH). A transient flap on the EXECUTION quote would\n // surface as a terminal \"no route\" right after a successful display\n // quote, so ride through it: up to two retries on liquidity flaps,\n // 5xx and network errors. Real rejections (bad address, unknown\n // asset) still fail on the first answer.\n let res: Response | null = null;\n let data: OneClickQuote = {};\n for (let attempt = 0; ; attempt++) {\n try {\n res = await fetch(`${apiBase}/quote`, {\n method: \"POST\",\n headers: authHeaders(config.jwt),\n body: JSON.stringify(body),\n signal: signal ?? timeoutSignal(12_000),\n });\n data = (await res.json().catch(() => ({}))) as OneClickQuote;\n } catch (err) {\n if (attempt >= 2 || signal?.aborted) throw err;\n res = null;\n }\n if (res?.ok) break;\n const flaky =\n res === null ||\n res.status >= 500 ||\n (res.status === 400 && /no liquidity/i.test(String(data.message ?? \"\")));\n if (!flaky || attempt >= 2 || signal?.aborted) break;\n await new Promise((resolve) => setTimeout(resolve, 500 * (attempt + 1)));\n }\n if (!res?.ok) {\n const message = String(data.message ?? \"\").slice(0, 200);\n // A known amount floor goes out as a stable, presentable reason; any other answer keeps the raw text.\n const below = res?.status === 400 ? minimumRefusal(message, origin) : null;\n return refuse(\n `1Click ${res?.status ?? \"network error\"}: ${message}`,\n below ?? undefined,\n below ? \"amount_too_small\" : oneClickRefusal(res?.status, res?.headers?.get?.(\"retry-after\"), message),\n );\n }\n const q = (data.quote ?? {}) as Record<string, unknown>;\n\n const depositAddress = typeof q.depositAddress === \"string\" ? q.depositAddress : \"\";\n if (!dry && !depositAddress) return refuse(\"live quote came back without a deposit address\", undefined, \"upstream_unavailable\");\n const inUsd = Number.parseFloat(String(q.amountInUsd ?? \"0\"));\n const outUsd = Number.parseFloat(String(q.amountOutUsd ?? \"0\"));\n const parsedDeadline = Date.parse(String(q.deadline ?? \"\"));\n if (!dry && (!Number.isFinite(parsedDeadline) || parsedDeadline <= Date.now())) {\n return refuse(`unusable deadline ${String(q.deadline)}`, undefined, Number.isFinite(parsedDeadline) ? \"quote_expired\" : \"upstream_unavailable\");\n }\n const deadline = Number.isFinite(parsedDeadline) && parsedDeadline > Date.now()\n ? Math.min(parsedDeadline, Date.now() + QUOTE_TTL_MS)\n : Date.now() + QUOTE_TTL_MS;\n\n if (q.amountIn !== undefined && String(q.amountIn) !== params.amountIn) return refuse(`amountIn mismatch (${String(q.amountIn)} vs ${params.amountIn})`, undefined, \"policy_refused\");\n\n // amountOut is optimistic, not a guaranteed floor. Live execution must\n // not fabricate a minimum when the provider omits it.\n if (q.minAmountOut === undefined || q.minAmountOut === null) return refuse(\"quote has no minAmountOut\", undefined, \"upstream_unavailable\");\n const minDestAmount = String(q.minAmountOut);\n if (params.minAmountOut !== undefined && BigInt(minDestAmount) < BigInt(params.minAmountOut)) return refuse(`floor breach (min=${minDestAmount} < floor=${params.minAmountOut})`, undefined, \"price_check_failed\");\n const depositMemo =\n (typeof q.depositMemo === \"string\" && q.depositMemo) ||\n (typeof q.memo === \"string\" && q.memo) ||\n null;\n return {\n provider: \"near_intents\",\n intentId: depositAddress ? encodeIntent(depositAddress, depositMemo) : `dry:${crypto.randomUUID()}`,\n depositAddress,\n depositMemo,\n sourceAmount: params.amountIn,\n destAmount: String(q.amountOut ?? \"0\"),\n minDestAmount,\n feeUsd: Math.max(0, inUsd - outUsd),\n etaSeconds: Number(q.timeEstimate ?? 60),\n reliability: 0.95,\n validUntilMs: deadline,\n };\n } catch (err) {\n // The network, 1Click's own 12 s deadline or an answer that does not parse; the caller's own abort is not classified.\n return refuse(\n `threw: ${err instanceof Error ? err.message.slice(0, 200) : String(err).slice(0, 200)}`,\n undefined,\n signal?.aborted ? undefined : (refusalOf(err) ?? \"upstream_unavailable\"),\n );\n }\n },\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n return {\n chain: \"\",\n to: quote.depositAddress,\n value: quote.sourceAmount,\n ...(quote.depositMemo ? {memo: quote.depositMemo} : {}),\n };\n },\n\n async notifyDeposit(intentId: string, txHash: string): Promise<void> {\n const {depositAddress} = decodeIntent(intentId);\n const res = await fetch(`${apiBase}/deposit/submit`, {\n method: \"POST\",\n headers: authHeaders(config.jwt),\n body: JSON.stringify({depositAddress, txHash}),\n signal: timeoutSignal(12_000),\n }).catch((err: unknown) => {\n // Unreachable, or slower than its own 12 s deadline (there is no caller signal here).\n throw err instanceof Error ? withReason(err, \"upstream_unavailable\") : err;\n });\n if (!res.ok) {\n const error = new Error(`near-intents: deposit notification failed (${res.status})`);\n const info = httpRefusal(res.status, res.headers?.get?.(\"retry-after\"));\n throw info ? withReason(error, info) : error;\n }\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n const {depositAddress, depositMemo} = decodeIntent(ref.intentId);\n // Durable retry: BaseSwap2Protocol embeds the source hash in the swap2\n // id. If the post-broadcast notify failed, every status poll retries it.\n if (ref.sourceTxHash) {\n await this.notifyDeposit?.(ref.intentId, ref.sourceTxHash).catch(() => {});\n }\n try {\n const query = new URLSearchParams({depositAddress});\n if (depositMemo) query.set(\"depositMemo\", depositMemo);\n const res = await fetch(\n `${apiBase}/status?${query.toString()}`,\n {headers: authHeaders(config.jwt), signal: timeoutSignal(12_000)},\n );\n if (!res.ok) return {state: \"pending\"};\n const s = (await res.json()) as {\n status?: string;\n swapDetails?: {destinationChainTxHashes?: unknown[]};\n };\n const map: Record<string, IntentStatus[\"state\"]> = {\n PENDING_DEPOSIT: \"pending\",\n KNOWN_DEPOSIT_TX: \"pending\",\n INCOMPLETE_DEPOSIT: \"pending\",\n PROCESSING: \"pending\",\n SUCCESS: \"completed\",\n FAILED: \"failed\",\n REFUNDED: \"refunded\",\n };\n const state = map[s.status ?? \"PENDING_DEPOSIT\"] ?? \"pending\";\n // KNOWN_DEPOSIT_TX: 1Click has the deposit tx (submitted, not yet\n // credited). Counted as received so a caller with no source hash of\n // its own does not expire a swap that is already on its way.\n const depositReceived = s.status === \"KNOWN_DEPOSIT_TX\" || s.status === \"PROCESSING\" || s.status === \"INCOMPLETE_DEPOSIT\";\n const destTx = txHashOf(s.swapDetails?.destinationChainTxHashes?.[0]);\n return {state, depositReceived, ...(destTx ? {destTxHash: destTx} : {})};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n","import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {nearIntents as nearIntentsCfg} from \"./config.js\";\nimport {nearIntentsProvider, type NearIntentsProviderConfig} from \"./provider.js\";\n\nexport interface NearIntentsSwap2Config extends Swap2EngineConfig, NearIntentsProviderConfig {}\n\nexport class NearIntentsSwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n constructor(account: Swap2Account | undefined, config: NearIntentsSwap2Config) {\n super(account, config);\n this.provider = nearIntentsProvider(config);\n }\n protected override chainSupported(caip2: string): boolean {\n return nearIntentsCfg.supports(caip2, \"eip155:1\") || nearIntentsCfg.supports(\"eip155:1\", caip2);\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return nearIntentsCfg.supports(fromChain, toChain);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,kBAAwB;AACxB,0BAAsB;;;ACFtB,oBAA2B;AAO3B,IAAM,YAAQ,4BAAa;AAEpB,IAAM,OAAO,MAAM;AACnB,IAAM,WAAW,MAAM;;;ADJ9B,IAAM,kBAAkB,oBAAI,IAAI;AAAA,EAC9B;AAAA,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C;AAC7E,UAAM,SAAS,MAAM;AACrB,SAAK,WAAW,oBAAoB,MAAM;AAAA,EAC5C;AAAA,EACmB,eAAe,OAAwB;AACxD,WAAO,YAAe,SAAS,OAAO,UAAU,KAAK,YAAe,SAAS,YAAY,KAAK;AAAA,EAChG;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,YAAe,SAAS,WAAW,OAAO;AAAA,EACnD;AACF;","names":["import_util","import_swap2_assets","import_errors"]}
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  NearIntentsSwap2Protocol
3
- } from "./chunk-GE5KDZVH.js";
3
+ } from "./chunk-QHZAE2FO.js";
4
4
  import {
5
5
  nearIntentsProvider
6
- } from "./chunk-4GRRM3WT.js";
6
+ } from "./chunk-4DBCMQCI.js";
7
7
  import {
8
8
  nearIntents,
9
9
  nearIntentsChainRefusal,
10
10
  nearIntentsPins
11
- } from "./chunk-DIFUONLL.js";
11
+ } from "./chunk-RS5GYHTU.js";
12
12
  import {
13
13
  NEAR_INTENTS_CONTRACT,
14
14
  NEAR_INTENTS_MODULE,
package/dist/protocol.cjs CHANGED
@@ -28,6 +28,14 @@ var import_single = require("@anywalletkit/protocol-swap2-core/swap2/single");
28
28
  // src/config.ts
29
29
  var import_util = require("@anywalletkit/protocol-swap2-core/util");
30
30
  var import_swap2_assets = require("@anywalletkit/swap2-assets");
31
+
32
+ // src/refusals.ts
33
+ var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
34
+ var notes = (0, import_errors.refusalNotes)();
35
+ var note = notes.note;
36
+ var reasonOf = notes.reasonOf;
37
+
38
+ // src/config.ts
31
39
  var NEAR_INTENTS_NS = /* @__PURE__ */ new Set([
32
40
  "eip155",
33
41
  "solana",
@@ -46,11 +54,11 @@ var NEAR_INTENTS_NS = /* @__PURE__ */ new Set([
46
54
  "aptos"
47
55
  ]);
48
56
  function nearIntentsChainRefusal(chain, suspended = {}) {
49
- if (!NEAR_INTENTS_NS.has((0, import_util.namespace)(chain))) return `1Click does not serve ${chain}`;
57
+ if (!NEAR_INTENTS_NS.has((0, import_util.namespace)(chain))) return note(`1Click does not serve ${chain}`, "unsupported_pair");
50
58
  const why = suspended[chain];
51
- if (why) return `1Click corridor paused by the app: ${chain} \u2014 ${why}`;
59
+ if (why) return note(`1Click corridor paused by the app: ${chain} \u2014 ${why}`, "policy_refused");
52
60
  const listed = (0, import_swap2_assets.ccChain)(chain)?.assets.some((a) => a.assetId.length > 0) ?? false;
53
- return listed ? null : `1Click does not list ${chain}`;
61
+ return listed ? null : note(`1Click does not list ${chain}`, "unsupported_pair");
54
62
  }
55
63
  var nearIntents = {
56
64
  enabled: () => true,
@@ -98,6 +106,7 @@ function describeNearIntentsActivity(tx, ctx) {
98
106
  // src/provider.ts
99
107
  var import_util2 = require("@anywalletkit/protocol-swap2-core/util");
100
108
  var import_swap2_assets2 = require("@anywalletkit/swap2-assets");
109
+ var import_errors2 = require("@anywalletkit/protocol-swap2-core/errors");
101
110
  var ONE_CLICK_DEFAULT = "https://1click.chaindefuser.com/v0";
102
111
  var QUOTE_TTL_MS = 55e3;
103
112
  var INTENT_PREFIX = "near1click:";
@@ -178,6 +187,30 @@ function minimumRefusal(message, origin) {
178
187
  if (units) return `near_intents: below the 1Click minimum (at least ${unitsText(units, origin.decimals)} ${origin.symbol})`;
179
188
  return null;
180
189
  }
190
+ var ONE_CLICK_MESSAGE_REASONS = [
191
+ [/no liquidity|insufficient liquidity|not enough liquidity/i, "insufficient_liquidity"],
192
+ [/minimum swap amount|amount is too (?:low|small)|below the minimum/i, "amount_too_small"],
193
+ [/maximum swap amount|amount is too (?:high|large)|above the maximum/i, "amount_too_large"],
194
+ [/rate limit|too many requests/i, "rate_limited"],
195
+ [/invalid (?:recipient|refund)|(?:recipient|refund)\w* (?:address )?is (?:not valid|invalid)/i, "recipient_mismatch"],
196
+ [/paused|halted|maintenance|suspended/i, "chain_halted"],
197
+ [/unknown asset|not supported|unsupported|not available|is not valid/i, "unsupported_pair"],
198
+ [/no quote|no route|failed to get quote/i, "no_route"]
199
+ ];
200
+ var ONE_CLICK_TRANSIENT_REASONS = /* @__PURE__ */ new Set(["insufficient_liquidity", "rate_limited", "chain_halted"]);
201
+ function oneClickRefusal(status, retryAfter, message) {
202
+ if (status === void 0) return { reason: "upstream_unavailable" };
203
+ const http = (0, import_errors2.httpRefusal)(status, retryAfter);
204
+ if (http && http.reason !== "upstream_unavailable") return http;
205
+ const byMessage = ONE_CLICK_MESSAGE_REASONS.find(([pattern]) => pattern.test(message))?.[1];
206
+ if (http && !(byMessage !== void 0 && ONE_CLICK_TRANSIENT_REASONS.has(byMessage))) return http;
207
+ if (byMessage === "rate_limited") {
208
+ const wait = (0, import_errors2.parseRetryAfter)(retryAfter);
209
+ return { reason: byMessage, httpStatus: status, ...wait !== void 0 ? { retryAfterMs: wait } : {} };
210
+ }
211
+ if (byMessage) return { reason: byMessage };
212
+ return { reason: "no_route" };
213
+ }
181
214
  var NEAR_ACCOUNT_ID = /^(?=.{2,64}$)(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/;
182
215
  var INTENTS_TOKEN_ID = /^nep(141|245):\S+$/;
183
216
  function intentsAccountId(id) {
@@ -221,24 +254,26 @@ function nearIntentsProvider(config = {}) {
221
254
  return !!(0, import_swap2_assets2.ccChain)(from.chain) && !!asset?.assetId && !!destinationAsset(to.chain, to.token);
222
255
  },
223
256
  async getQuote(params, signal) {
224
- const refuse = (reason, shown) => {
257
+ const refuse = (reason, shown, why) => {
225
258
  const detail = `${reason} [dry=${params.dry !== false} ${params.sourceChain}->${params.destChain} amount=${params.amountIn}]`;
226
259
  console.warn(`near-intents: no quote \u2014 ${detail.replace(/[\u0000-\u001f\u007f]/g, " ")}`);
227
- params.onRefusal?.(shown ?? detail);
260
+ const info = typeof why === "string" ? { reason: why } : why;
261
+ if (info) params.onRefusal?.(shown ?? detail, info);
262
+ else params.onRefusal?.(shown ?? detail);
228
263
  return null;
229
264
  };
230
265
  const paused = config.suspendedChains ?? {};
231
266
  const rawIntentsDest = intents && INTENTS_TOKEN_ID.test(params.destToken);
232
267
  const chainRefusal = nearIntentsChainRefusal(params.sourceChain, paused) ?? (rawIntentsDest ? null : nearIntentsChainRefusal(params.destChain, paused));
233
- if (chainRefusal) return refuse(chainRefusal);
234
- if (!intentsDestOk(params.destChain)) return refuse(`${recipientType} credits intents.near: destChain must be a NEAR chain, not ${params.destChain}`);
268
+ if (chainRefusal) return refuse(chainRefusal, void 0, reasonOf(chainRefusal));
269
+ if (!intentsDestOk(params.destChain)) return refuse(`${recipientType} credits intents.near: destChain must be a NEAR chain, not ${params.destChain}`, void 0, "unsupported_pair");
235
270
  if (intents && !intentsAccountId(params.destAddress)) {
236
- return refuse(`${recipientType} recipient must be a NEAR Intents account id`);
271
+ return refuse(`${recipientType} recipient must be a NEAR Intents account id`, void 0, "recipient_mismatch");
237
272
  }
238
273
  const origin = (0, import_swap2_assets2.ccAsset)(params.sourceChain, params.sourceToken);
239
- if (!origin?.assetId) return refuse(`1Click does not list ${params.sourceChain} ${params.sourceToken}`);
274
+ if (!origin?.assetId) return refuse(`1Click does not list ${params.sourceChain} ${params.sourceToken}`, void 0, "unsupported_pair");
240
275
  const destination = destinationAsset(params.destChain, params.destToken);
241
- if (!destination) return refuse(`1Click does not list ${params.destChain} ${params.destToken}`);
276
+ if (!destination) return refuse(`1Click does not list ${params.destChain} ${params.destToken}`, void 0, "unsupported_pair");
242
277
  const dry = params.dry !== false;
243
278
  const refund = params.refundAddress ?? (dry ? placeholderFor(params.sourceChain) : "");
244
279
  const dcfg = depositConfig(params.sourceChain, refund, dry);
@@ -286,20 +321,26 @@ function nearIntentsProvider(config = {}) {
286
321
  if (!res?.ok) {
287
322
  const message = String(data.message ?? "").slice(0, 200);
288
323
  const below = res?.status === 400 ? minimumRefusal(message, origin) : null;
289
- return refuse(`1Click ${res?.status ?? "network error"}: ${message}`, below ?? void 0);
324
+ return refuse(
325
+ `1Click ${res?.status ?? "network error"}: ${message}`,
326
+ below ?? void 0,
327
+ below ? "amount_too_small" : oneClickRefusal(res?.status, res?.headers?.get?.("retry-after"), message)
328
+ );
290
329
  }
291
330
  const q = data.quote ?? {};
292
331
  const depositAddress = typeof q.depositAddress === "string" ? q.depositAddress : "";
293
- if (!dry && !depositAddress) return refuse("live quote came back without a deposit address");
332
+ if (!dry && !depositAddress) return refuse("live quote came back without a deposit address", void 0, "upstream_unavailable");
294
333
  const inUsd = Number.parseFloat(String(q.amountInUsd ?? "0"));
295
334
  const outUsd = Number.parseFloat(String(q.amountOutUsd ?? "0"));
296
335
  const parsedDeadline = Date.parse(String(q.deadline ?? ""));
297
- if (!dry && (!Number.isFinite(parsedDeadline) || parsedDeadline <= Date.now())) return refuse(`unusable deadline ${String(q.deadline)}`);
336
+ if (!dry && (!Number.isFinite(parsedDeadline) || parsedDeadline <= Date.now())) {
337
+ return refuse(`unusable deadline ${String(q.deadline)}`, void 0, Number.isFinite(parsedDeadline) ? "quote_expired" : "upstream_unavailable");
338
+ }
298
339
  const deadline = Number.isFinite(parsedDeadline) && parsedDeadline > Date.now() ? Math.min(parsedDeadline, Date.now() + QUOTE_TTL_MS) : Date.now() + QUOTE_TTL_MS;
299
- if (q.amountIn !== void 0 && String(q.amountIn) !== params.amountIn) return refuse(`amountIn mismatch (${String(q.amountIn)} vs ${params.amountIn})`);
300
- if (q.minAmountOut === void 0 || q.minAmountOut === null) return refuse("quote has no minAmountOut");
340
+ if (q.amountIn !== void 0 && String(q.amountIn) !== params.amountIn) return refuse(`amountIn mismatch (${String(q.amountIn)} vs ${params.amountIn})`, void 0, "policy_refused");
341
+ if (q.minAmountOut === void 0 || q.minAmountOut === null) return refuse("quote has no minAmountOut", void 0, "upstream_unavailable");
301
342
  const minDestAmount = String(q.minAmountOut);
302
- if (params.minAmountOut !== void 0 && BigInt(minDestAmount) < BigInt(params.minAmountOut)) return refuse(`floor breach (min=${minDestAmount} < floor=${params.minAmountOut})`);
343
+ if (params.minAmountOut !== void 0 && BigInt(minDestAmount) < BigInt(params.minAmountOut)) return refuse(`floor breach (min=${minDestAmount} < floor=${params.minAmountOut})`, void 0, "price_check_failed");
303
344
  const depositMemo = typeof q.depositMemo === "string" && q.depositMemo || typeof q.memo === "string" && q.memo || null;
304
345
  return {
305
346
  provider: "near_intents",
@@ -315,7 +356,11 @@ function nearIntentsProvider(config = {}) {
315
356
  validUntilMs: deadline
316
357
  };
317
358
  } catch (err) {
318
- return refuse(`threw: ${err instanceof Error ? err.message.slice(0, 200) : String(err).slice(0, 200)}`);
359
+ return refuse(
360
+ `threw: ${err instanceof Error ? err.message.slice(0, 200) : String(err).slice(0, 200)}`,
361
+ void 0,
362
+ signal?.aborted ? void 0 : (0, import_errors2.refusalOf)(err) ?? "upstream_unavailable"
363
+ );
319
364
  }
320
365
  },
321
366
  async buildDeposit(quote) {
@@ -333,8 +378,14 @@ function nearIntentsProvider(config = {}) {
333
378
  headers: authHeaders(config.jwt),
334
379
  body: JSON.stringify({ depositAddress, txHash }),
335
380
  signal: (0, import_util2.timeoutSignal)(12e3)
381
+ }).catch((err) => {
382
+ throw err instanceof Error ? (0, import_errors2.withReason)(err, "upstream_unavailable") : err;
336
383
  });
337
- if (!res.ok) throw new Error(`near-intents: deposit notification failed (${res.status})`);
384
+ if (!res.ok) {
385
+ const error = new Error(`near-intents: deposit notification failed (${res.status})`);
386
+ const info = (0, import_errors2.httpRefusal)(res.status, res.headers?.get?.("retry-after"));
387
+ throw info ? (0, import_errors2.withReason)(error, info) : error;
388
+ }
338
389
  },
339
390
  async trackIntent(ref) {
340
391
  const { depositAddress, depositMemo } = decodeIntent(ref.intentId);