@toon-protocol/client 5.1.0 → 5.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-BHGJXLS7.js → chunk-GNPJRJ6U.js} +60 -16
- package/dist/chunk-GNPJRJ6U.js.map +1 -0
- package/dist/cli/main.js +13 -4
- package/dist/cli/main.js.map +1 -1
- package/dist/{client-DF3LZVLC.js → client-RO3VITXU.js} +4 -2
- package/dist/index.d.ts +38 -10
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-BHGJXLS7.js.map +0 -1
- /package/dist/{client-DF3LZVLC.js.map → client-RO3VITXU.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/errors.ts","../src/btp/protocol.ts","../src/channel/batch-settlement/offers.ts","../src/connector/x402.ts","../src/connector/self-description.ts","../src/utils/binary.ts","../src/utils/fulfillment.ts","../src/ilp/ilp-send.ts","../src/btp/IsomorphicBtpClient.ts","../src/ilp/response-meta.ts","../src/utils/retry.ts","../src/btp/BtpRuntimeClient.ts","../src/http/HttpIlpClient.ts","../src/utils/url.ts","../src/connector/ConnectorEdgeClient.ts","../src/btp/transport-select.ts","../src/btp/BtpPaidWriteTransport.ts","../src/wire/oer.ts","../src/wire/envelope.ts","../src/wire/giftwrap.ts","../src/wire/sealed-exchange.ts","../src/client/config.ts","../src/channel/ChannelStore.ts","../src/client/channel-facade.ts","../src/channel/batch-settlement/evm.ts","../src/channel/batch-settlement/svm.ts","../src/channel/solana/payment-channel.ts","../src/channel/evm/receipt.ts","../src/channel/solana/wire-transaction.ts","../src/channel/batch-settlement/exit.ts","../src/transport/rpc.ts","../src/wallet/balances.ts","../src/wallet/transfer.ts","../src/wallet/faucet.ts","../src/signing/evm-signer.ts","../src/client/wallet-facade.ts","../src/client/ToonClient.ts","../src/channel/batch-settlement/deposit-gas.ts","../src/channel/batch-settlement/facilitator.ts","../src/channel/batch-settlement/claim.ts","../src/channel/batch-settlement/sponsor.ts","../src/channel/batch-settlement/challenge.ts","../src/channel/batch-settlement/payer.ts","../src/channel/batch-settlement/manager.ts","../src/client/send.ts"],"sourcesContent":["/**\n * Everything this client throws.\n *\n * ## The rule that orders this file\n *\n * **A reject is returned as `fulfilled: false`; it is never thrown.** Everything\n * declared here happened either *before* the packet went out — a missing key, a\n * route with no price, a chain this client holds no key for, a greeting demanding\n * payment or a different carriage — or *on chain*, where a transaction of the\n * caller's own reverted. Nothing here is the connector's verdict on a packet that\n * actually travelled.\n *\n * That split is not stylistic. A refusal is an outcome the wire is designed to\n * produce (`client-edge-spec.md` §1.3's five-step gate ends in a REJECT, not a\n * transport failure), and it carries facts a caller wants — what the path cost,\n * which claim was spent, who refused. Flattening it into an exception would throw\n * those away and would put the ordinary case of \"you underpaid, here is the\n * price\" onto the same path as \"your RPC is unreachable\".\n *\n * The one edge: {@link PaymentRequiredError} and {@link TransportRequiredError}\n * are *thrown by the transports* when the connector answers HTTP `402` rather\n * than routing at all, because at that layer there is no packet outcome to\n * return. {@link ../client/send.js}'s pipeline catches both and converts them\n * into a {@link ../client/types.js!SendRefused} with `refusedBy: 'edge'`, so a\n * caller of {@link ../client/ToonClient.js!ToonClient.send} still never sees a\n * refusal as an exception.\n */\nimport type { PaymentTerms, ChainKind } from './types.js';\n\n/**\n * Base error class for all TOON client errors.\n */\nexport class ToonClientError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n cause?: Error\n ) {\n super(message, { cause });\n this.name = 'ToonClientError';\n }\n}\n\n/**\n * Network error for connection failures (ECONNREFUSED, ETIMEDOUT).\n * These errors trigger retry logic with exponential backoff.\n */\nexport class NetworkError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'NETWORK_ERROR', cause);\n this.name = 'NetworkError';\n }\n}\n\n/**\n * Connector error for a transport-level failure at the client edge: a `4xx`\n * that is not a greeting, or a `5xx`.\n *\n * Deliberately NOT how an ILP reject arrives. `client-edge-spec.md` §1.1 gives\n * `POST /ilp` a `200` for both a FULFILL and a REJECT, and reserves non-2xx for\n * the request never having become a packet at all (400 undecodable, 401 bad\n * `ILP-Peer-Id`, 413 over 2 MiB). So this class means \"the connector did not\n * process a packet\", never \"the connector refused one\".\n */\nexport class ConnectorError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'CONNECTOR_ERROR', cause);\n this.name = 'ConnectorError';\n }\n}\n\n/**\n * Validation error for invalid input parameters.\n * These errors are thrown before making any HTTP requests.\n */\nexport class ValidationError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'VALIDATION_ERROR', cause);\n this.name = 'ValidationError';\n }\n}\n\n// ─── Configuration and capability ───────────────────────────────────────────\n\n/**\n * The configuration this client was handed cannot produce a working client, and\n * no amount of retrying will change that: no key material, a connector URL that\n * is not a URL, a negative deposit — or a fact this client checked against the\n * chain and found to disagree with what the node published.\n *\n * That last case is the one worth naming. `self-description-spec.md` ND-07 says\n * a node proves each settlement entry against a live chain before publishing it,\n * so a `tokenNetwork` that the `TokenNetworkRegistry` does not agree is the token\n * network for that token is a contradiction between two authorities, not a\n * recoverable condition. Signing a claim under the wrong `verifyingContract`\n * produces a signature that verifies against nothing, and the only symptom is a\n * refused claim — so it is caught here, before any collateral is locked.\n */\nexport class ConfigError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'CONFIG', cause);\n this.name = 'ConfigError';\n }\n}\n\n/**\n * The node settles on chains, but not on one this client holds a key for — or\n * not on the one {@link ../client/types.js!ToonClientConfig.chain} named.\n *\n * Carries {@link offered}, the networks the node *does* publish in its\n * `batchSettlements[]`, because the remedy is always to pick one of them (or to\n * configure a key for one) and a message that only says \"no\" makes the caller go\n * read the self-description by hand to find out what would have worked.\n */\nexport class ChainUnavailableError extends ToonClientError {\n /** The CAIP-2 networks the node publishes (`eip155:84532`, `solana:EtWT…`). */\n readonly offered: string[];\n\n constructor(message: string, offered: string[], cause?: Error) {\n super(message, 'CHAIN_UNAVAILABLE', cause);\n this.name = 'ChainUnavailableError';\n this.offered = [...offered];\n }\n}\n\n/**\n * An operation needs an open payment channel and there is not one.\n *\n * Thrown rather than returned because it is a precondition, not a verdict: no\n * packet is formed, no claim is signed and nothing reaches the connector. The\n * usual cause is `autoOpenChannel: false` with nothing opened yet, or a\n * `deposit`/`close`/`settle` called before `open`.\n */\nexport class ChannelNotOpenError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'CHANNEL_NOT_OPEN', cause);\n this.name = 'ChannelNotOpenError';\n }\n}\n\n/**\n * The destination is not a route this connector prices, so there is no amount to\n * put on a packet.\n *\n * `GET /ilp/routes/price` answered `404` — which is an *answer*, not a failure\n * (see {@link ../connector/ConnectorEdgeClient.js!ConnectorEdgeClient.getRoutePrice}):\n * this connector does not terminate that destination. Pass\n * {@link ../client/types.js!SendOptions.amount} explicitly to send anyway, which\n * is what a *forwarded* destination needs — its price lives at the connector that\n * terminates it, not at the one being posted to.\n */\nexport class RouteNotPricedError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'ROUTE_NOT_PRICED', cause);\n this.name = 'RouteNotPricedError';\n }\n}\n\n/**\n * The caller's own {@link ../client/types.js!SendOptions.beforePay} refused this\n * send, and nothing was paid.\n *\n * Thrown rather than returned, and that is consistent with this file's rule\n * rather than an exception to it: a {@link ../client/types.js!SendRefused} is\n * the *connector's* verdict on a packet that travelled, and here no packet\n * exists. The price was resolved, the hook said no, and the pipeline stopped\n * before a channel was ensured or a voucher was signed — which is the whole\n * point of the hook, since a signed voucher is a bearer instrument that cannot\n * be recalled.\n *\n * A distinct class rather than a {@link ValidationError} because the two are\n * acted on differently: a `ValidationError` says this client could not use an\n * argument, while this says the caller's own rule rejected a request this client\n * was perfectly able to send. {@link reason} is the hook's string, unedited, so\n * the caller reads back exactly what its own check said.\n */\nexport class BeforePayRefusedError extends ToonClientError {\n /** The reason the hook returned, verbatim. */\n readonly reason: string;\n /** The route the refused packet was addressed to. */\n readonly destination: string;\n /** The resolved price the hook was shown, in base units. */\n readonly amount: bigint;\n\n constructor(reason: string, destination: string, amount: bigint) {\n super(\n `beforePay refused this send to \"${destination}\" for ${amount.toString()}: ${reason}`,\n 'BEFORE_PAY_REFUSED'\n );\n this.name = 'BeforePayRefusedError';\n this.reason = reason;\n this.destination = destination;\n this.amount = amount;\n }\n}\n\n// ─── Greetings: refusals raised before the packet was routed ────────────────\n\n/**\n * The connector answered an unpaid (or insufficiently paid) request with its\n * terms instead of routing it — HTTP `402`, `client-edge-spec.md` §1.4.\n *\n * The terms are the point: {@link terms} carries the route's price and the\n * chains it settles on, which is everything needed to open a channel and pay.\n * This is the greeting a first-contact client is *supposed* to receive.\n *\n * Thrown by the transport, where there is no packet outcome to return; converted\n * by {@link ../client/send.js} into a `SendRefused` with\n * `code: 'PAYMENT_REQUIRED'` and `refusedBy: 'edge'`, so a `send()` caller sees\n * an outcome rather than an exception. Catch it directly only when driving a\n * transport by hand.\n */\nexport class PaymentRequiredError extends ToonClientError {\n /** The route's terms, parsed from the x402 challenge body. */\n readonly terms: PaymentTerms;\n\n constructor(message: string, terms: PaymentTerms, cause?: Error) {\n super(message, 'PAYMENT_REQUIRED', cause);\n this.name = 'PaymentRequiredError';\n this.terms = terms;\n }\n}\n\n/**\n * The route refuses the carriage this request arrived on.\n *\n * A node may pin a route to one transport — the devnet relay's `g.toon.relay` is\n * BTP-only — and it says so two ways: in its self-description's\n * `requiredTransport`, and in the greeting it answers a wrong-carriage request\n * with (`extra.requiredTransport`, or an `F02` on BTP). Distinct from\n * {@link PaymentRequiredError} because the remedy is different: paying more will\n * never help, and re-sending over the other carriage always will.\n *\n * {@link required} is the carriage the node insists on, when it named one.\n */\nexport class TransportRequiredError extends ToonClientError {\n /** The carriage the node requires, when the refusal named one. */\n readonly required: 'http' | 'btp' | undefined;\n /** The route's terms, when the refusal carried them. */\n readonly terms: PaymentTerms | undefined;\n\n constructor(\n message: string,\n options: { required?: 'http' | 'btp'; terms?: PaymentTerms; cause?: Error } = {}\n ) {\n super(message, 'TRANSPORT_REQUIRED', options.cause);\n this.name = 'TransportRequiredError';\n this.required = options.required;\n this.terms = options.terms;\n }\n}\n\n// ─── On-chain and channel lifecycle ─────────────────────────────────────────\n\n/**\n * Thrown when the one-time on-chain payment-channel OPEN reverts because the\n * local settlement wallet has no native gas to pay for its own\n * approve/openChannel/setTotalDeposit transactions. This is the channel OPEN\n * only — per-write settlement rides the packet and never spends gas. We remap\n * ONLY this case so callers get an actionable message (fund the wallet) instead\n * of the raw viem \"...exceeds the balance of the account\" string (toon-meta#65).\n * Retryable once the wallet is funded; the underlying viem/RPC error is\n * preserved as `cause`.\n */\nexport class ChannelFundingError extends ToonClientError {\n readonly retryable = true;\n constructor(message: string, cause?: Error) {\n super(message, 'CHANNEL_FUNDING', cause);\n this.name = 'ChannelFundingError';\n }\n}\n\n/**\n * Thrown when a persisted connector→channel binding names a channel whose CLAIM\n * WATERMARK (nonce + cumulative amount) is missing from the channel store.\n *\n * Resuming it anyway would re-track the live channel at nonce 0, and the\n * connector rejects every claim that does not strictly advance the nonce it has\n * already banked (`client-edge-spec.md` §1.3 step 2) — the `F01` failure from the\n * live measurement runs. Opening a fresh channel instead would silently strand\n * the collateral in the existing one. Neither is safe to do quietly, so this is a\n * hard error: the operator decides (settle the old channel, or restore the\n * watermark file). Never delete a channel store for a live channel.\n */\nexport class ChannelResumeError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'CHANNEL_RESUME', cause);\n this.name = 'ChannelResumeError';\n }\n}\n\n/**\n * Thrown by {@link ../wallet/transfer.js!sendTransfer} when the sender cannot\n * cover the requested amount (plus, where applicable, the chain's own transaction\n * fee) on the source chain. A PREFLIGHT failure — thrown before any transaction\n * is built or submitted, so it never costs gas/fees.\n */\nexport class InsufficientBalanceError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'INSUFFICIENT_BALANCE', cause);\n this.name = 'InsufficientBalanceError';\n }\n}\n\n/**\n * Thrown when an EVM RPC never converges on a just-confirmed channel open —\n * the read-after-write hole behind `sepolia.base.org`'s load balancer, whose\n * replicas can serve a state that predates the `openChannel` receipt, making\n * the follow-up `setTotalDeposit` revert `InvalidChannelState()` (#489).\n */\nexport class StaleRpcReadError extends ToonClientError {\n readonly retryable = true;\n constructor(message: string, cause?: Error) {\n super(message, 'STALE_RPC_READ', cause);\n this.name = 'StaleRpcReadError';\n }\n}\n\n/**\n * Thrown by {@link ../wallet/transfer.js!sendTransfer} when `chain` is not one\n * this client can send on — either an unrecognized chain identifier, or a\n * recognized chain the client instance has no configuration for. Distinct from\n * {@link InvalidAddressError} (the chain is fine, the destination isn't) and from\n * {@link ChainUnavailableError} (this client is fine, the *node* does not settle\n * there).\n */\nexport class UnknownChainError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'UNKNOWN_CHAIN', cause);\n this.name = 'UnknownChainError';\n }\n}\n\n/**\n * Thrown by {@link ../wallet/transfer.js!sendTransfer} when the destination\n * address is malformed for the target chain (wrong format, wrong length, invalid\n * charset) — checked BEFORE any transaction is built, so a typo never costs\n * gas/fees or risks sending funds into a black hole.\n */\nexport class InvalidAddressError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'INVALID_ADDRESS', cause);\n this.name = 'InvalidAddressError';\n }\n}\n\n/**\n * Thrown by {@link ../wallet/transfer.js!sendTransfer} when a send was ACCEPTED\n * by the chain (a landed, non-reverted transaction / a node-accepted payment)\n * but the destination's observed balance never rose by the sent amount within\n * the bounded wait. This is the failure {@link ../wallet/transfer.js!sendTransfer}\n * exists to catch: the devnet faucet's Solana leg has been observed returning\n * success with a real transaction signature while delivering 0 lamports\n * (toon-protocol/connector#691) — trusting the send call's return value alone\n * would report a funded destination that in fact holds nothing.\n */\nexport class TransferNotDeliveredError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'TRANSFER_NOT_DELIVERED', cause);\n this.name = 'TransferNotDeliveredError';\n }\n}\n\n/**\n * Thrown by {@link ../wallet/transfer.js!sendTransfer} for a chain/asset\n * combination that is not implemented yet — today, a settlement token on a chain\n * whose token path this client does not build.\n */\nexport class TransferUnsupportedError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'TRANSFER_UNSUPPORTED', cause);\n this.name = 'TransferUnsupportedError';\n }\n}\n\n/**\n * An x402 facilitator answered, and refused to settle an x402 `batch-settlement`\n * deposit (connector ADR 0074). {@link reason} is its own `errorReason` verbatim\n * — `invalid_batch_settlement_evm_…` — because each one names a different remedy:\n * a zero voucher on a fresh channel, a missing Permit2 approval, an expired\n * authorization. Nothing reached a connector, and no channel was funded.\n *\n * A facilitator that did not answer is a {@link NetworkError}, not this.\n */\nexport class FacilitatorError extends ToonClientError {\n constructor(\n message: string,\n public readonly reason: string,\n cause?: Error\n ) {\n super(message, 'FACILITATOR', cause);\n this.name = 'FacilitatorError';\n }\n}\n\n/**\n * The receiving connector's Solana sponsor endpoint answered, and did not open\n * the x402 `batch-settlement` channel (connector ADR 0074 decision 9).\n * {@link reason} is its own refusal name — `token_program_unsupported`,\n * `cluster_rent_threshold_unsupported`, `sponsor_busy`, … — because each names\n * a different remedy. Nothing was spent: the endpoint signs and sends nothing\n * until every check passes.\n */\nexport class SponsorRefusedError extends ToonClientError {\n /**\n * @param status the endpoint's HTTP status. `502` is its \"failed\" class — a\n * co-signed open that was sent and did not confirm — so, unlike every other\n * refusal, it does not prove nothing landed.\n */\n constructor(\n message: string,\n public readonly reason: string,\n public readonly status?: number,\n cause?: Error\n ) {\n super(message, 'SPONSOR_REFUSED', cause);\n this.name = 'SponsorRefusedError';\n }\n}\n\n// ─── Error classification helpers ───────────────────────────────────────────\n\n/**\n * Substrings that mark an insufficient-native-gas revert from an on-chain\n * channel-open tx. viem surfaces the node's message verbatim and the exact\n * phrasing varies by RPC (anvil/geth/hardhat), so we match a set of known\n * markers case-insensitively.\n */\nconst INSUFFICIENT_GAS_MARKERS = [\n 'exceeds the balance of the account',\n 'insufficient funds for gas',\n 'insufficient funds for intrinsic transaction cost',\n 'insufficient funds for transfer',\n];\n\n/**\n * True when `err` (or any error in its nested `cause` chain) is an\n * insufficient-native-gas revert. viem wraps the node error one or more levels\n * deep, so the whole chain is flattened and scanned.\n */\nexport function isInsufficientGasError(err: unknown): boolean {\n const parts: string[] = [];\n let cur: unknown = err;\n for (let i = 0; i < 10 && cur != null; i++) {\n parts.push(cur instanceof Error ? cur.message : String(cur));\n cur = cur instanceof Error ? (cur as { cause?: unknown }).cause : undefined;\n }\n const text = parts.join(' | ').toLowerCase();\n return INSUFFICIENT_GAS_MARKERS.some((m) => text.includes(m));\n}\n\n/**\n * Build the message a {@link ChainUnavailableError} carries, naming what the node\n * offered so the remedy is in the error rather than in the docs.\n */\nexport function chainUnavailableMessage(\n wanted: ChainKind | undefined,\n offered: string[],\n reason: 'no-key' | 'not-offered' | 'none'\n): string {\n const list = offered.length > 0 ? offered.join(', ') : '(none)';\n if (reason === 'none') {\n return (\n 'This connector publishes no settlement chains at all, so there is no ' +\n 'channel to open and nothing can be paid for. Check that it is configured ' +\n 'with a settlement backend.'\n );\n }\n if (reason === 'not-offered') {\n return (\n `This connector does not settle on \"${String(wanted)}\". It settles on: ` +\n `${list}. Set \\`chain\\` to 'evm' or 'solana' to match one of those, or ` +\n 'leave it unset to take the first one this client holds a key for.'\n );\n }\n return (\n `This client holds no key for any chain this connector settles on (${list}). ` +\n 'Supply a `mnemonic` — which derives both an EVM and a Solana key — or the ' +\n 'raw key for one of those chains.'\n );\n}\n\n/**\n * A chain write that was sent and did not end confirmed and clean. It names the\n * transaction, so whoever handles it can look the transaction up before doing\n * anything that would repeat it (connector ADR 0073, decision 5).\n *\n * - `failed`: it landed and its execution failed. Nothing to reconcile.\n * - `expired`: Solana only. Its blockhash is past `lastValidBlockHeight` and it\n * never appeared, so it cannot land. Safe to send again.\n * - `unknown`: no answer settled it before the deadline, usually because the RPC\n * stopped answering. It may still land. Repeating it blindly can do the thing\n * twice. A Solana deposit is incremental, so a repeated one deposits twice.\n *\n * Distinct from a {@link NetworkError}: that one means the request may never\n * have reached the chain. This one means it did, or may have.\n */\nexport class TransactionOutcomeError extends ToonClientError {\n constructor(\n message: string,\n readonly chain: ChainKind,\n readonly txHash: string,\n readonly outcome: 'failed' | 'expired' | 'unknown',\n cause?: Error\n ) {\n super(message, 'TRANSACTION_OUTCOME', cause);\n this.name = 'TransactionOutcomeError';\n }\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion -- bounds-checked binary parsing */\n/**\n * Isomorphic BTP + ILP binary protocol.\n * Uses Uint8Array and DataView — no Buffer, no Node.js dependencies.\n *\n * BTP (Bilateral Transfer Protocol) message format:\n * 1 byte — message type\n * 4 bytes — request ID (uint32 BE)\n * variable — payload (MESSAGE data or ERROR data)\n *\n * ILP (Interledger Protocol) OER-encoded packets:\n * PREPARE (type 12), FULFILL (type 13), REJECT (type 14)\n */\n\n// ─── Text codec (isomorphic) ────────────────────────────────────────────────\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n// ─── BTP types ──────────────────────────────────────────────────────────────\n\nexport const BTPMessageType = {\n RESPONSE: 1,\n ERROR: 2,\n MESSAGE: 6,\n /**\n * RFC-0023's symmetric grammar (connector issue #697, toon-client#493):\n * `Transfer ::= SEQUENCE { amount, protocolData }` — settlement value, no\n * ILP-packet field. Byte-compatible with the connector's `btp.rs`.\n */\n TRANSFER: 7,\n} as const;\n\nexport const ILPPacketType = {\n PREPARE: 12,\n FULFILL: 13,\n REJECT: 14,\n} as const;\n\nexport interface BTPProtocolData {\n protocolName: string;\n contentType: number;\n data: Uint8Array;\n}\n\nexport interface BTPMessageData {\n protocolData: BTPProtocolData[];\n ilpPacket?: Uint8Array;\n}\n\n/** A TRANSFER's body — no `ilpPacket` field exists in this frame type, ever. */\nexport interface BTPTransferData {\n amount: bigint;\n protocolData: BTPProtocolData[];\n}\n\nexport interface BTPMessage {\n type: number;\n requestId: number;\n data: BTPMessageData | BTPErrorData | BTPTransferData;\n}\n\nexport interface BTPErrorData {\n code: string;\n name: string;\n triggeredAt: string;\n /** The trailing `data` octet string decoded as UTF-8 — the human-readable error text. */\n message: string;\n data: Uint8Array;\n}\n\nexport interface ILPPreparePacket {\n type: typeof ILPPacketType.PREPARE;\n amount: bigint;\n destination: string;\n /**\n * Whether this PREPARE declares itself a bootstrap/greeting probe rather\n * than a real payment attempt (connector ADR 0069, issue #1269). One byte\n * on the wire, where a 32-byte `executionCondition` used to sit.\n *\n * The connector's client edge consults it only when no claim rides with\n * the packet: an unclaimed `greeting` PREPARE is never routed, never\n * priced and never fulfilled — it is answered with the x402 terms instead\n * (`client-edge-spec.md` §1.4). A claim header suppresses the greeting\n * unconditionally, so setting this on a paid packet cannot make it free.\n */\n greeting: boolean;\n expiresAt: Date;\n data: Uint8Array;\n}\n\nexport interface ILPFulfillPacket {\n type: typeof ILPPacketType.FULFILL;\n /**\n * The 32-byte fulfillment preimage from the wire — the one thing ADR 0069\n * left in the return direction untouched. A termination derives it from\n * the shared secret sealed inside the request (ADR 0019), so a sender that\n * kept that secret checks a delivery end to end by comparing these bytes\n * against its own `deriveFulfillment(sharedSecret)`. There is no condition\n * on the wire to check it against any more.\n */\n fulfillment: Uint8Array;\n data: Uint8Array;\n}\n\nexport interface ILPRejectPacket {\n type: typeof ILPPacketType.REJECT;\n code: string;\n /** The ILP address that raised the reject. Empty when the raiser is unknown/unset. */\n triggeredBy?: string;\n message: string;\n data: Uint8Array;\n}\n\nexport type ILPResponsePacket = ILPFulfillPacket | ILPRejectPacket;\n\n// ─── Byte helpers ───────────────────────────────────────────────────────────\n\nfunction concat(...arrays: Uint8Array[]): Uint8Array {\n const totalLength = arrays.reduce((sum, a) => sum + a.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const a of arrays) {\n result.set(a, offset);\n offset += a.length;\n }\n return result;\n}\n\nfunction readUint8(buf: Uint8Array, offset: number): number {\n if (offset >= buf.length) throw new Error('Buffer underflow reading uint8');\n return buf[offset]!;\n}\n\nfunction readUint16BE(buf: Uint8Array, offset: number): number {\n if (offset + 2 > buf.length)\n throw new Error('Buffer underflow reading uint16');\n return (buf[offset]! << 8) | buf[offset + 1]!;\n}\n\nfunction readUint32BE(buf: Uint8Array, offset: number): number {\n if (offset + 4 > buf.length)\n throw new Error('Buffer underflow reading uint32');\n return (\n ((buf[offset]! << 24) |\n (buf[offset + 1]! << 16) |\n (buf[offset + 2]! << 8) |\n buf[offset + 3]!) >>>\n 0\n );\n}\n\nfunction readUint64BE(buf: Uint8Array, offset: number): bigint {\n if (offset + 8 > buf.length)\n throw new Error('Buffer underflow reading uint64');\n let value = 0n;\n for (let i = 0; i < 8; i++) {\n value = (value << 8n) | BigInt(buf[offset + i]!);\n }\n return value;\n}\n\nfunction writeUint8(value: number): Uint8Array {\n return new Uint8Array([value]);\n}\n\nfunction writeUint16BE(value: number): Uint8Array {\n return new Uint8Array([(value >> 8) & 0xff, value & 0xff]);\n}\n\nfunction writeUint32BE(value: number): Uint8Array {\n return new Uint8Array([\n (value >> 24) & 0xff,\n (value >> 16) & 0xff,\n (value >> 8) & 0xff,\n value & 0xff,\n ]);\n}\n\nfunction writeUint64BE(value: bigint): Uint8Array {\n const bytes = new Uint8Array(8);\n let remaining = value;\n for (let i = 7; i >= 0; i--) {\n bytes[i] = Number(remaining & 0xffn);\n remaining >>= 8n;\n }\n return bytes;\n}\n\nfunction sliceUtf8(buf: Uint8Array, offset: number, length: number): string {\n return textDecoder.decode(buf.slice(offset, offset + length));\n}\n\n// ─── OER encoding (ILP wire format) ─────────────────────────────────────────\n\nfunction encodeVarUInt(value: bigint): Uint8Array {\n if (value >= 0n && value <= 127n) {\n return new Uint8Array([Number(value)]);\n }\n const bytes: number[] = [];\n let remaining = value;\n while (remaining > 0n) {\n bytes.unshift(Number(remaining & 0xffn));\n remaining = remaining >> 8n;\n }\n return new Uint8Array([0x80 | bytes.length, ...bytes]);\n}\n\nfunction decodeVarUInt(\n buf: Uint8Array,\n offset: number\n): { value: bigint; bytesRead: number } {\n const firstByte = readUint8(buf, offset);\n if (firstByte <= 127) {\n return { value: BigInt(firstByte), bytesRead: 1 };\n }\n const length = firstByte & 0x7f;\n if (offset + 1 + length > buf.length)\n throw new Error('VarUInt buffer underflow');\n let value = 0n;\n for (let i = 0; i < length; i++) {\n value = (value << 8n) | BigInt(buf[offset + 1 + i]!);\n }\n return { value, bytesRead: 1 + length };\n}\n\nfunction encodeVarOctetString(data: Uint8Array): Uint8Array {\n return concat(encodeVarUInt(BigInt(data.length)), data);\n}\n\nfunction decodeVarOctetString(\n buf: Uint8Array,\n offset: number\n): { value: Uint8Array; bytesRead: number } {\n const { value: length, bytesRead: lenBytes } = decodeVarUInt(buf, offset);\n const dataLen = Number(length);\n const start = offset + lenBytes;\n if (start + dataLen > buf.length)\n throw new Error('VarOctetString buffer underflow');\n return {\n value: buf.slice(start, start + dataLen),\n bytesRead: lenBytes + dataLen,\n };\n}\n\nfunction encodeGeneralizedTime(date: Date): Uint8Array {\n const y = date.getUTCFullYear().toString().padStart(4, '0');\n const mo = (date.getUTCMonth() + 1).toString().padStart(2, '0');\n const d = date.getUTCDate().toString().padStart(2, '0');\n const h = date.getUTCHours().toString().padStart(2, '0');\n const mi = date.getUTCMinutes().toString().padStart(2, '0');\n const s = date.getUTCSeconds().toString().padStart(2, '0');\n const ms = date.getUTCMilliseconds().toString().padStart(3, '0');\n return textEncoder.encode(`${y}${mo}${d}${h}${mi}${s}.${ms}Z`);\n}\n\n/** Fixed-length `YYYYMMDDHHMMSS.mmmZ` — {@link encodeGeneralizedTime}'s mirror. */\nconst GENERALIZED_TIME_LENGTH = 19;\n\nfunction decodeGeneralizedTime(\n buf: Uint8Array,\n offset: number\n): { value: Date; bytesRead: number } {\n if (offset + GENERALIZED_TIME_LENGTH > buf.length) {\n throw new Error('Buffer underflow reading GeneralizedTime');\n }\n const text = sliceUtf8(buf, offset, GENERALIZED_TIME_LENGTH);\n const match =\n /^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})\\.(\\d{3})Z$/.exec(text);\n if (!match) {\n throw new Error(`Malformed GeneralizedTime: \"${text}\"`);\n }\n const [, y, mo, d, h, mi, s, ms] = match;\n const value = new Date(\n Date.UTC(\n Number(y),\n Number(mo) - 1,\n Number(d),\n Number(h),\n Number(mi),\n Number(s),\n Number(ms)\n )\n );\n return { value, bytesRead: GENERALIZED_TIME_LENGTH };\n}\n\n// ─── ILP packet serialization ───────────────────────────────────────────────\n\n/**\n * Encode a PREPARE. The `greeting` flag is a single `0x00`/`0x01` octet\n * between `expiresAt` and `destination` — `connector-domain::Prepare::encode`\n * writes `u8::from(self.greeting)` there, and writes nothing else in its\n * place (connector ADR 0069).\n */\nexport function serializeIlpPrepare(packet: ILPPreparePacket): Uint8Array {\n return concat(\n writeUint8(ILPPacketType.PREPARE),\n encodeVarUInt(packet.amount),\n encodeGeneralizedTime(packet.expiresAt),\n writeUint8(packet.greeting ? 1 : 0),\n encodeVarOctetString(textEncoder.encode(packet.destination)),\n encodeVarOctetString(packet.data)\n );\n}\n\n/**\n * Decode an inbound PREPARE — the server-role mirror of {@link serializeIlpPrepare}\n * (toon-client#494: a connector-originated MESSAGE carries a PREPARE for this\n * client to answer). Byte-for-byte the same layout `connector-domain::Prepare::decode`\n * reads.\n */\nexport function deserializeIlpPrepare(buf: Uint8Array): ILPPreparePacket {\n if (buf.length === 0) throw new Error('Empty ILP packet');\n const type = buf[0]!;\n if (type !== ILPPacketType.PREPARE) {\n throw new Error(`Expected PREPARE (type ${ILPPacketType.PREPARE}), got type ${type}`);\n }\n let offset = 1;\n\n const { value: amount, bytesRead: amountBytes } = decodeVarUInt(buf, offset);\n offset += amountBytes;\n\n const { value: expiresAt, bytesRead: timeBytes } = decodeGeneralizedTime(\n buf,\n offset\n );\n offset += timeBytes;\n\n // One octet, and only 0 or 1 — `Prepare::decode` answers anything else\n // with `PacketError::InvalidType` rather than coercing it to a truthy\n // value, so a decoder here must refuse the same bytes it would.\n if (offset >= buf.length) {\n throw new Error('Buffer underflow reading PREPARE greeting flag');\n }\n const greetingByte = buf[offset]!;\n if (greetingByte !== 0 && greetingByte !== 1) {\n throw new Error(\n `Malformed PREPARE greeting flag: expected 0x00 or 0x01, got 0x${greetingByte\n .toString(16)\n .padStart(2, '0')}`\n );\n }\n const greeting = greetingByte === 1;\n offset += 1;\n\n const { value: destinationBytes, bytesRead: destBytes } =\n decodeVarOctetString(buf, offset);\n offset += destBytes;\n const destination = textDecoder.decode(destinationBytes);\n\n const { value: data } = decodeVarOctetString(buf, offset);\n\n return {\n type: ILPPacketType.PREPARE,\n amount,\n destination,\n greeting,\n expiresAt,\n data,\n };\n}\n\nexport function deserializeIlpPacket(buf: Uint8Array): ILPResponsePacket {\n if (buf.length === 0) throw new Error('Empty ILP packet');\n const type = buf[0]!;\n if (type === ILPPacketType.FULFILL) return deserializeIlpFulfill(buf);\n if (type === ILPPacketType.REJECT) return deserializeIlpReject(buf);\n throw new Error(`Unknown ILP packet type: ${type}`);\n}\n\nfunction deserializeIlpFulfill(buf: Uint8Array): ILPFulfillPacket {\n let offset = 1; // skip type byte\n // 32-byte fulfillment preimage. Was skipped (\"unused in TOON\") before\n // sender-chosen execution conditions (toon-client#350) made it load-bearing.\n if (buf.length < offset + 32) {\n throw new Error('Buffer underflow reading FULFILL fulfillment');\n }\n const fulfillment = buf.slice(offset, offset + 32);\n offset += 32;\n const { value: data } = decodeVarOctetString(buf, offset);\n return { type: ILPPacketType.FULFILL, fulfillment, data };\n}\n\nfunction deserializeIlpReject(buf: Uint8Array): ILPRejectPacket {\n let offset = 1; // skip type byte\n // 3-byte error code\n const code = sliceUtf8(buf, offset, 3);\n offset += 3;\n // triggeredBy\n const { value: tbBuf, bytesRead: tbBytes } = decodeVarOctetString(\n buf,\n offset\n );\n offset += tbBytes;\n const triggeredBy = textDecoder.decode(tbBuf);\n // message\n const { value: msgBuf, bytesRead: msgBytes } = decodeVarOctetString(\n buf,\n offset\n );\n offset += msgBytes;\n const message = textDecoder.decode(msgBuf);\n // data\n const { value: data } = decodeVarOctetString(buf, offset);\n return { type: ILPPacketType.REJECT, code, triggeredBy, message, data };\n}\n\n/**\n * Encode an outbound FULFILL — the server-role mirror of {@link deserializeIlpPacket}'s\n * FULFILL arm (toon-client#494: answering a connector-originated job PREPARE).\n * Byte-for-byte the same layout `connector-domain::Fulfill::encode` reads.\n *\n * @throws {Error} `fulfillment` is not exactly 32 bytes — silently zero-filling\n * or truncating it would produce a preimage that provably cannot satisfy the\n * PREPARE's execution condition.\n */\nexport function serializeIlpFulfill(packet: {\n fulfillment: Uint8Array;\n data: Uint8Array;\n}): Uint8Array {\n if (packet.fulfillment.length !== 32) {\n throw new Error(\n `FULFILL fulfillment must be exactly 32 bytes, got ${packet.fulfillment.length}`\n );\n }\n return concat(\n writeUint8(ILPPacketType.FULFILL),\n packet.fulfillment,\n encodeVarOctetString(packet.data)\n );\n}\n\n/**\n * Encode an outbound REJECT — the server-role mirror of {@link deserializeIlpPacket}'s\n * REJECT arm. Byte-for-byte the same layout `connector-domain::Reject::encode`\n * reads. `accumulated_cost` is deliberately absent from the wire, matching the\n * Rust struct's own doc: it rides beside the packet, never inside it.\n *\n * @throws {Error} `code` is not exactly 3 ASCII characters (RFC-0027 §3.3).\n */\nexport function serializeIlpReject(packet: {\n code: string;\n triggeredBy?: string;\n message: string;\n data: Uint8Array;\n}): Uint8Array {\n if (!/^[A-Za-z0-9]{3}$/.test(packet.code)) {\n throw new Error(`REJECT code must be exactly 3 ASCII characters, got \"${packet.code}\"`);\n }\n return concat(\n writeUint8(ILPPacketType.REJECT),\n textEncoder.encode(packet.code),\n encodeVarOctetString(textEncoder.encode(packet.triggeredBy ?? '')),\n encodeVarOctetString(textEncoder.encode(packet.message)),\n encodeVarOctetString(packet.data)\n );\n}\n\n// ─── BTP message serialization ──────────────────────────────────────────────\n\n/** `protocolData count` + each entry — the layout every frame type shares. */\nfunction pushProtocolData(parts: Uint8Array[], protocolData: BTPProtocolData[]): void {\n parts.push(writeUint8(protocolData.length));\n for (const pd of protocolData) {\n const nameBytes = textEncoder.encode(pd.protocolName);\n parts.push(writeUint8(nameBytes.length));\n parts.push(nameBytes);\n parts.push(writeUint16BE(pd.contentType));\n parts.push(writeUint32BE(pd.data.length));\n if (pd.data.length > 0) parts.push(pd.data);\n }\n}\n\nfunction readProtocolData(\n buf: Uint8Array,\n offset: number\n): { protocolData: BTPProtocolData[]; offset: number } {\n const pdCount = readUint8(buf, offset);\n offset += 1;\n const protocolData: BTPProtocolData[] = [];\n for (let i = 0; i < pdCount; i++) {\n const nameLen = readUint8(buf, offset);\n offset += 1;\n const protocolName = sliceUtf8(buf, offset, nameLen);\n offset += nameLen;\n const contentType = readUint16BE(buf, offset);\n offset += 2;\n const dataLen = readUint32BE(buf, offset);\n offset += 4;\n const data = buf.slice(offset, offset + dataLen);\n offset += dataLen;\n protocolData.push({ protocolName, contentType, data });\n }\n return { protocolData, offset };\n}\n\nexport function serializeBtpMessage(message: BTPMessage): Uint8Array {\n const parts: Uint8Array[] = [\n writeUint8(message.type),\n writeUint32BE(message.requestId),\n ];\n\n if (message.type === BTPMessageType.ERROR) {\n // code/name/triggeredAt as 1-byte-length-prefixed strings, then the\n // diagnostic text as a u32-length-prefixed trailer — the layout\n // `parseBtpMessage`'s ERROR arm reads, mirroring the connector's own\n // `encode_error`.\n const data = message.data as BTPErrorData;\n for (const field of [data.code, data.name, data.triggeredAt ?? '']) {\n const bytes = textEncoder.encode(field);\n parts.push(writeUint8(bytes.length));\n parts.push(bytes);\n }\n const errorData = data.data ?? textEncoder.encode(data.message ?? '');\n parts.push(writeUint32BE(errorData.length));\n if (errorData.length > 0) parts.push(errorData);\n return concat(...parts);\n }\n\n if (message.type === BTPMessageType.TRANSFER) {\n // RFC-0023 `Transfer ::= SEQUENCE { amount, protocolData }`: amount\n // immediately follows requestId, then protocolData — no ILP trailer.\n const data = message.data as BTPTransferData;\n parts.push(writeUint64BE(data.amount));\n pushProtocolData(parts, data.protocolData ?? []);\n return concat(...parts);\n }\n\n const data = message.data as BTPMessageData;\n pushProtocolData(parts, data.protocolData ?? []);\n\n // ILP packet\n const ilpPacket = data.ilpPacket ?? new Uint8Array(0);\n parts.push(writeUint32BE(ilpPacket.length));\n if (ilpPacket.length > 0) parts.push(ilpPacket);\n\n return concat(...parts);\n}\n\nexport function parseBtpMessage(buf: Uint8Array): BTPMessage {\n if (buf.length < 5) throw new Error('BTP message too short');\n let offset = 0;\n\n const type = readUint8(buf, offset);\n offset += 1;\n const requestId = readUint32BE(buf, offset);\n offset += 4;\n\n if (type === BTPMessageType.ERROR) {\n // code\n const codeLen = readUint8(buf, offset);\n offset += 1;\n const code = sliceUtf8(buf, offset, codeLen);\n offset += codeLen;\n // name\n const nameLen = readUint8(buf, offset);\n offset += 1;\n const name = sliceUtf8(buf, offset, nameLen);\n offset += nameLen;\n // triggeredAt\n const taLen = readUint8(buf, offset);\n offset += 1;\n const triggeredAt = sliceUtf8(buf, offset, taLen);\n offset += taLen;\n // data\n const dataLen = readUint32BE(buf, offset);\n offset += 4;\n const data = buf.slice(offset, offset + dataLen);\n const message = textDecoder.decode(data);\n return {\n type,\n requestId,\n data: { code, name, triggeredAt, message, data },\n };\n }\n\n if (type === BTPMessageType.TRANSFER) {\n // RFC-0023 `Transfer ::= SEQUENCE { amount, protocolData }`: amount\n // precedes protocolData, and there is no ILP-packet trailer to read —\n // unlike MESSAGE/RESPONSE, a TRANSFER carries settlement value, not a\n // routed packet.\n const amount = readUint64BE(buf, offset);\n offset += 8;\n const { protocolData } = readProtocolData(buf, offset);\n return { type, requestId, data: { amount, protocolData } };\n }\n\n // MESSAGE or RESPONSE\n const { protocolData, offset: afterProtocolData } = readProtocolData(\n buf,\n offset\n );\n offset = afterProtocolData;\n\n let ilpPacket: Uint8Array | undefined;\n if (offset + 4 <= buf.length) {\n const ilpLen = readUint32BE(buf, offset);\n offset += 4;\n if (ilpLen > 0 && offset + ilpLen <= buf.length) {\n ilpPacket = buf.slice(offset, offset + ilpLen);\n }\n }\n\n return { type, requestId, data: { protocolData, ilpPacket } };\n}\n","/**\n * Reading a connector's x402 `batch-settlement` offers, and choosing one\n * (connector ADR 0074 decision 8; connector #1345, #1357).\n *\n * A node publishes the same facts twice, as two projections of one list\n * (ND-11):\n *\n * - the greeting's `accepts[]` carries one x402-valid entry per chain — a\n * full x402 `PaymentRequirements`, route price included;\n * - `GET /ilp` carries them under `batchSettlements`, flat and unpriced,\n * because a price belongs to a route and not to a chain.\n *\n * Either one yields a {@link BatchSettlementOffer}: the greeting directly, the\n * self-description through {@link offerFromTerms} once the route's charge is\n * known.\n *\n * An x402 channel is one-way, client to connector, and it is the only way a\n * connector is paid (ADR 0075).\n *\n * These offers are also where the Solana sponsor key comes from: the key\n * `buildSponsoredOpen` insists on must be read off the RECEIVING connector's own\n * document, never taken from a caller.\n */\n\nimport type { BatchSettlementEvmOffer } from './evm.js';\nimport type { BatchSettlementSvmOffer } from './svm.js';\n\n/** A priced offer, on the chain its network names. */\nexport type BatchSettlementOffer =\n | { chain: 'evm'; offer: BatchSettlementEvmOffer }\n | { chain: 'solana'; offer: BatchSettlementSvmOffer };\n\n/** One `batchSettlements` entry of `GET /ilp`: an offer's facts, without a price. */\nexport type BatchSettlementTerms =\n | {\n chain: 'evm';\n network: string;\n asset: string;\n payTo: string;\n extra: BatchSettlementEvmOffer['extra'];\n }\n | {\n chain: 'solana';\n network: string;\n asset: string;\n payTo: string;\n extra: BatchSettlementSvmOffer['extra'];\n };\n\n/**\n * The `maxTimeoutSeconds` a connector puts on every greeting entry\n * (`connector_domain::x402::X402_MAX_TIMEOUT_SECONDS`). It bounds how long a\n * deposit authorization stays valid, so an offer priced from `GET /ilp` carries\n * the same one the greeting would have.\n */\nexport const CONNECTOR_MAX_TIMEOUT_SECONDS = 60;\n\n/**\n * One greeting `accepts[]` entry, when it is a well-formed `batch-settlement`\n * offer on a chain this client pays from; `undefined` for anything else.\n */\nexport function parseBatchSettlementOffer(\n raw: unknown\n): BatchSettlementOffer | undefined {\n const entry = asRecord(raw);\n if (!entry || entry['scheme'] !== 'batch-settlement') return undefined;\n const amount = entry['amount'];\n const maxTimeoutSeconds = entry['maxTimeoutSeconds'];\n if (typeof amount !== 'string' || !/^\\d+$/.test(amount)) return undefined;\n if (!isPositiveInteger(maxTimeoutSeconds)) return undefined;\n\n const terms = parseBatchSettlementTerms({\n ...entry,\n ...(asRecord(entry['extra']) ?? {}),\n });\n return terms && offerFromTerms(terms, BigInt(amount), maxTimeoutSeconds);\n}\n\n/**\n * One `batchSettlements` entry of `GET /ilp`. The chain is the network's CAIP-2\n * namespace; every field that chain's open or deposit needs must be present.\n */\nexport function parseBatchSettlementTerms(\n raw: unknown\n): BatchSettlementTerms | undefined {\n const r = asRecord(raw);\n if (!r) return undefined;\n const network = str(r['network']);\n const asset = str(r['asset']);\n const payTo = str(r['payTo']);\n const withdrawDelay = r['withdrawDelay'];\n if (!network || !asset || !payTo || !isPositiveInteger(withdrawDelay))\n return undefined;\n\n if (network.startsWith('eip155:')) {\n const receiverAuthorizer = str(r['receiverAuthorizer']);\n if (!receiverAuthorizer) return undefined;\n const name = str(r['name']);\n const version = str(r['version']);\n const method = r['assetTransferMethod'];\n // A method this client cannot sign would only fail at deposit time.\n if (method !== undefined && method !== 'eip3009' && method !== 'permit2')\n return undefined;\n const facilitator = httpUrl(r['facilitator']);\n return {\n chain: 'evm',\n network,\n asset,\n payTo,\n extra: {\n receiverAuthorizer,\n withdrawDelay,\n ...(name !== undefined ? { name } : {}),\n ...(version !== undefined ? { version } : {}),\n ...(method !== undefined ? { assetTransferMethod: method } : {}),\n ...(facilitator !== undefined ? { facilitator } : {}),\n },\n };\n }\n\n if (network.startsWith('solana:')) {\n const feePayer = str(r['feePayer']);\n const tokenProgram = str(r['tokenProgram']);\n const sponsorEndpoint = str(r['sponsorEndpoint']);\n const minDeposit = r['minDeposit'];\n if (!feePayer || !tokenProgram || !sponsorEndpoint) return undefined;\n if (typeof minDeposit !== 'string' || !/^\\d+$/.test(minDeposit))\n return undefined;\n return {\n chain: 'solana',\n network,\n asset,\n payTo,\n extra: {\n feePayer,\n withdrawDelay,\n tokenProgram,\n minDeposit,\n sponsorEndpoint,\n },\n };\n }\n\n return undefined;\n}\n\n/** Price `terms` into the offer the greeting would carry for a route charging `amount`. */\nexport function offerFromTerms(\n terms: BatchSettlementTerms,\n amount: bigint,\n maxTimeoutSeconds: number = CONNECTOR_MAX_TIMEOUT_SECONDS\n): BatchSettlementOffer {\n const common = {\n scheme: 'batch-settlement' as const,\n network: terms.network,\n amount: amount.toString(),\n asset: terms.asset,\n payTo: terms.payTo,\n maxTimeoutSeconds,\n };\n return terms.chain === 'evm'\n ? { chain: 'evm', offer: { ...common, extra: { ...terms.extra } } }\n : { chain: 'solana', offer: { ...common, extra: { ...terms.extra } } };\n}\n\n/**\n * The node's `batch-settlement` terms on the chain this client pays from — on\n * `network` when the caller names one — or `undefined` when there are none, in\n * which case the node cannot be paid on that chain.\n */\nexport function chooseBatchSettlement(\n desc: { batchSettlements: BatchSettlementTerms[] },\n chain: 'evm' | 'solana',\n network?: string\n): BatchSettlementTerms | undefined {\n return desc.batchSettlements.find(\n (t) => t.chain === chain && (network === undefined || t.network === network)\n );\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction str(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim().length > 0\n ? value.trim()\n : undefined;\n}\n\nfunction isPositiveInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value > 0;\n}\n\n/** `value` when it is an http(s) URL, else `undefined`. */\nfunction httpUrl(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n try {\n const url = new URL(value);\n return url.protocol === 'https:' || url.protocol === 'http:' ? value : undefined;\n } catch {\n return undefined;\n }\n}\n","/**\n * The x402 \"payment required\" greeting a connector answers an unpaid request\n * to a priced route with (`client-edge-spec.md` §1.4).\n *\n * `POST /ilp` answers `402` with an x402 v2 `PaymentRequired` JSON document —\n * repeated byte-for-byte, base64-encoded, in a `Payment-Required` response\n * header — and the BTP carriage answers the same bytes as a `payment-required`\n * protocolData entry beside an `F06` REJECT. One parser serves both, because\n * the document is identical on either carriage.\n *\n * Since connector ADR 0075 the document is **x402-valid throughout**:\n *\n * - `accepts[]` holds only `batch-settlement` entries, one per chain the\n * node settles on — what a deposit or sponsored open is built from;\n * - TOON's own facts — the destination, the charge, the endpoint, the price —\n * ride in x402 v2's extension slot, `extensions.toon.info`.\n *\n * A reader that finds no `accepts[]` entry must not treat the route as free.\n *\n * Everything here reads defensively: a malformed body yields an empty parse\n * rather than throwing, so a caller can fall back to reporting the plain 402.\n */\n\nimport {\n parseBatchSettlementOffer,\n type BatchSettlementOffer,\n} from '../channel/batch-settlement/offers.js';\nimport type { PaymentTerms } from '../client/types.js';\n\n/**\n * `extensions.toon.info`: TOON's own terms for the greeted request\n * (`connector_domain::x402::X402ToonTerms`), preserved as-is so a field this\n * package does not yet name survives the round trip (issue #506).\n */\nexport interface ToonTermsInfo {\n ilpAddress?: string;\n amount?: string;\n endpoint?: string;\n price?: string;\n pricePerKib?: string;\n ilpAddresses?: string[];\n btpEndpoint?: string;\n requiredTransport?: string;\n /**\n * The connector's session lease TTL in milliseconds\n * (`connector_client_edge::session_registry::SESSION_LEASE_BACKSTOP_TTL`),\n * published so a consumer reads it instead of hardcoding a guess.\n */\n sessionLeaseTtlMs?: number;\n [key: string]: unknown;\n}\n\n/** The greeting's TOON terms, read out of `extensions.toon.info`. */\nexport interface ToonGreeting {\n /** The ILP destination to pay — the connector route fronting the URL. */\n destination: string;\n /** What this request costs, base units. */\n amount: bigint;\n /** The connector's `POST /ilp` URL, resolved against the answering origin. */\n httpEndpoint: string;\n /**\n * The carriage this route requires, when the greeting is the wrong-transport\n * refusal (`client-edge-spec.md` §1.4 \"Transport policy\", issue #701).\n * Present **only** on that refusal, so its presence is the signal.\n */\n requiredTransport?: 'http' | 'btp';\n /** `extensions.toon.info`, preserved verbatim. */\n info: ToonTermsInfo;\n}\n\n/** The parsed x402 402 body. */\nexport interface ParsedX402Challenge {\n x402Version?: number;\n /** TOON's own terms, or `undefined` for a greeting from something that is not a TOON connector. */\n toon?: ToonGreeting;\n /** Every well-formed `batch-settlement` entry of `accepts[]`, one per chain. */\n batchSettlements: BatchSettlementOffer[];\n}\n\n// ─── x402 challenge parsing (defensive) ─────────────────────────────────────\n\n/** First defined string among the given keys on `obj`. */\nfunction readString(obj: Record<string, unknown>, keys: string[]): string | undefined {\n for (const k of keys) {\n const v = obj[k];\n if (typeof v === 'string' && v.trim().length > 0) return v.trim();\n }\n return undefined;\n}\n\n/** A parseable bigint (string | number), or `undefined`. */\nfunction readAmount(value: unknown): bigint | undefined {\n if (typeof value === 'bigint') return value;\n if (typeof value === 'number' && Number.isFinite(value)) return BigInt(Math.trunc(value));\n if (typeof value === 'string' && /^\\d+$/.test(value.trim())) return BigInt(value.trim());\n return undefined;\n}\n\n/**\n * Turn an `endpoint` into something fetchable. The connector publishes a\n * RELATIVE one (`\"/ilp\"`), describing an endpoint on the origin that\n * answered; resolved against that origin it becomes the absolute `POST /ilp`\n * URL. An absolute one is returned unchanged.\n */\nfunction resolveEndpoint(endpoint: string | undefined, baseUrl: string | undefined): string | undefined {\n if (!endpoint || !baseUrl) return endpoint;\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(endpoint)) return endpoint;\n try {\n return new URL(endpoint, baseUrl).toString();\n } catch {\n return endpoint;\n }\n}\n\n/** Parse a 402 `Response` body into a {@link ParsedX402Challenge}. */\nexport async function parseX402Challenge(response: Response): Promise<ParsedX402Challenge> {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n return { batchSettlements: [] };\n }\n // `response.url` is the resource that answered 402 — the base a relative\n // endpoint has to be resolved against.\n return parseX402Body(body, response.url || undefined);\n}\n\n/**\n * Pure parser over an already-decoded x402 body.\n *\n * `baseUrl`, when given, is the absolute URL of the resource that answered\n * `402`; a relative endpoint is resolved against it.\n */\nexport function parseX402Body(body: unknown, baseUrl?: string): ParsedX402Challenge {\n if (typeof body !== 'object' || body === null) return { batchSettlements: [] };\n const b = body as Record<string, unknown>;\n const version = typeof b['x402Version'] === 'number' ? (b['x402Version'] as number) : undefined;\n\n const accepts = Array.isArray(b['accepts']) ? (b['accepts'] as unknown[]) : [];\n const batchSettlements = accepts\n .map(parseBatchSettlementOffer)\n .filter((o): o is BatchSettlementOffer => o !== undefined);\n\n const toon = readToonGreeting(b, baseUrl);\n return {\n ...(version !== undefined ? { x402Version: version } : {}),\n ...(toon !== undefined ? { toon } : {}),\n batchSettlements,\n };\n}\n\n/** `extensions.toon.info`, when it names at least where to pay, how much, and how to reach it. */\nfunction readToonGreeting(\n body: Record<string, unknown>,\n baseUrl: string | undefined\n): ToonGreeting | undefined {\n const extensions = body['extensions'];\n if (typeof extensions !== 'object' || extensions === null) return undefined;\n const toon = (extensions as Record<string, unknown>)['toon'];\n if (typeof toon !== 'object' || toon === null) return undefined;\n const info = (toon as Record<string, unknown>)['info'];\n if (typeof info !== 'object' || info === null) return undefined;\n const record = info as ToonTermsInfo;\n\n const destination = readString(record, ['ilpAddress']);\n const amount = readAmount(record['amount']) ?? readAmount(record['price']);\n const httpEndpoint = resolveEndpoint(readString(record, ['endpoint', 'httpEndpoint']), baseUrl);\n if (destination === undefined || amount === undefined || httpEndpoint === undefined) {\n return undefined;\n }\n const required = readString(record, ['requiredTransport']);\n return {\n destination,\n amount,\n httpEndpoint,\n ...(required === 'http' || required === 'btp' ? { requiredTransport: required } : {}),\n info: record,\n };\n}\n\n/**\n * Project a greeting onto {@link PaymentTerms} — the shape the client surface\n * reports a refusal with.\n *\n * The connector builds this document from the same `NodeFacts` its `GET /ilp`\n * self-description is built from, so the two can never disagree\n * (`self-description-spec.md` ND-11): `batchSettlements` here are the same\n * per-chain terms, priced for this request.\n *\n * `undefined` when the body carries no TOON terms at all — a vanilla x402\n * challenge from something that is not a TOON connector.\n */\nexport function parsePaymentTerms(body: unknown, baseUrl?: string): PaymentTerms | undefined {\n const parsed = parseX402Body(body, baseUrl);\n const toon = parsed.toon;\n if (!toon) return undefined;\n const btpEndpoint = readString(toon.info, ['btpEndpoint']);\n const ttl = toon.info.sessionLeaseTtlMs;\n return {\n destination: toon.destination,\n price: toon.amount,\n httpEndpoint: toon.httpEndpoint,\n ...(btpEndpoint !== undefined ? { btpEndpoint } : {}),\n ...(toon.requiredTransport !== undefined ? { requiredTransport: toon.requiredTransport } : {}),\n batchSettlements: parsed.batchSettlements,\n ...(typeof ttl === 'number' ? { sessionLeaseTtlMs: ttl } : {}),\n raw: body,\n };\n}\n","/**\n * The node self-description: the one document a connector answers `GET` on its\n * own client-edge URL with, and the whole of what a stranger needs in order to\n * transact with it (`self-description-spec.md`, connector ADR 0050).\n *\n * This replaces peer discovery entirely. Earlier versions of this client learned\n * a node's addresses, endpoints, sealing key and settlement facts by subscribing\n * to a relay and reading announcements it published about itself; the Rust\n * connector publishes nothing (ADR 0046 removed the announce, ADR 0022 says a\n * connector *answers*, it never announces). One free, unauthenticated `GET` now\n * carries every fact that mechanism used to scatter:\n *\n * - **`ilpAddresses`** — what to address.\n * - **`httpEndpoint` / `btpEndpoint`** — where to reach it, and how.\n * - **`edgeIdentity`** — the key a packet's payload is sealed to. Without it a\n * packet cannot be delivered at all (ND-06).\n * - **`batchSettlements`** — per chain, the x402 `batch-settlement` terms a\n * channel is opened and paid on (connector ADR 0074, 0075). Each was *proved\n * against a live chain* when the node booted (ND-07), which is why this is\n * the source for opening a channel rather than any preset this package ships.\n * - **`voucherSigners`** — per chain, the node's own voucher signer (ADR 0075\n * decision 10).\n * - **`routes`** — what each route costs.\n * - **`requiredTransport`** — when every route agrees on one carriage.\n *\n * Absent means absent: a field the node has nothing to say about is **omitted**,\n * never `null` and never an empty string, and `peerCarriages` is the sole field\n * always written even when empty (\"this node exposes no peer carriage\" is an\n * answer). The parser below preserves that distinction rather than substituting\n * defaults, because a substituted default is indistinguishable from a fact.\n */\nimport {\n parseBatchSettlementTerms,\n type BatchSettlementTerms,\n} from '../channel/batch-settlement/offers.js';\n\n/**\n * One chain's voucher signer, as `GET /ilp` publishes it (ADR 0075 decision\n * 10): the node's settlement address on EVM, its `authorized_signer` on\n * Solana — the key its own vouchers are signed with, and what a peer binds an\n * inbound channel by. A client paying the node never needs it; it is read so a\n * caller can see it.\n */\nexport interface VoucherSigner {\n /** CAIP-2. */\n network: string;\n signer: string;\n}\n\n/** The key a packet's payload is sealed to (ADR 0018). */\nexport interface EdgeIdentity {\n /** Opaque key id identifying which key this is. */\n keyId: string;\n /** Uncompressed secp256k1 public key, `0x04…`, exactly as published. */\n publicKey: string;\n}\n\n/**\n * What a route charges, independent of which endpoint reported it.\n *\n * Both `GET /ilp` (per entry in `routes`) and `GET /ilp/routes/price` answer\n * these two figures, so {@link chargeFor} takes this shape rather than either\n * concrete type.\n */\nexport interface RouteCharge {\n /**\n * The base price per packet, in the settlement asset's base units.\n *\n * A `bigint` here, though the wire carries a decimal **string** — deliberately\n * so, because a price past 2^53 is a real amount and a JSON number would round\n * it. (`GET /ilp/routes/price` answers the same figure as a JSON *number*;\n * that inconsistency is the connector's, and both are normalized to `bigint`\n * by this client.)\n *\n * This is the *base*, not the total: a route that also publishes\n * {@link RouteCharge.pricePerKib} charges more than this for every packet.\n * {@link chargeFor} is the only thing that should decide what to put on a\n * claim.\n */\n price: bigint;\n /**\n * Added per kibibyte of sealed payload, when the route meters by size.\n *\n * Absent on a flat-priced route, which is most of them. Published as\n * `pricePerKib` on `GET /ilp` and as `price_per_kib` on\n * `GET /ilp/routes/price` — the same inconsistency the price itself has.\n */\n pricePerKib?: bigint;\n}\n\n/** One route the node serves, and what it costs. */\nexport interface RoutePrice extends RouteCharge {\n /** The ILP address prefix. Longest matching prefix wins. */\n prefix: string;\n /**\n * The carriage a request to **this** prefix must arrive on, when the route\n * pins one (connector ND-05a / ADR 0072, TOON_Network#111).\n *\n * Absent — never `'both'` — on a route that accepts either, which is every\n * route no operator pinned.\n *\n * This is what makes `auto` work against a node whose routes disagree, and\n * the devnet relay is one: `g.toon.relay` is pinned to BTP,\n * `g.toon.relay.ephemeral` is not, so\n * {@link NodeSelfDescription.requiredTransport} has no honest answer and says\n * nothing while the pin is enforced on every packet.\n * {@link requiredTransportFor} reads this first and that field only as a\n * fallback.\n */\n requiredTransport?: RequiredTransport;\n}\n\n/** How many bytes one step of `pricePerKib` buys — a kibibyte, as the name says. */\nconst BYTES_PER_KIB = 1024n;\n\n/**\n * What one packet actually costs on `terms`, given the size of its **sealed**\n * payload.\n *\n * The metered quantity is the gift-wrapped payload the PREPARE carries — the\n * bytes of `SealedExchange.data`, not the caller's request body, which is\n * smaller by the envelope and the wrap. So a charge can only be computed after\n * sealing, which is why {@link ../client/send.js!send} seals before it prices.\n * Those bytes are the PREPARE's `data` field verbatim on both carriages\n * (`HttpIlpClient.postPrepare`, `BtpRuntimeClient`), so `sealedBytes` is exactly\n * the `prepare.data.len()` the connector prices — no envelope, header or framing\n * sits between the two counts.\n *\n * The unit count is `ceil(bytes / 1024)`: whole kibibytes plus one for any\n * remainder, and **zero** for an empty payload, which pays the base alone. That\n * is the connector's own `Price::charge`\n * (`connector-domain/src/price.rs`, `bytes.div_ceil(1024)`, connector ADR 0065),\n * evaluated there against the same `prepare.data.len()` at every gate that\n * charges — the client edge, the peer price gate, and the termination.\n *\n * Measured against the deployed store node at `1000 + 10/KiB`, whose x402\n * greeting quotes the charge for the packet it was handed:\n * 0 bytes → 1000, 1 → 1010, 1023 → 1010, **1024 → 1010**, 1025 → 1020,\n * **2048 → 1020**, 2049 → 1030, 5161 → 1060.\n *\n * This used to compute `floor(bytes / 1024) + 1` (toon-client#629), which agrees\n * with `ceil` everywhere except an exact multiple of 1024 and an empty payload,\n * where it charged one kibibyte too many. Every size that had actually been\n * measured was a non-multiple, so the fit held and the overpay — silent, since a\n * claim that advances more than the price is simply accepted — went unnoticed.\n *\n * The charge saturates at `u64::MAX`, as the connector's does (the `charge`\n * vectors' `saturating_*` cases): an amount past it is one no claim can carry.\n */\nexport function chargeFor(terms: RouteCharge, sealedBytes: number): bigint {\n const perKib = terms.pricePerKib;\n if (perKib === undefined || perKib === 0n) return saturateU64(terms.price);\n const bytes = BigInt(Math.max(0, Math.trunc(sealedBytes)));\n const units = (bytes + BYTES_PER_KIB - 1n) / BYTES_PER_KIB;\n return saturateU64(terms.price + perKib * units);\n}\n\nconst U64_MAX = 2n ** 64n - 1n;\n\nfunction saturateU64(amount: bigint): bigint {\n return amount > U64_MAX ? U64_MAX : amount;\n}\n\n/** Which carriage a route insists on, when its routes agree on one. */\nexport type RequiredTransport = 'http' | 'btp';\n\n/**\n * A connector's answer to `GET /ilp`.\n *\n * Every optional field below is optional *on the wire*: its absence is a fact\n * about the node, not a parse failure.\n */\nexport interface NodeSelfDescription {\n /** The addresses this node answers to. Self-asserted — nothing allocates one. */\n ilpAddresses: string[];\n /** The `POST /ilp` URL, when the node publishes one. */\n httpEndpoint?: string;\n /** The `GET /ilp/btp` websocket URL, when the node publishes one. */\n btpEndpoint?: string;\n /** Which peer carriages the node exposes: `btp`, `http`. Always present, possibly empty. */\n peerCarriages: string[];\n /** The sealing key. Absent only from a node whose signer is broken. */\n edgeIdentity?: EdgeIdentity;\n /**\n * The x402 `batch-settlement` terms, one per chain the node has opted in to\n * (connector ADR 0074 decision 8). Empty when it has opted in to none —\n * which is every node that does not say otherwise.\n */\n batchSettlements: BatchSettlementTerms[];\n /** Per chain, the node's own voucher signer. Empty when it publishes none. */\n voucherSigners: VoucherSigner[];\n /** The node's routes and their prices. Absent — not empty — when it serves none. */\n routes: RoutePrice[];\n /** Set only when every route that covers this node's own addresses agrees on one carriage. */\n requiredTransport?: RequiredTransport;\n /** Client-edge versions this node serves. `[1]` today. */\n supportedVersions: number[];\n /** The version unversioned `POST /ilp` resolves to. Always `1` — the path is a permanent alias. */\n defaultVersion: number;\n /**\n * The normalized client-edge base URL this document was read from, when the\n * reader knew it.\n *\n * Not a field on the wire — the node cannot know the URL a client reached it\n * by. It is recorded because `httpEndpoint`/`btpEndpoint` are configured\n * strings a node MAY publish relative (the x402 greeting's sibling field is\n * literally `\"/ilp\"`), and a relative endpoint is only resolvable against the\n * origin that answered. {@link ../btp/transport-select.js}'s `selectTransport`\n * uses it for exactly that.\n */\n readFrom?: string;\n /** The document exactly as received, for facts this client does not yet name. */\n raw: unknown;\n}\n\n/** First defined non-empty string among `keys` on `obj`. */\nfunction readString(obj: Record<string, unknown>, key: string): string | undefined {\n const v = obj[key];\n return typeof v === 'string' && v.trim().length > 0 ? v.trim() : undefined;\n}\n\n/**\n * A `requiredTransport` value, on a route entry or on the document itself.\n *\n * One reader for both, so the two can never be understood by different rules.\n * Anything that is not one of the two spellings — including `'both'`, which the\n * connector omits rather than emits — reads as \"no requirement\": a carriage this\n * client cannot dial is not a carriage it should try to guess at.\n */\nfunction readRequiredTransport(value: unknown): RequiredTransport | undefined {\n return value === 'http' || value === 'btp' ? value : undefined;\n}\n\n/** Parse a decimal-string | number amount to bigint; `undefined` when unusable. */\nexport function readBaseUnits(value: unknown): bigint | undefined {\n if (typeof value === 'bigint') return value;\n if (typeof value === 'number' && Number.isFinite(value)) return BigInt(Math.trunc(value));\n if (typeof value === 'string' && /^\\d+$/.test(value.trim())) return BigInt(value.trim());\n return undefined;\n}\n\n/**\n * Parse a `GET /ilp` body.\n *\n * Never throws on a shape it does not recognise: an unreadable field is dropped\n * and the rest of the document survives, because a client that refuses to read a\n * node's price list over one unexpected key is a client that cannot be deployed\n * ahead of a connector release.\n */\nexport function parseSelfDescription(\n body: unknown,\n readFrom?: string\n): NodeSelfDescription {\n const b = (typeof body === 'object' && body !== null ? body : {}) as Record<string, unknown>;\n\n const ilpAddresses = Array.isArray(b['ilpAddresses'])\n ? (b['ilpAddresses'] as unknown[]).filter((a): a is string => typeof a === 'string')\n : [];\n const peerCarriages = Array.isArray(b['peerCarriages'])\n ? (b['peerCarriages'] as unknown[]).filter((a): a is string => typeof a === 'string')\n : [];\n\n const rawIdentity = b['edgeIdentity'];\n let edgeIdentity: EdgeIdentity | undefined;\n if (typeof rawIdentity === 'object' && rawIdentity !== null) {\n const id = rawIdentity as Record<string, unknown>;\n const keyId = readString(id, 'keyId');\n const publicKey = readString(id, 'publicKey');\n if (publicKey !== undefined) edgeIdentity = { keyId: keyId ?? '', publicKey };\n }\n\n\n const batchSettlements = Array.isArray(b['batchSettlements'])\n ? (b['batchSettlements'] as unknown[])\n .map(parseBatchSettlementTerms)\n .filter((t): t is BatchSettlementTerms => t !== undefined)\n : [];\n\n const voucherSigners = Array.isArray(b['voucherSigners'])\n ? (b['voucherSigners'] as unknown[]).flatMap((raw): VoucherSigner[] => {\n if (typeof raw !== 'object' || raw === null) return [];\n const r = raw as Record<string, unknown>;\n const network = readString(r, 'network');\n const signer = readString(r, 'signer');\n return network !== undefined && signer !== undefined ? [{ network, signer }] : [];\n })\n : [];\n\n const routes = Array.isArray(b['routes'])\n ? (b['routes'] as unknown[])\n .map((raw): RoutePrice | undefined => {\n if (typeof raw !== 'object' || raw === null) return undefined;\n const r = raw as Record<string, unknown>;\n const prefix = readString(r, 'prefix');\n const price = readBaseUnits(r['price']);\n if (prefix === undefined || price === undefined) return undefined;\n // `pricePerKib` here, `price_per_kib` on GET /ilp/routes/price. Both\n // are read so neither endpoint silently under-quotes a metered route.\n const pricePerKib = readBaseUnits(r['pricePerKib'] ?? r['price_per_kib']);\n // The carriage this prefix pins (ND-05a). A value that is neither\n // spelling is dropped rather than carried: an unrecognised carriage\n // is one this client cannot dial, and guessing would send the packet\n // somewhere the route refuses.\n const routeTransport = readRequiredTransport(r['requiredTransport']);\n return {\n prefix,\n price,\n ...(pricePerKib !== undefined ? { pricePerKib } : {}),\n ...(routeTransport !== undefined ? { requiredTransport: routeTransport } : {}),\n };\n })\n .filter((r): r is RoutePrice => r !== undefined)\n : [];\n\n const requiredTransport = readRequiredTransport(b['requiredTransport']);\n\n const supportedVersions = Array.isArray(b['supportedVersions'])\n ? (b['supportedVersions'] as unknown[]).filter((v): v is number => typeof v === 'number')\n : [1];\n const defaultVersion = typeof b['defaultVersion'] === 'number' ? (b['defaultVersion'] as number) : 1;\n\n const httpEndpoint = readString(b, 'httpEndpoint');\n const btpEndpoint = readString(b, 'btpEndpoint');\n\n return {\n ilpAddresses,\n ...(httpEndpoint !== undefined ? { httpEndpoint } : {}),\n ...(btpEndpoint !== undefined ? { btpEndpoint } : {}),\n peerCarriages,\n ...(edgeIdentity !== undefined ? { edgeIdentity } : {}),\n batchSettlements,\n voucherSigners,\n routes,\n ...(requiredTransport !== undefined ? { requiredTransport } : {}),\n supportedVersions,\n defaultVersion,\n ...(readFrom !== undefined ? { readFrom } : {}),\n raw: body,\n };\n}\n\n/**\n * Where a packet goes when the caller named a node but not a route.\n *\n * A client is configured with a **URL** — the thing a person actually has — and\n * the node's own document says what to address it as. So there is no reason to\n * make a caller repeat a route string they just read off `GET /ilp`, and every\n * reason not to: a hand-copied destination is how you end up paying a node for a\n * route it does not serve.\n *\n * The first of `ilpAddresses` this node also PRICES wins. A node lists its own\n * addresses primary-first, but an address it serves without pricing cannot be\n * paid for, so pricing is the tie-break rather than order alone — and when none\n * of them is priced the first is still returned, because being refused with the\n * route's terms is a better answer than refusing to form a packet at all.\n *\n * `undefined` only when the node claims no address, which is a broken node.\n */\nexport function defaultDestinationFor(desc: NodeSelfDescription): string | undefined {\n const priced = desc.ilpAddresses.find((address) => routeFor(desc, address) !== undefined);\n return priced ?? desc.ilpAddresses[0];\n}\n\n/**\n * The price of the longest configured prefix that governs `destination`, or\n * `undefined` when this document lists no route that does.\n *\n * Matching is the connector's own rule: a prefix governs a destination when the\n * destination is the prefix, or continues it at a label boundary — so\n * `g.example.app` governs `g.example.app.sub` but never `g.example.appendix`.\n */\nexport function routePriceFor(desc: NodeSelfDescription, destination: string): bigint | undefined {\n return routeFor(desc, destination)?.price;\n}\n\n/**\n * The whole matching route rather than just its base price, so a caller can see\n * a `pricePerKib` that {@link routePriceFor} necessarily hides.\n *\n * Same longest-prefix rule; {@link routePriceFor} is this with `.price` on the\n * end, kept because a flat-priced route is still the common case.\n */\nexport function routeFor(\n desc: NodeSelfDescription,\n destination: string\n): RoutePrice | undefined {\n let best: RoutePrice | undefined;\n for (const route of desc.routes) {\n if (destination !== route.prefix && !destination.startsWith(`${route.prefix}.`)) continue;\n if (best === undefined || route.prefix.length > best.prefix.length) best = route;\n }\n return best;\n}\n\n/**\n * Which carriage a packet to `destination` has to ride, as this node states it.\n *\n * The route that governs `destination` is asked first; the node-wide field\n * answers only where that route names no carriage of its own. That order is the\n * connector's (ND-05b) and it is not a preference: the refusal is decided by\n * the longest-prefix route lookup, once per packet, so the route's own answer\n * is the one that will actually be enforced. The node-wide field is a summary\n * of the routes covering the node's own addresses, and says nothing at all when\n * those disagree — the state the devnet relay has been in while pinning\n * `g.toon.relay` to BTP (TOON_Network#111).\n *\n * The fallback also keeps a node that predates the per-route field working\n * unchanged: every route entry there names nothing, so the node-wide field is\n * read exactly as it was. It cannot mislead in the other direction either — a\n * route that accepts either carriage is reachable over the one the summary\n * names.\n *\n * With no `destination`, only the node-wide field can be answered, which is\n * what a caller asking about the node rather than a packet wants.\n *\n * `undefined` means **no requirement stated**, not \"HTTP\": a node that pins\n * nothing is left exactly as it was, free to be dialled on whichever carriage\n * it publishes.\n */\nexport function requiredTransportFor(\n desc: NodeSelfDescription,\n destination?: string\n): RequiredTransport | undefined {\n const route = destination !== undefined ? routeFor(desc, destination) : undefined;\n return route?.requiredTransport ?? desc.requiredTransport;\n}\n","/**\n * Isomorphic binary helpers — works in both Node.js and browser\n * without requiring Buffer polyfills.\n *\n * These replace Buffer usage throughout the client package so that\n * browser consumers (e.g. ditto) don't need the `buffer` npm polyfill.\n */\n\n/** Convert a Uint8Array to a base64 string (browser + Node compatible). */\nexport function toBase64(bytes: Uint8Array): string {\n // Node.js Buffer is a Uint8Array subclass and has toString('base64')\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(bytes)) {\n return (bytes as Buffer).toString('base64');\n }\n // Browser path: use btoa with binary string\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary);\n}\n\n/** Convert a base64 string to a Uint8Array (browser + Node compatible). */\nexport function fromBase64(base64: string): Uint8Array {\n if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {\n return new Uint8Array(Buffer.from(base64, 'base64'));\n }\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/** Convert a Uint8Array to a hex string. */\nexport function toHex(bytes: Uint8Array): string {\n let hex = '';\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/** Convert a hex string to a Uint8Array. */\nexport function fromHex(hex: string): Uint8Array {\n const clean = hex.startsWith('0x') ? hex.slice(2) : hex;\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/** Convert a UTF-8 string to Uint8Array. */\nexport function encodeUtf8(str: string): Uint8Array {\n return new TextEncoder().encode(str);\n}\n\n/** Convert a Uint8Array to a UTF-8 string. */\nexport function decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Check if a string is valid base64. */\nexport function isBase64(str: string): boolean {\n return /^[A-Za-z0-9+/]*={0,2}$/.test(str);\n}\n","/**\n * The sender's end-to-end delivery check (connector ADR 0069).\n *\n * Until issue #1269 a sender minted a random preimage, put `sha256(preimage)`\n * on the PREPARE as its `executionCondition`, and checked a returned\n * fulfilment by hashing it back to that value. ADR 0069 removes the condition\n * from the wire entirely: no hop carries one, no hop reads one, and no hop\n * verifies one. What survives is the check that was always the only one worth\n * anything — the SENDER comparing what came back against the fulfilment it can\n * derive itself.\n *\n * That derivation is `deriveFulfillment(sharedSecret)` in `wire/giftwrap.ts`\n * (ADR 0019): the terminating connector recovers the same secret by opening\n * the gift wrap and derives the same 32 bytes, so an honest FULFILL carries\n * exactly them. No intermediate hop can, because no intermediate hop can open\n * the wrap.\n *\n * There is no hashing left in either direction here, and deliberately no\n * `condition` vocabulary: a comparison of two locally-known 32-byte values is\n * the whole relation.\n *\n * Isomorphic: no Buffer, no node:crypto.\n */\n\n/** Exact byte length of an ILP fulfilment preimage. */\nexport const FULFILLMENT_LENGTH = 32;\n\n/**\n * True iff `returned` is exactly the 32 bytes the sender expected.\n *\n * Fail-closed: an absent, short or long fulfilment never matches. Plain\n * comparison is fine — both operands are values the sender already holds, and\n * a forger who could produce the expected bytes would already have the secret\n * that derives them, so there is no secret here for a timing side channel to\n * leak.\n */\nexport function fulfillmentMatches(\n returned: Uint8Array | undefined,\n expected: Uint8Array\n): boolean {\n if (returned === undefined || returned.length !== FULFILLMENT_LENGTH) {\n return false;\n }\n if (expected.length !== FULFILLMENT_LENGTH) return false;\n for (let i = 0; i < FULFILLMENT_LENGTH; i++) {\n if (returned[i] !== expected[i]) return false;\n }\n return true;\n}\n\n/**\n * Validate a caller-supplied expected fulfilment before a packet goes out.\n *\n * @throws {Error} when it is not exactly 32 bytes — a wrong-length value can\n * never match a real FULFILL, so every delivery would be counted failed and\n * every paid packet thrown away. Failing here says why.\n */\nexport function assertValidFulfillment(fulfillment: Uint8Array): void {\n if (fulfillment.length !== FULFILLMENT_LENGTH) {\n throw new Error(\n `an expected fulfillment must be exactly ${FULFILLMENT_LENGTH} bytes, got ${fulfillment.length}`\n );\n }\n}\n","/**\n * Shared sender-side plumbing for both ILP carriages: how a PREPARE's\n * non-routing fields are resolved, and how the answer is read.\n *\n * Connector ADR 0069 (issue #1269) removed the execution condition from the\n * wire. Two things changed here and nothing else did:\n *\n * - the PREPARE carries a one-byte `greeting` flag where a 32-byte\n * condition used to sit — see {@link IlpSendParams.greeting};\n * - the sender's delivery check compares a FULFILL's preimage directly\n * against the fulfilment its own sealed secret derives\n * ({@link IlpSendParams.expectedFulfillment}), rather than hashing it back\n * to a condition that no longer exists.\n *\n * Both transports (HTTP `POST /ilp` and BTP) take the SAME params and map\n * FULFILL/REJECT through the SAME verifier, so the two paths cannot drift.\n * Omitting `expectedFulfillment` keeps a FULFILL unverified — the right shape\n * for a caller that never sealed anything and so has nothing to compare\n * against.\n */\n\nimport type { IlpSendResult } from './types.js';\nimport { ILPPacketType, type ILPResponsePacket } from '../btp/protocol.js';\nimport { fromBase64, toBase64 } from '../utils/binary.js';\nimport { fulfillmentMatches } from '../utils/fulfillment.js';\n\n/**\n * Send parameters accepted by both ILP transports.\n */\nexport interface IlpSendParams {\n destination: string;\n amount: string;\n /** Base64 ILP `data` payload. */\n data: string;\n /** Transport timeout in ms; also the default expiry window. */\n timeout?: number;\n /**\n * Declare this PREPARE a bootstrap/greeting probe (connector ADR 0069).\n *\n * Defaults to `false`, which is what every real send wants: a greeting is\n * never routed, never priced and never fulfilled — the connector answers\n * the x402 terms instead. Set it only to ASK for those terms without a\n * route match, the shape `ConnectorEdgeClient` uses for bootstrap. A claim\n * riding with the packet suppresses the greeting either way, so this can\n * never turn a paid packet into a free one.\n */\n greeting?: boolean;\n /**\n * The 32 bytes an honest FULFILL must carry: `deriveFulfillment(sharedSecret)`\n * for the secret sealed inside this packet's gift wrap (ADR 0019), which\n * `sealExchange` returns as `SealedExchange.fulfillment`.\n *\n * Present = verify; absent = accept a FULFILL unchecked, which is the only\n * honest option for a caller that sealed nothing and therefore knows no\n * secret. This is the sender's own end-to-end check and the ONLY fulfilment\n * check left anywhere on the path (ADR 0069) — no hop performs one.\n *\n * Accepts the raw 32 bytes or their base64 encoding; normalize with\n * {@link resolveExpectedFulfillment} before touching the bytes.\n */\n expectedFulfillment?: Uint8Array | string;\n /**\n * Explicit PREPARE `expiresAt`. Defaults to `now + timeout` plus\n * {@link PACKET_EXPIRY_HEADROOM_MS}. Accepts a `Date` or an ISO 8601 string.\n */\n expiresAt?: Date | string;\n}\n\n/**\n * Normalize an `IlpSendParams.expectedFulfillment` to raw bytes.\n *\n * The two representations are the two callers: this package's own senders\n * pass the bytes `sealExchange` derived, while a caller typed against the\n * JSON-shaped port passes their base64 spelling. Both mean the same 32 bytes.\n *\n * Length is NOT validated here — that stays with `assertValidFulfillment` at\n * the transports, so a malformed value fails with the same message on both\n * paths regardless of which representation it arrived in.\n */\nexport function resolveExpectedFulfillment(\n fulfillment: Uint8Array | string | undefined\n): Uint8Array | undefined {\n if (fulfillment === undefined) return undefined;\n return typeof fulfillment === 'string' ? fromBase64(fulfillment) : fulfillment;\n}\n\n/**\n * How much longer a packet lives on the wire than the sender is prepared to wait.\n *\n * The packet's expiry and the sender's own abort used to be the same number, and\n * on clearnet nothing showed: both are far longer than a round trip. They are not\n * the same thing, though, and over a slow carriage the difference is money. If a\n * PREPARE expires at the instant the client gives up, then a late answer arrives\n * to a client that has already stopped listening, having *already presented a\n * signed claim* — the packet is paid for and the verdict is lost. Worse, the\n * expiry is stamped when the packet is built, which over a hidden service is\n * before the circuit even exists, so seconds of it are spent before the connector\n * has seen a byte.\n *\n * Giving the wire the longer deadline means the client is always the first of the\n * two to give up: whatever the client stops waiting for is still, briefly, a live\n * packet the connector can answer and this client can reconcile — never one that\n * expired underneath a claim.\n */\nexport const PACKET_EXPIRY_HEADROOM_MS = 15_000;\n\n/**\n * Normalize an `IlpSendParams.expiresAt` to a `Date`.\n *\n * Default: now + timeout + {@link PACKET_EXPIRY_HEADROOM_MS}. An explicit\n * `expiresAt` is honoured exactly as given — a caller who names a deadline has\n * one, and it is not this function's business to extend it.\n */\nexport function resolveExpiresAt(\n expiresAt: Date | string | undefined,\n timeoutMs: number\n): Date {\n if (expiresAt === undefined) return new Date(Date.now() + timeoutMs + PACKET_EXPIRY_HEADROOM_MS);\n return expiresAt instanceof Date ? new Date(expiresAt.getTime()) : new Date(expiresAt);\n}\n\n/**\n * `IlpSendResult` plus the FULFILL preimage, populated only when the sender\n * knew what to expect and the bytes matched.\n */\nexport interface IlpSendResultWithFulfillment extends IlpSendResult {\n /** Base64 32-byte fulfillment preimage (verified against the expected one). */\n fulfillment?: string;\n}\n\n/** ILP code used for a client-side fulfillment-verification failure. */\nexport const FULFILLMENT_MISMATCH_CODE = 'F99';\n\n/** Message for a client-side fulfillment-verification failure. */\nexport const FULFILLMENT_MISMATCH_MESSAGE =\n 'FULFILL fulfillment is not the one this packet\\'s sealed secret derives ' +\n '(ADR 0019) — packet counted failed';\n\n/**\n * Map a parsed ILP response packet to an `IlpSendResult`, enforcing the\n * sender's end-to-end delivery check when it knows what to expect.\n *\n * Verification is fail-closed: when `expectedFulfillment` is given, a FULFILL\n * whose preimage is absent, not exactly 32 bytes, or simply different yields\n * `accepted: false` (code F99). The result shape — not a thrown error — is\n * deliberate: transports only retry thrown `NetworkError`s, so a forged or\n * wrong FULFILL is never retried, because re-sending would re-spend the\n * attached claim.\n *\n * Since ADR 0069 this is the only fulfilment check anywhere on the path. A\n * candidate FULFILL rides home through every hop unexamined, which is exactly\n * why the sender must still make it.\n */\nexport function mapIlpResponse(\n packet: ILPResponsePacket,\n expectedFulfillment?: Uint8Array\n): IlpSendResultWithFulfillment {\n if (packet.type === ILPPacketType.FULFILL) {\n const dataField =\n packet.data.length > 0 ? { data: toBase64(packet.data) } : {};\n\n // Nothing to compare against: a caller that sealed no request holds no\n // secret and can derive no fulfilment, so there is no check to make.\n if (expectedFulfillment === undefined) {\n return { accepted: true, ...dataField };\n }\n\n if (!fulfillmentMatches(packet.fulfillment, expectedFulfillment)) {\n return {\n accepted: false,\n code: FULFILLMENT_MISMATCH_CODE,\n message: FULFILLMENT_MISMATCH_MESSAGE,\n ...dataField,\n };\n }\n\n return {\n accepted: true,\n fulfillment: toBase64(packet.fulfillment),\n ...dataField,\n };\n }\n\n // REJECT\n return {\n accepted: false,\n code: packet.code,\n message: packet.message,\n ...(packet.data.length > 0 ? { data: toBase64(packet.data) } : {}),\n };\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion -- ws is guaranteed non-null when _isConnected */\n/**\n * Isomorphic BTP client — works in both browser and Node.js.\n * Uses native WebSocket (browser) or globalThis.WebSocket (Node 21+).\n * No dependency on `ws`, `events`, or `Buffer`.\n *\n * Replaces the @toon-protocol/connector BTPClient for the client SDK.\n */\n\nimport {\n BTPMessageType,\n serializeBtpMessage,\n serializeIlpPrepare,\n parseBtpMessage,\n deserializeIlpPacket,\n type BTPProtocolData,\n type BTPMessageData,\n type BTPTransferData,\n type BTPErrorData,\n type ILPPreparePacket,\n type ILPResponsePacket,\n} from './protocol.js';\n\nconst textEncoder = new TextEncoder();\n\n/** A server-originated MESSAGE (RFC-0023 symmetric grammar, toon-client#493). */\nexport interface InboundBtpMessage {\n requestId: number;\n protocolData: BTPProtocolData[];\n ilpPacket?: Uint8Array;\n}\n\n/** A server-originated TRANSFER — settlement value, never an ILP packet. */\nexport interface InboundBtpTransfer {\n requestId: number;\n amount: bigint;\n protocolData: BTPProtocolData[];\n}\n\n/**\n * The client's x402 channel, declared on the BTP auth frame as its\n * `channelChallenge` (connector ADR 0075, issue #1384; the vectors'\n * `client_auth_channel_challenge`), which binds the session to the channel\n * before it has presented a voucher.\n *\n * It is the voucher claim-state challenge (`channel/batch-settlement/\n * challenge.ts`) — the same object `POST /ilp/claim-state` takes — and never a\n * voucher, so it can never be replayed as a payment. It replaces the retired\n * `auth_channel_proof`, which a connector now refuses by name.\n */\nexport type BtpChannelDeclaration = Record<string, unknown>;\n\n/**\n * The BTP `auth` entry's JSON, in the vectors' key order: `channelChallenge`\n * when the client declares a channel, then `peerId` and `secret`.\n */\nexport function btpAuthEntry(\n peerId: string,\n secret: string,\n channelChallenge: BtpChannelDeclaration | undefined\n): string {\n return JSON.stringify({\n ...(channelChallenge !== undefined ? { channelChallenge } : {}),\n peerId,\n secret,\n });\n}\n\n/** What an inbound handler answers with — becomes the RESPONSE frame's body. */\nexport interface BtpHandlerResponse {\n protocolData?: BTPProtocolData[];\n ilpPacket?: Uint8Array;\n}\n\nexport type BtpMessageHandler = (\n message: InboundBtpMessage\n) => Promise<BtpHandlerResponse> | BtpHandlerResponse;\n\nexport type BtpTransferHandler = (\n transfer: InboundBtpTransfer\n) => Promise<BtpHandlerResponse> | BtpHandlerResponse;\n\nexport interface IsomorphicBtpClientConfig {\n url: string;\n peerId: string;\n authToken: string;\n sendTimeoutMs?: number;\n authTimeoutMs?: number;\n /** Custom WebSocket constructor (e.g., the Node `ws` package, or for testing). */\n createWebSocket?: (url: string) => WebSocket;\n /**\n * Handles a server-originated MESSAGE. Unset: an inbound MESSAGE is\n * dropped unanswered, matching the pre-#493 dialect (the server never\n * originated one).\n */\n onMessage?: BtpMessageHandler;\n /**\n * Handles a server-originated TRANSFER. Unset: every inbound TRANSFER\n * still gets an empty RESPONSE ack — RFC-0023 requires every request be\n * answered, and this mirrors the connector's own default (`btp.rs`:\n * received, not yet accounted).\n */\n onTransfer?: BtpTransferHandler;\n /**\n * Called when in-flight inbound work (a MESSAGE/TRANSFER handler that had\n * not yet replied) is orphaned by a disconnect, instead of silently\n * vanishing.\n */\n onInboundError?: (error: Error, requestId: number) => void;\n /**\n * Called every time the auth greeting is (re-)sent — initial `connect()`\n * and every explicit {@link IsomorphicBtpClient.reauthenticate}. Returns\n * the caller's current channel to declare, or `undefined` when none is\n * known yet. Additive: unset (or an `undefined` result) sends the\n * greeting exactly as it was before this hook existed (toon-client#513).\n */\n getChannelDeclaration?: () =>\n | Promise<BtpChannelDeclaration | undefined>\n | BtpChannelDeclaration\n | undefined;\n}\n\n/**\n * A RESPONSE to a packet this client sent: the answer packet, and everything\n * that rode BESIDE it in the same frame.\n *\n * The protocolData list is returned rather than discarded because the facts\n * that matter most about a refusal do not travel inside the OER packet at all:\n * `toon-accumulated-cost` (what the path cost — on an underpayment, the route's\n * price) and `payment-required` (the x402 terms on an `F06`/`F02` greeting)\n * ride as protocolData entries on the RESPONSE, exactly as their HTTP twins\n * ride as response headers (`client-edge-spec.md` §1.6, §1.9 steps 2–4). A\n * client that resolved only `ilpPacket` — as this one did before 1.0 — threw\n * them away and then had to guess a price by underpaying, which is precisely\n * what cost discovery exists to prevent.\n */\nexport interface BtpPacketResponse {\n /** The FULFILL or REJECT the connector answered with. */\n packet: ILPResponsePacket;\n /** Every protocolData entry on the same RESPONSE frame, in arrival order. */\n protocolData: BTPProtocolData[];\n}\n\ninterface PendingRequest {\n resolve: (response: BtpPacketResponse) => void;\n reject: (error: Error) => void;\n timeoutId: ReturnType<typeof setTimeout>;\n}\n\nexport class BtpConnectionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BtpConnectionError';\n }\n}\n\nexport class BtpAuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BtpAuthError';\n }\n}\n\n/**\n * Lightweight BTP client that speaks the BTP binary protocol over WebSocket.\n * Handles: connect → authenticate → send ILP packets → receive responses.\n */\nexport class IsomorphicBtpClient {\n private ws: WebSocket | null = null;\n private _isConnected = false;\n private requestIdCounter = 0;\n private readonly pendingRequests = new Map<number, PendingRequest>();\n /**\n * requestIds of server-originated MESSAGE/TRANSFER frames whose handler\n * has not yet replied. A wholly separate space from `pendingRequests`\n * (client-allocated ids awaiting a RESPONSE/ERROR): this client never\n * resolves a `pendingRequests` entry from an inbound MESSAGE/TRANSFER, and\n * never answers an inbound MESSAGE/TRANSFER as though it were one of its\n * own — the two are correlated purely by BTP frame type, not by whether an\n * id happens to collide (toon-client#493).\n */\n private readonly inFlightInbound = new Set<number>();\n /** Config keys that stay optional after defaults are applied — everything else becomes required. */\n private readonly config: Required<\n Omit<\n IsomorphicBtpClientConfig,\n | 'createWebSocket'\n | 'onMessage'\n | 'onTransfer'\n | 'onInboundError'\n | 'getChannelDeclaration'\n >\n > &\n Pick<\n IsomorphicBtpClientConfig,\n | 'createWebSocket'\n | 'onMessage'\n | 'onTransfer'\n | 'onInboundError'\n | 'getChannelDeclaration'\n >;\n\n constructor(config: IsomorphicBtpClientConfig) {\n this.config = {\n sendTimeoutMs: 30_000,\n authTimeoutMs: 5_000,\n ...config,\n };\n }\n\n get isConnected(): boolean {\n return this._isConnected;\n }\n\n async connect(): Promise<void> {\n if (this._isConnected) return;\n\n return new Promise<void>((resolve, reject) => {\n try {\n this.ws = this.config.createWebSocket\n ? this.config.createWebSocket(this.config.url)\n : new WebSocket(this.config.url);\n this.ws.binaryType = 'arraybuffer';\n } catch (err) {\n reject(\n new BtpConnectionError(\n `Failed to create WebSocket: ${err instanceof Error ? err.message : String(err)}`\n )\n );\n return;\n }\n\n this.ws.onopen = async () => {\n try {\n await this.authenticate();\n this._isConnected = true;\n resolve();\n } catch (err) {\n this._isConnected = false;\n this.ws?.close();\n reject(err);\n }\n };\n\n this.ws.onmessage = (event: MessageEvent) => {\n this.handleMessage(event.data);\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.ws.onerror = (event: any) => {\n const underlying = event?.error ?? event?.message;\n const detail =\n underlying instanceof Error\n ? underlying.message\n : typeof underlying === 'string'\n ? underlying\n : null;\n reject(\n new BtpConnectionError(\n detail\n ? `WebSocket connection error: ${detail}`\n : 'WebSocket connection error'\n )\n );\n };\n\n this.ws.onclose = () => {\n this._isConnected = false;\n // Reject all pending requests\n for (const [id, pending] of this.pendingRequests) {\n clearTimeout(pending.timeoutId);\n pending.reject(new BtpConnectionError('Connection closed'));\n this.pendingRequests.delete(id);\n }\n this.failInFlightInbound('Connection closed before inbound request could be answered');\n };\n });\n }\n\n async disconnect(): Promise<void> {\n this._isConnected = false;\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n for (const [id, pending] of this.pendingRequests) {\n clearTimeout(pending.timeoutId);\n pending.reject(new BtpConnectionError('Disconnected'));\n this.pendingRequests.delete(id);\n }\n this.failInFlightInbound('Disconnected before inbound request could be answered');\n }\n\n /**\n * Send an ILP PREPARE packet, optionally with protocol data (e.g. the\n * payment-channel claim). Resolves with the answer packet AND the\n * protocolData that rode beside it — see {@link BtpPacketResponse}.\n */\n async sendPacket(\n packet: ILPPreparePacket,\n protocolData?: BTPProtocolData[]\n ): Promise<BtpPacketResponse> {\n if (!this._isConnected || !this.ws) {\n throw new BtpConnectionError('Not connected');\n }\n\n const serializedIlp = serializeIlpPrepare(packet);\n const requestId = this.nextRequestId();\n\n const btpMessage = serializeBtpMessage({\n type: BTPMessageType.MESSAGE,\n requestId,\n data: {\n protocolData: protocolData ?? [],\n ilpPacket: serializedIlp,\n },\n });\n\n this.ws.send(btpMessage);\n\n // Calculate timeout from packet expiry or default\n let timeoutMs = this.config.sendTimeoutMs;\n if (packet.expiresAt) {\n const remaining = packet.expiresAt.getTime() - Date.now();\n timeoutMs = Math.max(remaining - 500, 1000);\n }\n\n return new Promise<BtpPacketResponse>((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n this.pendingRequests.delete(requestId);\n reject(new BtpConnectionError(`Packet send timeout (${timeoutMs}ms)`));\n }, timeoutMs);\n\n this.pendingRequests.set(requestId, { resolve, reject, timeoutId });\n });\n }\n\n /**\n * Send a fire-and-forget BTP MESSAGE carrying only protocol data (no ILP\n * packet). Used for out-of-band claim notifications that the connector's\n * ClaimReceiver consumes via `handleClaimMessage` — there is no RESPONSE\n * frame, so we resolve immediately after the WebSocket buffers the bytes.\n *\n * Mirrors `sendPacket` wire-format construction but uses an empty ILP\n * payload and does not enroll a pending request.\n */\n async sendProtocolData(\n protocolName: string,\n contentType: number,\n data: Uint8Array\n ): Promise<void> {\n if (!this._isConnected || !this.ws) {\n throw new BtpConnectionError('Not connected');\n }\n\n const requestId = this.nextRequestId();\n const btpMessage = serializeBtpMessage({\n type: BTPMessageType.MESSAGE,\n requestId,\n data: {\n protocolData: [{ protocolName, contentType, data }],\n ilpPacket: new Uint8Array(0),\n },\n });\n\n this.ws.send(btpMessage);\n }\n\n /**\n * Re-sends the auth greeting on the EXISTING session — no socket\n * reconnect — so a channel that became known (or changed) after the\n * initial `connect()` is declared on the live session. The connector\n * treats a second auth as a rebind under a fresh generation, so no new\n * message type is needed (toon-client#513). A no-op when not connected;\n * the next `connect()`/reconnect already re-declares via\n * `getChannelDeclaration`.\n */\n async reauthenticate(): Promise<void> {\n if (!this._isConnected || !this.ws) return;\n await this.authenticate();\n }\n\n // ─── Private ────────────────────────────────────────────────────────────\n\n private async authenticate(): Promise<void> {\n if (!this.ws) throw new BtpAuthError('WebSocket not connected');\n\n const declaration = await this.config.getChannelDeclaration?.();\n const authData = btpAuthEntry(this.config.peerId, this.config.authToken, declaration);\n\n const requestId = this.nextRequestId();\n const authMessage = serializeBtpMessage({\n type: BTPMessageType.MESSAGE,\n requestId,\n data: {\n protocolData: [\n {\n protocolName: 'auth',\n // UTF-8 text, as the vectors' `client_auth_channel_challenge` frames pin it.\n contentType: 1,\n data: textEncoder.encode(authData),\n },\n ],\n ilpPacket: new Uint8Array(0),\n },\n });\n\n return new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(new BtpAuthError('Authentication timeout'));\n }, this.config.authTimeoutMs);\n\n // Temporarily intercept messages for auth response\n const originalHandler = this.ws!.onmessage;\n this.ws!.onmessage = (event: MessageEvent) => {\n try {\n const data = this.toUint8Array(event.data);\n\n // Try JSON parse first (server may respond with JSON)\n try {\n const jsonStr = new TextDecoder().decode(data);\n if (jsonStr.startsWith('{')) {\n // JSON response — not a BTP binary auth response, ignore\n }\n } catch {\n /* not JSON */\n }\n\n // Parse as BTP binary\n const message = parseBtpMessage(data);\n if (message.requestId === requestId) {\n clearTimeout(timeout);\n this.ws!.onmessage = originalHandler;\n\n if (message.type === BTPMessageType.ERROR) {\n const errData = message.data as BTPErrorData;\n reject(\n new BtpAuthError(\n `Authentication failed: ${errData.code} msg=${errData.message ?? ''} trigger=${errData.triggeredAt ?? ''}`\n )\n );\n } else if (message.type === BTPMessageType.RESPONSE) {\n resolve();\n }\n }\n } catch (err) {\n clearTimeout(timeout);\n this.ws!.onmessage = originalHandler;\n reject(\n new BtpAuthError(err instanceof Error ? err.message : String(err))\n );\n }\n };\n\n this.ws!.send(authMessage);\n });\n }\n\n /**\n * Dispatch one inbound websocket frame.\n *\n * Binary BTP only. A JSON `{\"type\":\"FULFILL\"|\"REJECT\"}` fallback used to sit\n * in front of this, resolving the OLDEST pending request from a text frame —\n * a dialect the TypeScript connector spoke and the Rust one never has\n * (\"Frames: binary websocket messages, one BTP frame per message. Text\n * frames are ignored\", `client-edge-spec.md` §1.9). It was also unsound on\n * its own terms: responses may arrive out of order (§1.9 \"Ordering\"), so\n * correlating by \"whichever request is first in the map\" could hand one\n * send's answer to another. Removed rather than left dormant.\n */\n private handleMessage(raw: unknown): void {\n try {\n const data = this.toUint8Array(raw);\n const message = parseBtpMessage(data);\n\n // RESPONSE/ERROR answers a request THIS client originated — correlate\n // against `pendingRequests` only, never `inFlightInbound` (toon-client#493:\n // the two id spaces are distinguished by frame type, not by value).\n if (\n message.type === BTPMessageType.RESPONSE ||\n message.type === BTPMessageType.ERROR\n ) {\n const pending = this.pendingRequests.get(message.requestId);\n if (!pending) return;\n\n clearTimeout(pending.timeoutId);\n this.pendingRequests.delete(message.requestId);\n\n if (message.type === BTPMessageType.ERROR) {\n const errData = message.data as BTPErrorData;\n pending.reject(\n new BtpConnectionError(`BTP error: ${errData.code} ${errData.name}`)\n );\n return;\n }\n\n const msgData = message.data as BTPMessageData;\n if (!msgData.ilpPacket || msgData.ilpPacket.length === 0) {\n // A RESPONSE correlating to an outbound PREPARE always carries a\n // FULFILL or REJECT (§1.9 step 2); the empty RESPONSE is the auth\n // ack, which `authenticate()` intercepts on its own, and a\n // standalone claim MESSAGE is answered with nothing at all (step 5).\n // So this is a malformed answer — failed loudly rather than left to\n // time out, since the timeout was already cleared above and the\n // caller would otherwise wait forever.\n pending.reject(\n new BtpConnectionError(\n `BTP RESPONSE ${message.requestId} carried no ILP packet`\n )\n );\n return;\n }\n pending.resolve({\n packet: deserializeIlpPacket(msgData.ilpPacket),\n // Everything riding beside the packet — `toon-accumulated-cost` on a\n // REJECT, `payment-required` on a greeting, `claim-ack` — handed to\n // the caller instead of dropped.\n protocolData: msgData.protocolData ?? [],\n });\n return;\n }\n\n // MESSAGE/TRANSFER carrying a requestId this client never allocated —\n // a server-originated request (RFC-0023's symmetric grammar). Dispatch\n // to the configured handler and answer with the same requestId; never\n // consult or touch `pendingRequests`.\n if (message.type === BTPMessageType.MESSAGE) {\n this.handleInboundMessage(message.requestId, message.data as BTPMessageData);\n return;\n }\n if (message.type === BTPMessageType.TRANSFER) {\n this.handleInboundTransfer(message.requestId, message.data as BTPTransferData);\n return;\n }\n } catch {\n // Unparseable message — ignore\n }\n }\n\n private handleInboundMessage(requestId: number, data: BTPMessageData): void {\n const handler = this.config.onMessage;\n if (!handler) return; // additive: no handler configured, no answer (pre-#493 behavior)\n this.dispatchInbound(requestId, () =>\n handler({\n requestId,\n protocolData: data.protocolData ?? [],\n ilpPacket: data.ilpPacket,\n })\n );\n }\n\n private handleInboundTransfer(requestId: number, data: BTPTransferData): void {\n const handler = this.config.onTransfer;\n this.dispatchInbound(requestId, () =>\n handler\n ? handler({\n requestId,\n amount: data.amount,\n protocolData: data.protocolData ?? [],\n })\n : {}\n );\n }\n\n private dispatchInbound(\n requestId: number,\n invoke: () => Promise<BtpHandlerResponse> | BtpHandlerResponse\n ): void {\n this.inFlightInbound.add(requestId);\n Promise.resolve()\n .then(invoke)\n .then(\n (result) => this.replyToInbound(requestId, result ?? {}),\n (err) => this.replyToInboundError(requestId, err)\n );\n }\n\n /** True if the reply is still owed — false means a disconnect already failed it loudly. */\n private takeInFlight(requestId: number): boolean {\n return this.inFlightInbound.delete(requestId);\n }\n\n private replyToInbound(requestId: number, result: BtpHandlerResponse): void {\n if (!this.takeInFlight(requestId)) return;\n this.sendInboundReply(requestId, '', () =>\n serializeBtpMessage({\n type: BTPMessageType.RESPONSE,\n requestId,\n data: {\n protocolData: result.protocolData ?? [],\n ilpPacket: result.ilpPacket ?? new Uint8Array(0),\n },\n })\n );\n }\n\n private replyToInboundError(requestId: number, error: unknown): void {\n if (!this.takeInFlight(requestId)) return;\n const message = error instanceof Error ? error.message : String(error);\n this.sendInboundReply(requestId, ` (handler error: ${message})`, () =>\n serializeBtpMessage({\n type: BTPMessageType.ERROR,\n requestId,\n data: {\n code: 'F00',\n name: 'NotAcceptedError',\n triggeredAt: '',\n message,\n data: textEncoder.encode(message),\n },\n })\n );\n }\n\n /**\n * Sends a RESPONSE/ERROR frame answering an inbound request, reporting\n * through `onInboundError` (never throwing) if the socket is gone or\n * `send` itself fails. `notConnectedSuffix` lets the caller fold in extra\n * context (e.g. the handler error that `replyToInboundError` is reporting)\n * when the \"not connected\" case fires.\n */\n private sendInboundReply(\n requestId: number,\n notConnectedSuffix: string,\n build: () => Uint8Array\n ): void {\n if (!this._isConnected || !this.ws) {\n this.config.onInboundError?.(\n new BtpConnectionError(\n `Cannot answer inbound request ${requestId}: not connected${notConnectedSuffix}`\n ),\n requestId\n );\n return;\n }\n try {\n this.ws.send(build());\n } catch (err) {\n this.config.onInboundError?.(\n err instanceof Error ? err : new Error(String(err)),\n requestId\n );\n }\n }\n\n /** Fail every inbound request still awaiting its handler, loudly rather than silently. */\n private failInFlightInbound(reason: string): void {\n for (const requestId of this.inFlightInbound) {\n this.config.onInboundError?.(new BtpConnectionError(reason), requestId);\n }\n this.inFlightInbound.clear();\n }\n\n private toUint8Array(data: unknown): Uint8Array {\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n if (data instanceof Uint8Array) return data;\n if (typeof data === 'string') return textEncoder.encode(data);\n throw new Error(`Unexpected WebSocket data type: ${typeof data}`);\n }\n\n private nextRequestId(): number {\n this.requestIdCounter = (this.requestIdCounter + 1) & 0xffffffff;\n return this.requestIdCounter;\n }\n}\n","/**\n * What rides **beside** the answer packet, decoded once for both carriages.\n *\n * Three facts about a paid write are deliberately not part of the OER\n * FULFILL/REJECT encoding — the accumulated cost, the connector's verdict on\n * the claim, and an x402 greeting — so each travels alongside the packet\n * instead of inside it. The two carriages spell them differently and mean\n * exactly the same thing:\n *\n * | Concept | HTTP response header | BTP protocolData entry |\n * | ---------------- | ------------------------- | ------------------------- |\n * | accumulated cost | `toon-accumulated-cost` | `toon-accumulated-cost` |\n * | claim ack | `toon-claim-ack` | `claim-ack` |\n * | x402 greeting | `payment-required` | `payment-required` |\n *\n * That table is the connector's own `connector_btp::CARRIAGE_NAMES`, which\n * declares each concept's two names *as a pair* so a header cannot be added\n * without its protocolData twin (`peer-carriage-spec.md` invariant I2).\n * The only encoding difference is that HTTP base64s the two JSON-valued\n * fields, because base64 is a header artefact and nothing else\n * (`client-edge-spec.md` §1.3 vs §1.9 step 2 makes the same point about the\n * claim itself: HTTP sends `base64(JSON)`, BTP sends the raw UTF-8 JSON).\n *\n * Everything below therefore takes an already-de-base64'd string or the raw\n * bytes, so the HTTP reader in `../http/HttpIlpClient.ts` and the BTP reader\n * in `../btp/BtpRuntimeClient.ts` are two thin adapters over ONE decoder each.\n * That is the same discipline the connector holds itself to (invariant I1:\n * \"a decoder written twice is a rule enforced once, and a rule enforced once\n * is a rule the two carriages cannot disagree about\"), and the connector's\n * `vectors/wire-vectors.json` pins the two spellings of each value as a pair,\n * so a client that decoded them differently would fail the vector replay.\n */\n\nimport type { ClaimAck, IlpSendResult } from './types.js';\nimport { decodeUtf8, fromBase64 } from '../utils/binary.js';\n\n/** The HTTP response header carrying the running cost of a REJECT. */\nexport const ACCUMULATED_COST_HEADER = 'toon-accumulated-cost';\n/** The BTP protocolData entry carrying the running cost of a REJECT. */\nexport const ACCUMULATED_COST_PROTOCOL = 'toon-accumulated-cost';\n/** The HTTP response header carrying the connector's verdict on the claim. */\nexport const CLAIM_ACK_HEADER = 'toon-claim-ack';\n/**\n * The BTP protocolData entry carrying the connector's verdict on the claim.\n * Note the name is NOT the header's: `claim-ack`, not `toon-claim-ack`\n * (`connector_btp::CLAIM_ACK_PROTOCOL` vs `CLAIM_ACK_HEADER`). It is the one\n * pair in the table whose two halves are spelled differently, which is\n * exactly why they are declared here together rather than at each use site.\n */\nexport const CLAIM_ACK_PROTOCOL = 'claim-ack';\n/** The HTTP response header carrying the x402 terms, base64 of the 402 body. */\nexport const PAYMENT_REQUIRED_HEADER = 'payment-required';\n/** The BTP protocolData entry carrying the same x402 terms, raw UTF-8 JSON. */\nexport const PAYMENT_REQUIRED_PROTOCOL = 'payment-required';\n\n/**\n * The three fields of an {@link IlpSendResult} that arrive beside the packet\n * rather than inside it. A key is present only when the carriage actually\n * carried a readable value — never defaulted, since a substituted default is\n * indistinguishable from a fact the connector stated.\n */\nexport type IlpResponseMeta = Pick<\n IlpSendResult,\n 'accumulatedCost' | 'claimAck' | 'paymentRequired'\n>;\n\n/**\n * The four refusal reasons a `claim-ack` may name\n * (`connector_peer_btp::ack::reason_name`, `peer-carriage-spec.md` §6.1).\n * Closed on purpose: the connector's own decoder refuses a spelling its build\n * does not know, and §6.3 makes that \"not acknowledged\" rather than a fifth\n * verdict.\n */\nexport const CLAIM_REJECT_REASONS = [\n 'signature_invalid',\n 'nonce_not_advancing',\n 'amount_not_advancing',\n 'unknown_channel',\n] as const;\n\n/**\n * Decode the accumulated-cost value — a decimal `uint64` as UTF-8 text on\n * either carriage (`client-edge-spec.md` §1.6).\n *\n * `undefined` for anything that is not a bare run of digits. A cost is a\n * number the sender may reason about (an underpayment reports the route's\n * price, which is the cheapest way to learn one), so a value this client\n * cannot read is reported as absent rather than guessed at or coerced to `0` —\n * `0` is itself a meaningful answer, meaning \"nothing was traversed and\n * nothing terminated\".\n */\nexport function decodeAccumulatedCost(value: string): bigint | undefined {\n const trimmed = value.trim();\n if (!/^\\d+$/.test(trimmed)) return undefined;\n return BigInt(trimmed);\n}\n\n/**\n * Decode a `claim-ack` document: `{\"result\":\"accepted\"}` or\n * `{\"result\":\"rejected\",\"reason\":\"<one of CLAIM_REJECT_REASONS>\"}`.\n *\n * **Absence and malformation both mean NOT ACKNOWLEDGED**\n * (`peer-carriage-spec.md` §6.3), so every shape that is not exactly one of\n * those two — undecodable JSON, an unknown `result`, a `rejected` carrying no\n * reason or an unknown one — yields `undefined`, and a caller must never read\n * `undefined` as either verdict. This mirrors `connector_peer_btp::ack::decode`\n * arm for arm; the connector's `ack_malformed` vector (`{\"result\":\"maybe\"}`)\n * is exactly this case, pinned on both carriages.\n */\nexport function decodeClaimAck(json: string): ClaimAck | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const result = (parsed as Record<string, unknown>)['result'];\n if (result === 'accepted') return { result: 'accepted' };\n if (result !== 'rejected') return undefined;\n const reason = (parsed as Record<string, unknown>)['reason'];\n if (typeof reason !== 'string') return undefined;\n if (!(CLAIM_REJECT_REASONS as readonly string[]).includes(reason)) {\n return undefined;\n }\n return { result: 'rejected', reason };\n}\n\n/**\n * Decode an x402 terms document that rode beside a packet, returning it raw.\n *\n * Raw, not parsed into {@link ../connector/x402.js}'s shape, because\n * `IlpSendResult.paymentRequired` is the document as the connector stated it:\n * the transports' job is to stop losing it, and deciding what it means is the\n * caller's. `undefined` when the bytes are not JSON at all.\n */\nexport function decodePaymentRequired(json: string): unknown {\n try {\n return JSON.parse(json) as unknown;\n } catch {\n return undefined;\n }\n}\n\n/** Assemble a meta object, omitting every field the carriage did not carry. */\nexport function buildResponseMeta(parts: {\n accumulatedCost?: bigint | undefined;\n claimAck?: ClaimAck | undefined;\n paymentRequired?: unknown;\n}): IlpResponseMeta {\n return {\n ...(parts.accumulatedCost !== undefined\n ? { accumulatedCost: parts.accumulatedCost }\n : {}),\n ...(parts.claimAck !== undefined ? { claimAck: parts.claimAck } : {}),\n ...(parts.paymentRequired !== undefined\n ? { paymentRequired: parts.paymentRequired }\n : {}),\n };\n}\n\n/**\n * Decode a base64 header value to its UTF-8 text, or `undefined` when it is\n * not decodable base64. Used for the two JSON-valued HTTP headers, whose BTP\n * twins carry the same text with no base64 layer at all.\n */\nexport function decodeBase64Text(value: string): string | undefined {\n try {\n return decodeUtf8(fromBase64(value.trim()));\n } catch {\n return undefined;\n }\n}\n","/**\n * Configuration options for retry behavior with exponential backoff.\n */\nexport interface RetryOptions {\n /** Maximum number of retry attempts (default: 3) */\n maxRetries: number;\n /** Initial delay in milliseconds between retries (default: 1000) */\n retryDelay: number;\n /** Use exponential backoff for delays (default: true) */\n exponentialBackoff?: boolean;\n /** Maximum delay cap in milliseconds (default: 30000) */\n maxDelay?: number;\n /** Custom predicate to determine if an error should trigger a retry */\n shouldRetry?: (error: Error) => boolean;\n}\n\n/**\n * Executes an async operation with retry logic and exponential backoff.\n *\n * @param operation - The async function to execute\n * @param options - Retry configuration options\n * @returns The result of the successful operation\n * @throws The last error if all retries are exhausted\n *\n * @example\n * ```typescript\n * const result = await withRetry(\n * async () => fetchData(),\n * {\n * maxRetries: 3,\n * retryDelay: 1000,\n * shouldRetry: (err) => err.name === 'NetworkError'\n * }\n * );\n * ```\n */\nexport async function withRetry<T>(\n operation: () => Promise<T>,\n options: RetryOptions\n): Promise<T> {\n const {\n maxRetries,\n retryDelay,\n exponentialBackoff = true,\n maxDelay = 30000,\n shouldRetry,\n } = options;\n\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Check if we should retry this error\n if (shouldRetry && !shouldRetry(lastError)) {\n throw lastError;\n }\n\n // If this was the last attempt, throw the error\n if (attempt === maxRetries) {\n throw lastError;\n }\n\n // Calculate delay with exponential backoff\n const currentDelay = exponentialBackoff\n ? Math.min(retryDelay * Math.pow(2, attempt), maxDelay)\n : retryDelay;\n\n // Wait before retrying\n await new Promise((resolve) => setTimeout(resolve, currentDelay));\n }\n }\n\n // This should never be reached, but TypeScript needs it\n throw lastError ?? new Error('Unknown error during retry');\n}\n","import {\n IsomorphicBtpClient,\n BtpConnectionError,\n type BtpChannelDeclaration,\n type BtpMessageHandler,\n type BtpTransferHandler,\n} from '../btp/IsomorphicBtpClient.js';\nimport { type BTPProtocolData } from '../btp/protocol.js';\nimport type { IlpClient, IlpSendResult } from '../ilp/types.js';\nimport {\n ACCUMULATED_COST_PROTOCOL,\n CLAIM_ACK_PROTOCOL,\n PAYMENT_REQUIRED_PROTOCOL,\n buildResponseMeta,\n decodeAccumulatedCost,\n decodeClaimAck,\n decodePaymentRequired,\n type IlpResponseMeta,\n} from '../ilp/response-meta.js';\nimport { withRetry } from '../utils/retry.js';\nimport { fromBase64, encodeUtf8, decodeUtf8 } from '../utils/binary.js';\nimport {\n mapIlpResponse,\n resolveExpectedFulfillment,\n resolveExpiresAt,\n type IlpSendParams,\n} from '../ilp/ilp-send.js';\nimport { assertValidFulfillment } from '../utils/fulfillment.js';\n\nexport type { BtpChannelDeclaration };\n\nexport interface BtpRuntimeClientConfig {\n btpUrl: string;\n peerId: string;\n authToken: string;\n /** Max reconnection attempts on send failure (default: 3) */\n maxRetries?: number;\n /** Delay between reconnection attempts in ms (default: 1000) */\n retryDelay?: number;\n /** Custom WebSocket constructor (for testing / custom transports). */\n createWebSocket?: (url: string) => WebSocket;\n /**\n * Handles a server-originated MESSAGE (RFC-0023 symmetric grammar,\n * toon-client#493). Re-registered on every `connect()`/`reconnect()` since\n * each creates a fresh `IsomorphicBtpClient` for the new socket.\n */\n onMessage?: BtpMessageHandler;\n /** Handles a server-originated TRANSFER. Re-registered the same way as `onMessage`. */\n onTransfer?: BtpTransferHandler;\n /** Surfaces in-flight inbound work orphaned by a disconnect instead of silently vanishing. */\n onInboundError?: (error: Error, requestId: number) => void;\n /**\n * Called on every `connect()`/`reconnect()` and every explicit\n * {@link BtpRuntimeClient.reauthenticate} to fetch the caller's current\n * channel to declare on the greeting. Additive: unset (or an `undefined`\n * result) leaves the greeting unchanged (toon-client#513).\n */\n getChannelDeclaration?: () =>\n | Promise<BtpChannelDeclaration | undefined>\n | BtpChannelDeclaration\n | undefined;\n}\n\n/**\n * Read the three facts that ride BESIDE the answer packet off a RESPONSE\n * frame's protocolData entries — the BTP twin of `HttpIlpClient`'s\n * `readResponseMeta(headers)`.\n *\n * The two MUST produce identical values from the connector's paired vectors,\n * which is why both delegate to the one decoder each in\n * `../ilp/response-meta.js` rather than parsing here. The ONE thing that\n * differs between the carriages is the envelope, and only that: a websocket\n * frame has no headers, so BTP carries each value as raw UTF-8 in a\n * protocolData entry where HTTP base64s it into a header\n * (`client-edge-spec.md` §1.9 step 2 — \"no base64 layer; that is an\n * HTTP-header artifact\"). The entry names come from\n * `connector_btp::CARRIAGE_NAMES`, which declares each concept's BTP and HTTP\n * spellings as a pair; note `claim-ack` is the one whose two halves differ\n * (`claim-ack` here, `toon-claim-ack` there).\n *\n * Every field is independently optional. In particular `accumulatedCost` is\n * present on a REJECT and absent from a FULFILL (§1.6), while a `claim-ack` of\n * `rejected` can sit on a FULFILL — the packet's verdict and the claim's are\n * separate answers to separate questions and are never inferred from each\n * other.\n */\nexport function readResponseMeta(\n protocolData: BTPProtocolData[]\n): IlpResponseMeta {\n const entry = (name: string): string | undefined => {\n const found = protocolData.find((pd) => pd.protocolName === name);\n return found ? decodeUtf8(found.data) : undefined;\n };\n\n const cost = entry(ACCUMULATED_COST_PROTOCOL);\n const ack = entry(CLAIM_ACK_PROTOCOL);\n const terms = entry(PAYMENT_REQUIRED_PROTOCOL);\n\n return buildResponseMeta({\n accumulatedCost: cost !== undefined ? decodeAccumulatedCost(cost) : undefined,\n claimAck: ack !== undefined ? decodeClaimAck(ack) : undefined,\n paymentRequired: terms !== undefined ? decodePaymentRequired(terms) : undefined,\n });\n}\n\n/**\n * Returns true if the error is a connection-level error worth retrying.\n * ILP application-level rejects (F02, T01, etc.) are NOT retried.\n */\nfunction isConnectionError(error: Error): boolean {\n const msg = error.message.toLowerCase();\n return (\n msg.includes('not connected') ||\n msg.includes('connection') ||\n msg.includes('websocket') ||\n msg.includes('econnrefused') ||\n msg.includes('econnreset') ||\n msg.includes('socket hang up') ||\n msg.includes('timeout')\n );\n}\n\n/**\n * BTP transport implementing IlpClient.\n * Uses IsomorphicBtpClient (browser-native, no Node.js dependencies).\n */\nexport class BtpRuntimeClient implements IlpClient {\n private btpClient: IsomorphicBtpClient | null = null;\n private readonly config: BtpRuntimeClientConfig;\n private _isConnected = false;\n\n constructor(config: BtpRuntimeClientConfig) {\n this.config = config;\n }\n\n /**\n * Connects to the BTP peer via WebSocket.\n */\n async connect(): Promise<void> {\n this.btpClient = new IsomorphicBtpClient({\n url: this.config.btpUrl,\n peerId: this.config.peerId,\n authToken: this.config.authToken,\n createWebSocket: this.config.createWebSocket,\n onMessage: this.config.onMessage,\n onTransfer: this.config.onTransfer,\n onInboundError: this.config.onInboundError,\n getChannelDeclaration: this.config.getChannelDeclaration,\n });\n\n await this.btpClient.connect();\n this._isConnected = true;\n }\n\n /**\n * Re-sends the auth greeting on the EXISTING session — no reconnect — so a\n * channel that became known (or changed) after `connect()` is declared on\n * the live session (toon-client#513). A no-op when not connected; the next\n * `connect()`/`reconnect()` already re-declares via `getChannelDeclaration`.\n */\n async reauthenticate(): Promise<void> {\n if (!this._isConnected || !this.btpClient) return;\n await this.btpClient.reauthenticate();\n }\n\n /**\n * Attempts to reconnect by creating a fresh client and connecting.\n */\n async reconnect(): Promise<void> {\n if (this.btpClient) {\n try {\n await this.btpClient.disconnect();\n } catch {\n // Ignore disconnect errors during reconnect\n }\n this.btpClient = null;\n this._isConnected = false;\n }\n\n await this.connect();\n }\n\n /**\n * Disconnects from the BTP peer.\n */\n async disconnect(): Promise<void> {\n if (this.btpClient) {\n await this.btpClient.disconnect();\n this._isConnected = false;\n this.btpClient = null;\n }\n }\n\n get isConnected(): boolean {\n return this._isConnected;\n }\n\n /**\n * Sends an ILP packet via BTP with auto-reconnect on connection errors.\n * Satisfies IlpClient interface.\n *\n * `params` may carry an `expectedFulfillment` (the sender's end-to-end\n * check, ADR 0069), a `greeting` flag and an explicit `expiresAt`. With an\n * expected fulfilment the FULFILL preimage is compared against it and a\n * mismatch is surfaced as a failed result — see `mapIlpResponse`.\n */\n async sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult> {\n return withRetry(() => this._sendIlpPacketOnce(params), {\n maxRetries: this.config.maxRetries ?? 3,\n retryDelay: this.config.retryDelay ?? 1000,\n shouldRetry: (error) => {\n if (!isConnectionError(error)) return false;\n this._isConnected = false;\n return true;\n },\n });\n }\n\n /**\n * Sends a voucher claim via BTP protocol data, then sends an ILP packet.\n * Auto-reconnects on connection errors.\n *\n * `expectedFulfillment` / `greeting` / `expiresAt` semantics are identical\n * to {@link sendIlpPacket}.\n */\n async sendIlpPacketWithClaim(\n params: IlpSendParams,\n claim: Record<string, unknown>\n ): Promise<IlpSendResult> {\n return withRetry(() => this._sendIlpPacketWithClaimOnce(params, claim), {\n maxRetries: this.config.maxRetries ?? 3,\n retryDelay: this.config.retryDelay ?? 1000,\n shouldRetry: (error) => {\n if (!isConnectionError(error)) return false;\n this._isConnected = false;\n return true;\n },\n });\n }\n\n /**\n * Send a standalone `payment-channel-claim` BTP MESSAGE (no ILP packet\n * attached). The connector's ClaimReceiver consumes this fire-and-forget\n * to register cumulative claim state independently of the per-packet\n * forwarding path. Auto-reconnects on connection errors.\n */\n async sendClaimMessage(claim: Record<string, unknown>): Promise<void> {\n return withRetry(() => this._sendClaimMessageOnce(claim), {\n maxRetries: this.config.maxRetries ?? 3,\n retryDelay: this.config.retryDelay ?? 1000,\n shouldRetry: (error) => {\n if (!isConnectionError(error)) return false;\n this._isConnected = false;\n return true;\n },\n });\n }\n\n private async _sendClaimMessageOnce(\n claim: Record<string, unknown>\n ): Promise<void> {\n if (!this._isConnected) {\n await this.reconnect();\n }\n\n if (!this.btpClient) {\n throw new BtpConnectionError('BTP client not connected');\n }\n\n await this.btpClient.sendProtocolData(\n 'payment-channel-claim',\n 1,\n encodeUtf8(JSON.stringify(claim))\n );\n }\n\n /**\n * Build the ILP PREPARE for a send, applying the\n * explicit expiry when provided, carrying the `greeting` flag ADR 0069 put\n * where the execution condition used to be, and validating that an expected\n * fulfilment is exactly 32 bytes (a wrong-length one could never match a\n * real FULFILL, so every delivery would be counted failed).\n */\n private buildPrepare(params: IlpSendParams): {\n prepare: {\n type: 12;\n amount: bigint;\n destination: string;\n greeting: boolean;\n expiresAt: Date;\n data: Uint8Array;\n };\n expectedFulfillment: Uint8Array | undefined;\n } {\n const expectedFulfillment = resolveExpectedFulfillment(\n params.expectedFulfillment\n );\n if (expectedFulfillment !== undefined) {\n assertValidFulfillment(expectedFulfillment);\n }\n return {\n prepare: {\n type: 12 as const,\n amount: BigInt(params.amount),\n destination: params.destination,\n greeting: params.greeting ?? false,\n expiresAt: resolveExpiresAt(params.expiresAt, params.timeout ?? 30000),\n data: fromBase64(params.data),\n },\n expectedFulfillment,\n };\n }\n\n /**\n * Single-attempt ILP packet send. Reconnects if not connected.\n */\n private async _sendIlpPacketOnce(\n params: IlpSendParams\n ): Promise<IlpSendResult> {\n if (!this._isConnected) {\n await this.reconnect();\n }\n\n const { prepare, expectedFulfillment } = this.buildPrepare(params);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed by reconnect() above\n const response = await this.btpClient!.sendPacket(prepare);\n\n return {\n ...mapIlpResponse(response.packet, expectedFulfillment),\n ...readResponseMeta(response.protocolData),\n };\n }\n\n /**\n * Single-attempt claim + ILP packet send. Reconnects if not connected.\n */\n private async _sendIlpPacketWithClaimOnce(\n params: IlpSendParams,\n claim: Record<string, unknown>\n ): Promise<IlpSendResult> {\n if (!this._isConnected) {\n await this.reconnect();\n }\n\n if (!this.btpClient) {\n throw new BtpConnectionError('BTP client not connected');\n }\n\n const protocolData: BTPProtocolData[] = [\n {\n protocolName: 'payment-channel-claim',\n contentType: 1,\n data: encodeUtf8(JSON.stringify(claim)),\n },\n ];\n\n const { prepare, expectedFulfillment } = this.buildPrepare(params);\n const response = await this.btpClient.sendPacket(prepare, protocolData);\n\n return {\n ...mapIlpResponse(response.packet, expectedFulfillment),\n ...readResponseMeta(response.protocolData),\n };\n }\n}\n","/**\n * ILP-over-HTTP (RFC-0035) transport for the TOON client — the `POST /ilp`\n * carriage of `client-edge-spec.md` §1.1.\n *\n * The connector serves this and BTP on the same port. This adapter does\n * stateless one-shot writes over HTTP and can upgrade to a duplex BTP session\n * when a client needs to receive server-initiated packets.\n *\n * Wire contract:\n * - One-shot write: `POST /ilp`\n * body: OER-encoded ILP PREPARE (`application/octet-stream`), in\n * TOON's own dialect (ADR 0063), not RFC-0027's bytes.\n * header: `ILP-Payment-Channel-Claim: base64(JSON of the claim)` — the\n * SAME claim JSON the BTP path attaches as the\n * `payment-channel-claim` protocolData entry, raw (§1.3, §1.9).\n * optional: `ILP-Peer-Id` + `Authorization: Bearer <secret>` identity —\n * sent as a PAIR or not at all (issue #565), since the connector\n * 401s a presented id it cannot authenticate.\n * response: `200 OK` with an OER FULFILL or REJECT body — an ILP-level\n * outcome is ALWAYS 200. A non-2xx is a transport-level failure\n * and never carries an OER body: 400 undecodable, 401 a\n * presented identity that failed to authenticate, 402 terms\n * instead of work, 413 over 2 MiB.\n * beside the packet: `toon-accumulated-cost`, `toon-claim-ack` and\n * `payment-required` response headers — see\n * {@link readResponseMeta}, and `../ilp/response-meta.js` for\n * why they are not part of the packet encoding.\n * - Upgrade to BTP: standard HTTP `Upgrade` with `Sec-WebSocket-Protocol: btp`\n * plus the same `ILP-Peer-Id` + `Authorization` headers. The connector\n * pre-authenticates the BTP session from those headers (continuity), so\n * after `101` we send BTP frames WITHOUT a separate in-band auth frame.\n * Omitting the auth headers falls back to the normal BTP auth-frame flow.\n *\n * Reuses `serializeIlpPrepare`/`deserializeIlpPacket` from `btp/protocol.ts` —\n * the SAME OER codec the BTP path uses. Claim signing/construction is owned by\n * the caller; this transport never builds or signs claims.\n *\n * **What this no longer does.** Up to 0.x a `401` or a `requiredTransport`\n * `402` was caught here and re-thrown as \"retry this over BTP\", because the\n * only way to learn a route's carriage was to be refused over the wrong one.\n * 1.0 reads the node's own self-description first and picks a carriage from it\n * (`../btp/transport-select.js`), so that fallback is gone: a `401` is an\n * ordinary transport error again, and a `402` is terms — thrown as\n * {@link PaymentRequiredError} carrying them.\n */\n\nimport type { IlpClient, IlpSendResult } from '../ilp/types.js';\nimport type WSModule from 'ws';\nimport {\n ILPPacketType,\n serializeIlpPrepare,\n deserializeIlpPacket,\n} from '../btp/protocol.js';\nimport { BtpRuntimeClient } from '../btp/BtpRuntimeClient.js';\nimport {\n NetworkError,\n ConnectorError,\n PaymentRequiredError,\n TransportRequiredError,\n} from '../client/errors.js';\nimport { parsePaymentTerms } from '../connector/x402.js';\nimport {\n ACCUMULATED_COST_HEADER,\n CLAIM_ACK_HEADER,\n PAYMENT_REQUIRED_HEADER,\n buildResponseMeta,\n decodeAccumulatedCost,\n decodeBase64Text,\n decodeClaimAck,\n decodePaymentRequired,\n type IlpResponseMeta,\n} from '../ilp/response-meta.js';\nimport { withRetry } from '../utils/retry.js';\nimport { toBase64, fromBase64, encodeUtf8 } from '../utils/binary.js';\nimport {\n mapIlpResponse,\n resolveExpectedFulfillment,\n resolveExpiresAt,\n type IlpSendParams,\n} from '../ilp/ilp-send.js';\nimport { assertValidFulfillment } from '../utils/fulfillment.js';\n\n/** Header carrying the base64(JSON) payment-channel claim. */\nexport const ILP_CLAIM_HEADER = 'ILP-Payment-Channel-Claim';\n/** Header carrying the peer identity. */\nexport const ILP_PEER_ID_HEADER = 'ILP-Peer-Id';\n\n/** Anything a response's headers can be handed over as. */\nexport type ResponseHeaderSource =\n | Headers\n | Iterable<readonly [string, string]>\n | Record<string, string>;\n\n/**\n * Read the three facts that ride BESIDE the answer packet off an HTTP\n * response's headers (`client-edge-spec.md` §1.6, and connector\n * `connector_btp::CARRIAGE_NAMES` for the header/protocolData pairing).\n *\n * The BTP twin is `BtpRuntimeClient`'s `readResponseMeta(protocolData)`, and\n * the two MUST agree: the connector's vector set pins each value's two\n * spellings as a pair (`peer_carriage.reject_with_cost` carries\n * `toon-accumulated-cost: \"4200\"` as a header and the same `4200` as a\n * protocolData entry). Both funnel into the one decoder each in\n * `../ilp/response-meta.js`; the only thing this side adds is stripping the\n * base64 layer off the two JSON-valued headers, which is a header artefact and\n * nothing else.\n *\n * Header names are matched case-insensitively (RFC 9110); the canonical\n * lower-case spellings are the ones the vectors pin.\n *\n * Exported because the wire-vector replay reads a vector's `http_headers`\n * array straight into it — the same function the live transport uses, so a\n * vector cannot pass while the transport disagrees with it.\n */\nexport function readResponseMeta(headers: ResponseHeaderSource): IlpResponseMeta {\n const get = headerReader(headers);\n\n const costHeader = get(ACCUMULATED_COST_HEADER);\n const ackHeader = get(CLAIM_ACK_HEADER);\n const termsHeader = get(PAYMENT_REQUIRED_HEADER);\n\n const ackJson = ackHeader !== undefined ? decodeBase64Text(ackHeader) : undefined;\n const termsJson =\n termsHeader !== undefined ? decodeBase64Text(termsHeader) : undefined;\n\n return buildResponseMeta({\n accumulatedCost:\n costHeader !== undefined ? decodeAccumulatedCost(costHeader) : undefined,\n claimAck: ackJson !== undefined ? decodeClaimAck(ackJson) : undefined,\n paymentRequired:\n termsJson !== undefined ? decodePaymentRequired(termsJson) : undefined,\n });\n}\n\n/** A case-insensitive single-value lookup over any of the header shapes above. */\nfunction headerReader(\n headers: ResponseHeaderSource\n): (name: string) => string | undefined {\n if (typeof Headers !== 'undefined' && headers instanceof Headers) {\n return (name) => headers.get(name) ?? undefined;\n }\n const pairs: [string, string][] =\n typeof (headers as Iterable<readonly [string, string]>)[Symbol.iterator] ===\n 'function'\n ? [...(headers as Iterable<readonly [string, string]>)].map(([k, v]) => [\n k,\n v,\n ])\n : Object.entries(headers as Record<string, string>);\n return (name) => {\n const wanted = name.toLowerCase();\n for (const [key, value] of pairs) {\n if (key.toLowerCase() === wanted) return value;\n }\n return undefined;\n };\n}\n\nexport interface HttpIlpClientConfig {\n /** The peer's `POST /ilp` URL (the `httpEndpoint` from discovery). */\n httpEndpoint: string;\n /**\n * Optional peer identity. With no `peerId`/`authToken` the connector treats\n * the request as an anonymous no-auth peer (permissionless default) and\n * derives an ephemeral id from the claim signer.\n *\n * NOTE (issue #565): this is only PRESENTED on the wire when an `authToken`\n * accompanies it — see {@link HttpIlpClient.authHeaders}. It is still used\n * as the BTP auth-frame id on the {@link HttpIlpClient.upgradeToBtp} path.\n */\n peerId?: string;\n /** Bearer secret for `Authorization`. Omit for the no-auth peer path. */\n authToken?: string;\n /** Request timeout in milliseconds (default: 30000). */\n timeout?: number;\n /** Max retry attempts for transport-level network failures (default: 3). */\n maxRetries?: number;\n /** Initial retry delay in milliseconds (default: 1000). */\n retryDelay?: number;\n /** Custom fetch implementation (for testing / custom transports). */\n httpClient?: typeof fetch;\n /**\n * Custom WebSocket constructor for the BTP upgrade path (for testing /\n * custom transports). Forwarded to the underlying BtpRuntimeClient.\n */\n createWebSocket?: (url: string) => WebSocket;\n}\n\n/**\n * Stateless ILP-over-HTTP transport implementing `IlpClient`.\n *\n * Use this for pure one-shot consumers (publish-and-forget writes). When the\n * client needs a duplex session — to receive server-initiated packets or to act\n * as a peer — call {@link upgradeToBtp} to obtain a connected BtpRuntimeClient\n * that reuses the existing BTP code path.\n */\nexport class HttpIlpClient implements IlpClient {\n private readonly httpEndpoint: string;\n private readonly peerId: string | undefined;\n private readonly authToken: string | undefined;\n private readonly timeout: number;\n private readonly retryConfig: { maxRetries: number; retryDelay: number };\n private readonly httpClient: typeof fetch;\n private readonly createWebSocket: ((url: string) => WebSocket) | undefined;\n\n constructor(config: HttpIlpClientConfig) {\n this.httpEndpoint = config.httpEndpoint;\n this.peerId = config.peerId;\n this.authToken = config.authToken;\n this.timeout = config.timeout ?? 30000;\n this.retryConfig = {\n maxRetries: config.maxRetries ?? 3,\n retryDelay: config.retryDelay ?? 1000,\n };\n this.httpClient = config.httpClient ?? fetch;\n this.createWebSocket = config.createWebSocket;\n }\n\n /**\n * The client edge this transport pays — the origin `GET /ilp/identity` and\n * `GET /ilp/routes/price` hang off (`ConnectorEdgeClient` normalizes the\n * trailing `/ilp` away). Exposed because a sealed write must ask the\n * connector it is ACTUALLY paying for its key, not a configured guess.\n */\n get clientEdgeEndpoint(): string {\n return this.httpEndpoint;\n }\n\n /**\n * Send an ILP PREPARE via `POST /ilp` WITHOUT a claim. The connector accepts\n * this only on free/zero-amount routes; paid writes must use\n * {@link sendIlpPacketWithClaim}. Satisfies the IlpClient interface.\n *\n * `params` may carry an `expectedFulfillment` (the sender's end-to-end\n * check, ADR 0069), a `greeting` flag and an explicit `expiresAt`. With an\n * expected fulfilment the FULFILL preimage is compared against it and a\n * mismatch is surfaced as a failed result — see {@link mapIlpResponse}.\n */\n async sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult> {\n return withRetry(() => this.postPrepare(params), {\n maxRetries: this.retryConfig.maxRetries,\n retryDelay: this.retryConfig.retryDelay,\n exponentialBackoff: true,\n shouldRetry: (error) => error instanceof NetworkError,\n });\n }\n\n /**\n * Send an ILP PREPARE via `POST /ilp` with the payment-channel claim attached\n * as the `ILP-Payment-Channel-Claim` header. `claim` is the SAME JSON object\n * the BTP path attaches as the `payment-channel-claim` protocolData entry —\n * we base64(JSON.stringify(claim)) it, byte-for-byte identical to BTP.\n *\n * `expectedFulfillment` / `greeting` / `expiresAt` semantics are identical\n * to {@link sendIlpPacket}.\n */\n async sendIlpPacketWithClaim(\n params: IlpSendParams,\n claim: unknown\n ): Promise<IlpSendResult> {\n return withRetry(() => this.postPrepare(params, claim), {\n maxRetries: this.retryConfig.maxRetries,\n retryDelay: this.retryConfig.retryDelay,\n exponentialBackoff: true,\n shouldRetry: (error) => error instanceof NetworkError,\n });\n }\n\n /**\n * Upgrade to a duplex BTP session over the SAME endpoint.\n *\n * Derives the `ws(s)://` URL from `httpEndpoint`, opens a WebSocket with\n * `Sec-WebSocket-Protocol: btp` and the same `ILP-Peer-Id` + `Authorization`\n * headers, and returns a connected {@link BtpRuntimeClient}. When auth headers\n * are present the connector pre-authenticates the session (no in-band auth\n * frame); without them the BtpRuntimeClient falls back to the normal BTP\n * auth-frame flow.\n *\n * NOTE: passing per-connection headers + a subprotocol to a WebSocket is\n * Node-only (the `ws` package). Browsers cannot set arbitrary request headers\n * on a WebSocket handshake, so a browser consumer must use the gateway\n * transport or BTP-with-auth-frame instead.\n */\n async upgradeToBtp(): Promise<BtpRuntimeClient> {\n const btpUrl = httpEndpointToBtpUrl(this.httpEndpoint);\n\n // Default WS factory negotiates `btp` + carries the auth headers so the\n // connector pre-authenticates. Built lazily (Node-only) — browsers must\n // pass an explicit `createWebSocket` (they can't set handshake headers).\n const createWebSocket =\n this.createWebSocket ??\n (await makeBtpWebSocketFactory(this.authHeaders()));\n\n const client = new BtpRuntimeClient({\n btpUrl,\n // BtpRuntimeClient sends an auth frame using these; when the connector\n // pre-authenticated via Upgrade headers it accepts the (redundant) frame.\n peerId: this.peerId ?? 'client',\n authToken: this.authToken ?? '',\n createWebSocket,\n });\n await client.connect();\n return client;\n }\n\n // ─── Private ──────────────────────────────────────────────────────────────\n\n /**\n * The identity headers to present, if any.\n *\n * A peer id and its bearer secret are ONE credential, so both are sent or\n * neither is (issue #565). Presenting a `peerId` this client cannot back\n * with a secret is strictly WORSE than presenting nothing: the connector's\n * client edge resolves a PRESENTED identity first and answers `401` before\n * it ever looks at the route\n * (connector `crates/connector-client-edge/src/lib.rs`, whose own comment\n * reads \"A request presenting no `ILP-Peer-Id` is unaffected here — it is\n * anonymous, resolved once the claim (if any) has been admitted\"), whereas\n * anonymous + a valid payment-channel claim is the supported permissionless\n * path. The live devnet daemon shipped `ILP-Peer-Id: g.toon.client` with an\n * EMPTY token — an id no connector has a registration for — so every default\n * paid write over `POST /ilp` 401'd before the claim was read at all.\n *\n * An empty-string token is not a credential; `''` is falsy here on purpose.\n *\n * This REMOVES the 401 rather than recovering from it, which is why 1.0 can\n * drop the \"a 401 means retry over BTP\" fallback entirely: anonymous + a\n * valid claim is the supported permissionless path, so a 401 now means a\n * genuinely misconfigured credential and is surfaced as the transport error\n * it is.\n */\n private authHeaders(): Record<string, string> {\n if (!this.peerId || !this.authToken) return {};\n return {\n [ILP_PEER_ID_HEADER]: this.peerId,\n Authorization: `Bearer ${this.authToken}`,\n };\n }\n\n /**\n * Single attempt: serialize the PREPARE, POST it, and map the response.\n * @throws {NetworkError} On connection/timeout failures (retried).\n * @throws {ConnectorError} On non-retryable transport errors (5xx / unexpected).\n */\n private async postPrepare(\n params: IlpSendParams,\n claim?: unknown\n ): Promise<IlpSendResult> {\n const requestTimeout = params.timeout ?? this.timeout;\n\n // Validate the expected fulfilment's length up front: a wrong-length\n // value can never match a real FULFILL, so every delivery would be\n // counted failed — and paid for — before anyone noticed why.\n const expectedFulfillment = resolveExpectedFulfillment(\n params.expectedFulfillment\n );\n if (expectedFulfillment !== undefined) {\n assertValidFulfillment(expectedFulfillment);\n }\n\n const prepare = serializeIlpPrepare({\n type: ILPPacketType.PREPARE,\n amount: BigInt(params.amount),\n destination: params.destination,\n greeting: params.greeting ?? false,\n expiresAt: resolveExpiresAt(params.expiresAt, requestTimeout),\n data: fromBase64(params.data),\n });\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/octet-stream',\n ...this.authHeaders(),\n };\n if (claim !== undefined) {\n headers[ILP_CLAIM_HEADER] = toBase64(encodeUtf8(JSON.stringify(claim)));\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), requestTimeout);\n\n try {\n const response = await this.httpClient(this.httpEndpoint, {\n method: 'POST',\n headers,\n // Copy into a fresh ArrayBuffer so fetch sees a clean body, not a view.\n body: prepare.slice(),\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n return await this.mapResponse(response, expectedFulfillment);\n } catch (error) {\n clearTimeout(timeoutId);\n throw this.mapTransportError(error, requestTimeout);\n }\n }\n\n /**\n * Map a `200 OK` body (OER FULFILL/REJECT) to an IlpSendResult; map a non-2xx\n * to a transport error. Per the wire contract, ILP-level rejects arrive as a\n * 200 + REJECT body — only HTTP non-2xx means a transport-layer failure.\n *\n * When `expectedFulfillment` is given the FULFILL preimage is compared\n * against it; a mismatch yields `accepted: false` (shared `mapIlpResponse`\n * logic, identical to the BTP path).\n */\n private async mapResponse(\n response: Response,\n expectedFulfillment?: Uint8Array\n ): Promise<IlpSendResult> {\n if (response.ok) {\n const buf = new Uint8Array(await response.arrayBuffer());\n if (buf.length === 0) {\n throw new ConnectorError(\n 'Empty 200 body from /ilp (expected OER ILP response)'\n );\n }\n // The packet's own verdict and everything riding beside it are read\n // independently and merged. They are genuinely independent: a FULFILL\n // can carry a `claimAck` of `rejected` (the connector delivered the\n // work and separately refused the claim that came with it), and a\n // REJECT always carries `accumulatedCost` where a FULFILL never does\n // (§1.6 — \"present on every REJECT this edge answers with … absent\n // from a FULFILL\"). Inferring either from the other loses money.\n return {\n ...mapIlpResponse(deserializeIlpPacket(buf), expectedFulfillment),\n ...readResponseMeta(response.headers),\n };\n }\n\n // Transport-level error (400 malformed, 401 auth, 413 too large, 5xx).\n const body = await response.text().catch(() => '');\n const detail = body ? `: ${body}` : '';\n\n // `402` is not a transport failure at all: the connector answered with\n // TERMS instead of doing the work — an unpaid request to a priced route,\n // or a request that arrived over a carriage this route does not accept\n // (§1.4). Both carry the same x402 v2 document, the second adding\n // `extra.requiredTransport`. Thrown with the parsed terms so a caller can\n // act on them rather than re-parse an English message.\n //\n // Pre-1.0 this class caught a 402 (and a bare 401) purely to signal\n // \"retry over BTP\". That fallback is gone: 1.0 decides its carriage up\n // front from the node's own self-description (`selectTransport`), so\n // reaching a 402 that names a required transport now means the\n // self-description and the route policy disagree — a fact worth\n // surfacing, not a step in the happy path.\n if (response.status === 402) {\n let parsedBody: unknown;\n try {\n parsedBody = JSON.parse(body);\n } catch {\n parsedBody = undefined;\n }\n const terms = parsePaymentTerms(parsedBody, this.httpEndpoint);\n const required = terms?.requiredTransport;\n // A greeting that NAMES a carriage is a different refusal from one that\n // merely asks to be paid, because the remedy is different: paying more\n // will never help, and re-sending over the named carriage always will.\n if (required !== undefined) {\n throw new TransportRequiredError(\n `The connector at ${this.httpEndpoint} refused this write over HTTP; ` +\n `the route requires the ${required} transport.`,\n { required, ...(terms !== undefined ? { terms } : {}) }\n );\n }\n if (terms !== undefined) {\n throw new PaymentRequiredError(\n `The connector at ${this.httpEndpoint} answered 402 with terms for ` +\n `${terms.destination} at ${terms.price}.`,\n terms\n );\n }\n // A 402 this client cannot read as a TOON greeting at all — a vanilla\n // x402 challenge, or a malformed body. Surfaced as the transport error\n // it is rather than as terms nobody can act on.\n throw new ConnectorError(\n `Connector answered 402 with no usable TOON terms${detail}`\n );\n }\n\n if (response.status >= 500) {\n throw new ConnectorError(\n `Connector transport error (${response.status} ${response.statusText})${detail}`\n );\n }\n // 4xx — non-retryable client/transport error.\n throw new ConnectorError(\n `ILP-over-HTTP request rejected (${response.status} ${response.statusText})${detail}`\n );\n }\n\n private mapTransportError(error: unknown, requestTimeout: number): Error {\n if (\n error instanceof ConnectorError ||\n error instanceof NetworkError ||\n // Thrown by `mapResponse` inside the same try. Neither is a\n // `ConnectorError` (carrying the terms is the whole point of those\n // classes), so each needs its own check to pass through unwrapped — and\n // neither may be retried: repeating the POST only repeats the 402.\n error instanceof PaymentRequiredError ||\n error instanceof TransportRequiredError\n ) {\n return error;\n }\n if (error instanceof Error && error.name === 'AbortError') {\n return new NetworkError(\n `Request timeout after ${requestTimeout}ms`,\n error\n );\n }\n if (\n error instanceof TypeError &&\n (error.message.includes('fetch failed') ||\n error.message.includes('ECONNREFUSED') ||\n error.message.includes('ECONNRESET') ||\n error.message.includes('ETIMEDOUT') ||\n error.message.includes('network'))\n ) {\n return new NetworkError(\n `Network connection failed: ${error.message}`,\n error\n );\n }\n return new ConnectorError(\n `Unexpected error during ILP-over-HTTP request: ${\n error instanceof Error ? error.message : String(error)\n }`,\n error instanceof Error ? error : undefined\n );\n }\n}\n\n/**\n * Derive the BTP WebSocket URL from a `POST /ilp` HTTP endpoint. The connector\n * serves BTP on the SAME path, so we only swap the scheme (http→ws, https→wss).\n */\nexport function httpEndpointToBtpUrl(httpEndpoint: string): string {\n return httpEndpoint\n .replace(/^https:\\/\\//i, 'wss://')\n .replace(/^http:\\/\\//i, 'ws://');\n}\n\n/**\n * Build a WebSocket factory that opens the BTP upgrade with a `btp` subprotocol\n * and the given handshake headers. Node-only — lazily loads the `ws` package via\n * a dynamically-imported `createRequire` so the node-only `node:module`/`ws`\n * deps never enter a browser bundle (per-connection headers aren't settable on\n * the browser WebSocket anyway).\n */\nasync function makeBtpWebSocketFactory(\n headers: Record<string, string>\n): Promise<(url: string) => WebSocket> {\n const { createRequire } = await import('node:module');\n const require = createRequire(import.meta.url);\n const WS = require('ws') as typeof WSModule;\n\n // CJS/ESM interop: walk the constructor ladder (class / .default / .WebSocket)\n // so this works under any loader.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const ws = WS as any;\n const WSClass = (typeof ws === 'function'\n ? ws\n : typeof ws.default === 'function'\n ? ws.default\n : typeof ws.WebSocket === 'function'\n ? ws.WebSocket\n : null) as unknown as typeof WSModule.prototype.constructor;\n if (WSClass === null) {\n throw new Error(\n \"makeBtpWebSocketFactory: require('ws') did not yield a constructor on .default, .WebSocket, or the module root.\"\n );\n }\n\n // `ws` accepts (url, protocols, options); the connector negotiates `btp` and\n // pre-authenticates the session from the `ILP-Peer-Id`/`Authorization` headers.\n return (url: string): WebSocket =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (WSClass as any)(url, 'btp', { headers }) as unknown as WebSocket;\n}\n","/**\n * URL string handling that stays linear on adversarial input.\n *\n * Every URL this package trims arrives from a caller — a `connector` in the\n * config, a `faucetUrl`, an endpoint read off a node's self-description — so it\n * is library input rather than a constant, and the cost of handling it should\n * not depend on how it is shaped.\n */\n\n/** `/`, compared by code unit so no substring is allocated per character. */\nconst SLASH = 0x2f;\n\n/**\n * `url` with any trailing `/` removed.\n *\n * Written as a scan rather than `replace(/\\/+$/, '')` because that regular\n * expression backtracks: with `+` under an end anchor, a string of many slashes\n * that does NOT end in one makes the engine retry the run from each position in\n * turn, which is quadratic in the length of the run (`js/polynomial-redos`).\n * The equivalent scan visits each trailing slash once and allocates one string.\n */\nexport function trimTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url.charCodeAt(end - 1) === SLASH) end -= 1;\n return end === url.length ? url : url.slice(0, end);\n}\n","/**\n * Ask a connector who it is, what it charges, and what a path would cost — the\n * steps that have to happen BEFORE a packet can be formed at all.\n *\n * ADR 0018 makes holding the terminating connector's public key a\n * precondition of forming a packet: `Prepare.data` is sealed to that key, and\n * sealing to the wrong one is a confidentiality failure, not a delivery\n * failure. ADR 0022 says the connector *answers* — it never announces — so\n * every fact here is fetched from the connector's own client edge\n * (`docs/protocol/client-edge-spec.md`), never pushed to this client and never\n * read out of a preset.\n *\n * - `GET /ilp` → the node self-description: addresses, endpoints, sealing key,\n * per-chain settlement facts, route prices, required carriage. The one\n * document a stranger needs, and what replaced peer discovery entirely\n * ({@link describe}).\n * - `GET /ilp/identity` → `{ \"keyId\": \"...\", \"publicKey\": \"0x04...\" }` — the\n * uncompressed secp256k1 key, 65 bytes, `0x`-prefixed hex (§1.7). The\n * self-description carries the same key; this endpoint predates it and is\n * the fallback for a node whose document omits `edgeIdentity`.\n * - `GET /ilp/routes/price?destination=<ILP address>` →\n * `{ \"destination\": \"...\", \"price\": 100 }`, or `404` when no configured\n * route matches (§1.7).\n * - `POST /ilp` with no claim → the x402 greeting for a route ({@link terms},\n * §1.4). Free by the wire's own contract.\n * - `POST /ilp/probe` → what a path costs, learned without paying for it\n * ({@link probe}, §1.6). The one call here that needs a claim, and the claim\n * identifies rather than pays.\n * - `POST /ilp/claim-state` → the credited position of channels this client\n * controls ({@link getClaimState}, §1.10).\n *\n * All but the last two are unauthenticated, and none of them changes state.\n *\n * ─── What this module refuses to do ────────────────────────────────────────\n * Unlike the 402-challenge parser next door (which degrades gracefully so an\n * unrecognised connector shape falls back to the vanilla 402), an identity is\n * parsed STRICTLY. A key that is the wrong length, not `0x04`-prefixed, or not\n * valid hex is refused with a distinguishable error rather than carried\n * forward: a half-understood key would be sealed to, and the failure would be\n * silent. There is no \"best effort\" reading of a public key.\n *\n * Pure transport + parsing: no keys are held, nothing is signed, and the only\n * state is the identity cache.\n */\n\nimport { NetworkError, ToonClientError, ConnectorError } from '../client/errors.js';\nimport {\n ILPPacketType,\n deserializeIlpPacket,\n serializeIlpPrepare,\n} from '../btp/protocol.js';\nimport { parseX402Body, type ToonTermsInfo } from './x402.js';\nimport type { BatchSettlementOffer } from '../channel/batch-settlement/offers.js';\nimport {\n parseSelfDescription,\n readBaseUnits,\n type NodeSelfDescription,\n type RouteCharge,\n} from './self-description.js';\nimport {\n mapIlpResponse,\n resolveExpectedFulfillment,\n resolveExpiresAt,\n type IlpSendParams,\n} from '../ilp/ilp-send.js';\nimport type { IlpSendResult } from '../ilp/types.js';\nimport { readResponseMeta } from '../http/HttpIlpClient.js';\nimport { toBase64, encodeUtf8, fromBase64 } from '../utils/binary.js';\nimport { assertValidFulfillment } from '../utils/fulfillment.js';\nimport { trimTrailingSlashes } from '../utils/url.js';\n\n// ─── Identity ───────────────────────────────────────────────────────────────\n\n/** The terminating connector's own identity, as reported by `GET /ilp/identity`. */\nexport interface ConnectorIdentity {\n /** The key id identifying the key (opaque to this client). */\n keyId: string;\n /** The uncompressed secp256k1 public key — exactly 65 raw bytes, leading `0x04`. */\n publicKey: Uint8Array;\n /** The key exactly as reported, `0x`-prefixed lowercase hex (65 bytes → 132 chars). */\n publicKeyHex: string;\n /** The normalized client-edge base URL this identity was read from. */\n endpoint: string;\n}\n\n/**\n * A route's terms as the x402 greeting states them (ADR 0075): what it costs,\n * and — per chain the node settles on — the x402 `batch-settlement` offer a\n * channel is opened on.\n */\nexport interface ConnectorRouteTerms {\n destination: string;\n price: string;\n /** One offer per chain, priced for this route. */\n batchSettlements: BatchSettlementOffer[];\n /** `extensions.toon.info`, preserved verbatim (issue #509). */\n info: ToonTermsInfo;\n}\n\n/** What a locally-terminated route costs, as reported by `GET /ilp/routes/price`. */\nexport interface ConnectorRoutePrice extends RouteCharge {\n /** The ILP destination that was asked about (echoed by the connector). */\n destination: string;\n}\n\n// ─── Claim state (client-edge-spec.md §1.10, connector #693) ──────────────\n\n/**\n * One `POST /ilp/claim-state` request entry: a voucher claim-state challenge\n * (`channel/batch-settlement/challenge.ts`), proving control of the channel's\n * voucher signer without moving value. Built by `signEvmChallenge` /\n * `signSolanaChallenge`, and sent as they built it.\n */\nexport type ClaimStateRequestEntry = Record<string, unknown>;\n\n/**\n * Where the connector stands on one x402 channel this client controls (ADR\n * 0075). A voucher has no nonce, so neither does this: the next voucher must\n * strictly exceed `cumulativeClaimed`. Money fields are decimal strings.\n */\nexport interface ClaimStateOk {\n blockchain: 'evm' | 'solana';\n channelId: string;\n ok: true;\n scheme: 'batch-settlement';\n /** The highest cumulative amount the connector has accepted a voucher for; `\"0\"` for none. */\n cumulativeClaimed: string;\n /** The highest cumulative a voucher may name and still be accepted, as the gate reads it now. */\n maxCumulative: string;\n /** `maxCumulative − cumulativeClaimed`, at least zero: what the next voucher may add. */\n available: string;\n /**\n * Best-effort and non-durable (unlike every other field here): `null`\n * means \"unknown\", NEVER \"never claimed\" — see client-edge-spec.md §1.10.\n */\n lastClaimTime: number | null;\n}\n\n/**\n * A failed claim-state entry. `error` is deliberately coarse, so a caller\n * learns nothing about a channel it does not control: `\"unverified\"` covers\n * \"no such channel\" and \"bad signature\" identically. `\"toon-channel-refused\"`\n * names an entry for a retired `toon-channel` channel.\n */\nexport interface ClaimStateFailed {\n blockchain: 'evm' | 'solana';\n channelId?: string;\n ok: false;\n error: 'expired' | 'unverified' | 'toon-channel-refused';\n}\n\nexport type ClaimStateResult = ClaimStateOk | ClaimStateFailed;\n\n/**\n * Every distinguishable way asking a connector for its identity or terms can\n * fail. Each code names exactly one cause; there is no catch-all, because the\n * caller's next move differs per cause (retry a transport failure; never\n * retry a malformed key).\n */\nexport type ConnectorEdgeErrorCode =\n /** Non-2xx from `GET /ilp/identity`. */\n | 'IDENTITY_HTTP_STATUS'\n /** `GET /ilp/identity` answered 2xx with a body that is not the documented object. */\n | 'IDENTITY_MALFORMED'\n /** `publicKey` is present but is not `0x`-prefixed even-length hex. */\n | 'IDENTITY_KEY_NOT_HEX'\n /** `publicKey` decodes, but not to exactly 65 bytes. */\n | 'IDENTITY_KEY_LENGTH'\n /** `publicKey` is 65 bytes but does not start with the SEC1 uncompressed tag `0x04`. */\n | 'IDENTITY_KEY_NOT_UNCOMPRESSED'\n /** Non-2xx, non-404 from `GET /ilp/routes/price` (404 is not an error — see below). */\n | 'ROUTE_PRICE_HTTP_STATUS'\n /** `GET /ilp/routes/price` answered 2xx with a body that is not the documented object. */\n | 'ROUTE_PRICE_MALFORMED'\n /** A destination that cannot be put in a query string was asked about. */\n | 'INVALID_DESTINATION'\n /** A 402 greeting whose body is not the documented x402 shape (or whose\n * optional `settlement` facts are present but malformed — refused rather\n * than silently dropped, since they would be opened AGAINST). */\n | 'TERMS_MALFORMED'\n /** Non-2xx from `POST /ilp/claim-state`. */\n | 'CLAIM_STATE_HTTP_STATUS'\n /** `POST /ilp/claim-state` answered 2xx with a body that is not the documented shape. */\n | 'CLAIM_STATE_MALFORMED'\n /** Non-2xx, non-429 from `GET /ilp` (the node self-description). */\n | 'SELF_DESCRIPTION_HTTP_STATUS'\n /** `GET /ilp` answered 2xx with a body that is not JSON at all. */\n | 'SELF_DESCRIPTION_MALFORMED'\n /**\n * `GET /ilp` answered `429`: the node's unresolvable-lookup budget is spent.\n *\n * Its own code, not folded into {@link SELF_DESCRIPTION_HTTP_STATUS},\n * because it is the one self-description failure that is purely temporal —\n * the same request succeeds once the shaper drains. The connector runs this\n * endpoint through the shaper that already guards chain lookups rather than\n * a limiter of its own (connector ADR 0050), so the bucket is shared: a\n * flood of channel resolutions can spend the budget a description request\n * then finds empty. Back off and re-ask; never re-derive the document from\n * a preset.\n */\n | 'SELF_DESCRIPTION_BUDGETED'\n /** `POST /ilp/probe` answered a non-2xx, non-403 status. */\n | 'PROBE_HTTP_STATUS'\n /**\n * `POST /ilp/probe` answered `403`.\n *\n * Deliberately distinct from a `401` (`IDENTITY_*`/transport auth): the\n * sender may be perfectly well authenticated and simply not *authorized to\n * probe* (`client-edge-spec.md` §1.6). It means one of exactly two things —\n * this connector recognizes no payment channel of the sender's, or the\n * sender is over its per-channel probe rate limit — and the remedies differ\n * from an auth failure's entirely: open (or pay on) a channel, or wait.\n */\n | 'PROBE_FORBIDDEN';\n\n/**\n * A refusal to carry a connector's answer forward. Distinct from\n * {@link NetworkError} (which this module throws for a transport failure), so\n * \"the connector is unreachable\" and \"the connector answered something I will\n * not seal to\" are never confused.\n */\nexport class ConnectorEdgeError extends ToonClientError {\n /** Narrowed from `ToonClientError`'s `string`; type-only, no runtime field. */\n declare readonly code: ConnectorEdgeErrorCode;\n\n constructor(message: string, code: ConnectorEdgeErrorCode, cause?: Error) {\n super(message, code, cause);\n this.name = 'ConnectorEdgeError';\n }\n}\n\n// ─── URL handling ───────────────────────────────────────────────────────────\n\n/**\n * Normalize any client-edge URL a caller already holds into the base the\n * `/ilp/*` routes hang off.\n *\n * Callers reach this module holding whatever the x402 offer or their config\n * gave them — `https://apex.example`, `https://apex.example/`, or the\n * `POST /ilp` endpoint `https://apex.example/ilp` itself. All three name the\n * same client edge, so all three normalize to `https://apex.example`.\n */\nexport function connectorEdgeBaseUrl(endpoint: string): string {\n let url: URL;\n try {\n url = new URL(endpoint);\n } catch (error) {\n throw new ConnectorEdgeError(\n `not a valid connector endpoint URL: ${endpoint}`,\n 'IDENTITY_MALFORMED',\n error instanceof Error ? error : undefined\n );\n }\n // Drop a trailing `/ilp` (the POST endpoint) and any trailing slashes.\n let path = trimTrailingSlashes(url.pathname);\n if (path.endsWith('/ilp')) path = path.slice(0, -'/ilp'.length);\n url.pathname = path;\n url.search = '';\n url.hash = '';\n return trimTrailingSlashes(url.toString());\n}\n\n// ─── Parsing (pure, exported so the wire shape is testable without a server) ─\n\nconst UNCOMPRESSED_KEY_BYTES = 65;\nconst SEC1_UNCOMPRESSED_TAG = 0x04;\n\n/**\n * Decode a `0x`-prefixed hex public key into its 65 raw bytes, refusing\n * anything that is not exactly one uncompressed secp256k1 key.\n */\nexport function decodeConnectorPublicKey(publicKeyHex: string): Uint8Array {\n const trimmed = publicKeyHex.trim();\n if (!/^0x[0-9a-fA-F]*$/.test(trimmed) || trimmed.length % 2 !== 0) {\n throw new ConnectorEdgeError(\n `connector publicKey is not 0x-prefixed hex: ${publicKeyHex}`,\n 'IDENTITY_KEY_NOT_HEX'\n );\n }\n const hex = trimmed.slice(2);\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n if (bytes.length !== UNCOMPRESSED_KEY_BYTES) {\n throw new ConnectorEdgeError(\n `connector publicKey must be ${UNCOMPRESSED_KEY_BYTES} bytes, got ${bytes.length}`,\n 'IDENTITY_KEY_LENGTH'\n );\n }\n const tag = bytes[0] ?? 0;\n if (tag !== SEC1_UNCOMPRESSED_TAG) {\n throw new ConnectorEdgeError(\n `connector publicKey must be SEC1-uncompressed (0x04 prefix), got 0x${tag.toString(16).padStart(2, '0')}`,\n 'IDENTITY_KEY_NOT_UNCOMPRESSED'\n );\n }\n return bytes;\n}\n\n/**\n * Parse an already-decoded `GET /ilp/identity` body. Exported so the shape the\n * connector actually emits can be pinned without standing up a server.\n */\nexport function parseConnectorIdentity(\n body: unknown,\n endpoint: string\n): ConnectorIdentity {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n throw new ConnectorEdgeError(\n 'GET /ilp/identity did not answer a JSON object',\n 'IDENTITY_MALFORMED'\n );\n }\n const record = body as Record<string, unknown>;\n const keyId = record['keyId'];\n const publicKeyHex = record['publicKey'];\n if (typeof keyId !== 'string' || keyId.length === 0) {\n throw new ConnectorEdgeError(\n 'GET /ilp/identity answered without a keyId',\n 'IDENTITY_MALFORMED'\n );\n }\n if (typeof publicKeyHex !== 'string' || publicKeyHex.length === 0) {\n throw new ConnectorEdgeError(\n 'GET /ilp/identity answered without a publicKey',\n 'IDENTITY_MALFORMED'\n );\n }\n return {\n keyId,\n publicKey: decodeConnectorPublicKey(publicKeyHex),\n publicKeyHex: publicKeyHex.trim().toLowerCase(),\n endpoint,\n };\n}\n\n/** Parse an already-decoded `GET /ilp/routes/price` 200 body. */\nexport function parseConnectorRoutePrice(body: unknown): ConnectorRoutePrice {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n throw new ConnectorEdgeError(\n 'GET /ilp/routes/price did not answer a JSON object',\n 'ROUTE_PRICE_MALFORMED'\n );\n }\n const record = body as Record<string, unknown>;\n const destination = record['destination'];\n const price = record['price'];\n if (typeof destination !== 'string' || destination.length === 0) {\n throw new ConnectorEdgeError(\n 'GET /ilp/routes/price answered without a destination',\n 'ROUTE_PRICE_MALFORMED'\n );\n }\n if (\n typeof price !== 'number' ||\n !Number.isFinite(price) ||\n !Number.isInteger(price) ||\n price < 0\n ) {\n throw new ConnectorEdgeError(\n `GET /ilp/routes/price answered a non-integer price: ${String(price)}`,\n 'ROUTE_PRICE_MALFORMED'\n );\n }\n // `price_per_kib` is snake_case here and camelCase in `GET /ilp`; both spellings\n // are accepted so a metered route is never quoted at its base price alone.\n // Unusable is treated as absent — this endpoint is the cheap pre-flight, and\n // refusing the whole answer over a rate would be worse than the flat quote\n // callers had before.\n const pricePerKib = readBaseUnits(record['price_per_kib'] ?? record['pricePerKib']);\n return {\n destination,\n price: BigInt(price),\n ...(pricePerKib !== undefined ? { pricePerKib } : {}),\n };\n}\n\n/** A required-string reader, refusing a missing/wrong-typed field by name. */\nfunction claimStr(\n e: Record<string, unknown>,\n key: string,\n entryIndex: number\n): string {\n const value = e[key];\n if (typeof value !== 'string') {\n throw new ConnectorEdgeError(\n `claim-state channel entry ${entryIndex} lacks a string '${key}'`,\n 'CLAIM_STATE_MALFORMED'\n );\n }\n return value;\n}\n\n/** Parse one already-object-checked claim-state response entry. */\nfunction parseClaimStateEntry(raw: unknown, entryIndex: number): ClaimStateResult {\n if (typeof raw !== 'object' || raw === null) {\n throw new ConnectorEdgeError(\n `claim-state channel entry ${entryIndex} is not an object`,\n 'CLAIM_STATE_MALFORMED'\n );\n }\n const e = raw as Record<string, unknown>;\n const blockchain = e['blockchain'];\n if (blockchain !== 'evm' && blockchain !== 'solana') {\n throw new ConnectorEdgeError(\n `claim-state channel entry ${entryIndex} names neither 'evm' nor 'solana'`,\n 'CLAIM_STATE_MALFORMED'\n );\n }\n const channelId =\n typeof e['channelId'] === 'string'\n ? e['channelId']\n : typeof e['channelAccount'] === 'string'\n ? e['channelAccount']\n : undefined;\n\n if (e['ok'] === false) {\n const error = e['error'];\n if (error !== 'expired' && error !== 'unverified' && error !== 'toon-channel-refused') {\n throw new ConnectorEdgeError(\n `claim-state channel entry ${entryIndex} has an undocumented error: ${String(error)}`,\n 'CLAIM_STATE_MALFORMED'\n );\n }\n return { blockchain, ...(channelId !== undefined ? { channelId } : {}), ok: false, error };\n }\n if (e['ok'] !== true) {\n throw new ConnectorEdgeError(\n `claim-state channel entry ${entryIndex} lacks a boolean 'ok'`,\n 'CLAIM_STATE_MALFORMED'\n );\n }\n if (channelId === undefined) {\n throw new ConnectorEdgeError(\n `claim-state channel entry ${entryIndex} names no channel`,\n 'CLAIM_STATE_MALFORMED'\n );\n }\n const lastClaimTime = e['lastClaimTime'] ?? null;\n if (\n lastClaimTime !== null &&\n (typeof lastClaimTime !== 'number' || !Number.isInteger(lastClaimTime))\n ) {\n throw new ConnectorEdgeError(\n `claim-state channel entry ${entryIndex}'s lastClaimTime is neither an integer nor null`,\n 'CLAIM_STATE_MALFORMED'\n );\n }\n return {\n blockchain,\n channelId,\n ok: true,\n scheme: 'batch-settlement',\n cumulativeClaimed: claimStr(e, 'cumulativeClaimed', entryIndex),\n maxCumulative: claimStr(e, 'maxCumulative', entryIndex),\n available: claimStr(e, 'available', entryIndex),\n lastClaimTime,\n };\n}\n\n/**\n * Parse an already-decoded `POST /ilp/claim-state` body. Exported so the wire\n * shape is testable without a server. Refuses a body that is not the\n * documented `{ channels: [...] }` object, or any entry within it that is\n * not the documented ok/failed shape — a half-understood credited balance\n * would misreport an agent's runway, which is the one thing this endpoint\n * exists to get right (toon-meta#262 decision 9).\n */\nexport function parseClaimStateResponse(body: unknown): ClaimStateResult[] {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n throw new ConnectorEdgeError(\n 'POST /ilp/claim-state did not answer a JSON object',\n 'CLAIM_STATE_MALFORMED'\n );\n }\n const channels = (body as Record<string, unknown>)['channels'];\n if (!Array.isArray(channels)) {\n throw new ConnectorEdgeError(\n \"POST /ilp/claim-state answered without a 'channels' array\",\n 'CLAIM_STATE_MALFORMED'\n );\n }\n return channels.map((entry, i) => parseClaimStateEntry(entry, i));\n}\n\n// ─── Client ─────────────────────────────────────────────────────────────────\n\nexport interface ConnectorEdgeClientConfig {\n /** HTTP fetch implementation. Default: global `fetch`. Injectable for tests. */\n fetch?: typeof fetch;\n /** Per-request timeout in milliseconds. Default 10_000. */\n timeout?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/**\n * Separator between a client-edge base URL and an ILP destination in a price\n * cache key. NUL can appear in neither, so no pair can be spelled two ways\n * and no two pairs can collide.\n */\nconst PRICE_KEY_SEPARATOR = '\\u0000';\n\n/** Cache key for one (client edge, destination) pair. */\nfunction priceCacheKey(base: string, destination: string): string {\n return `${base}${PRICE_KEY_SEPARATOR}${destination}`;\n}\n\n/**\n * The prefix every key for `base` shares — `priceCacheKey`'s own output for\n * an empty destination, so the two cannot drift into disagreeing about the\n * separator. They once did, and the endpoint-wide invalidation below then\n * silently matched nothing.\n */\nfunction priceCacheKeyPrefix(base: string): string {\n return priceCacheKey(base, '');\n}\n\n/**\n * Asks connectors for their identity and their terms, caching each identity\n * per client-edge endpoint and each route price per (endpoint, destination).\n *\n * The cache is per endpoint rather than per client instance because a sender\n * routinely speaks to several connectors, and re-fetching a key per packet\n * would put a network round trip in front of every send. Nothing here expires\n * on a timer: an operator key rotation, or a route being repriced, is a\n * deliberate event, so {@link invalidateIdentity} / {@link invalidateRoutePrice}\n * are how a stale answer is dropped.\n *\n * A price is cached the same way and for the same reason (toon-client#452):\n * under ADR 0020 a route's price is FLAT — one handler, one price — so it does\n * not vary with what is being sent, and asking again per packet would buy\n * nothing but latency.\n */\nexport class ConnectorEdgeClient {\n private readonly fetchImpl: typeof fetch;\n private readonly timeout: number;\n private readonly identities = new Map<string, Promise<ConnectorIdentity>>();\n private readonly prices = new Map<\n string,\n Promise<ConnectorRoutePrice | null>\n >();\n private readonly descriptions = new Map<\n string,\n Promise<NodeSelfDescription>\n >();\n\n constructor(config: ConnectorEdgeClientConfig = {}) {\n this.fetchImpl = config.fetch ?? globalThis.fetch.bind(globalThis);\n this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;\n }\n\n /**\n * The terminating connector's public key, fetched once per endpoint.\n *\n * `endpoint` MUST already be the TERMINATING connector's client edge, not\n * merely whatever origin a caller is about to POST an ILP packet to —\n * those are the same machine for most routes today, but never for a\n * forwarded prefix (ADR 0022, toon-client#526). This method trusts\n * `endpoint` and fetches exactly that origin's `/ilp/identity`; resolving\n * a destination address to its terminator first is the caller's job.\n *\n * @param endpoint the TERMINATING connector's client-edge URL\n * (`https://apex`, `https://apex/ilp`) — already resolved from the\n * destination, never assumed to be the posting edge.\n * @param options `forceRefresh` bypasses (and replaces) the cache entry.\n */\n async getIdentity(\n endpoint: string,\n options: { forceRefresh?: boolean } = {}\n ): Promise<ConnectorIdentity> {\n const base = connectorEdgeBaseUrl(endpoint);\n if (options.forceRefresh) this.identities.delete(base);\n\n const cached = this.identities.get(base);\n if (cached) return cached;\n\n // Cache the in-flight promise so concurrent senders share one round trip;\n // drop it again on failure so a transient error is not cached forever.\n const inFlight = this.fetchIdentity(base).catch((error: unknown) => {\n this.identities.delete(base);\n throw error;\n });\n this.identities.set(base, inFlight);\n return inFlight;\n }\n\n /**\n * Drop a cached identity — one endpoint's, or every endpoint's when\n * `endpoint` is omitted. The way to react to a key rotation.\n */\n invalidateIdentity(endpoint?: string): void {\n if (endpoint === undefined) {\n this.identities.clear();\n return;\n }\n this.identities.delete(connectorEdgeBaseUrl(endpoint));\n }\n\n /** Whether an identity for `endpoint` is already held (no request is made). */\n hasCachedIdentity(endpoint: string): boolean {\n return this.identities.has(connectorEdgeBaseUrl(endpoint));\n }\n\n /**\n * The node's own self-description — `GET /ilp`, the one free, unauthenticated\n * document that carries every fact needed to transact with it\n * (`client-edge-spec.md` §1.7's siblings, connector ADR 0050): the addresses\n * it answers to, the endpoints it answers on, the key a packet is sealed to,\n * the per-chain channel-opening facts, its route prices, and — when its own\n * routes agree on one — the carriage it requires.\n *\n * This is what replaced peer discovery. A 1.0 client asks the connector it\n * is configured against instead of subscribing to a relay for announcements\n * the Rust fleet never makes (ADR 0022: a connector answers, it never\n * announces; ADR 0046 removed the announce).\n *\n * Cached per client-edge endpoint for the same reason an identity is: a\n * sender speaks to a connector many times per session and the document\n * changes only on an operator action. It is generated from live state on\n * every request the connector serves, though — a route written through the\n * operator surface shows up in the next answer — so a caller that has reason\n * to believe the node changed passes `forceRefresh`, and\n * {@link invalidateDescription} drops a cached one outright.\n *\n * @param endpoint the connector's client-edge URL (`https://apex`,\n * `https://apex/ilp` — both normalize to the same base).\n * @param options `forceRefresh` bypasses (and replaces) the cache entry.\n * @throws {NetworkError} the connector could not be reached.\n * @throws {ConnectorEdgeError} `SELF_DESCRIPTION_BUDGETED` when the node's\n * lookup budget is spent (`429` — retry later), `SELF_DESCRIPTION_HTTP_STATUS`\n * for any other non-2xx, `SELF_DESCRIPTION_MALFORMED` for a non-JSON body.\n */\n async describe(\n endpoint: string,\n options: { forceRefresh?: boolean } = {}\n ): Promise<NodeSelfDescription> {\n const base = connectorEdgeBaseUrl(endpoint);\n if (options.forceRefresh) this.descriptions.delete(base);\n\n const cached = this.descriptions.get(base);\n if (cached) return cached;\n\n // Cache the in-flight promise so concurrent callers share one round trip;\n // drop it again on failure so neither a transport error nor an exhausted\n // lookup budget — the most transient failure this endpoint has — is\n // cached as though it were the node's answer.\n const inFlight = this.fetchDescription(base).catch((error: unknown) => {\n this.descriptions.delete(base);\n throw error;\n });\n this.descriptions.set(base, inFlight);\n return inFlight;\n }\n\n /**\n * Drop a cached self-description — one endpoint's, or every endpoint's when\n * `endpoint` is omitted. The way to react to an operator changing a node.\n */\n invalidateDescription(endpoint?: string): void {\n if (endpoint === undefined) {\n this.descriptions.clear();\n return;\n }\n this.descriptions.delete(connectorEdgeBaseUrl(endpoint));\n }\n\n /** Whether a self-description for `endpoint` is already held (no request is made). */\n hasCachedDescription(endpoint: string): boolean {\n return this.descriptions.has(connectorEdgeBaseUrl(endpoint));\n }\n\n /**\n * Learn what a path costs without paying for it: `POST /ilp/probe`\n * (`client-edge-spec.md` §1.6, connector ADR 0011).\n *\n * Request body and response framing are `POST /ilp`'s exactly — the same OER\n * PREPARE in, the same `200` + OER FULFILL/REJECT out — and the answer is\n * read through the same {@link mapIlpResponse} the paying carriages use, so\n * a probe's outcome and a write's outcome cannot be shaped differently. What\n * differs is the gate in front and that nothing is charged.\n *\n * The `claim` **identifies rather than pays**. It runs §1.3's gate in full\n * against a price of `0`, so possession of the channel is proven and a\n * replay is still refused, but no value need advance: a sender probes by\n * reissuing at the same cumulative amount with a fresh nonce. Passing a\n * claim that DOES advance value is legal and simply spends a nonce for\n * nothing.\n *\n * The whole point is the answer's `accumulatedCost`: a destination this\n * connector terminates is answered `F03` carrying that route's price rather\n * than being delivered (free traversal is all a probe buys — it does not\n * also buy the work behind a priced route), and a destination beyond it is\n * routed normally, so what comes back is one figure covering every hop's fee\n * plus the terminating route's price.\n *\n * @throws {NetworkError} the connector could not be reached.\n * @throws {ConnectorEdgeError} `PROBE_FORBIDDEN` on `403` — no channel this\n * connector recognizes, or over the probe rate limit; never confuse it\n * with a `401`, which is a failure to authenticate rather than a refusal\n * to authorize.\n */\n async probe(\n endpoint: string,\n params: IlpSendParams,\n claim: Record<string, unknown>\n ): Promise<IlpSendResult> {\n const base = connectorEdgeBaseUrl(endpoint);\n const url = `${base}/ilp/probe`;\n\n // Same discipline as the paying transports: an expected fulfilment must\n // be exactly 32 bytes, or nothing a real FULFILL could carry would ever\n // match it.\n const expectedFulfillment = resolveExpectedFulfillment(\n params.expectedFulfillment\n );\n if (expectedFulfillment !== undefined) {\n assertValidFulfillment(expectedFulfillment);\n }\n const timeout = params.timeout ?? this.timeout;\n const prepare = serializeIlpPrepare({\n type: ILPPacketType.PREPARE,\n amount: BigInt(params.amount),\n destination: params.destination,\n greeting: params.greeting ?? false,\n expiresAt: resolveExpiresAt(params.expiresAt, timeout),\n data: fromBase64(params.data),\n });\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/octet-stream',\n // The plaintext claim header, base64(JSON) — the HTTP spelling of\n // the same object BTP sends as raw UTF-8 (§1.3 vs §1.9 step 2).\n 'ILP-Payment-Channel-Claim': toBase64(\n encodeUtf8(JSON.stringify(claim))\n ),\n },\n body: prepare.slice(),\n signal: controller.signal,\n });\n } catch (error) {\n throw new NetworkError(\n `could not reach the connector client edge at ${url}`,\n error instanceof Error ? error : undefined\n );\n } finally {\n clearTimeout(timer);\n }\n\n if (response.status === 403) {\n throw new ConnectorEdgeError(\n `POST /ilp/probe answered 403: ${await response\n .text()\n .catch(() => 'not authorized to probe')}`,\n 'PROBE_FORBIDDEN'\n );\n }\n if (!response.ok) {\n throw new ConnectorEdgeError(\n `POST /ilp/probe answered ${response.status}`,\n 'PROBE_HTTP_STATUS'\n );\n }\n\n const body = new Uint8Array(await response.arrayBuffer());\n if (body.length === 0) {\n throw new ConnectorError(\n 'Empty 200 body from /ilp/probe (expected an OER ILP response)'\n );\n }\n // `toon-accumulated-cost` rides beside the packet, never inside it\n // (§1.6) — reading it is the whole reason to probe.\n return {\n ...mapIlpResponse(deserializeIlpPacket(body), expectedFulfillment),\n ...readResponseMeta(response.headers),\n };\n }\n\n /**\n * What `destination` costs at this connector, or `null` when the connector\n * answers `404` — no locally-terminated route matches it.\n *\n * `null` is the answer to \"you do not terminate this\", which is information;\n * a transport failure throws {@link NetworkError} instead, so a caller can\n * always tell \"not mine\" from \"could not ask\".\n *\n * Fetched once per (endpoint, destination) and reused. ADR 0020 makes a\n * price flat per handler, so it does not vary with the packet — a route\n * being repriced is an operator event, and {@link invalidateRoutePrice} is\n * how a caller reacts to one.\n *\n * @param options `forceRefresh` bypasses (and replaces) the cache entry.\n */\n async getRoutePrice(\n endpoint: string,\n destination: string,\n options: { forceRefresh?: boolean } = {}\n ): Promise<ConnectorRoutePrice | null> {\n if (typeof destination !== 'string' || destination.trim().length === 0) {\n throw new ConnectorEdgeError(\n 'a route price needs a non-empty ILP destination',\n 'INVALID_DESTINATION'\n );\n }\n const base = connectorEdgeBaseUrl(endpoint);\n const key = priceCacheKey(base, destination);\n if (options.forceRefresh) this.prices.delete(key);\n\n const cached = this.prices.get(key);\n if (cached) return cached;\n\n // Cache the in-flight promise so concurrent senders share one round trip;\n // drop it again on failure so a transient error is not cached forever. A\n // `404` IS cached: \"this connector does not terminate that\" is an answer.\n const inFlight = this.fetchRoutePrice(base, destination).catch(\n (error: unknown) => {\n this.prices.delete(key);\n throw error;\n }\n );\n this.prices.set(key, inFlight);\n return inFlight;\n }\n\n /**\n * Ask a route for its full x402 terms — the greeting a claimless PREPARE\n * is answered with (client-edge-spec.md §1.4) — including, from a settling\n * node, the channel-opening facts (connector #617).\n *\n * This is a real `POST /ilp` carrying a minimal PREPARE with no claim\n * header. It is free by the wire's own contract: an unpaid request to a\n * priced route is answered with terms instead of performed, and nothing\n * is charged for asking. `null` when the connector does not price the\n * destination (the request would be routed or refused, not greeted) —\n * mapped from anything other than a 402 answer.\n */\n async terms(\n endpoint: string,\n destination: string\n ): Promise<ConnectorRouteTerms | null> {\n if (typeof destination !== 'string' || destination.trim().length === 0) {\n throw new ConnectorEdgeError(\n 'route terms need a non-empty ILP destination',\n 'INVALID_DESTINATION'\n );\n }\n const base = connectorEdgeBaseUrl(endpoint);\n // A syntactically complete PREPARE with a near-term expiry and no data;\n // the amount is irrelevant to the greeting.\n //\n // `greeting: false` is deliberate, and is what this method meant before\n // ADR 0069 took the execution condition off the wire: it sent a PRESENT\n // condition, so the edge's greeting gate fired only on `charge > 0` — a\n // route this connector actually prices. Setting the flag would broaden\n // that to every destination, and the terms this returns would stop\n // meaning \"this route costs that much\". `null` for a destination the\n // connector does not price is the answer, not a gap to paper over.\n const prepare = serializeIlpPrepare({\n type: ILPPacketType.PREPARE,\n amount: 0n,\n destination,\n greeting: false,\n expiresAt: new Date(Date.now() + 30_000),\n data: new Uint8Array(0),\n });\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n let response: Response;\n try {\n response = await this.fetchImpl(`${base}/ilp`, {\n method: 'POST',\n headers: { 'content-type': 'application/octet-stream' },\n body: prepare.slice(),\n signal: controller.signal,\n });\n } catch (error) {\n throw new NetworkError(\n `could not reach the connector client edge at ${base}/ilp`,\n error instanceof Error ? error : undefined\n );\n } finally {\n clearTimeout(timer);\n }\n\n if (response.status !== 402) return null;\n let body: unknown;\n try {\n body = await response.json();\n } catch (error) {\n throw new ConnectorEdgeError(\n 'connector answered 402 with a body that is not JSON',\n 'TERMS_MALFORMED',\n error instanceof Error ? error : undefined\n );\n }\n return parseConnectorRouteTerms(body);\n }\n\n /**\n * The credited/spendable position of one or more channels this client\n * controls (`POST /ilp/claim-state`, client-edge-spec.md §1.10) — the\n * runway source of truth (toon-meta#261/#262 decision 9): earnings net\n * off-chain on the same channel a client spends from, so this is also\n * where a credited balance is read. Never cached: unlike identity/price,\n * a claim watermark changes on every accepted claim, on EITHER side.\n *\n * Each entry is independently authenticated (own signature, own\n * blockchain) — a request MAY mix EVM and Solana channels. Returns `[]`\n * without a request when `channels` is empty.\n *\n * @throws {NetworkError} the connector could not be reached.\n * @throws {ConnectorEdgeError} a non-2xx status, or a body that is not the\n * documented shape.\n */\n async getClaimState(\n endpoint: string,\n channels: ClaimStateRequestEntry[]\n ): Promise<ClaimStateResult[]> {\n if (channels.length === 0) return [];\n const base = connectorEdgeBaseUrl(endpoint);\n const url = `${base}/ilp/claim-state`;\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n accept: 'application/json',\n },\n body: JSON.stringify({ channels }),\n signal: controller.signal,\n });\n } catch (error) {\n throw new NetworkError(\n `could not reach the connector client edge at ${url}`,\n error instanceof Error ? error : undefined\n );\n } finally {\n clearTimeout(timer);\n }\n\n if (!response.ok) {\n throw new ConnectorEdgeError(\n `POST /ilp/claim-state answered ${response.status}`,\n 'CLAIM_STATE_HTTP_STATUS'\n );\n }\n return parseClaimStateResponse(\n await this.readJson(response, 'CLAIM_STATE_MALFORMED')\n );\n }\n\n /**\n * Drop a cached route price — one (endpoint, destination)'s, every\n * destination's at one endpoint when `destination` is omitted, or all of\n * them when both are. The way to react to a route being repriced.\n */\n invalidateRoutePrice(endpoint?: string, destination?: string): void {\n if (endpoint === undefined) {\n this.prices.clear();\n return;\n }\n const base = connectorEdgeBaseUrl(endpoint);\n if (destination !== undefined) {\n this.prices.delete(priceCacheKey(base, destination));\n return;\n }\n const prefix = priceCacheKeyPrefix(base);\n for (const key of this.prices.keys()) {\n if (key.startsWith(prefix)) this.prices.delete(key);\n }\n }\n\n /**\n * Whether a price for `(endpoint, destination)` is already held (no request\n * is made).\n */\n hasCachedRoutePrice(endpoint: string, destination: string): boolean {\n return this.prices.has(\n priceCacheKey(connectorEdgeBaseUrl(endpoint), destination)\n );\n }\n\n private async fetchRoutePrice(\n base: string,\n destination: string\n ): Promise<ConnectorRoutePrice | null> {\n const url = `${base}/ilp/routes/price?destination=${encodeURIComponent(destination)}`;\n const response = await this.get(url);\n\n if (response.status === 404) return null;\n if (!response.ok) {\n throw new ConnectorEdgeError(\n `GET /ilp/routes/price answered ${response.status}`,\n 'ROUTE_PRICE_HTTP_STATUS'\n );\n }\n return parseConnectorRoutePrice(\n await this.readJson(response, 'ROUTE_PRICE_MALFORMED')\n );\n }\n\n private async fetchDescription(base: string): Promise<NodeSelfDescription> {\n const response = await this.get(`${base}/ilp`);\n if (response.status === 429) {\n throw new ConnectorEdgeError(\n `GET /ilp answered 429: the node's lookup budget is spent — back off and re-ask`,\n 'SELF_DESCRIPTION_BUDGETED'\n );\n }\n if (!response.ok) {\n throw new ConnectorEdgeError(\n `GET /ilp answered ${response.status}`,\n 'SELF_DESCRIPTION_HTTP_STATUS'\n );\n }\n // `parseSelfDescription` never throws on a shape it does not recognise —\n // an unreadable field is dropped and the rest of the document survives —\n // so the only failure left here is a body that is not JSON at all.\n return parseSelfDescription(\n await this.readJson(response, 'SELF_DESCRIPTION_MALFORMED'),\n base\n );\n }\n\n private async fetchIdentity(base: string): Promise<ConnectorIdentity> {\n const response = await this.get(`${base}/ilp/identity`);\n if (!response.ok) {\n throw new ConnectorEdgeError(\n `GET /ilp/identity answered ${response.status}`,\n 'IDENTITY_HTTP_STATUS'\n );\n }\n return parseConnectorIdentity(\n await this.readJson(response, 'IDENTITY_MALFORMED'),\n base\n );\n }\n\n private async readJson(\n response: Response,\n code: ConnectorEdgeErrorCode\n ): Promise<unknown> {\n try {\n return await response.json();\n } catch (error) {\n throw new ConnectorEdgeError(\n 'connector answered a body that is not JSON',\n code,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /** GET with a timeout, mapping any transport failure onto {@link NetworkError}. */\n private async get(url: string): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n try {\n return await this.fetchImpl(url, {\n method: 'GET',\n headers: { accept: 'application/json' },\n signal: controller.signal,\n });\n } catch (error) {\n throw new NetworkError(\n `could not reach the connector client edge at ${url}`,\n error instanceof Error ? error : undefined\n );\n } finally {\n clearTimeout(timer);\n }\n }\n}\n\n/**\n * Parse an x402 v2 greeting body into {@link ConnectorRouteTerms}. Pure and\n * exported so the wire shape is testable without a server. Refuses a body\n * with no TOON terms, or a priced route offering no x402 `batch-settlement`\n * channel — a reader that finds no `accepts[]` entry must not treat the route\n * as free.\n */\nexport function parseConnectorRouteTerms(body: unknown): ConnectorRouteTerms {\n if (typeof body !== 'object' || body === null) {\n throw new ConnectorEdgeError('x402 greeting is not an object', 'TERMS_MALFORMED');\n }\n const parsed = parseX402Body(body);\n if (parsed.toon === undefined) {\n throw new ConnectorEdgeError(\n 'x402 greeting carries no TOON terms (extensions.toon.info)',\n 'TERMS_MALFORMED'\n );\n }\n if (parsed.toon.amount > 0n && parsed.batchSettlements.length === 0) {\n throw new ConnectorEdgeError(\n 'x402 greeting prices the route but offers no batch-settlement channel to pay it on',\n 'TERMS_MALFORMED'\n );\n }\n return {\n destination: parsed.toon.destination,\n price: parsed.toon.amount.toString(),\n batchSettlements: parsed.batchSettlements,\n info: parsed.toon.info,\n };\n}\n","/**\n * Which carriage to pay a node over, decided BEFORE a packet is formed.\n *\n * The connector serves ILP-over-HTTP (`POST /ilp`) and BTP (`GET /ilp/btp`) on\n * the same port, and a route's transport policy — `both` by default, or\n * restricted to one — is per-connector configuration, not a protocol constant\n * (`client-edge-spec.md` §1.4 \"Transport policy\", issue #701). A request over a\n * carriage its route does not accept is refused before payment is considered at\n * all: `402` on HTTP, an `F02` REJECT on BTP, both carrying the same x402 terms\n * with `extra.requiredTransport` naming the carriage the route does require.\n *\n * So a 1.0 client asks first. The node's self-description (`GET /ilp`) carries\n * `httpEndpoint`, `btpEndpoint`, a `requiredTransport` on **each route that\n * pins one** (connector ND-05a / ADR 0072) and a node-wide one summarising the\n * routes that cover its own addresses, and this module reads a carriage off\n * that document. That is the whole of the change from 0.x, which\n * had no such document: it keyed this decision on a peer discovered from a\n * kind:10032 relay announce, then POSTed over HTTP and treated the resulting\n * `402`/`401` as the signal to retry over BTP. Both halves of that are gone —\n * the announce (connector ADR 0046) and the catch-a-failure fallback.\n *\n * This module decides; it opens nothing. Turning a {@link TransportChoice} into\n * a live transport is the caller's job.\n */\n\nimport type { NodeSelfDescription } from '../connector/self-description.js';\nimport { requiredTransportFor } from '../connector/self-description.js';\nimport type { TransportPreference } from '../client/types.js';\nimport { TransportRequiredError } from '../client/errors.js';\n\n/**\n * `'auto'` is a preference, not an instruction: it defers to the node. An\n * explicit `'http'`/`'btp'` is an instruction, and is refused rather than\n * silently downgraded when the node publishes no such endpoint — a client that\n * asked for BTP and got HTTP would be paying over a carriage it deliberately\n * did not choose.\n */\nexport type { TransportPreference };\n\n/** The carriage to use, and the absolute URL to reach it at. */\nexport interface TransportChoice {\n kind: 'http' | 'btp';\n /**\n * `POST /ilp` for `http`, the `ws(s)://` websocket URL for `btp` — absolute,\n * resolved against the base the description was read from when the node\n * published a relative endpoint.\n */\n url: string;\n}\n\n/**\n * Choose a carriage for `description`.\n *\n * - `'http'` / `'btp'`: honoured when the node publishes that endpoint;\n * {@link TransportRequiredError} otherwise, naming the node's own\n * `requiredTransport` when it stated one so the caller learns what to ask\n * for instead.\n * - `'auto'`: the carriage the node requires for `destination` when it states\n * one, else HTTP when it publishes an `httpEndpoint`, else BTP. HTTP is the\n * default because it is stateless — one request, no session to keep alive —\n * and a client that needs ordered claim nonces across many writes is a client\n * that will ask for BTP explicitly (§1.9: one socket, one order, no racing\n * into `F01 NonceNotAdvancing`).\n *\n * **The requirement is read per destination**, through\n * {@link requiredTransportFor}: the route governing `destination` first, the\n * node-wide `requiredTransport` only where that route names none. A pin is\n * enforced by a longest-prefix route lookup, once per packet, so a per-node\n * answer describes it only on a node whose routes happen to agree — and a node\n * with a pinned apex and a free sub-lane does not. Naming no `destination` asks\n * about the node alone, which is all a caller with no packet in hand can mean.\n *\n * @param description the node's `GET /ilp` answer.\n * @param preference what the caller asked for. Default `'auto'`.\n * @param baseUrl the client-edge URL the description was read from, for\n * resolving a relative endpoint. Defaults to `description.readFrom`, which\n * `ConnectorEdgeClient.describe` records; an absolute endpoint needs neither.\n * @param destination the ILP address this carriage will carry packets to, so\n * the route that governs it answers rather than the node-wide summary.\n * @throws {TransportRequiredError} the requested carriage is unavailable, or\n * the node publishes no usable endpoint at all.\n */\nexport function selectTransport(\n description: NodeSelfDescription,\n preference: TransportPreference = 'auto',\n baseUrl: string | undefined = description.readFrom,\n destination?: string\n): TransportChoice {\n const http = resolveEndpoint(description.httpEndpoint, baseUrl);\n const btp = resolveEndpoint(description.btpEndpoint, baseUrl);\n const required = requiredTransportFor(description, destination);\n\n if (preference === 'http' || preference === 'btp') {\n const url = preference === 'http' ? http : btp;\n if (url === undefined) {\n throw new TransportRequiredError(\n `the connector publishes no ${preference} endpoint` +\n (required !== undefined\n ? `; its self-description requires the ${required} transport`\n : ''),\n required !== undefined ? { required } : {}\n );\n }\n return { kind: preference, url };\n }\n\n // 'auto'. A node that states a requirement for this destination has already\n // made the decision — that is the carriage its route lookup will insist on,\n // packet by packet — so honouring it is not a preference but the only way a\n // packet gets routed at all.\n if (required !== undefined) {\n const url = required === 'http' ? http : btp;\n if (url === undefined) {\n throw new TransportRequiredError(\n `the connector requires the ${required} transport but publishes no ${required} endpoint`,\n { required }\n );\n }\n return { kind: required, url };\n }\n\n if (http !== undefined) return { kind: 'http', url: http };\n if (btp !== undefined) return { kind: 'btp', url: btp };\n throw new TransportRequiredError(\n 'the connector publishes neither an httpEndpoint nor a btpEndpoint'\n );\n}\n\n/**\n * Make a published endpoint absolute.\n *\n * A node's endpoints are configured strings, not introspected ones — a\n * container sees `0.0.0.0:4000` and can never learn its own public name\n * (`connector_domain::NodeFacts`) — so an operator MAY publish a relative one,\n * as the sibling x402 greeting field literally does (`\"httpEndpoint\": \"/ilp\"`).\n * A relative endpoint means \"on the origin that answered\", which is exactly\n * what `baseUrl` is. An already-absolute endpoint is returned unchanged, and an\n * unresolvable one is passed through rather than dropped: a caller reporting a\n * bad URL is more useful than one reporting no endpoint at all.\n */\nfunction resolveEndpoint(\n endpoint: string | undefined,\n baseUrl: string | undefined\n): string | undefined {\n const trimmed = endpoint?.trim();\n if (!trimmed) return undefined;\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) return trimmed;\n if (!baseUrl) return trimmed;\n try {\n return new URL(trimmed, baseUrl).toString();\n } catch {\n return trimmed;\n }\n}\n","/**\n * Persistent, strictly-ordered BTP transport for paid writes (issue #482).\n *\n * ─── Why this exists ─────────────────────────────────────────────────────\n * `HttpIlpClient` (the default paid-write transport, `POST /ilp`) is\n * stateless: every write is an independent HTTP request, and the connector's\n * claim gate advances a channel's nonce watermark per request in WHATEVER\n * order those requests happen to arrive — client-edge-spec.md §1.3 step 2. A\n * burst of concurrent paid writes on one channel can therefore race each\n * other into `F01 NonceNotAdvancing`: two requests both built against the\n * same last-known nonce, one arrives first and advances the watermark, the\n * other is now stale.\n *\n * The connector's client-facing BTP websocket ingress (client-edge-spec.md\n * §1.9, connector#680/#674) processes frames on ONE session strictly in\n * arrival order — the next frame is not read until the previous frame's\n * claim has been judged. A client that dispatches its OWN claims in the same\n * order it enqueued them therefore never races itself. This was measured on\n * the huddle-over-ILP prototype (`toon-meta/prototypes/huddle-over-ilp`,\n * branch `proto/huddle-over-ilp`): 0 F01 rejects across 4,156 events at a\n * paced 50fps (audio-frame-rate) sustained load, where the equivalent\n * unordered concurrent-HTTP baseline raced.\n *\n * This module productizes that pattern as a reusable transport rather than\n * a one-off harness: a caller that needs many ordered paid writes on one\n * channel (the motivating consumer is relay-native huddle audio, ~140fps of\n * measured headroom per session) constructs one `BtpPaidWriteTransport`\n * around a `BtpRuntimeClient` session and sends through it exactly like any\n * other `sendIlpPacketWithClaim`-shaped transport.\n *\n * ─── What it adds over a bare `BtpRuntimeClient` ────────────────────────\n * - **Persistent session**: the underlying session is connected once,\n * lazily, on the first write, and stays open across every subsequent\n * write. This is NOT the `Http402Client.upgradeToBtp()` pattern (open,\n * send one packet, immediately disconnect) — the whole point is to reuse\n * one ordered socket across a burst.\n * - **Strictly ordered dispatch**: every `sendIlpPacketWithClaim` call is\n * appended to a FIFO queue; the next call is not dispatched onto the wire\n * until the previous one has fully settled (fulfilled, rejected, or\n * fallen back to HTTP). Callers may still fire writes concurrently\n * (`Promise.all`) — ordering is enforced here, not pushed onto the\n * caller.\n * - **Reconnect + resume**: a write that fails on a connection-level error\n * (socket dropped mid-burst) reconnects the SAME session and retries\n * that write in place, without losing its position in the queue and\n * without reordering the writes queued behind it — they simply wait for\n * it to resolve one way or another.\n * - **Falls back to HTTP**: once the reconnect budget for one write is\n * exhausted, the write is handed to `fallback` (typically the existing\n * `HttpIlpClient`) when one is configured, so a BTP outage degrades a\n * session to the pre-existing one-shot behavior instead of failing the\n * write outright.\n *\n * Only CONNECTION-level failures (dropped socket, timeout — the errors\n * `BtpRuntimeClient`/`IsomorphicBtpClient` throw) are retried or routed to\n * the fallback. An ILP-level REJECT (F02, T01, ...) is a normal\n * `IlpSendResult`, exactly like every other transport here — it is returned\n * to the caller unchanged, never retried and never silently resent over\n * HTTP (a claim that was actually judged and refused must not be replayed).\n */\n\nimport type { IlpSendResult } from '../ilp/types.js';\nimport type { IlpSendParams } from '../ilp/ilp-send.js';\nimport { NetworkError } from '../client/errors.js';\n\n/**\n * The narrow shape a paid-write transport candidate needs — the same method\n * `ToonClient.getClaimTransport()` already requires of `HttpIlpClient` and\n * `BtpRuntimeClient`. Declared independently so this module (and its tests)\n * do not need the concrete transport classes.\n */\nexport interface ClaimSendingTransport {\n sendIlpPacketWithClaim(\n params: IlpSendParams,\n claim: unknown\n ): Promise<IlpSendResult>;\n sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;\n}\n\n/**\n * The subset of `BtpRuntimeClient` this transport drives. `BtpRuntimeClient`\n * satisfies this structurally — no adapter needed — but tests can supply a\n * lightweight fake instead of a real WebSocket-backed instance.\n */\nexport interface OrderedBtpSession {\n readonly isConnected: boolean;\n connect(): Promise<void>;\n reconnect(): Promise<void>;\n disconnect(): Promise<void>;\n sendIlpPacketWithClaim(\n params: IlpSendParams,\n claim: Record<string, unknown>\n ): Promise<IlpSendResult>;\n sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;\n}\n\nexport interface BtpPaidWriteTransportConfig {\n /**\n * The persistent BTP session this transport owns the connect/reconnect\n * lifecycle of. May already be connected (the common case — `modes/http.ts`\n * connects `btpClient` at startup) or not; either way it is connected\n * lazily on first use and never disconnected between writes.\n */\n session: OrderedBtpSession;\n /**\n * Stateless fallback used once a write's reconnect budget is exhausted.\n * Typically an `HttpIlpClient` pointed at the same connector's `POST /ilp`.\n * Omit to have an exhausted BTP session fail the write outright.\n */\n fallback?: ClaimSendingTransport;\n /**\n * Reconnect attempts for one write before giving up on BTP (and, if\n * configured, falling back to HTTP). Default 1 — one explicit reconnect\n * beyond whatever retrying the session already does internally.\n */\n maxReconnectAttempts?: number;\n /** Delay before each reconnect attempt, in ms. Default 250. */\n reconnectDelay?: number;\n}\n\n/** Message substrings that identify a connection-level (retryable) failure,\n * as opposed to an application-level one. Mirrors `BtpRuntimeClient`'s own\n * `isConnectionError` — duplicated rather than imported since that helper is\n * private to a different transport and this module must not reach into it. */\nfunction isConnectionError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const msg = error.message.toLowerCase();\n return (\n msg.includes('not connected') ||\n msg.includes('connection') ||\n msg.includes('websocket') ||\n msg.includes('econnrefused') ||\n msg.includes('econnreset') ||\n msg.includes('socket hang up') ||\n msg.includes('timeout')\n );\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Wraps an {@link OrderedBtpSession} (a `BtpRuntimeClient`) as a first-class,\n * persistent, strictly-ordered paid-write transport with an optional HTTP\n * fallback. See the module docs above for the full rationale.\n */\nexport class BtpPaidWriteTransport implements ClaimSendingTransport {\n private readonly session: OrderedBtpSession;\n private readonly fallback: ClaimSendingTransport | undefined;\n private readonly maxReconnectAttempts: number;\n private readonly reconnectDelay: number;\n /**\n * Tail of the ordering queue. ALWAYS settles (never rejects) so one\n * failed write can never strand every write queued behind it — only the\n * write itself carries its own outcome, via the promise `sendIlpPacketWithClaim`\n * returns to its caller.\n */\n private queueTail: Promise<void> = Promise.resolve();\n\n constructor(config: BtpPaidWriteTransportConfig) {\n this.session = config.session;\n this.fallback = config.fallback;\n this.maxReconnectAttempts = config.maxReconnectAttempts ?? 1;\n this.reconnectDelay = config.reconnectDelay ?? 250;\n }\n\n /** Whether the underlying session currently holds an open socket. */\n get isConnected(): boolean {\n return this.session.isConnected;\n }\n\n /** Explicitly closes the persistent session (e.g. `ToonClient.stop()`). */\n async disconnect(): Promise<void> {\n await this.session.disconnect();\n }\n\n /**\n * Enqueue a claim-bearing write. The returned promise resolves/rejects\n * with THIS write's own outcome; its position in the queue only controls\n * WHEN it is dispatched onto the wire, never what it returns.\n */\n sendIlpPacketWithClaim(\n params: IlpSendParams,\n claim: unknown\n ): Promise<IlpSendResult> {\n const dispatched = this.queueTail.then(() =>\n this.dispatchWithRetry(params, claim)\n );\n this.queueTail = dispatched.then(\n () => undefined,\n () => undefined\n );\n return dispatched;\n }\n\n /**\n * Send a packet with no claim, for a route priced at zero.\n *\n * Enqueued behind the same tail as a paid write. The ordering exists for\n * claims — nonces on one socket must not race — and an unpaid packet carries\n * none, so strictly it needs no slot. It takes one anyway: the queue also\n * serialises this transport's connect/reconnect policy, and letting an unpaid\n * send dial concurrently with a paid one would race the session itself rather\n * than the nonces.\n */\n sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult> {\n const dispatched = this.queueTail.then(() => this.dispatchUnpaid(params));\n this.queueTail = dispatched.then(\n () => undefined,\n () => undefined\n );\n return dispatched;\n }\n\n /** Connect if need be, then send once. No claim, so nothing to re-spend. */\n private async dispatchUnpaid(params: IlpSendParams): Promise<IlpSendResult> {\n if (!this.session.isConnected) await this.session.connect();\n return this.session.sendIlpPacket(params);\n }\n\n /**\n * One write's worth of connect/send/reconnect/fallback policy. Runs\n * strictly after every write enqueued ahead of it has settled.\n */\n private async dispatchWithRetry(\n params: IlpSendParams,\n claim: unknown\n ): Promise<IlpSendResult> {\n let attempt = 0;\n let lastError: unknown;\n\n // attempt 0: use the session as-is (connecting it if this is the very\n // first write). attempt 1..maxReconnectAttempts: explicit reconnect,\n // i.e. \"resume\" — the queue already guarantees nothing behind this write\n // has been dispatched early, so a reconnect here reorders nothing.\n while (attempt <= this.maxReconnectAttempts) {\n try {\n if (!this.session.isConnected) {\n if (attempt === 0) {\n await this.session.connect();\n } else {\n await sleep(this.reconnectDelay * attempt);\n await this.session.reconnect();\n }\n }\n return await this.session.sendIlpPacketWithClaim(\n params,\n claim as Record<string, unknown>\n );\n } catch (error) {\n lastError = error;\n if (!isConnectionError(error)) {\n throw error;\n }\n attempt += 1;\n }\n }\n\n if (this.fallback) {\n return this.fallback.sendIlpPacketWithClaim(params, claim);\n }\n\n throw lastError instanceof Error\n ? lastError\n : new NetworkError(\n 'BTP paid-write transport exhausted its reconnect budget and no HTTP fallback is configured'\n );\n }\n}\n","/**\n * Canonical OER length primitives (RFC-0030), ported byte-for-byte from\n * `connector_domain::oer` so the Rust and TypeScript fleets agree on the wire.\n *\n * \"Canonical\" is the whole point (ADR 0023): every value has exactly ONE\n * encoding, and a decoder that quietly accepts a second spelling of the same\n * value is a decoder two implementations can disagree through. So a\n * determinant is refused unless the bytes it introduces are exactly what\n * {@link encodeVarUint} would have produced:\n *\n * - `0x81 0x03` — a long form for `3`, which `0x03` already encodes — is\n * {@link OerErrorKind.NonCanonicalLength}, not `3`.\n * - `0x80` — a zero-byte long form aliasing `0x00` — is\n * {@link OerErrorKind.NonCanonicalLength}, not `0`.\n * - `0x89 …` — nine length bytes, which cannot fit a `u64` without silently\n * discarding the high-order ones — is\n * {@link OerErrorKind.LengthDeterminantOverflow}, not a truncated read.\n *\n * Values are `bigint` because the wire type is `u64` and `number` cannot hold\n * one; the caller narrows.\n *\n * Pure: no I/O, no keys, no clock.\n */\n\n/** The three, and only three, ways a length determinant can be refused. */\nexport enum OerErrorKind {\n /** The buffer ends before the field it declares does. */\n BufferUnderflow = 'buffer_underflow',\n /** A determinant that is not the minimal encoding of its own value. */\n NonCanonicalLength = 'non_canonical_length',\n /** A determinant wider than eight bytes (cannot be a `u64`). */\n LengthDeterminantOverflow = 'length_determinant_overflow',\n}\n\n/** A refusal from the length primitives, carrying which of the three it is. */\nexport class OerError extends Error {\n constructor(readonly kind: OerErrorKind) {\n super(OER_ERROR_MESSAGES[kind]);\n this.name = 'OerError';\n }\n}\n\nconst OER_ERROR_MESSAGES: Record<OerErrorKind, string> = {\n [OerErrorKind.BufferUnderflow]: 'buffer underflow: the value is truncated',\n [OerErrorKind.NonCanonicalLength]:\n 'non-canonical OER length determinant: not the minimal encoding of its value',\n [OerErrorKind.LengthDeterminantOverflow]:\n 'OER length determinant wider than 8 bytes',\n};\n\nconst MAX_DETERMINANT_BYTES = 8;\n\n/** Encode a VarUInt: `0..=127` as one byte, `128+` as a length-prefixed BE value. */\nexport function encodeVarUint(value: bigint): Uint8Array {\n if (value < 0n)\n throw new RangeError('VarUInt cannot encode a negative value');\n if (value <= 127n) return Uint8Array.of(Number(value));\n\n const body: number[] = [];\n let remaining = value;\n while (remaining > 0n) {\n body.unshift(Number(remaining & 0xffn));\n remaining >>= 8n;\n }\n if (body.length > MAX_DETERMINANT_BYTES) {\n throw new RangeError('VarUInt cannot encode a value wider than 8 bytes');\n }\n return Uint8Array.from([0x80 | body.length, ...body]);\n}\n\n/** A decoded field: its value, and how many bytes it consumed. */\nexport interface Decoded<T> {\n value: T;\n consumed: number;\n}\n\n/**\n * Decode a VarUInt at `offset`, refusing any non-canonical spelling.\n *\n * @throws {OerError} and nothing else — arbitrary bytes never produce a\n * `RangeError`, a `TypeError`, or a plausible-but-wrong value.\n */\nexport function decodeVarUint(\n buf: Uint8Array,\n offset: number\n): Decoded<bigint> {\n const first = buf[offset];\n if (first === undefined) throw new OerError(OerErrorKind.BufferUnderflow);\n if (first <= 127) return { value: BigInt(first), consumed: 1 };\n\n const length = first & 0x7f;\n if (length > MAX_DETERMINANT_BYTES) {\n throw new OerError(OerErrorKind.LengthDeterminantOverflow);\n }\n const start = offset + 1;\n const end = start + length;\n if (end > buf.length) throw new OerError(OerErrorKind.BufferUnderflow);\n\n let value = 0n;\n for (let i = start; i < end; i++) {\n value = (value << 8n) | BigInt(buf[i] as number);\n }\n const consumed = 1 + length;\n\n // The canonicality test, exactly as `connector_domain::oer` states it:\n // re-encode and demand the same bytes back. This is what rejects the\n // non-minimal long form and the zero-length alias in one check.\n const canonical = encodeVarUint(value);\n if (\n canonical.length !== consumed ||\n !canonical.every((byte, i) => byte === buf[offset + i])\n ) {\n throw new OerError(OerErrorKind.NonCanonicalLength);\n }\n return { value, consumed };\n}\n\n/** Encode a VarOctetString: a VarUInt length prefix followed by the bytes. */\nexport function encodeVarOctetString(data: Uint8Array): Uint8Array {\n const prefix = encodeVarUint(BigInt(data.length));\n const out = new Uint8Array(prefix.length + data.length);\n out.set(prefix, 0);\n out.set(data, prefix.length);\n return out;\n}\n\n/**\n * Decode a VarOctetString at `offset`.\n *\n * @throws {OerError} and nothing else.\n */\nexport function decodeVarOctetString(\n buf: Uint8Array,\n offset: number\n): Decoded<Uint8Array> {\n const { value: length, consumed: lengthBytes } = decodeVarUint(buf, offset);\n\n // A declared length larger than the whole buffer is underflow, checked in\n // `bigint` BEFORE any `Number` conversion so a `u64`-scale length can never\n // wrap into a plausible small one.\n if (length > BigInt(buf.length)) {\n throw new OerError(OerErrorKind.BufferUnderflow);\n }\n const start = offset + lengthBytes;\n const end = start + Number(length);\n if (end > buf.length) throw new OerError(OerErrorKind.BufferUnderflow);\n\n // A copy, not a view: a decoded body that aliases the input buffer would\n // change under a caller who reuses that buffer.\n return {\n value: buf.slice(start, end),\n consumed: lengthBytes + Number(length),\n };\n}\n","/**\n * The structured envelope (ADR 0018): what a packet carries between a\n * connector and the app behind it, encoded with the same OER primitives an ILP\n * packet already uses rather than as HTTP text.\n *\n * A faithful port of `connector_domain::envelope`\n * (`crates/connector-domain/src/envelope.rs`) — a method, target, ordered\n * headers and body going in; a two-byte big-endian status, headers and body\n * coming back. `vectors/wire-vectors.json` is the contract this is checked\n * against, and `wire-vectors.test.ts` is where that check happens; the prose\n * here describes the same thing but the bytes decide.\n *\n * ─── Why not HTTP text ─────────────────────────────────────────────────────\n * `utils/store-envelope.ts` builds latin1 HTTP/1.1 request text and\n * `utils/fulfill-http.ts` hand-parses a status line and scans for `\\r\\n\\r\\n`,\n * which is how they acquired leniencies nobody chose: a missing header/body\n * separator yielding an empty body, blank header lines skipped, spaces\n * tolerated inside the target. A structured encoding has exactly one\n * representation per message and nothing to smuggle. This module lands BESIDE\n * those two rather than replacing them — the swap is a later child — so it can\n * be reviewed against the vectors in isolation.\n *\n * ─── Headers are a list, not a map ─────────────────────────────────────────\n * A count prefix then `(name, value)` pairs in order. Both header ORDER and\n * DUPLICATE NAMES are meaningful on this wire and both survive a round trip; a\n * `Record<string, string>` would silently destroy each.\n *\n * Pure: no keys, no I/O, no clock. `@noble/*` is not involved.\n */\n\nimport {\n OerError,\n OerErrorKind,\n decodeVarOctetString,\n decodeVarUint,\n encodeVarOctetString,\n encodeVarUint,\n} from './oer.js';\n\nconst TYPE_ENVELOPE_REQUEST = 1;\nconst TYPE_ENVELOPE_RESPONSE = 2;\n\n/**\n * Every distinguishable way an envelope can fail to decode. These strings are\n * the vector file's `expected_error` values verbatim — the same names\n * `EnvelopeError` uses in `connector-domain` — so a replay compares reasons,\n * not just \"it threw\".\n *\n * There is deliberately no catch-all: a decoder with an `Invalid` bucket is a\n * decoder that can be lenient without anyone noticing.\n */\nexport enum EnvelopeErrorKind {\n /** The buffer ends before the envelope does. */\n BufferUnderflow = 'buffer_underflow',\n /** A length determinant that is not the minimal encoding of its value. */\n NonCanonicalLength = 'non_canonical_length',\n /** A length determinant wider than eight bytes. */\n LengthDeterminantOverflow = 'length_determinant_overflow',\n /** The type byte is not the one the requested direction requires. */\n InvalidType = 'invalid_type',\n /** A field that must be UTF-8 is not. */\n InvalidUtf8 = 'invalid_utf8',\n /** Bytes remain after a fully decoded envelope. */\n TrailingBytes = 'trailing_bytes',\n}\n\n/**\n * A refusal to decode. `kind` is the machine-readable reason; `field` names\n * the offending field for {@link EnvelopeErrorKind.InvalidUtf8}, matching\n * `EnvelopeError::InvalidUtf8(&'static str)` on the Rust side.\n */\nexport class EnvelopeError extends Error {\n constructor(\n readonly kind: EnvelopeErrorKind,\n readonly field?: string\n ) {\n super(\n field === undefined\n ? ENVELOPE_ERROR_MESSAGES[kind]\n : `${ENVELOPE_ERROR_MESSAGES[kind]} (field '${field}')`\n );\n this.name = 'EnvelopeError';\n }\n}\n\nconst ENVELOPE_ERROR_MESSAGES: Record<EnvelopeErrorKind, string> = {\n [EnvelopeErrorKind.BufferUnderflow]:\n 'buffer underflow: envelope is truncated',\n [EnvelopeErrorKind.NonCanonicalLength]:\n 'non-canonical OER length determinant: not the minimal encoding of its value',\n [EnvelopeErrorKind.LengthDeterminantOverflow]:\n 'OER length determinant wider than 8 bytes',\n [EnvelopeErrorKind.InvalidType]:\n 'invalid envelope type byte: expected 1 (REQUEST) or 2 (RESPONSE)',\n [EnvelopeErrorKind.InvalidUtf8]: 'invalid UTF-8 in envelope field',\n [EnvelopeErrorKind.TrailingBytes]:\n 'trailing bytes after a fully decoded envelope',\n};\n\n/** One `(name, value)` header, in wire order. Duplicates are legal. */\nexport type EnvelopeHeader = readonly [name: string, value: string];\n\n/** The request a connector is to make of the app behind a terminated route. */\nexport interface EnvelopeRequest {\n method: string;\n target: string;\n headers: readonly EnvelopeHeader[];\n body: Uint8Array;\n}\n\n/** The app's response back to the connector. */\nexport interface EnvelopeResponse {\n /** HTTP status, two bytes big-endian on the wire (`0..=65535`). */\n status: number;\n headers: readonly EnvelopeHeader[];\n body: Uint8Array;\n}\n\n/** Either direction, tagged — the shape the vector file's `decoded` carries. */\nexport type Envelope =\n | ({ direction: 'request' } & EnvelopeRequest)\n | ({ direction: 'response' } & EnvelopeResponse);\n\n// ─── Shared helpers ─────────────────────────────────────────────────────────\n\nconst UTF8_ENCODER = new TextEncoder();\n/** `fatal` is load-bearing: a lenient decoder would turn bad bytes into U+FFFD. */\nconst UTF8_DECODER = new TextDecoder('utf-8', { fatal: true });\n\n/** Map an {@link OerError} onto its envelope-level counterpart, 1:1. */\nfunction fromOerError(error: unknown): EnvelopeError {\n if (error instanceof OerError) {\n switch (error.kind) {\n case OerErrorKind.BufferUnderflow:\n return new EnvelopeError(EnvelopeErrorKind.BufferUnderflow);\n case OerErrorKind.NonCanonicalLength:\n return new EnvelopeError(EnvelopeErrorKind.NonCanonicalLength);\n case OerErrorKind.LengthDeterminantOverflow:\n return new EnvelopeError(EnvelopeErrorKind.LengthDeterminantOverflow);\n }\n }\n throw error;\n}\n\nfunction decodeOctets(\n buf: Uint8Array,\n offset: number\n): { value: Uint8Array; consumed: number } {\n try {\n return decodeVarOctetString(buf, offset);\n } catch (error) {\n throw fromOerError(error);\n }\n}\n\nfunction decodeCount(\n buf: Uint8Array,\n offset: number\n): {\n value: bigint;\n consumed: number;\n} {\n try {\n return decodeVarUint(buf, offset);\n } catch (error) {\n throw fromOerError(error);\n }\n}\n\n/** Decode a VarOctetString and validate it as UTF-8 in one step. */\nfunction decodeStringField(\n buf: Uint8Array,\n offset: number,\n field: string\n): { value: string; consumed: number } {\n const { value: bytes, consumed } = decodeOctets(buf, offset);\n try {\n return { value: UTF8_DECODER.decode(bytes), consumed };\n } catch {\n throw new EnvelopeError(EnvelopeErrorKind.InvalidUtf8, field);\n }\n}\n\nfunction checkTypeByte(buf: Uint8Array, expected: number): number {\n const typeByte = buf[0];\n if (typeByte === undefined) {\n throw new EnvelopeError(EnvelopeErrorKind.BufferUnderflow);\n }\n if (typeByte !== expected) {\n throw new EnvelopeError(EnvelopeErrorKind.InvalidType);\n }\n return 1;\n}\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction encodeHeaders(headers: readonly EnvelopeHeader[]): Uint8Array {\n const parts: Uint8Array[] = [encodeVarUint(BigInt(headers.length))];\n for (const [name, value] of headers) {\n parts.push(encodeVarOctetString(UTF8_ENCODER.encode(name)));\n parts.push(encodeVarOctetString(UTF8_ENCODER.encode(value)));\n }\n return concat(parts);\n}\n\nfunction decodeHeaders(\n buf: Uint8Array,\n offset: number\n): { value: EnvelopeHeader[]; consumed: number } {\n const { value: count, consumed: countBytes } = decodeCount(buf, offset);\n\n // Every header costs at least two bytes, so a count exceeding what remains\n // cannot be honoured. Checked in `bigint`, before any loop, so a `u64`-scale\n // count is refused as underflow instead of spinning.\n if (count * 2n > BigInt(buf.length - offset - countBytes)) {\n throw new EnvelopeError(EnvelopeErrorKind.BufferUnderflow);\n }\n\n let consumed = countBytes;\n const headers: EnvelopeHeader[] = [];\n for (let i = 0n; i < count; i++) {\n const name = decodeStringField(buf, offset + consumed, 'header name');\n consumed += name.consumed;\n const value = decodeStringField(buf, offset + consumed, 'header value');\n consumed += value.consumed;\n headers.push([name.value, value.value]);\n }\n return { value: headers, consumed };\n}\n\n// ─── Request ────────────────────────────────────────────────────────────────\n\n/** Encode a request envelope. The inverse of {@link decodeEnvelopeRequest}. */\nexport function encodeEnvelopeRequest(request: EnvelopeRequest): Uint8Array {\n return concat([\n Uint8Array.of(TYPE_ENVELOPE_REQUEST),\n encodeVarOctetString(UTF8_ENCODER.encode(request.method)),\n encodeVarOctetString(UTF8_ENCODER.encode(request.target)),\n encodeHeaders(request.headers),\n encodeVarOctetString(request.body),\n ]);\n}\n\n/**\n * Decode a request envelope, consuming the WHOLE buffer.\n *\n * @throws {EnvelopeError} and nothing else, for any input whatsoever.\n */\nexport function decodeEnvelopeRequest(buf: Uint8Array): EnvelopeRequest {\n let offset = checkTypeByte(buf, TYPE_ENVELOPE_REQUEST);\n\n const method = decodeStringField(buf, offset, 'method');\n offset += method.consumed;\n\n const target = decodeStringField(buf, offset, 'target');\n offset += target.consumed;\n\n const headers = decodeHeaders(buf, offset);\n offset += headers.consumed;\n\n const body = decodeOctets(buf, offset);\n offset += body.consumed;\n\n if (offset !== buf.length) {\n throw new EnvelopeError(EnvelopeErrorKind.TrailingBytes);\n }\n return {\n method: method.value,\n target: target.value,\n headers: headers.value,\n body: body.value,\n };\n}\n\n// ─── Response ───────────────────────────────────────────────────────────────\n\n/** Encode a response envelope. The inverse of {@link decodeEnvelopeResponse}. */\nexport function encodeEnvelopeResponse(response: EnvelopeResponse): Uint8Array {\n if (\n !Number.isInteger(response.status) ||\n response.status < 0 ||\n response.status > 0xffff\n ) {\n throw new RangeError(\n `envelope status must fit two bytes, got ${response.status}`\n );\n }\n return concat([\n Uint8Array.of(\n TYPE_ENVELOPE_RESPONSE,\n (response.status >> 8) & 0xff,\n response.status & 0xff\n ),\n encodeHeaders(response.headers),\n encodeVarOctetString(response.body),\n ]);\n}\n\n/**\n * Decode a response envelope, consuming the WHOLE buffer.\n *\n * @throws {EnvelopeError} and nothing else, for any input whatsoever.\n */\nexport function decodeEnvelopeResponse(buf: Uint8Array): EnvelopeResponse {\n let offset = checkTypeByte(buf, TYPE_ENVELOPE_RESPONSE);\n\n const high = buf[offset];\n const low = buf[offset + 1];\n if (high === undefined || low === undefined) {\n throw new EnvelopeError(EnvelopeErrorKind.BufferUnderflow);\n }\n const status = (high << 8) | low;\n offset += 2;\n\n const headers = decodeHeaders(buf, offset);\n offset += headers.consumed;\n\n const body = decodeOctets(buf, offset);\n offset += body.consumed;\n\n if (offset !== buf.length) {\n throw new EnvelopeError(EnvelopeErrorKind.TrailingBytes);\n }\n return { status, headers: headers.value, body: body.value };\n}\n\n// ─── Direction-tagged façade ────────────────────────────────────────────────\n\n/** Encode either direction from its tagged form. */\nexport function encodeEnvelope(envelope: Envelope): Uint8Array {\n return envelope.direction === 'request'\n ? encodeEnvelopeRequest(envelope)\n : encodeEnvelopeResponse(envelope);\n}\n\n/**\n * Decode as the named direction. The direction is an INPUT, never guessed from\n * the type byte: a caller that asked for a request and got a response has been\n * handed the wrong bytes, and `invalid_type` is the honest answer.\n */\nexport function decodeEnvelope(\n buf: Uint8Array,\n direction: 'request' | 'response'\n): Envelope {\n return direction === 'request'\n ? { direction, ...decodeEnvelopeRequest(buf) }\n : { direction, ...decodeEnvelopeResponse(buf) };\n}\n","/**\n * The gift wrap (ADR 0018) and the fulfilment a shared secret derives (ADR\n * 0019): the seal around the {@link ./envelope.js | envelope}, so a packet\n * payload is readable only by the connector that terminates it and the\n * preimage that pays for it needs no app participation.\n *\n * A faithful port of `connector_signer::giftwrap`\n * (`crates/connector-signer/src/giftwrap.rs` on toon-protocol/connector `main`)\n * and of `connector_domain::condition::derive_condition`\n * (`crates/connector-domain/src/condition.rs:27`). `vectors/wire-vectors.json`'s\n * `giftwrap` and `fulfilment` sections are the contract, replayed byte-for-byte\n * in `wire-vectors.test.ts`; the prose here describes the same thing but the\n * bytes decide.\n *\n * ─── The mechanism, as read off the Rust ────────────────────────────────────\n * Recorded here because it cannot be inferred from the vector file's field\n * names, and because the acceptance criterion for toon-client#449 asks for it\n * in writing. Every line below is cited to\n * `crates/connector-signer/src/giftwrap.rs` unless stated otherwise.\n *\n * - **Curve and ECDH.** The receiver's identity key is secp256k1; the value a\n * real connector reports from `GET /ilp/identity` is its 65-byte\n * uncompressed form (`0x04 ‖ X ‖ Y`). The sender ECDHs a fresh, per-packet\n * ephemeral key against it and uses the **raw X-coordinate** of the\n * resulting point — `crypto.rs`'s `ecdh_x_coordinate` does\n * `tweak_mul_assign` then `serialize_compressed()[1..]`, deliberately *not*\n * `libsecp256k1::SharedSecret`'s digest-mixing variant. So: not hashed, and\n * not the 33-byte compressed point.\n * - **Key derivation.** `HKDF-SHA256`, **no salt** (`Hkdf::new(None, ikm)`,\n * i.e. HKDF-Extract with an all-zero salt), expanded to 32 bytes under one\n * of three fixed ASCII `info` strings — `giftwrap.rs`'s `hkdf_key`:\n * - `toon-giftwrap-request` — the request AEAD key, over the ECDH X.\n * - `toon-giftwrap-response` — the response AEAD key, over the shared secret.\n * - `toon-giftwrap-fulfillment` — the fulfilment, over the shared secret.\n * (American spelling on the wire; the vector *section* is `fulfilment`.)\n * These three strings are the only domain separation between two AEAD keys\n * and a payment preimage all derived from the same input, so one wrong\n * character silently yields bytes that decrypt nothing and satisfy no\n * condition.\n * - **AEAD.** ChaCha20-Poly1305 (RFC 8439), 12-byte nonce, **no** additional\n * authenticated data.\n * - **Request framing.** `0x01 ‖ ephemeral_public(65) ‖ nonce(12) ‖\n * ciphertext`, where the encrypted plaintext is `shared_secret(32) ‖\n * encoded_envelope`. The secret rides *inside* the sealed request, which is\n * what lets the response be sealed with no second key exchange.\n * - **Response framing.** `0x02 ‖ nonce(12) ‖ ciphertext`, the plaintext being\n * just the encoded envelope. Sealed directly with the request's shared\n * secret.\n * - **Fulfilment.** `fulfilment = HKDF-SHA256(shared_secret,\n * \"toon-giftwrap-fulfillment\")`. The terminating connector recovers the\n * secret by opening the wrap and derives the preimage without asking the\n * app anything; the sender, which drew that secret, derives the same bytes\n * and so can check a delivery end to end. Nothing is minted onto the\n * PREPARE from it — connector ADR 0069 took the execution condition off the\n * wire entirely.\n * - **Telling a sealed reject from a plaintext one.** The leading type byte,\n * and only that (`looks_like_sealed_response`). A reject raised short of the\n * termination shares no secret with the sender and carries empty `data`; an\n * empty `data` is never sealed, so a sealed reject is positive proof that\n * the destination itself said no.\n *\n * ─── Two failure modes, two types ───────────────────────────────────────────\n * A wrap that cannot be OPENED throws {@link GiftWrapError}. A wrap that opens\n * cleanly but whose recovered plaintext is not a valid envelope throws\n * `EnvelopeError`, from `envelope.ts` — a different class entirely, raised\n * above this module rather than by it. The Rust keeps the same separation\n * (`GiftWrapError` vs `connector_domain::EnvelopeError`) for the same reason:\n * \"I could not read this\" and \"I read this and it was malformed\" are different\n * facts about a peer, and collapsing them loses the distinction at every call\n * site.\n *\n * ─── Callers ────────────────────────────────────────────────────────────────\n * `ToonClient.publishEvent` (toon-client#450) seals to a connector that\n * TERMINATES the destination and lets it derive the fulfilment (ADR 0019),\n * via `wire/sealed-exchange.ts`. `serve-job.ts`'s `createJobMessageHandler`\n * (toon-client#537) is the other direction: THIS client is the destination,\n * so it opens a request addressed to its own {@link giftWrapPublicKey} and\n * seals the answer back — never a connector-derived fulfilment, since the\n * hashlock preimage there comes from `hashlock-delivery.ts` instead.\n */\n\nimport { secp256k1 } from '@noble/curves/secp256k1.js';\nimport { chacha20poly1305 } from '@noble/ciphers/chacha.js';\nimport { hkdf } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\n\n// ─── Constants (giftwrap.rs:36-46) ──────────────────────────────────────────\n\n/** ChaCha20-Poly1305 nonce length. */\nexport const GIFTWRAP_NONCE_LENGTH = 12;\n/** The shared secret carried inside a sealed request, and the fulfilment. */\nexport const GIFTWRAP_SECRET_LENGTH = 32;\n/** The uncompressed secp256k1 public key a sealed request carries. */\nexport const GIFTWRAP_PUBLIC_KEY_LENGTH = 65;\n\nconst REQUEST_INFO = 'toon-giftwrap-request';\nconst RESPONSE_INFO = 'toon-giftwrap-response';\nconst FULFILLMENT_INFO = 'toon-giftwrap-fulfillment';\n\n/** `TYPE_GIFTWRAP_REQUEST` — the leading byte of a sealed request. */\nexport const GIFTWRAP_TYPE_REQUEST = 1;\n/** `TYPE_GIFTWRAP_RESPONSE` — the leading byte of a sealed response. */\nexport const GIFTWRAP_TYPE_RESPONSE = 2;\n\n/** Poly1305 tag length — the minimum a non-empty ciphertext can be. */\nconst TAG_LENGTH = 16;\n\n// ─── Errors ─────────────────────────────────────────────────────────────────\n\n/**\n * Every distinguishable way a wrap can fail to open — the four variants of\n * `GiftWrapError` in `giftwrap.rs:57-71`, named the same way. There is\n * deliberately no catch-all: this module must never be able to fail \"somehow\".\n *\n * None of these ever carries decrypted plaintext, matching the Rust's own\n * guarantee.\n */\nexport enum GiftWrapErrorKind {\n /** The leading byte is not the one this direction requires. */\n InvalidType = 'invalid_type',\n /** The bytes end before the framing does. */\n Truncated = 'truncated',\n /** An ephemeral or receiver public key that is not a usable curve point. */\n InvalidKey = 'invalid_key',\n /** The AEAD refused: wrong key, wrong nonce, or a tampered ciphertext. */\n OpenFailed = 'open_failed',\n}\n\nconst GIFTWRAP_ERROR_MESSAGES: Record<GiftWrapErrorKind, string> = {\n [GiftWrapErrorKind.InvalidType]: 'invalid gift wrap type byte',\n [GiftWrapErrorKind.Truncated]: 'gift wrap is truncated',\n [GiftWrapErrorKind.InvalidKey]: 'invalid ephemeral or peer public key',\n [GiftWrapErrorKind.OpenFailed]: 'gift wrap failed to decrypt',\n};\n\n/**\n * A refusal to open a wrap. `kind` is the machine-readable reason;\n * `expectedType` names the type byte that was required, for\n * {@link GiftWrapErrorKind.InvalidType} — mirroring\n * `GiftWrapError::InvalidType(u8)`.\n */\nexport class GiftWrapError extends Error {\n constructor(\n readonly kind: GiftWrapErrorKind,\n readonly expectedType?: number\n ) {\n super(\n expectedType === undefined\n ? GIFTWRAP_ERROR_MESSAGES[kind]\n : `${GIFTWRAP_ERROR_MESSAGES[kind]}: expected ${expectedType}`\n );\n this.name = 'GiftWrapError';\n }\n}\n\n// ─── Shapes ─────────────────────────────────────────────────────────────────\n\n/**\n * What sealing a request produces: the bytes to carry as `Prepare.data`, and\n * the shared secret that both derives this packet's fulfilment and opens the\n * answer. The sender must keep the secret — it is the only thing that opens\n * the response, and the only thing that proves the fulfilment it is paid\n * against was earned rather than guessed.\n */\nexport interface SealedRequest {\n /** `0x01 ‖ ephemeral_public(65) ‖ nonce(12) ‖ ciphertext`. */\n readonly wrapped: Uint8Array;\n /** The 32 random bytes sealed inside `wrapped`. */\n readonly sharedSecret: Uint8Array;\n}\n\n/** What opening a sealed request recovers. */\nexport interface OpenedRequest {\n /** The encoded envelope — feed to `decodeEnvelopeRequest`. */\n readonly envelopeBytes: Uint8Array;\n /** The 32-byte secret the sender chose, for the fulfilment and the answer. */\n readonly sharedSecret: Uint8Array;\n}\n\n/**\n * A key agreement that never hands out secret key material — the TypeScript\n * counterpart of `giftwrap.rs`'s dependency on `Signer::ecdh`, and the reason\n * {@link openRequest} takes this rather than a raw private key: a remote or\n * hardware-backed identity can open a wrap without its key leaving its own\n * boundary.\n *\n * Returns the raw 32-byte ECDH X-coordinate, or throws.\n */\nexport interface GiftWrapEcdh {\n ecdh(ephemeralPublicKey: Uint8Array): Uint8Array;\n}\n\n// ─── Primitives ─────────────────────────────────────────────────────────────\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\n/**\n * `HKDF-SHA256(ikm, salt = none, info, L = 32)` — `giftwrap.rs`'s `hkdf_key`.\n * The absent salt is load-bearing: HKDF-Extract runs with an all-zero salt, so\n * passing a salt of any kind produces a different, silently-wrong key.\n */\nfunction hkdfKey(ikm: Uint8Array, info: string): Uint8Array {\n return hkdf(sha256, ikm, undefined, info, 32);\n}\n\n/** `giftwrap.rs`'s `encrypt_with_nonce`: `nonce ‖ ciphertext`. */\nfunction encryptWithNonce(\n key: Uint8Array,\n plaintext: Uint8Array,\n nonce: Uint8Array\n): Uint8Array {\n return concat([nonce, chacha20poly1305(key, nonce).encrypt(plaintext)]);\n}\n\n/** `giftwrap.rs`'s `decrypt`: splits `nonce ‖ ciphertext` and opens it. */\nfunction decrypt(key: Uint8Array, nonceAndCiphertext: Uint8Array): Uint8Array {\n if (nonceAndCiphertext.length < GIFTWRAP_NONCE_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n const nonce = nonceAndCiphertext.subarray(0, GIFTWRAP_NONCE_LENGTH);\n const ciphertext = nonceAndCiphertext.subarray(GIFTWRAP_NONCE_LENGTH);\n // A ciphertext shorter than the Poly1305 tag cannot be an AEAD output at\n // all. `@noble/ciphers` throws a plain `Error` for that rather than failing\n // the tag check, so classify it here instead of letting a foreign error type\n // escape this module.\n if (ciphertext.length < TAG_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n try {\n return chacha20poly1305(key, nonce).decrypt(ciphertext);\n } catch {\n throw new GiftWrapError(GiftWrapErrorKind.OpenFailed);\n }\n}\n\n/**\n * The raw ECDH X-coordinate of `secret * public` — `crypto.rs`'s\n * `ecdh_x_coordinate`. `@noble/curves` returns the compressed point, whose\n * bytes `1..33` are exactly the `serialize_compressed()[1..]` the Rust takes.\n */\nfunction ecdhXCoordinate(\n secretKey: Uint8Array,\n publicKey: Uint8Array\n): Uint8Array {\n let compressed: Uint8Array;\n try {\n compressed = secp256k1.getSharedSecret(secretKey, publicKey, true);\n } catch {\n throw new GiftWrapError(GiftWrapErrorKind.InvalidKey);\n }\n return compressed.slice(1);\n}\n\n/**\n * The ordinary local case of {@link GiftWrapEcdh}: a 32-byte secp256k1 secret\n * key held in this process. `openRequest` accepts a bare key too and wraps it\n * in this.\n */\nexport function localGiftWrapEcdh(secretKey: Uint8Array): GiftWrapEcdh {\n return {\n ecdh: (ephemeralPublicKey) =>\n ecdhXCoordinate(secretKey, ephemeralPublicKey),\n };\n}\n\n/**\n * The 65-byte uncompressed secp256k1 public key a `secretKey` opens gift\n * wraps under — the counterpart {@link openRequest}/{@link localGiftWrapEcdh}\n * derive their ECDH from, and the same format a real connector reports from\n * `GET /ilp/identity` (`ConnectorIdentity.publicKey`). A caller publishes\n * this as a `kind:31990` advertisement's `seal_pubkey` tag (toon-meta#266\n * §3.1) so a buyer can seal a job's PREPARE `data` to it directly, without a\n * `GET /identity` this client cannot serve (ADR 0022).\n */\nexport function giftWrapPublicKey(secretKey: Uint8Array): Uint8Array {\n try {\n return secp256k1.getPublicKey(secretKey, false);\n } catch {\n throw new GiftWrapError(GiftWrapErrorKind.InvalidKey);\n }\n}\n\n// ─── Request direction ──────────────────────────────────────────────────────\n\n/**\n * The deterministic core of {@link sealRequest}, parameterized on every value\n * a real seal draws at random — the counterpart of the Rust's\n * `seal_request_with_randomness`, which that crate gates behind a `test-util`\n * feature for a reason worth repeating: **reusing a (key, nonce) pair under\n * ChaCha20-Poly1305 is catastrophic**, so caller-supplied randomness is a\n * footgun, not a convenience. Use {@link sealRequest} unless you are replaying\n * a fixed vector.\n *\n * `receiverPublicKey` may be the 65-byte uncompressed form a connector's\n * `GET /ilp/identity` reports, or the 33-byte compressed form; the ECDH result\n * is the same point either way. The ephemeral key is always emitted\n * uncompressed, because that is what the framing pins.\n */\nexport function sealRequestWithRandomness(\n plaintext: Uint8Array,\n receiverPublicKey: Uint8Array,\n ephemeralSecretKey: Uint8Array,\n sharedSecret: Uint8Array,\n nonce: Uint8Array\n): Uint8Array {\n if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n if (nonce.length !== GIFTWRAP_NONCE_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n\n let ephemeralPublicKey: Uint8Array;\n try {\n ephemeralPublicKey = secp256k1.getPublicKey(ephemeralSecretKey, false);\n } catch {\n throw new GiftWrapError(GiftWrapErrorKind.InvalidKey);\n }\n\n const aeadKey = hkdfKey(\n ecdhXCoordinate(ephemeralSecretKey, receiverPublicKey),\n REQUEST_INFO\n );\n const inner = concat([sharedSecret, plaintext]);\n\n return concat([\n Uint8Array.of(GIFTWRAP_TYPE_REQUEST),\n ephemeralPublicKey,\n encryptWithNonce(aeadKey, inner, nonce),\n ]);\n}\n\n/**\n * Seal `plaintext` (an encoded envelope) to `receiverPublicKey`. A fresh\n * ephemeral key pair, shared secret and nonce are drawn for this call alone,\n * so no two sealed requests — even to the same receiver, even with the same\n * plaintext — share any of the three.\n *\n * Returns the wire bytes and the shared secret. Keep that secret: the\n * terminating connector recovers the same one by opening this wrap, so\n * {@link deriveFulfillment} of it is the preimage an honest FULFILL will\n * carry — the sender's only way to check a delivery end to end now that no\n * condition rides on the wire (connector ADR 0069).\n */\nexport function sealRequest(\n plaintext: Uint8Array,\n receiverPublicKey: Uint8Array\n): SealedRequest {\n const ephemeralSecretKey = secp256k1.utils.randomSecretKey();\n const sharedSecret = randomBytes(GIFTWRAP_SECRET_LENGTH);\n const nonce = randomBytes(GIFTWRAP_NONCE_LENGTH);\n\n return {\n wrapped: sealRequestWithRandomness(\n plaintext,\n receiverPublicKey,\n ephemeralSecretKey,\n sharedSecret,\n nonce\n ),\n sharedSecret,\n };\n}\n\n/**\n * Open a sealed request addressed to `identity`, recovering the encoded\n * envelope and the shared secret carried alongside it.\n *\n * `identity` is either a 32-byte secp256k1 secret key or a {@link GiftWrapEcdh}\n * that never exposes one. `serve-job.ts` calls this for real (toon-client#537):\n * when this client is itself the BTP destination, it is the party that opens\n * the wrap. It also makes the seal testable from both ends — and the vectors'\n * \"opening it with the fixture's secret key must recover the envelope and the\n * secret exactly\" a check this repo can actually run.\n */\nexport function openRequest(\n bytes: Uint8Array,\n identity: Uint8Array | GiftWrapEcdh\n): OpenedRequest {\n if (bytes.length === 0) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n if (bytes[0] !== GIFTWRAP_TYPE_REQUEST) {\n throw new GiftWrapError(\n GiftWrapErrorKind.InvalidType,\n GIFTWRAP_TYPE_REQUEST\n );\n }\n if (bytes.length < 1 + GIFTWRAP_PUBLIC_KEY_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n\n const ephemeralPublicKey = bytes.slice(1, 1 + GIFTWRAP_PUBLIC_KEY_LENGTH);\n const ciphertext = bytes.subarray(1 + GIFTWRAP_PUBLIC_KEY_LENGTH);\n\n const agreement =\n identity instanceof Uint8Array ? localGiftWrapEcdh(identity) : identity;\n let ecdhSecret: Uint8Array;\n try {\n ecdhSecret = agreement.ecdh(ephemeralPublicKey);\n } catch (error) {\n throw error instanceof GiftWrapError\n ? error\n : new GiftWrapError(GiftWrapErrorKind.InvalidKey);\n }\n\n const plaintext = decrypt(hkdfKey(ecdhSecret, REQUEST_INFO), ciphertext);\n if (plaintext.length < GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n\n return {\n envelopeBytes: plaintext.slice(GIFTWRAP_SECRET_LENGTH),\n sharedSecret: plaintext.slice(0, GIFTWRAP_SECRET_LENGTH),\n };\n}\n\n// ─── Response direction ─────────────────────────────────────────────────────\n\n/**\n * The deterministic core of {@link sealResponse}, parameterized on the nonce.\n * Same footgun, same warning as {@link sealRequestWithRandomness}: a nonce\n * reused under one shared secret destroys the confidentiality of both\n * responses sealed with it.\n */\nexport function sealResponseWithRandomness(\n sharedSecret: Uint8Array,\n plaintext: Uint8Array,\n nonce: Uint8Array\n): Uint8Array {\n if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n if (nonce.length !== GIFTWRAP_NONCE_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n return concat([\n Uint8Array.of(GIFTWRAP_TYPE_RESPONSE),\n encryptWithNonce(hkdfKey(sharedSecret, RESPONSE_INFO), plaintext, nonce),\n ]);\n}\n\n/**\n * Seal `plaintext` — an encoded response envelope, or a reject's diagnostic\n * bytes — with the request's own `sharedSecret`. No second key exchange: the\n * secret is bidirectional by construction, which is also why a sealed reject\n * can only have come from the termination.\n */\nexport function sealResponse(\n sharedSecret: Uint8Array,\n plaintext: Uint8Array\n): Uint8Array {\n return sealResponseWithRandomness(\n sharedSecret,\n plaintext,\n randomBytes(GIFTWRAP_NONCE_LENGTH)\n );\n}\n\n/**\n * Open a sealed response with the shared secret {@link sealRequest} returned\n * for the request it answers. No signer, no key exchange, no identity key.\n */\nexport function openResponse(\n sharedSecret: Uint8Array,\n bytes: Uint8Array\n): Uint8Array {\n if (bytes.length === 0) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n if (bytes[0] !== GIFTWRAP_TYPE_RESPONSE) {\n throw new GiftWrapError(\n GiftWrapErrorKind.InvalidType,\n GIFTWRAP_TYPE_RESPONSE\n );\n }\n if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n return decrypt(hkdfKey(sharedSecret, RESPONSE_INFO), bytes.subarray(1));\n}\n\n/**\n * Whether `bytes` is shaped like a sealed response — the leading type byte and\n * nothing else, exactly as `looks_like_sealed_response` does it. This is how a\n * sender tells a reject raised BY the destination from one raised on the way\n * to it, without holding the secret to try opening it.\n *\n * Empty `data`, which every reject raised short of a termination carries, is\n * never sealed.\n */\nexport function looksLikeSealedResponse(bytes: Uint8Array): boolean {\n return bytes.length > 0 && bytes[0] === GIFTWRAP_TYPE_RESPONSE;\n}\n\n// ─── Fulfilment ─────────────────────────────────────────────────────────────\n\n/**\n * The fulfilment a request's shared secret derives (ADR 0019):\n * `HKDF-SHA256(shared_secret, \"toon-giftwrap-fulfillment\")`, 32 bytes.\n * Domain-separated by its own `info` string from both AEAD keys the same\n * secret also derives, so it can never collide with either.\n */\nexport function deriveFulfillment(sharedSecret: Uint8Array): Uint8Array {\n if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n return hkdfKey(sharedSecret, FULFILLMENT_INFO);\n}\n","/**\n * One sealed request/answer exchange with a terminating connector (ADR 0018,\n * ADR 0019, ADR 0020) — the whole shape of a packet's payload, from the\n * envelope going out to the answer coming back, behind two functions.\n *\n * A sender's obligations on this wire are not independent of one another, and\n * getting any of them separately wrong is silent:\n *\n * - The `data` is a gift wrap addressed to the connector that TERMINATES the\n * route, around an OER envelope — never HTTP text, never a bare payload.\n * - The fulfilment an honest answer carries is DERIVED from the very secret\n * that wrap carries (ADR 0019). Since ADR 0069 took the execution condition\n * off the wire, comparing a returned preimage against that derivation is\n * the sender's only delivery check — and the only one made anywhere on the\n * path, since no hop verifies a FULFILL any more.\n * - The answer is sealed with that same secret, so opening it requires having\n * kept it from the seal.\n *\n * {@link sealExchange} produces all three from one call so they cannot drift\n * apart, and {@link readExchangeOutcome} is the only thing that reads the\n * answer. The secret is the token joining them.\n *\n * ─── Why the outcome is a tagged union ─────────────────────────────────────\n * ADR 0018 gives a sender something it never had: a REJECT sealed with the\n * request's own secret can ONLY have come from the termination, because only\n * the termination could recover that secret. A reject raised short of it is\n * necessarily plaintext — an intermediate hop shares no secret and cannot\n * seal. So \"the destination said no\" and \"somebody on the path said no\" are\n * now genuinely different facts, and flattening both into one error string\n * would throw away the distinction the seal was introduced to create.\n *\n * ADR 0020 draws the other line this union encodes: an HTTP status inside a\n * response envelope is envelope CONTENT, not a packet outcome. A 404 arrives\n * on a FULFILL and value moved. {@link ExchangeOutcome.Answered} therefore\n * carries any status at all, and it is the caller's business — not this\n * module's — whether a given status means its own operation succeeded.\n *\n * Pure: no I/O, no clock, no network. Randomness only through\n * {@link sealRequest}.\n */\n\nimport {\n decodeEnvelopeResponse,\n encodeEnvelopeRequest,\n EnvelopeError,\n type EnvelopeRequest,\n type EnvelopeResponse,\n} from './envelope.js';\nimport {\n deriveFulfillment,\n GiftWrapError,\n looksLikeSealedResponse,\n openResponse,\n sealRequest,\n} from './giftwrap.js';\n\n/**\n * A sealed request, ready to become a PREPARE: what goes in `data`, the secret\n * needed to read the answer, and the fulfilment that answer must carry.\n *\n * The three are produced together and belong together: opening the answer with\n * any other secret fails, and checking a FULFILL against any other fulfilment\n * rejects a delivery that was genuine.\n */\nexport interface SealedExchange {\n /** The gift wrap to carry as the PREPARE's `data`. */\n readonly data: Uint8Array;\n /**\n * The 32-byte secret sealed inside the wrap. Keep it until the answer is\n * read; it is the only thing that opens the response. Never send it\n * anywhere else, and never reuse it for a second packet.\n */\n readonly sharedSecret: Uint8Array;\n /**\n * The fulfilment the terminating connector will return —\n * `deriveFulfillment(sharedSecret)`. Pass it to a transport as\n * `expectedFulfillment`: comparing a FULFILL's preimage against this is the\n * sender's end-to-end check, and since ADR 0069 the only fulfilment check\n * made anywhere on the path.\n */\n readonly fulfillment: Uint8Array;\n}\n\n/**\n * How an exchange ended. Three outcomes, deliberately not two: a refusal's\n * ORIGIN is the fact ADR 0018 makes knowable for the first time.\n */\nexport type ExchangeOutcome =\n /**\n * The termination answered. `response` is whatever it said, at whatever\n * status — a non-2xx here is a real answer that was paid for (ADR 0020),\n * not a failure of the packet.\n */\n | { readonly kind: 'answered'; readonly response: EnvelopeResponse }\n /**\n * The DESTINATION refused, provably: the reject's `data` was sealed with\n * this exchange's own secret, which only the terminating connector could\n * hold. `detail` is whatever it sealed alongside (often empty).\n */\n | {\n readonly kind: 'destination-refused';\n readonly code: string;\n readonly message: string;\n readonly detail: Uint8Array;\n }\n /**\n * Somebody ON THE PATH refused — no route, expiry, a ceiling, a rejected\n * claim — short of the termination, so nothing was sealed. Unauthenticated\n * by construction: any hop can produce this, and it should be read as a\n * hint, not a verdict from the destination.\n */\n | {\n readonly kind: 'path-refused';\n readonly code: string;\n readonly message: string;\n };\n\n/**\n * Why an answer that arrived could not be read. Distinct from an\n * {@link ExchangeOutcome}: these are not the destination's answer at all, but\n * bytes that failed to be one.\n */\nexport type SealedResponseErrorKind =\n /** A FULFILL whose `data` is absent, or does not begin with the sealed-response type byte. */\n | 'not-sealed'\n /** The wrap is shaped right but does not open under this exchange's secret. */\n | 'unopenable'\n /** It opened, and what came out is not a response envelope. */\n | 'malformed-envelope';\n\n/** A refusal to read an answer. Never carries recovered plaintext. */\nexport class SealedResponseError extends Error {\n constructor(\n readonly kind: SealedResponseErrorKind,\n message: string,\n override readonly cause?: Error\n ) {\n super(message);\n this.name = 'SealedResponseError';\n }\n}\n\n/**\n * Seal `request` to `connectorPublicKey` — the identity of the connector that\n * TERMINATES the destination, as read from its own client edge\n * (`ConnectorEdgeClient`). Sealing to any other key is a confidentiality\n * failure that presents as an undeliverable packet.\n *\n * @param request the envelope to seal.\n * @param connectorPublicKey the terminating connector's 65-byte uncompressed\n * secp256k1 identity key.\n */\nexport function sealExchange(\n request: EnvelopeRequest,\n connectorPublicKey: Uint8Array\n): SealedExchange {\n const { wrapped, sharedSecret } = sealRequest(\n encodeEnvelopeRequest(request),\n connectorPublicKey\n );\n return {\n data: wrapped,\n sharedSecret,\n fulfillment: deriveFulfillment(sharedSecret),\n };\n}\n\n/**\n * Read what came back.\n *\n * `accepted` distinguishes a FULFILL from a REJECT; `data` is the packet's\n * payload bytes, absent when it carried none. Both come straight off the\n * transport's result, so this stays testable without a socket.\n *\n * A FULFILL must be sealed and must decode: value moved, so bytes that are\n * neither are a broken counterparty, and this throws rather than inventing an\n * outcome. A REJECT is classified instead of thrown on — an unopenable one is\n * simply a path reject that happened to carry bytes.\n *\n * @throws {SealedResponseError} for a FULFILL that is not a readable sealed\n * response envelope.\n */\nexport function readExchangeOutcome(\n result: { accepted: boolean; code?: string; message?: string },\n data: Uint8Array | undefined,\n sharedSecret: Uint8Array\n): ExchangeOutcome {\n if (result.accepted) {\n return { kind: 'answered', response: openAnswer(data, sharedSecret) };\n }\n\n const code = result.code ?? 'F00';\n const message = result.message ?? '';\n\n // Only the termination could have sealed this, so only a wrap that actually\n // OPENS proves the destination refused. A leading type byte alone is a\n // claim, not evidence — an intermediary can write one byte.\n if (data !== undefined && looksLikeSealedResponse(data)) {\n try {\n return {\n kind: 'destination-refused',\n code,\n message,\n detail: openResponse(sharedSecret, data),\n };\n } catch (error) {\n if (!(error instanceof GiftWrapError)) throw error;\n // Fall through: bytes that pose as sealed but do not open are not the\n // destination's word, and must not be reported as if they were.\n }\n }\n\n return { kind: 'path-refused', code, message };\n}\n\nfunction openAnswer(\n data: Uint8Array | undefined,\n sharedSecret: Uint8Array\n): EnvelopeResponse {\n if (data === undefined || data.length === 0) {\n throw new SealedResponseError(\n 'not-sealed',\n 'FULFILL carried no data; a terminated route always seals a response envelope'\n );\n }\n if (!looksLikeSealedResponse(data)) {\n throw new SealedResponseError(\n 'not-sealed',\n `FULFILL data is not a sealed response (leading byte 0x${(data[0] ?? 0)\n .toString(16)\n .padStart(2, '0')}, expected 0x02)`\n );\n }\n\n let opened: Uint8Array;\n try {\n opened = openResponse(sharedSecret, data);\n } catch (error) {\n if (!(error instanceof GiftWrapError)) throw error;\n throw new SealedResponseError(\n 'unopenable',\n 'FULFILL data did not open under this packet\\'s shared secret',\n error\n );\n }\n\n try {\n return decodeEnvelopeResponse(opened);\n } catch (error) {\n if (!(error instanceof EnvelopeError)) throw error;\n throw new SealedResponseError(\n 'malformed-envelope',\n `sealed answer opened but did not decode as a response envelope: ${error.message}`,\n error\n );\n }\n}\n\n/** Read a response header, case-insensitively; the first match wins. */\nexport function envelopeHeader(\n response: EnvelopeResponse,\n name: string\n): string | undefined {\n const wanted = name.toLowerCase();\n for (const [header, value] of response.headers) {\n if (header.toLowerCase() === wanted) return value;\n }\n return undefined;\n}\n","/**\n * Turning a {@link ToonClientConfig} into the settled facts the rest of the\n * client runs on: validated, defaulted, keys derived, store opened.\n *\n * Everything here happens **before** any network or chain access, and that is\n * the point. `ToonClient.create` must not touch a chain (a client that opened an\n * RPC connection to be constructed could not be constructed offline, and a CLI\n * that only wants to print an address should not pay for one), so every question\n * that can be answered from the configuration alone is answered here, once, and\n * the answers are immutable afterwards.\n *\n * Two questions deliberately are NOT answered here, because their answer belongs\n * to the connector rather than to the caller: **which chain** to settle on, and\n * **what a route costs**. Both come from the node's own `GET /ilp`\n * (`self-description-spec.md` ND-07 — the node proved each settlement fact\n * against a live chain at boot), so this module records a *preference* for the\n * chain and nothing at all for the price.\n */\nimport { deriveFullIdentity, evmIdentityFromKey } from '../keys/KeyDerivation.js';\nimport { base58Decode, base58Encode } from '../utils/base58.js';\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { connectorEdgeBaseUrl } from '../connector/ConnectorEdgeClient.js';\nimport {\n InMemoryChannelStore,\n JsonFileChannelStore,\n type ChannelStore,\n} from '../channel/ChannelStore.js';\nimport { DEVNET, defaultRpcUrl } from '../presets.js';\nimport { ConfigError } from './errors.js';\nimport { assertRoutableHsHostname, isHiddenServiceUrl } from '../transport/hs-hostname.js';\nimport { validateSocks5hUrl } from '../transport/socks-url.js';\nimport type {\n ChainKind,\n KeyDerivationScheme,\n ToonClientConfig,\n TransportPreference,\n} from './types.js';\n\n/** Per-packet timeout when the caller sets none. */\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * Per-packet timeout when the caller sets none and the connector is a hidden\n * service. Building a circuit to a cold hidden service routinely takes tens of\n * seconds before the connector has seen a single byte, so the clearnet default\n * would expire packets that were merely in transit.\n */\nexport const DEFAULT_HS_TIMEOUT_MS = 120_000;\n/** What a channel is opened with, and topped up by, base units — 0.1 USDC at 6 decimals. */\nexport const DEFAULT_DEPOSIT = 100_000n;\n\n/**\n * How one chain's RPC leaves this process when it rides the proxy: two shapes of\n * one pinned circuit, because the two chains' clients take different objects.\n */\nexport interface ProxiedChainRpc {\n /** The undici dispatcher, for viem, which calls the global `fetch` itself (EVM). */\n dispatcher: unknown;\n /** `fetch` bound to that dispatcher, for Solana's JSON-RPC. */\n fetch: typeof fetch;\n}\n\n/** The keys this client holds, per chain. Absent means \"no key for that chain\". */\nexport interface ResolvedIdentity {\n evm?: { privateKey: Uint8Array; address: string };\n solana?: { secretKey: Uint8Array; publicKey: string };\n}\n\n/**\n * A configuration with every question answered that could be answered without\n * asking anybody. Frozen: a client's identity, store and endpoint do not change\n * under it after construction.\n */\nexport interface ResolvedConfig {\n /** The client-edge base URL, with any trailing `/ilp` normalised away. */\n connector: string;\n /** True when {@link connector} is a `.anyone` hidden service. */\n connectorIsHiddenService: boolean;\n /** The `socks5h://` proxy to reach it through, when there is one. */\n socksProxy: string | undefined;\n /** Whether chain RPC rides that proxy too (ADR 0002). */\n proxyRpc: boolean;\n /**\n * Per chain, the proxy-bound route its RPC takes, each on its own pinned\n * circuit; `undefined` when chain RPC dials directly.\n *\n * Deliberately not filled in here: building it means loading a Node-only\n * module, and resolving a config must stay synchronous and browser-safe. It is\n * the client's job to construct the routes, so {@link resolveConfig} only\n * reserves the slot and leaves it `undefined`.\n */\n chainRpc: Record<ChainKind, ProxiedChainRpc> | undefined;\n identity: ResolvedIdentity;\n /** The caller's chain preference, or `undefined` to take the node's first. */\n chain: ChainKind | undefined;\n /** RPC URL per chain: an explicit `rpcUrl` overrides both; else this package's preset. */\n rpcUrls: Record<ChainKind, string>;\n transport: TransportPreference;\n /** An explicit `senderId`, or `undefined` to use the selected chain's address. */\n senderId: string | undefined;\n deposit: bigint;\n /** The x402 facilitator for Base deposits, or `undefined` for the network's default. */\n facilitatorUrl: string | undefined;\n /** `undefined`: whatever the connector's offer names, else `eip3009`. */\n depositMethod: 'eip3009' | 'permit2' | undefined;\n depositGas: 'auto' | 'facilitator' | 'self';\n autoOpenChannel: boolean;\n timeoutMs: number;\n channelStore: ChannelStore;\n /** True when the store is the in-memory fallback rather than one the caller chose. */\n channelStoreIsEphemeral: boolean;\n btp: {\n maxReconnectAttempts?: number;\n reconnectDelay?: number;\n declareChannel: boolean;\n };\n faucetUrl: string;\n fetch: typeof fetch;\n createWebSocket: ((url: string) => unknown) | undefined;\n keyDerivation: KeyDerivationScheme;\n accountIndex: number;\n}\n\n/**\n * Validate, derive and default.\n *\n * @throws {ConfigError} for anything a caller must fix: no connector, no key\n * material, a connector that is not a URL, a negative deposit, key bytes of\n * the wrong length. Every one of these would otherwise surface much later as\n * an unexplained refusal or an unhandled exception mid-send.\n */\nexport function resolveConfig(config: ToonClientConfig): ResolvedConfig {\n const connector = resolveConnector(config.connector);\n const connectorIsHiddenService = isHiddenServiceUrl(connector);\n const socksProxy = resolveSocksProxy(config.socksProxy, connector, connectorIsHiddenService);\n const accountIndex = resolveAccountIndex(config.accountIndex);\n const keyDerivation = config.keyDerivation ?? 'standard';\n const identity = resolveIdentity(config, keyDerivation, accountIndex);\n\n if (config.chain !== undefined && config.chain !== 'evm' && config.chain !== 'solana') {\n throw new ConfigError(\n `chain must be 'evm' or 'solana'; got ${JSON.stringify(config.chain)}.`\n );\n }\n if (config.chain !== undefined && identity[config.chain] === undefined) {\n throw new ConfigError(\n `chain is set to '${config.chain}', but this client holds no ${config.chain} ` +\n 'key. Supply a mnemonic (which derives both), or the raw key for that chain.'\n );\n }\n\n const transport = config.transport ?? 'auto';\n if (transport !== 'auto' && transport !== 'http' && transport !== 'btp') {\n throw new ConfigError(\n `transport must be 'auto', 'http' or 'btp'; got ${JSON.stringify(transport)}.`\n );\n }\n\n const deposit = resolveDeposit(config.deposit);\n const timeoutMs =\n config.timeoutMs ?? (connectorIsHiddenService ? DEFAULT_HS_TIMEOUT_MS : DEFAULT_TIMEOUT_MS);\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new ConfigError(`timeoutMs must be a positive number; got ${String(timeoutMs)}.`);\n }\n\n const { channelStore, channelStoreIsEphemeral } = resolveChannelStore(config.channelStore);\n\n const rpcUrls: Record<ChainKind, string> = {\n evm: config.rpcUrl ?? defaultRpcUrl('evm'),\n solana: config.rpcUrl ?? defaultRpcUrl('solana'),\n };\n\n return {\n connector,\n identity,\n chain: config.chain,\n rpcUrls,\n transport,\n senderId: config.senderId,\n deposit,\n facilitatorUrl: config.facilitatorUrl,\n depositMethod: config.depositMethod,\n depositGas: config.depositGas ?? 'auto',\n connectorIsHiddenService,\n socksProxy,\n proxyRpc: config.proxyRpc ?? true,\n chainRpc: undefined,\n autoOpenChannel: config.autoOpenChannel ?? true,\n timeoutMs,\n channelStore,\n channelStoreIsEphemeral,\n btp: {\n ...(config.btp?.maxReconnectAttempts !== undefined\n ? { maxReconnectAttempts: config.btp.maxReconnectAttempts }\n : {}),\n ...(config.btp?.reconnectDelay !== undefined\n ? { reconnectDelay: config.btp.reconnectDelay }\n : {}),\n declareChannel: config.btp?.declareChannel ?? true,\n },\n faucetUrl: config.faucetUrl ?? DEVNET.faucet,\n fetch: config.fetch ?? globalThis.fetch.bind(globalThis),\n createWebSocket: config.createWebSocket,\n keyDerivation,\n accountIndex,\n };\n}\n\n/** This client's address on `chain`, or `undefined` when it holds no key there. */\nexport function addressFor(\n identity: ResolvedIdentity,\n chain: ChainKind\n): string | undefined {\n return chain === 'evm' ? identity.evm?.address : identity.solana?.publicKey;\n}\n\n// ─── Pieces ─────────────────────────────────────────────────────────────────\n\nfunction resolveConnector(connector: string | undefined): string {\n if (typeof connector !== 'string' || connector.trim().length === 0) {\n throw new ConfigError(\n 'connector is required: the client-edge URL of the node to pay, e.g. ' +\n `'${DEVNET.connector}'. One free GET on it returns every other fact ` +\n 'needed to transact (self-description-spec.md, connector ADR 0050).'\n );\n }\n let base: string;\n try {\n base = connectorEdgeBaseUrl(connector.trim());\n } catch (error) {\n throw new ConfigError(\n `connector ${JSON.stringify(connector)} is not a URL.`,\n error instanceof Error ? error : undefined\n );\n }\n if (!/^https?:\\/\\//i.test(base)) {\n throw new ConfigError(\n `connector ${JSON.stringify(connector)} must be an http(s) URL; got ${JSON.stringify(base)}.`\n );\n }\n // A `.anon` or `.onion` connector is not a typo to pass through: `anon` would\n // treat the first as a clearnet name and fail late with `HostUnreachable`, and\n // the second belongs to a network this client does not dial at all. Both are\n // caught here, where the message can still name the fix.\n const host = new URL(base).hostname;\n if (/\\.(anon|onion)$/.test(host)) {\n try {\n assertRoutableHsHostname(host);\n } catch (error) {\n throw new ConfigError(\n `connector ${JSON.stringify(connector)} is not reachable: ` +\n (error instanceof Error ? error.message : String(error)),\n error instanceof Error ? error : undefined\n );\n }\n }\n return base;\n}\n\n/**\n * A hidden service needs a proxy. A proxy beside a clearnet connector means the\n * payer is the one hiding.\n *\n * Without a proxy, a `.anyone` address resolves nowhere, but only after the\n * hostname has gone out in a plaintext DNS query, which is the one thing the\n * address exists to avoid. So that fails here, before anything dials.\n *\n * A proxy beside a clearnet connector was refused too, once, as \"nothing would\n * ride the proxy\". That was never true, and TOON_Network#167 reversed it: every\n * byte the client sends rides it, chain RPC included (the \"hidden payer\"). Only\n * `socks5h://` is accepted either way. Under `socks5://` this process would\n * resolve every name it dials itself.\n */\nfunction resolveSocksProxy(\n socksProxy: string | undefined,\n connector: string,\n connectorIsHiddenService: boolean\n): string | undefined {\n if (socksProxy === undefined) {\n if (!connectorIsHiddenService) return undefined;\n throw new ConfigError(\n `connector ${JSON.stringify(connector)} is a hidden service, which is reachable ` +\n 'only through a SOCKS5h proxy. Set `socksProxy` to a running Anyone Protocol ' +\n '`anon` daemon (e.g. \"socks5h://127.0.0.1:9050\"), or use the `toon-client` CLI, which ' +\n 'can start one for you.'\n );\n }\n try {\n validateSocks5hUrl(socksProxy);\n } catch (error) {\n throw new ConfigError(\n error instanceof Error ? error.message : String(error),\n error instanceof Error ? error : undefined\n );\n }\n return socksProxy;\n}\n\nfunction resolveAccountIndex(accountIndex: number | undefined): number {\n const index = accountIndex ?? 0;\n if (!Number.isInteger(index) || index < 0) {\n throw new ConfigError(\n `accountIndex must be a non-negative whole number; got ${String(accountIndex)}.`\n );\n }\n return index;\n}\n\nfunction resolveDeposit(deposit: bigint | string | undefined): bigint {\n if (deposit === undefined) return DEFAULT_DEPOSIT;\n let value: bigint;\n try {\n value = typeof deposit === 'bigint' ? deposit : BigInt(deposit);\n } catch {\n throw new ConfigError(\n `deposit must be a whole number of base units; got ${JSON.stringify(deposit)}.`\n );\n }\n if (value < 0n) throw new ConfigError('deposit cannot be negative.');\n return value;\n}\n\n/**\n * Derive both chain keys from the mnemonic, or take whichever raw keys were\n * supplied. A raw key WINS over the mnemonic's for its own chain, so a caller\n * can hold a phrase for one chain and a hardware-exported key for the other.\n */\nfunction resolveIdentity(\n config: ToonClientConfig,\n scheme: KeyDerivationScheme,\n accountIndex: number\n): ResolvedIdentity {\n const identity: ResolvedIdentity = {};\n\n if (config.mnemonic !== undefined) {\n if (typeof config.mnemonic !== 'string' || config.mnemonic.trim().length === 0) {\n throw new ConfigError('mnemonic must be a non-empty BIP-39 phrase.');\n }\n let derived;\n try {\n derived = deriveFullIdentity(config.mnemonic.trim(), { accountIndex, scheme });\n } catch (error) {\n throw new ConfigError(\n 'mnemonic is not a valid BIP-39 phrase (check the word list and the ' +\n 'checksum — a single mistyped word fails it).',\n error instanceof Error ? error : undefined\n );\n }\n identity.evm = derived.evm;\n identity.solana = derived.solana;\n }\n\n if (config.evmPrivateKey !== undefined) {\n identity.evm = evmIdentityFromKey(readEvmKey(config.evmPrivateKey));\n }\n if (config.solanaSecretKey !== undefined) {\n identity.solana = readSolanaKey(config.solanaSecretKey);\n }\n\n if (identity.evm === undefined && identity.solana === undefined) {\n throw new ConfigError(\n 'No key material: supply a `mnemonic` (which derives both an EVM and a ' +\n 'Solana key), or a raw `evmPrivateKey` / `solanaSecretKey`. A claim is ' +\n 'authorised by its signature against the channel\\'s on-chain counterparty ' +\n 'and by nothing else (connector ADR 0052), so there is no unauthenticated ' +\n 'way to pay.'\n );\n }\n return identity;\n}\n\n/** A 32-byte secp256k1 secret, from bytes or `0x`-prefixed hex. */\nfunction readEvmKey(key: string | Uint8Array): Uint8Array {\n if (key instanceof Uint8Array) {\n if (key.length !== 32) {\n throw new ConfigError(\n `evmPrivateKey must be 32 bytes; got ${key.length}.`\n );\n }\n return key;\n }\n const hex = key.startsWith('0x') || key.startsWith('0X') ? key.slice(2) : key;\n if (!/^[0-9a-fA-F]{64}$/.test(hex)) {\n throw new ConfigError(\n 'evmPrivateKey must be 32 bytes of hex (64 characters, optionally 0x-prefixed).'\n );\n }\n const bytes = new Uint8Array(32);\n for (let i = 0; i < 32; i++) bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n return bytes;\n}\n\n/**\n * A Solana keypair from a 32-byte seed or a 64-byte `seed ‖ pubkey` secret key,\n * as bytes or base58.\n *\n * Both lengths are accepted because both are in circulation: `solana-keygen`\n * writes the 64-byte form, while a BIP-39 derivation yields the 32-byte seed the\n * public half is computed from. Either way the seed is the first 32 bytes and the\n * public key is DERIVED rather than trusted — a 64-byte input whose trailing half\n * disagrees with its own seed is a corrupt file, and honouring it would produce\n * claims signed by one key and addressed to another.\n */\nfunction readSolanaKey(key: string | Uint8Array): {\n secretKey: Uint8Array;\n publicKey: string;\n} {\n let bytes: Uint8Array;\n if (key instanceof Uint8Array) {\n bytes = key;\n } else {\n try {\n bytes = base58Decode(key.trim());\n } catch (error) {\n throw new ConfigError(\n 'solanaSecretKey is not valid base58.',\n error instanceof Error ? error : undefined\n );\n }\n }\n if (bytes.length !== 32 && bytes.length !== 64) {\n throw new ConfigError(\n `solanaSecretKey must be a 32-byte seed or a 64-byte secret key; got ${bytes.length} bytes.`\n );\n }\n const seed = bytes.slice(0, 32);\n const publicKeyBytes = new Uint8Array(ed25519.getPublicKey(seed));\n const secretKey = new Uint8Array(64);\n secretKey.set(seed, 0);\n secretKey.set(publicKeyBytes, 32);\n return { secretKey, publicKey: base58Encode(publicKeyBytes) };\n}\n\n/**\n * Open the channel store.\n *\n * A string is a file path; a store object is used as given; and **nothing at all\n * gets an in-memory store and a warning**. The warning is not boilerplate: the\n * store holds the channel's nonce watermark, a claim must strictly advance the\n * nonce the connector has already banked (`client-edge-spec.md` §1.3 step 2), and\n * an in-memory watermark dies with the process. A restarted client re-signs from\n * nonce 1 on a channel the connector has banked hundreds of claims on, and every\n * one of those claims is refused `F01` — with the collateral still locked. The\n * default exists so a first script runs without ceremony, not because it is safe\n * to keep.\n */\nfunction resolveChannelStore(store: string | ChannelStore | undefined): {\n channelStore: ChannelStore;\n channelStoreIsEphemeral: boolean;\n} {\n if (typeof store === 'string') {\n if (store.trim().length === 0) {\n throw new ConfigError('channelStore path cannot be empty.');\n }\n return { channelStore: new JsonFileChannelStore(store), channelStoreIsEphemeral: false };\n }\n if (store !== undefined) {\n return { channelStore: store, channelStoreIsEphemeral: false };\n }\n console.warn(\n '[toon] No `channelStore` configured — the claim watermark will be held in ' +\n 'memory and lost when this process exits. A restarted client re-signs at ' +\n 'nonces the connector has already banked, and the connector refuses every ' +\n 'one of them while the channel\\'s collateral stays locked. Pass a file path ' +\n '(e.g. `channelStore: \"~/.toon/channels.json\"`) for anything that outlives ' +\n 'one run.'\n );\n return { channelStore: new InMemoryChannelStore(), channelStoreIsEphemeral: true };\n}\n","import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\n\nexport interface ChannelStoreEntry {\n nonce: number;\n cumulativeAmount: bigint;\n /**\n * The highest cumulative this client has ever SIGNED on the channel, which a\n * rollback deliberately does not lower. It is the ceiling on what the\n * connector can possibly have banked — nothing it never received a signature\n * for is claimable — and so the clamp on adopting the connector's own figure\n * (see `BatchChannelManager.adoptConnectorWatermark`).\n */\n signedCeiling?: bigint;\n /**\n * The highest cumulative the connector is PROVEN to hold: what the chain\n * shows landed, a voucher it banked, or one it refused as not advancing. The\n * floor under adopting the connector's own figure, as `signedCeiling` is the\n * ceiling over it.\n */\n provenFloor?: bigint;\n /**\n * Set when a signed claim's fate is unknown (a transport error or a timeout,\n * where the packet may have been delivered and banked anyway) or when the\n * connector refused one. It means \"our watermark and the connector's may\n * disagree\", and the next claim on this channel reconciles against\n * `POST /ilp/claim-state` before it is signed. Persisted because a timeout in\n * one `toon-client` invocation desyncs the next one.\n */\n watermarkUncertain?: boolean;\n /** Unix SECONDS when close was initiated (withdraw flow). */\n closedAt?: bigint;\n /** Unix SECONDS the channel becomes settleable (= closedAt + settlementTimeout). */\n settleableAt?: bigint;\n /** Unix SECONDS the channel was settled (collateral released). */\n settledAt?: bigint;\n}\n\n/** Where a channel lives: its chain, the x402 contract or program, and its token. */\nexport interface ChannelBindingContext {\n chainType: string;\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n /** Counterparty settlement address (required for Solana/Mina proofs). */\n recipient?: string;\n}\n\n/**\n * The config of an x402 `batch-settlement` channel (connector ADR 0074), in a\n * JSON-safe spelling: every field a string or a number, so both stores persist\n * it verbatim. Its id travels in every voucher and is never derived, so the\n * full config is what must survive a restart — on EVM the contract stores a\n * channel by id and never gives the config back.\n */\nexport type BatchSettlementBinding =\n | {\n chain: 'evm';\n /** CAIP-2, `eip155:<chainId>`. */\n network: string;\n config: {\n payer: string;\n payerAuthorizer: string;\n receiver: string;\n receiverAuthorizer: string;\n token: string;\n withdrawDelay: number;\n salt: string;\n };\n }\n | {\n chain: 'solana';\n /** CAIP-2, `solana:<genesis prefix>`. */\n network: string;\n /** The receiving connector's sponsor key: the channel's `payee` and `rent_payer`. */\n sponsor: string;\n config: {\n payer: string;\n payerAuthorizer: string;\n receiver: string;\n token: string;\n withdrawDelay: number;\n /** u64, decimal. */\n salt: string;\n /** u64, decimal. */\n openSlot: string;\n };\n };\n\n/**\n * One persisted peer→channel binding: WHICH on-chain channel this identity\n * already holds with a peer, on a given chain + token network (#489).\n */\nexport interface ChannelBinding {\n /** On-chain payment channel id (EVM bytes32 / Solana PDA / Mina zkApp). */\n channelId: string;\n /** Context for `trackChannel` on resume. */\n context: ChannelBindingContext;\n /** On-chain collateral locked at open time, when the open surfaced it. */\n depositTotal?: bigint;\n /** ISO timestamp of the open that created this binding. */\n openedAt?: string;\n /**\n * ISO timestamp this binding was RETIRED from the resume path because its\n * peer now announces a different settlement address than the channel was\n * opened against (see `counterpartyMatch` / {@link ChannelStore.supersedeBinding}).\n * A superseded binding is never resumed again, but stays in\n * {@link ChannelStore.listBindings} so whatever it holds on-chain can still\n * be found and reclaimed.\n */\n supersededAt?: string;\n /**\n * Set when the channel is an x402 `batch-settlement` channel rather than a\n * `TokenNetwork` / TOON-program one: its full config. Such a binding is kept\n * under its own key namespace (`batch|…`) and never resumed as a\n * `toon-channel` channel.\n */\n batchSettlement?: BatchSettlementBinding;\n /**\n * A deposit into this batch-settlement channel that was handed to a\n * facilitator or a sponsor and whose fate is not yet known. Recorded BEFORE\n * the deposit leaves, so a lost answer never loses the channel: the next use\n * reads the chain and settles it.\n */\n pendingDeposit?: bigint;\n /**\n * The last voucher this client sent on the channel, as the JSON that\n * travelled. A probe identifies by resending it byte for byte — a\n * retransmission the connector records nothing for (client-edge-spec §1.6).\n */\n lastVoucher?: string;\n /** The cumulative amount {@link lastVoucher} names. */\n lastVoucherAmount?: bigint;\n}\n\n/**\n * Persistence interface for payment channel nonce/amount state.\n *\n * The binding methods are OPTIONAL so a third-party `ChannelStore` written\n * against the pre-#489 surface still satisfies the type; a store that omits\n * them simply can't resume a peer's channel across restarts (it will open a\n * fresh one, the old behaviour). {@link JsonFileChannelStore} implements them.\n */\nexport interface ChannelStore {\n save(channelId: string, tracking: ChannelStoreEntry): void;\n load(channelId: string): ChannelStoreEntry | undefined;\n list(): string[];\n delete(channelId: string): void;\n /** Persist the channel a peer key is bound to. */\n saveBinding?(key: string, binding: ChannelBinding): void;\n /** The channel a peer key is bound to, if any. */\n loadBinding?(key: string): ChannelBinding | undefined;\n /** Every persisted binding, keyed as {@link saveBinding} stored it. */\n listBindings?(): { key: string; binding: ChannelBinding }[];\n /** Forget a binding (its nonce watermark is deliberately left intact). */\n deleteBinding?(key: string): void;\n /**\n * Retire a binding from the resume path — the counterparty terminating its\n * peer's route has been REPLACED, so the channel it names is dead to the\n * node now answering (`F01 - claim rejected`) even though every key field\n * still matches.\n *\n * ARCHIVES rather than deletes: the retired channel may still hold an\n * on-chain deposit, so dropping it would strand those funds behind\n * hand-editing the JSON. It disappears from {@link loadBinding} (never\n * resumed again) and frees its live key for the re-resolved channel, while\n * {@link listBindings} still shows it. Idempotent; a no-op for an unknown\n * key. Optional, like the rest of the binding surface: a store that omits it\n * simply keeps the pre-validation behaviour of overwriting the stale record.\n */\n supersedeBinding?(key: string): void;\n}\n\ninterface JsonEntry {\n nonce: number;\n /** Stored as string to preserve bigint precision */\n cumulativeAmount: string;\n /** Stored as string to preserve bigint precision. */\n signedCeiling?: string;\n provenFloor?: string;\n watermarkUncertain?: boolean;\n /** Withdraw-flow timers, string-encoded SECONDS (bigint precision). */\n closedAt?: string;\n settleableAt?: string;\n settledAt?: string;\n}\n\ninterface JsonBinding {\n channelId: string;\n context: ChannelBindingContext;\n /** Stored as string to preserve bigint precision. */\n depositTotal?: string;\n openedAt?: string;\n supersededAt?: string;\n batchSettlement?: BatchSettlementBinding;\n pendingDeposit?: string;\n lastVoucher?: string;\n lastVoucherAmount?: string;\n}\n\n/**\n * The archive key a superseded binding moves to: its live key plus the channel\n * id, so the retired record survives the re-resolved channel being written\n * under the live key, and several supersessions of one route never collide.\n */\nfunction supersededKey(key: string, channelId: string): string {\n return `${key}|superseded:${channelId}`;\n}\n\n/** `channels.json` → `channels.peers.json`. */\nfunction defaultBindingsPath(filePath: string): string {\n return filePath.replace(/\\.json$/i, '') + '.peers.json';\n}\n\n/**\n * JSON file-backed ChannelStore.\n * Uses synchronous I/O to match BatchChannelManager's sync API surface.\n *\n * Two files, on purpose: the nonce/cumulative watermark keeps its historical\n * `{ [channelId]: entry }` schema in `filePath` (rig and the MCP daemon parse\n * that file directly), while the peer→channel bindings live in a SIBLING file\n * (`channels.json` → `channels.peers.json`, override with `bindingsPath`).\n * Extending the watermark file's schema in place would have broken those\n * external readers.\n */\nexport class JsonFileChannelStore implements ChannelStore {\n private readonly filePath: string;\n private readonly bindingsPath: string;\n\n constructor(filePath: string, options?: { bindingsPath?: string }) {\n this.filePath = filePath;\n this.bindingsPath = options?.bindingsPath ?? defaultBindingsPath(filePath);\n }\n\n save(channelId: string, tracking: ChannelStoreEntry): void {\n const data = this.readFile();\n data[channelId] = {\n nonce: tracking.nonce,\n cumulativeAmount: tracking.cumulativeAmount.toString(),\n ...(tracking.signedCeiling !== undefined\n ? { signedCeiling: tracking.signedCeiling.toString() }\n : {}),\n ...(tracking.provenFloor !== undefined\n ? { provenFloor: tracking.provenFloor.toString() }\n : {}),\n ...(tracking.watermarkUncertain ? { watermarkUncertain: true } : {}),\n ...(tracking.closedAt !== undefined\n ? { closedAt: tracking.closedAt.toString() }\n : {}),\n ...(tracking.settleableAt !== undefined\n ? { settleableAt: tracking.settleableAt.toString() }\n : {}),\n ...(tracking.settledAt !== undefined\n ? { settledAt: tracking.settledAt.toString() }\n : {}),\n };\n this.writeFile(data);\n }\n\n load(channelId: string): ChannelStoreEntry | undefined {\n const data = this.readFile();\n const entry = data[channelId];\n if (!entry) return undefined;\n return {\n nonce: entry.nonce,\n cumulativeAmount: BigInt(entry.cumulativeAmount),\n ...(entry.signedCeiling !== undefined\n ? { signedCeiling: BigInt(entry.signedCeiling) }\n : {}),\n ...(entry.provenFloor !== undefined\n ? { provenFloor: BigInt(entry.provenFloor) }\n : {}),\n ...(entry.watermarkUncertain ? { watermarkUncertain: true } : {}),\n ...(entry.closedAt !== undefined\n ? { closedAt: BigInt(entry.closedAt) }\n : {}),\n ...(entry.settleableAt !== undefined\n ? { settleableAt: BigInt(entry.settleableAt) }\n : {}),\n ...(entry.settledAt !== undefined\n ? { settledAt: BigInt(entry.settledAt) }\n : {}),\n };\n }\n\n list(): string[] {\n return Object.keys(this.readFile());\n }\n\n delete(channelId: string): void {\n const data = this.readFile();\n const { [channelId]: _, ...rest } = data;\n this.writeFile(rest);\n }\n\n saveBinding(key: string, binding: ChannelBinding): void {\n const data = this.readBindings();\n data[key] = {\n channelId: binding.channelId,\n context: binding.context,\n ...(binding.depositTotal !== undefined\n ? { depositTotal: binding.depositTotal.toString() }\n : {}),\n openedAt: binding.openedAt ?? new Date().toISOString(),\n ...(binding.supersededAt !== undefined\n ? { supersededAt: binding.supersededAt }\n : {}),\n ...(binding.batchSettlement !== undefined\n ? { batchSettlement: binding.batchSettlement }\n : {}),\n ...(binding.pendingDeposit !== undefined\n ? { pendingDeposit: binding.pendingDeposit.toString() }\n : {}),\n ...(binding.lastVoucher !== undefined\n ? { lastVoucher: binding.lastVoucher }\n : {}),\n ...(binding.lastVoucherAmount !== undefined\n ? { lastVoucherAmount: binding.lastVoucherAmount.toString() }\n : {}),\n };\n this.writeBindings(data);\n }\n\n loadBinding(key: string): ChannelBinding | undefined {\n const entry = this.readBindings()[key];\n if (!entry) return undefined;\n // A retired record is not a resume candidate, even if something wrote one\n // back under the live key.\n if (entry.supersededAt !== undefined) return undefined;\n return toBinding(entry);\n }\n\n listBindings(): { key: string; binding: ChannelBinding }[] {\n return Object.entries(this.readBindings()).map(([key, entry]) => ({\n key,\n binding: toBinding(entry),\n }));\n }\n\n deleteBinding(key: string): void {\n const data = this.readBindings();\n if (!(key in data)) return;\n const { [key]: _removed, ...rest } = data;\n this.writeBindings(rest);\n }\n\n supersedeBinding(key: string): void {\n const data = this.readBindings();\n const existing = data[key];\n if (!existing || existing.supersededAt !== undefined) return;\n const { [key]: _retired, ...rest } = data;\n this.writeBindings({\n ...rest,\n [supersededKey(key, existing.channelId)]: {\n ...existing,\n supersededAt: new Date().toISOString(),\n },\n });\n }\n\n private readFile(): Record<string, JsonEntry> {\n if (!existsSync(this.filePath)) {\n return {};\n }\n const raw = readFileSync(this.filePath, 'utf-8');\n return JSON.parse(raw) as Record<string, JsonEntry>;\n }\n\n private writeFile(data: Record<string, JsonEntry>): void {\n mkdirSync(dirname(this.filePath), { recursive: true });\n writeFileSync(this.filePath, JSON.stringify(data, null, 2), 'utf-8');\n }\n\n private readBindings(): Record<string, JsonBinding> {\n if (!existsSync(this.bindingsPath)) return {};\n const raw = readFileSync(this.bindingsPath, 'utf-8');\n return JSON.parse(raw) as Record<string, JsonBinding>;\n }\n\n private writeBindings(data: Record<string, JsonBinding>): void {\n mkdirSync(dirname(this.bindingsPath), { recursive: true });\n writeFileSync(this.bindingsPath, JSON.stringify(data, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n });\n }\n}\n\nfunction toBinding(entry: JsonBinding): ChannelBinding {\n return {\n channelId: entry.channelId,\n context: entry.context,\n ...(entry.depositTotal !== undefined\n ? { depositTotal: BigInt(entry.depositTotal) }\n : {}),\n ...(entry.openedAt !== undefined ? { openedAt: entry.openedAt } : {}),\n ...(entry.supersededAt !== undefined\n ? { supersededAt: entry.supersededAt }\n : {}),\n ...(entry.batchSettlement !== undefined\n ? { batchSettlement: entry.batchSettlement }\n : {}),\n ...(entry.pendingDeposit !== undefined\n ? { pendingDeposit: BigInt(entry.pendingDeposit) }\n : {}),\n ...(entry.lastVoucher !== undefined ? { lastVoucher: entry.lastVoucher } : {}),\n ...(entry.lastVoucherAmount !== undefined\n ? { lastVoucherAmount: BigInt(entry.lastVoucherAmount) }\n : {}),\n };\n}\n\n/**\n * In-memory {@link ChannelStore} (watermarks + bindings). Handy for tests and\n * for a process that wants resume semantics within its own lifetime without\n * touching disk.\n */\nexport class InMemoryChannelStore implements ChannelStore {\n private readonly entries = new Map<string, ChannelStoreEntry>();\n private readonly bindings = new Map<string, ChannelBinding>();\n\n save(channelId: string, tracking: ChannelStoreEntry): void {\n this.entries.set(channelId, { ...tracking });\n }\n\n load(channelId: string): ChannelStoreEntry | undefined {\n const entry = this.entries.get(channelId);\n return entry ? { ...entry } : undefined;\n }\n\n list(): string[] {\n return [...this.entries.keys()];\n }\n\n delete(channelId: string): void {\n this.entries.delete(channelId);\n }\n\n saveBinding(key: string, binding: ChannelBinding): void {\n this.bindings.set(key, {\n ...binding,\n openedAt: binding.openedAt ?? new Date().toISOString(),\n });\n }\n\n loadBinding(key: string): ChannelBinding | undefined {\n const binding = this.bindings.get(key);\n if (!binding || binding.supersededAt !== undefined) return undefined;\n return { ...binding };\n }\n\n listBindings(): { key: string; binding: ChannelBinding }[] {\n return [...this.bindings.entries()].map(([key, binding]) => ({\n key,\n binding: { ...binding },\n }));\n }\n\n deleteBinding(key: string): void {\n this.bindings.delete(key);\n }\n\n supersedeBinding(key: string): void {\n const binding = this.bindings.get(key);\n if (!binding || binding.supersededAt !== undefined) return;\n this.bindings.delete(key);\n this.bindings.set(supersededKey(key, binding.channelId), {\n ...binding,\n supersededAt: new Date().toISOString(),\n });\n }\n}\n","/**\n * `client.channel` — the x402 `batch-settlement` channels this client pays a\n * connector from (connector ADRs 0074, 0075): listing them, opening and topping\n * one up by hand, and leaving them.\n *\n * Paying needs nothing from here: `send()` onboards and vouchers on its own\n * unless `autoOpenChannel` is off. Exit is always by hand: it is the payer's\n * own transaction on its own chain account, the one step of the scheme that\n * costs native gas.\n *\n * Exit walks EVERY channel this client holds with the node, not only the one it\n * pays from now: a channel archived by a newer one — replaced when exhausted,\n * or left behind by a lost binding — still holds a deposit.\n */\n\nimport {\n createPublicClient,\n createWalletClient,\n defineChain,\n type Hex,\n} from 'viem';\nimport { privateKeyToAccount } from 'viem/accounts';\nimport type { NodeSelfDescription } from '../connector/self-description.js';\nimport type {\n BatchChannel,\n BatchChannelManager,\n} from '../channel/batch-settlement/manager.js';\nimport type { BatchSettlementPayer } from '../channel/batch-settlement/payer.js';\nimport {\n evmChainIdOf,\n readEvmBatchChannel,\n} from '../channel/batch-settlement/evm.js';\nimport { getSvmBatchChannel } from '../channel/batch-settlement/svm.js';\nimport { chooseBatchSettlement } from '../channel/batch-settlement/offers.js';\nimport {\n finalizeEvmBatchWithdraw,\n initiateEvmBatchWithdraw,\n requestSvmBatchClose,\n withdrawSvmBatchChannel,\n type EvmExitClients,\n} from '../channel/batch-settlement/exit.js';\nimport {\n getLamports,\n type Signer,\n type SolanaRpcTarget,\n} from '../channel/solana/payment-channel.js';\nimport { base58Encode } from '../utils/base58.js';\nimport { rpcTransport } from '../transport/rpc.js';\nimport {\n ChannelNotOpenError,\n ConfigError,\n InsufficientBalanceError,\n} from './errors.js';\nimport type { ChainKind } from './types.js';\n\n/** One batch-settlement channel, as this client records it. */\nexport interface BatchChannelSummary {\n channel: BatchChannel;\n depositTotal: bigint;\n /** The cumulative amount this client has signed on it. */\n signed: bigint;\n /** Unix seconds this client started leaving it. */\n closedAt?: bigint;\n /** Unix seconds its unspent deposit can be taken back. */\n settleableAt?: bigint;\n /** Unix seconds the unspent deposit came back. */\n settledAt?: bigint;\n}\n\n/** What one exit step did to one channel. */\nexport interface BatchExitResult {\n channelId: string;\n /** The transaction sent, when one was. A channel already done needs none. */\n transaction?: string;\n /** For a close: unix seconds its deposit can be taken back. */\n settleableAt?: bigint;\n /** Why this channel was left as it was. Other channels are still attempted. */\n error?: string;\n}\n\nexport interface ChannelFacade {\n /** Every x402 channel this client holds with the connector, live or archived. */\n channels(): BatchChannelSummary[];\n /** The channel a paid `send()` would draw on now, or `undefined` before one is open. */\n current(): Promise<BatchChannelSummary | undefined>;\n /**\n * Open a channel now rather than on the first paid `send()` — a deposit\n * through the facilitator on Base, a sponsored open on Solana — or return\n * the one already open.\n */\n open(): Promise<BatchChannelSummary>;\n /** Deposit `amount` more into the Base channel this client pays from. */\n deposit(amount: bigint): Promise<BatchChannelSummary>;\n /**\n * Start leaving every channel still open with the node: on EVM a timed\n * withdrawal of everything unclaimed, on Solana `request_close`. The next\n * paid `send()` onboards a fresh channel.\n */\n close(): Promise<BatchExitResult[]>;\n /**\n * Take back the unspent deposit of every channel whose exit window has\n * passed — including a Solana channel the connector sealed first. Channels\n * still inside their window are left for a later call; one that fails does\n * not stop the rest.\n */\n settle(): Promise<BatchExitResult[]>;\n}\n\nexport interface ChannelFacadeDeps {\n connector: string;\n payer: BatchSettlementPayer;\n chain: ChainKind;\n manager: BatchChannelManager;\n describe(): Promise<NodeSelfDescription>;\n evm?: { privateKey: Uint8Array; rpcUrl: string; rpcDispatcher: unknown };\n solana?: { signer: Signer; rpc: SolanaRpcTarget };\n now?: () => bigint;\n}\n\nexport class ClientChannelFacade implements ChannelFacade {\n constructor(private readonly deps: ChannelFacadeDeps) {}\n\n channels(): BatchChannelSummary[] {\n return this.deps.manager.channels(this.deps.connector);\n }\n\n async current(): Promise<BatchChannelSummary | undefined> {\n const terms = chooseBatchSettlement(await this.deps.describe(), this.deps.chain);\n if (terms === undefined) return undefined;\n const channel = this.deps.manager.resolve(this.deps.connector, terms.network, terms.asset);\n if (channel === undefined || this.deps.manager.isClosing(channel.channelId)) return undefined;\n return this.summary(channel.channelId);\n }\n\n async open(): Promise<BatchChannelSummary> {\n const channel = await this.deps.payer.open(\n await this.deps.describe(),\n this.deps.chain\n );\n if (channel === undefined) {\n throw new ConfigError(\n `${this.deps.connector} offers no x402 channel on ${this.deps.chain}`\n );\n }\n return this.summary(channel.channelId);\n }\n\n async deposit(amount: bigint): Promise<BatchChannelSummary> {\n const channel = await this.deps.payer.topUp(\n await this.deps.describe(),\n this.deps.chain,\n amount\n );\n return this.summary(channel.channelId);\n }\n\n async close(): Promise<BatchExitResult[]> {\n const open = this.deps.manager.openChannels(this.deps.connector);\n if (open.length === 0) {\n throw new ChannelNotOpenError(\n `this client holds no open channel with ${this.deps.connector}`\n );\n }\n const results: BatchExitResult[] = [];\n for (const channel of open) {\n results.push(\n await this.attempt(channel.channelId, () => this.closeOne(channel))\n );\n }\n return results;\n }\n\n async settle(): Promise<BatchExitResult[]> {\n const now = this.now();\n const results: BatchExitResult[] = [];\n for (const summary of this.channels()) {\n if (summary.settledAt !== undefined) continue;\n const due =\n summary.settleableAt !== undefined && summary.settleableAt <= now;\n // A Solana channel the connector sealed first is settleable with no\n // close of ours; an EVM one never is.\n if (!due && summary.channel.chain !== 'solana') continue;\n const result = await this.attempt(summary.channel.channelId, () =>\n this.settleOne(summary, due, now)\n );\n if (result !== undefined) results.push(result);\n }\n return results;\n }\n\n private async closeOne(channel: BatchChannel): Promise<BatchExitResult> {\n const now = this.now();\n const manager = this.deps.manager;\n if (channel.chain === 'evm') {\n const clients = this.evmClients(channel.network);\n const state = await readEvmBatchChannel(\n clients.publicClient,\n channel.channelId as Hex\n );\n if (\n state.balance <= state.totalClaimed &&\n state.pendingWithdrawal === 0n\n ) {\n // Nothing left to take back: everything deposited was claimed.\n manager.markClosing(channel.channelId, now, now);\n manager.markSettled(channel.channelId, now);\n return { channelId: channel.channelId };\n }\n await requireGas('ETH', clients.address, clients.nativeBalance(), 'close');\n const started = await initiateEvmBatchWithdraw(clients, channel);\n manager.markClosing(channel.channelId, now, started.finalizeAfter);\n return {\n channelId: channel.channelId,\n transaction: started.transaction,\n settleableAt: started.finalizeAfter,\n };\n }\n const solana = this.requireSolana();\n const state = await getSvmBatchChannel(solana.rpc, channel.channelId);\n if (\n state === null ||\n state.payerWithdrawnAt !== 0n ||\n state.status === 'distributed'\n ) {\n manager.markClosing(channel.channelId, now, now);\n manager.markSettled(channel.channelId, now);\n return { channelId: channel.channelId };\n }\n if (state.status !== 'open') {\n // Already closing or sealed — by the connector, or by an earlier run.\n const settleableAt =\n state.status === 'sealed'\n ? now\n : state.closureStartedAt + BigInt(state.gracePeriod);\n manager.markClosing(channel.channelId, now, settleableAt);\n return { channelId: channel.channelId, settleableAt };\n }\n await requireGas(\n 'SOL',\n base58Encode(solana.signer.publicKey),\n getLamports(solana.rpc, base58Encode(solana.signer.publicKey)),\n 'close'\n );\n const started = await requestSvmBatchClose(\n solana.rpc,\n solana.signer,\n channel.channelId\n );\n manager.markClosing(channel.channelId, now, started.settleableAt);\n return {\n channelId: channel.channelId,\n transaction: started.transaction,\n settleableAt: started.settleableAt,\n };\n }\n\n /** `undefined` when there is nothing to do yet for this channel. */\n private async settleOne(\n summary: BatchChannelSummary,\n due: boolean,\n now: bigint\n ): Promise<BatchExitResult | undefined> {\n const { channel } = summary;\n const manager = this.deps.manager;\n if (channel.chain === 'evm') {\n const clients = this.evmClients(channel.network);\n const state = await readEvmBatchChannel(\n clients.publicClient,\n channel.channelId as Hex\n );\n if (\n state.pendingWithdrawal === 0n &&\n state.balance <= state.totalClaimed\n ) {\n manager.markSettled(channel.channelId, now);\n return { channelId: channel.channelId };\n }\n await requireGas('ETH', clients.address, clients.nativeBalance(), 'settle');\n const { transaction } = await finalizeEvmBatchWithdraw(\n clients,\n channel,\n now\n );\n manager.markSettled(channel.channelId, now);\n return { channelId: channel.channelId, transaction };\n }\n\n const solana = this.requireSolana();\n const state = await getSvmBatchChannel(solana.rpc, channel.channelId);\n // Gone, or already refunded — `distribute` pays the payer too — is done.\n if (\n state === null ||\n state.payerWithdrawnAt !== 0n ||\n state.status === 'distributed'\n ) {\n if (summary.closedAt === undefined)\n manager.markClosing(channel.channelId, now, now);\n manager.markSettled(channel.channelId, now);\n return { channelId: channel.channelId };\n }\n const sealedByConnector = state.status === 'sealed';\n if (!due && !sealedByConnector) return undefined;\n await requireGas(\n 'SOL',\n base58Encode(solana.signer.publicKey),\n getLamports(solana.rpc, base58Encode(solana.signer.publicKey)),\n 'settle'\n );\n const { transaction } = await withdrawSvmBatchChannel(\n solana.rpc,\n solana.signer,\n channel.channelId,\n channel.config,\n now\n );\n if (summary.closedAt === undefined)\n manager.markClosing(channel.channelId, now, now);\n manager.markSettled(channel.channelId, now);\n return { channelId: channel.channelId, transaction };\n }\n\n /** Run one channel's step, turning a failure into that channel's result. */\n private async attempt<T extends BatchExitResult | undefined>(\n channelId: string,\n step: () => Promise<T>\n ): Promise<T | BatchExitResult> {\n try {\n return await step();\n } catch (err) {\n return {\n channelId,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n private summary(channelId: string): BatchChannelSummary {\n const found = this.channels().find(\n (c) => c.channel.channelId === channelId\n );\n if (found === undefined)\n throw new Error(`channel ${channelId} is not recorded`);\n return found;\n }\n\n private evmClients(network: string): EvmExitClients & {\n address: string;\n nativeBalance(): Promise<bigint>;\n } {\n const evm = this.deps.evm;\n if (!evm) {\n throw new ConfigError(\n 'leaving a Base batch-settlement channel needs this client’s EVM key'\n );\n }\n const chain = defineChain({\n id: evmChainIdOf(network),\n name: network,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [evm.rpcUrl] } },\n });\n const account = privateKeyToAccount(toHexKey(evm.privateKey));\n const transport = rpcTransport(evm.rpcUrl, evm.rpcDispatcher);\n const publicClient = createPublicClient({ chain, transport });\n const walletClient = createWalletClient({ account, chain, transport });\n return {\n publicClient: publicClient as unknown as EvmExitClients['publicClient'],\n walletClient: walletClient as unknown as EvmExitClients['walletClient'],\n address: account.address,\n nativeBalance: () => publicClient.getBalance({ address: account.address }),\n };\n }\n\n private requireSolana(): { signer: Signer; rpc: SolanaRpcTarget } {\n if (!this.deps.solana) {\n throw new ConfigError(\n 'leaving a Solana batch-settlement channel needs this client’s Solana key'\n );\n }\n return this.deps.solana;\n }\n\n private now(): bigint {\n return this.deps.now?.() ?? BigInt(Math.floor(Date.now() / 1000));\n }\n}\n\n/**\n * Leaving is the one step of the scheme that costs native gas, and a payer that\n * onboarded gaslessly may well hold none. Say so plainly, before a transaction\n * is built, rather than let the node's \"gas required exceeds allowance\" stand\n * in for the reason.\n */\nasync function requireGas(\n gas: 'ETH' | 'SOL',\n address: string,\n balance: Promise<bigint>,\n step: 'close' | 'settle'\n): Promise<void> {\n if ((await balance) > 0n) return;\n throw new InsufficientBalanceError(\n `leaving a channel needs ${gas} for the fee, and ${address} holds none. Opening and ` +\n `paying never did, so a wallet funded only with USDC has none yet: send it a little ` +\n `${gas}, then run ${step} again.`\n );\n}\n\nfunction toHexKey(key: Uint8Array): Hex {\n return `0x${Buffer.from(key).toString('hex')}`;\n}\n","/**\n * x402 `batch-settlement` on EVM — the chain half of a client that pays a\n * connector from an x402 channel instead of a `TokenNetwork` one (connector ADR\n * 0074, toon-client#679).\n *\n * Everything here is fixed by x402 and the contracts it deployed, not by TOON:\n * `x402BatchSettlement` and its two deposit collectors sit at one address on Base\n * Sepolia and Base mainnet, ownerless and immutable. Cited against x402 at\n * `0cb1a1f0` (`contracts/evm/src/x402BatchSettlement.sol`, and\n * `specs/schemes/batch-settlement/scheme_batch_settlement_evm.md`), and checked in\n * the tests against the published `@x402/evm` 2.27.0 client, which is the\n * reference this module must never drift from.\n *\n * 1. A channel is a {@link BatchChannelConfig}. Its id is the EIP-712 hash of\n * that config under the contract's domain (`getChannelId`), so the id binds\n * the chain and the contract — and, through a free `salt`, a client may hold\n * as many channels to one connector as it likes (ADR 0074 decision 2).\n * 2. A voucher signs `Voucher(bytes32 channelId, uint128 maxClaimableAmount)`\n * under the same domain. It is cumulative and carries no nonce: the\n * connector orders vouchers by amount alone (decision 3).\n * 3. The first deposit CREATES the channel, and anyone may submit it: the\n * payer signs an ERC-3009 `ReceiveWithAuthorization` (or a Permit2 witness\n * transfer, for a token without ERC-3009) whose nonce/witness binds it to\n * the channel id, and a facilitator relays it and pays the gas.\n *\n * What travels on TOON's wire — the claim JSON a voucher rides in — is NOT here.\n * The connector's vectors fix it (ADR 0074 decision 7), and they have not landed.\n */\n\nimport {\n encodeAbiParameters,\n getAddress,\n hashTypedData,\n keccak256,\n toHex,\n type Hex,\n} from 'viem';\nimport { ConfigError, ValidationError } from '../../client/errors.js';\n\n// ---------------------------------------------------------------------------\n// The deployment (identical on Base Sepolia and Base mainnet — ADR 0074 Sources)\n// ---------------------------------------------------------------------------\n\n/** `x402BatchSettlement`: the escrow every channel lives in. */\nexport const X402_BATCH_SETTLEMENT_ADDRESS =\n '0x4020074e9dF2ce1deE5A9C1b5c3f541D02a10003';\n/** The collector a deposit names when it is paid by an ERC-3009 authorization. */\nexport const ERC3009_DEPOSIT_COLLECTOR_ADDRESS =\n '0x4020806089470a89826cB9fB1f4059150b550004';\n/** The collector a deposit names when it is paid by a Permit2 witness transfer. */\nexport const PERMIT2_DEPOSIT_COLLECTOR_ADDRESS =\n '0x4020425FAf3B746C082C2f942b4E5159887B0005';\n/** Uniswap's canonical Permit2, the same address on every chain. */\nexport const PERMIT2_ADDRESS = '0x000000000022D473030F116dDEE9F6B43aC78BA3';\n\n/** `MIN_WITHDRAW_DELAY` / `MAX_WITHDRAW_DELAY` (`x402BatchSettlement.sol#L85-L86`), seconds. */\nexport const MIN_WITHDRAW_DELAY_SECONDS = 15 * 60;\nexport const MAX_WITHDRAW_DELAY_SECONDS = 30 * 24 * 60 * 60;\n\n/**\n * The largest EVM voucher amount: `uint128`, the width of `x402BatchSettlement`'s\n * `maxClaimableAmount` (connector#1439, amending ADR 0074 decision 3). One above\n * this is refused before it is signed. A Solana voucher stays `u64`.\n */\nconst MAX_VOUCHER_AMOUNT = 2n ** 128n - 1n;\nconst ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';\n\nconst CHANNEL_CONFIG_TYPES = {\n ChannelConfig: [\n { name: 'payer', type: 'address' },\n { name: 'payerAuthorizer', type: 'address' },\n { name: 'receiver', type: 'address' },\n { name: 'receiverAuthorizer', type: 'address' },\n { name: 'token', type: 'address' },\n { name: 'withdrawDelay', type: 'uint40' },\n { name: 'salt', type: 'bytes32' },\n ],\n} as const;\n\nconst VOUCHER_TYPES = {\n Voucher: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'maxClaimableAmount', type: 'uint128' },\n ],\n} as const;\n\nconst RECEIVE_WITH_AUTHORIZATION_TYPES = {\n ReceiveWithAuthorization: [\n { name: 'from', type: 'address' },\n { name: 'to', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'validAfter', type: 'uint256' },\n { name: 'validBefore', type: 'uint256' },\n { name: 'nonce', type: 'bytes32' },\n ],\n} as const;\n\nconst PERMIT2_WITNESS_TYPES = {\n PermitWitnessTransferFrom: [\n { name: 'permitted', type: 'TokenPermissions' },\n { name: 'spender', type: 'address' },\n { name: 'nonce', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n { name: 'witness', type: 'DepositWitness' },\n ],\n TokenPermissions: [\n { name: 'token', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n DepositWitness: [{ name: 'channelId', type: 'bytes32' }],\n} as const;\n\n/** The contract's EIP-712 domain: `(\"x402 Batch Settlement\", \"1\", chainId, contract)`. */\nfunction batchSettlementDomain(chainId: number) {\n return {\n name: 'x402 Batch Settlement',\n version: '1',\n chainId,\n verifyingContract: X402_BATCH_SETTLEMENT_ADDRESS as Hex,\n } as const;\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * A connector's `batch-settlement` offer on EVM: one `accepts[]` entry of its\n * greeting. It is x402-valid (ADR 0074 decision 8), so its shape is x402's\n * `PaymentRequirements`, field for field.\n */\nexport interface BatchSettlementEvmOffer {\n scheme: 'batch-settlement';\n /** CAIP-2, `eip155:<chainId>`. */\n network: string;\n /** Per-request price, atomic units. */\n amount: string;\n /** The token address. */\n asset: string;\n /** The connector's EVM settlement address — the channel's `receiver`. */\n payTo: string;\n maxTimeoutSeconds: number;\n extra: {\n /** Must be `payTo`: a connector never delegates it (ADR 0074 decision 5). */\n receiverAuthorizer: string;\n /** The connector's published MINIMUM `withdrawDelay`, seconds. */\n withdrawDelay: number;\n /** The token's own EIP-712 domain, which an ERC-3009 authorization signs under. */\n name?: string;\n version?: string;\n /**\n * How a deposit moves the token: `eip3009` (x402's default) for a token\n * with ERC-3009, `permit2` for any other ERC-20. x402's own field.\n */\n assetTransferMethod?: 'eip3009' | 'permit2';\n /**\n * The x402 facilitator this connector relays deposits through and pays the\n * gas of — TOON's addition, since here the payer, not the seller, calls it\n * (toon-client#695).\n */\n facilitator?: string;\n };\n}\n\n/** `x402BatchSettlement.ChannelConfig` — the seven immutable fields a channel id hashes. */\nexport interface BatchChannelConfig {\n payer: string;\n payerAuthorizer: string;\n receiver: string;\n receiverAuthorizer: string;\n token: string;\n withdrawDelay: number;\n salt: Hex;\n}\n\n/** A signed voucher, in x402's own spelling. `maxClaimableAmount` is decimal. */\nexport interface BatchVoucher {\n channelId: Hex;\n maxClaimableAmount: string;\n signature: Hex;\n}\n\n/** Anything that can sign EIP-712 typed data as one address — a viem `LocalAccount`. */\nexport interface TypedDataSigner {\n address: string;\n signTypedData: (params: never) => Promise<Hex>;\n}\n\n/** x402's `deposit` payload: a deposit authorization plus the voucher it must carry. */\nexport interface BatchDepositPayload<A> {\n type: 'deposit';\n channelConfig: BatchChannelConfig;\n voucher: BatchVoucher;\n deposit: { amount: string; authorization: A };\n}\n\nexport type Eip3009DepositPayload = BatchDepositPayload<{\n erc3009Authorization: {\n validAfter: string;\n validBefore: string;\n salt: Hex;\n signature: Hex;\n };\n}>;\n\nexport type Permit2DepositPayload = BatchDepositPayload<{\n permit2Authorization: {\n from: string;\n permitted: { token: string; amount: string };\n spender: string;\n nonce: string;\n deadline: string;\n witness: { channelId: Hex };\n signature: Hex;\n };\n}>;\n\n// ---------------------------------------------------------------------------\n// Channel config and id\n// ---------------------------------------------------------------------------\n\n/** The chain id of an `eip155:<id>` CAIP-2 network, or a {@link ConfigError}. */\nexport function evmChainIdOf(network: string): number {\n const match = /^eip155:(\\d+)$/.exec(network);\n const chainId = match ? Number(match[1]) : NaN;\n if (!Number.isSafeInteger(chainId) || chainId <= 0) {\n throw new ConfigError(\n `batch-settlement offer names ${network}, which is not an eip155 network`\n );\n }\n return chainId;\n}\n\n/**\n * The config of a NEW channel to the connector that made `offer`.\n *\n * The connector admits a channel only if `receiver` and `receiverAuthorizer` are\n * both its settlement address, `token` is one it settles in, and `withdrawDelay`\n * is at least its published minimum (ADR 0074 decision 2). An offer that breaks\n * the first rule is refused here: a channel whose `receiverAuthorizer` is someone\n * else hands that party the power to refund the connector's unclaimed earnings to\n * the payer (decision 5), and the connector would refuse every voucher on it.\n *\n * `payer`, `payerAuthorizer` and `salt` are the client's. A fresh random salt is\n * drawn unless one is given, because nothing at the client edge derives an x402\n * channel — the voucher names it.\n */\nexport function buildBatchChannelConfig(params: {\n payer: string;\n /** A session key that signs vouchers in place of `payer`. ECDSA only. */\n payerAuthorizer?: string;\n offer: BatchSettlementEvmOffer;\n /** Seconds; at least the offer's minimum. Defaults to that minimum. */\n withdrawDelay?: number;\n salt?: Hex;\n}): BatchChannelConfig {\n const { offer } = params;\n if (offer.scheme !== 'batch-settlement') {\n throw new ConfigError(\n `offer scheme is ${String(offer.scheme)}, not batch-settlement`\n );\n }\n evmChainIdOf(offer.network);\n\n const receiver = getAddress(offer.payTo);\n const receiverAuthorizer = getAddress(offer.extra.receiverAuthorizer);\n if (receiverAuthorizer === ZERO_ADDRESS || receiverAuthorizer !== receiver) {\n throw new ConfigError(\n `batch-settlement offer's receiverAuthorizer ${receiverAuthorizer} is not its payTo ${receiver}; ` +\n 'a connector never delegates it (connector ADR 0074 decision 5)'\n );\n }\n\n const minimum = offer.extra.withdrawDelay;\n const withdrawDelay = params.withdrawDelay ?? minimum;\n if (\n !Number.isInteger(withdrawDelay) ||\n withdrawDelay < MIN_WITHDRAW_DELAY_SECONDS ||\n withdrawDelay > MAX_WITHDRAW_DELAY_SECONDS\n ) {\n throw new ConfigError(\n `withdrawDelay ${withdrawDelay}s is outside the contract's ${MIN_WITHDRAW_DELAY_SECONDS}..${MAX_WITHDRAW_DELAY_SECONDS}s`\n );\n }\n if (withdrawDelay < minimum) {\n throw new ConfigError(\n `withdrawDelay ${withdrawDelay}s is below the connector's published minimum of ${minimum}s`\n );\n }\n\n return {\n payer: getAddress(params.payer),\n payerAuthorizer: getAddress(params.payerAuthorizer ?? params.payer),\n receiver,\n receiverAuthorizer,\n token: getAddress(offer.asset),\n withdrawDelay,\n salt: params.salt ?? randomBytes32(),\n };\n}\n\n/** `getChannelId(config)`: the EIP-712 hash of the config, bound to chain and contract. */\nexport function batchChannelId(\n config: BatchChannelConfig,\n chainId: number\n): Hex {\n return hashTypedData({\n domain: batchSettlementDomain(chainId),\n types: CHANNEL_CONFIG_TYPES,\n primaryType: 'ChannelConfig',\n message: {\n payer: config.payer as Hex,\n payerAuthorizer: config.payerAuthorizer as Hex,\n receiver: config.receiver as Hex,\n receiverAuthorizer: config.receiverAuthorizer as Hex,\n token: config.token as Hex,\n withdrawDelay: config.withdrawDelay,\n salt: config.salt,\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// Vouchers\n// ---------------------------------------------------------------------------\n\nfunction assertVoucherAmount(amount: bigint): void {\n if (amount < 0n || amount > MAX_VOUCHER_AMOUNT) {\n throw new ValidationError(\n `voucher amount ${amount} is outside 0..2^128-1, the uint128 a voucher carries`\n );\n }\n}\n\n/**\n * `getVoucherDigest(channelId, maxClaimableAmount)` — the digest a voucher\n * signature covers. Exposed so a vector can be checked against the deployed\n * contract's own view function (ADR 0074 decision 7).\n */\nexport function batchVoucherDigest(\n chainId: number,\n channelId: Hex,\n maxClaimableAmount: bigint\n): Hex {\n assertVoucherAmount(maxClaimableAmount);\n return hashTypedData({\n domain: batchSettlementDomain(chainId),\n types: VOUCHER_TYPES,\n primaryType: 'Voucher',\n message: { channelId, maxClaimableAmount },\n });\n}\n\n/**\n * Sign a cumulative voucher on `channelId`.\n *\n * The signer must be the channel's `payerAuthorizer` (or its `payer`, when the\n * authorizer is zero, which this client never builds). The connector checks it\n * against the config the client presented, never against anything in the claim.\n */\nexport async function signBatchVoucher(\n signer: TypedDataSigner,\n chainId: number,\n channelId: Hex,\n maxClaimableAmount: bigint\n): Promise<BatchVoucher> {\n assertVoucherAmount(maxClaimableAmount);\n const signature = await signer.signTypedData({\n domain: batchSettlementDomain(chainId),\n types: VOUCHER_TYPES,\n primaryType: 'Voucher',\n message: { channelId, maxClaimableAmount },\n } as never);\n return {\n channelId,\n maxClaimableAmount: maxClaimableAmount.toString(),\n signature,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Deposits\n// ---------------------------------------------------------------------------\n\ninterface DepositParams {\n /** The funding wallet — `config.payer`. */\n payer: TypedDataSigner;\n /** Signs the voucher; must be `config.payerAuthorizer`. Defaults to `payer`. */\n voucherSigner?: TypedDataSigner;\n offer: BatchSettlementEvmOffer;\n config: BatchChannelConfig;\n /** Atomic units moved into escrow. */\n amount: bigint;\n /**\n * The CUMULATIVE voucher the deposit carries, at least one unit: x402's\n * TypeScript and Python facilitators refuse a zero voucher on a fresh channel\n * (ADR 0074 prerequisite 1). On a first deposit the first packet's charge is\n * the natural choice, and that same voucher may then ride the first packet. On\n * a top-up it is the channel's running total, which may well exceed `amount`;\n * the facilitator bounds it by balance plus deposit, which only it can read.\n */\n voucherAmount: bigint;\n}\n\nasync function depositVoucher(\n params: DepositParams,\n chainId: number,\n channelId: Hex\n): Promise<BatchVoucher> {\n const { config, amount, voucherAmount } = params;\n if (amount <= 0n) {\n throw new ValidationError(`deposit amount must be positive, got ${amount}`);\n }\n if (voucherAmount < 1n) {\n throw new ValidationError(\n `a deposit's voucher must be at least 1 unit, got ${voucherAmount}`\n );\n }\n if (getAddress(params.payer.address) !== getAddress(config.payer)) {\n throw new ValidationError(\n `deposit signer ${params.payer.address} is not the channel payer ${config.payer}`\n );\n }\n const voucherSigner = params.voucherSigner ?? params.payer;\n if (\n getAddress(voucherSigner.address) !== getAddress(config.payerAuthorizer)\n ) {\n throw new ValidationError(\n `voucher signer ${voucherSigner.address} is not the channel's payerAuthorizer ${config.payerAuthorizer}`\n );\n }\n return signBatchVoucher(voucherSigner, chainId, channelId, voucherAmount);\n}\n\n/**\n * A deposit paid by ERC-3009 `receiveWithAuthorization` — fully gasless for the\n * payer, since a facilitator submits it. The authorization's nonce is\n * `keccak256(abi.encode(channelId, salt))` (`ERC3009DepositCollector.sol#L34-L51`),\n * so the payer's one signature binds the deposit to this channel and no other.\n *\n * The first deposit creates the channel; a later one on the same config is a\n * top-up, built the same way.\n */\nexport async function buildEip3009Deposit(\n params: DepositParams & {\n /** A 32-byte ERC-3009 salt; fresh and random by default. */\n salt?: Hex;\n }\n): Promise<Eip3009DepositPayload> {\n const { offer, config, amount } = params;\n const chainId = evmChainIdOf(offer.network);\n const { name, version } = offer.extra;\n if (!name || !version) {\n throw new ConfigError(\n `batch-settlement offer for ${offer.asset} carries no EIP-712 domain (extra.name / extra.version) ` +\n 'to sign an ERC-3009 authorization under'\n );\n }\n const channelId = batchChannelId(config, chainId);\n const voucher = await depositVoucher(params, chainId, channelId);\n\n const salt = params.salt ?? randomBytes32();\n const validBefore = BigInt(nowSeconds() + offer.maxTimeoutSeconds);\n const signature = await params.payer.signTypedData({\n domain: {\n name,\n version,\n chainId,\n verifyingContract: getAddress(offer.asset),\n },\n types: RECEIVE_WITH_AUTHORIZATION_TYPES,\n primaryType: 'ReceiveWithAuthorization',\n message: {\n from: getAddress(params.payer.address),\n to: ERC3009_DEPOSIT_COLLECTOR_ADDRESS,\n value: amount,\n validAfter: 0n,\n validBefore,\n nonce: keccak256(\n encodeAbiParameters(\n [{ type: 'bytes32' }, { type: 'uint256' }],\n [channelId, BigInt(salt)]\n )\n ),\n },\n } as never);\n\n return {\n type: 'deposit',\n channelConfig: config,\n voucher,\n deposit: {\n amount: amount.toString(),\n authorization: {\n erc3009Authorization: {\n validAfter: '0',\n validBefore: validBefore.toString(),\n salt,\n signature,\n },\n },\n },\n };\n}\n\n/**\n * A deposit paid by a Permit2 witness transfer, for a token without ERC-3009.\n * The witness is `DepositWitness(channelId)` (`Permit2DepositCollector.sol#L29-L33`).\n *\n * This is gasless only once the payer has approved Permit2 for the token, which\n * is a transaction of its own. On x402.org that approval was NOT sponsored in\n * practice (ADR 0074 prerequisite 2), so a client that holds no gas needs either\n * an ERC-3009 token or a facilitator that funds the approval itself.\n */\nexport async function buildPermit2Deposit(\n params: DepositParams & {\n /** A Permit2 unordered nonce; fresh and random by default. */\n nonce?: bigint;\n }\n): Promise<Permit2DepositPayload> {\n const { offer, config, amount } = params;\n const chainId = evmChainIdOf(offer.network);\n const channelId = batchChannelId(config, chainId);\n const voucher = await depositVoucher(params, chainId, channelId);\n\n const nonce = params.nonce ?? BigInt(randomBytes32());\n const deadline = BigInt(nowSeconds() + offer.maxTimeoutSeconds);\n const token = getAddress(offer.asset);\n const signature = await params.payer.signTypedData({\n domain: { name: 'Permit2', chainId, verifyingContract: PERMIT2_ADDRESS },\n types: PERMIT2_WITNESS_TYPES,\n primaryType: 'PermitWitnessTransferFrom',\n message: {\n permitted: { token, amount },\n spender: PERMIT2_DEPOSIT_COLLECTOR_ADDRESS,\n nonce,\n deadline,\n witness: { channelId },\n },\n } as never);\n\n return {\n type: 'deposit',\n channelConfig: config,\n voucher,\n deposit: {\n amount: amount.toString(),\n authorization: {\n permit2Authorization: {\n from: getAddress(params.payer.address),\n permitted: { token, amount: amount.toString() },\n spender: PERMIT2_DEPOSIT_COLLECTOR_ADDRESS,\n nonce: nonce.toString(),\n deadline: deadline.toString(),\n witness: { channelId },\n signature,\n },\n },\n },\n };\n}\n\nfunction randomBytes32(): Hex {\n return toHex(globalThis.crypto.getRandomValues(new Uint8Array(32)));\n}\n\nfunction nowSeconds(): number {\n return Math.floor(Date.now() / 1000);\n}\n\n// ---------------------------------------------------------------------------\n// Reading a channel back\n// ---------------------------------------------------------------------------\n\n/** `channels(id)` and `pendingWithdrawals(id)` (`x402BatchSettlement.sol`). */\nexport const X402_BATCH_SETTLEMENT_READ_ABI = [\n {\n type: 'function',\n name: 'channels',\n stateMutability: 'view',\n inputs: [{ name: 'channelId', type: 'bytes32' }],\n outputs: [\n { name: 'balance', type: 'uint128' },\n { name: 'totalClaimed', type: 'uint128' },\n ],\n },\n {\n type: 'function',\n name: 'pendingWithdrawals',\n stateMutability: 'view',\n inputs: [{ name: 'channelId', type: 'bytes32' }],\n outputs: [\n { name: 'amount', type: 'uint128' },\n { name: 'initiatedAt', type: 'uint40' },\n ],\n },\n] as const;\n\n/** An EVM batch-settlement channel as the chain holds it. */\nexport interface EvmBatchChannelState {\n /** Everything ever deposited, less what has left through a withdrawal or refund. */\n balance: bigint;\n /** What the receiver has claimed — a floor under the connector's watermark. */\n totalClaimed: bigint;\n /** A timed withdrawal in flight, zero if none. */\n pendingWithdrawal: bigint;\n /** Unix seconds the pending withdrawal started, zero if none. */\n withdrawalInitiatedAt: number;\n}\n\n/** Anything with viem's `readContract`, such as a `PublicClient`. */\nexport interface ContractReader {\n readContract: (params: never) => Promise<unknown>;\n}\n\n/** Read `channelId`'s escrow and claim totals, and any pending withdrawal. */\nexport async function readEvmBatchChannel(\n client: ContractReader,\n channelId: Hex\n): Promise<EvmBatchChannelState> {\n const read = (functionName: 'channels' | 'pendingWithdrawals') =>\n client.readContract({\n address: X402_BATCH_SETTLEMENT_ADDRESS,\n abi: X402_BATCH_SETTLEMENT_READ_ABI,\n functionName,\n args: [channelId],\n } as never) as Promise<readonly [bigint, bigint | number]>;\n const [[balance, totalClaimed], [pending, initiatedAt]] = await Promise.all([\n read('channels'),\n read('pendingWithdrawals'),\n ]);\n return {\n balance,\n totalClaimed: BigInt(totalClaimed),\n pendingWithdrawal: pending,\n withdrawalInitiatedAt: Number(initiatedAt),\n };\n}\n","/**\n * x402 `batch-settlement` on Solana — the chain half of a client that pays a\n * connector from a payment-channels channel instead of a TOON-program one\n * (connector ADR 0074, toon-client#679).\n *\n * The program is solana-foundation's payment-channels,\n * `CHNLxYvVA28MJP9PrFuDXccuoGXAx7jBacfLEkahyGsX` on devnet and mainnet-beta.\n * x402's own SVM TypeScript is unmerged (x402-foundation/x402#3164), so this\n * module reproduces the program's contract directly, cited to\n * `program/payment_channels/src/` at `3ffa4d67` and to x402's\n * `specs/schemes/batch-settlement/scheme_batch_settlement_svm.md` at `0cb1a1f0`,\n * and is tested against fixtures from the program's own codama client.\n *\n * 1. A channel is a PDA over `[\"channel\", payer, payee, mint,\n * authorized_signer, salt u64 LE, open_slot u64 LE]`\n * (`state/channel.rs#L238-L258`). `open_slot` is a seed nobody can\n * predict far ahead, so a channel is never derived by a connector — the\n * voucher names it (ADR 0074 decision 2).\n * 2. A voucher is 50 bytes, `0x56 0x01 ‖ channel ‖ u64 cumulative LE ‖ i64\n * expires_at LE` (`instructions/mod.rs`), Ed25519-signed by the channel's\n * `authorized_signer`. `expires_at` is always zero (decision 3).\n * 3. `open` is sponsored. The sponsor is fee payer, `rent_payer` AND the\n * zero-share `payee`, and the payee may seal the channel at any time and is\n * the only party that can land a voucher once the payer starts to close.\n * So the sponsor MUST be the receiving connector itself, and any other is\n * refused before the payer signs (decision 5).\n *\n * What travels on TOON's wire, and how the connector's sponsor endpoint is\n * reached (connector #1346), are NOT here. The vectors fix the first, and the\n * second is not built.\n */\n\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { base58Decode, base58Encode } from '../../utils/base58.js';\nimport { fromBase64, toBase64, encodeUtf8, toHex } from '../../utils/binary.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport {\n solanaRpc,\n type SolanaRpcTarget,\n compileLegacyMessage,\n deriveAssociatedTokenAccount,\n findProgramAddress,\n padTo32,\n serializeLegacyTransaction,\n type RawInstruction,\n type Signer,\n} from '../solana/payment-channel.js';\nimport { signSolanaWireTransaction } from '../solana/wire-transaction.js';\nimport { ConfigError, ValidationError } from '../../client/errors.js';\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** solana-foundation payment-channels — a network constant, never read off the wire. */\nexport const PAYMENT_CHANNELS_PROGRAM_ID =\n 'CHNLxYvVA28MJP9PrFuDXccuoGXAx7jBacfLEkahyGsX';\n\nconst TOKEN_PROGRAM_ID = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\nconst ASSOCIATED_TOKEN_PROGRAM_ID =\n 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';\nconst SYSTEM_PROGRAM_ID = '11111111111111111111111111111111';\nconst RENT_SYSVAR_ID = 'SysvarRent111111111111111111111111111111111';\nconst MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';\n\nconst IX_OPEN = 1;\nconst IX_TOP_UP = 3;\n/** `VOUCHER_MAGIC`: tag `'V'` and format version 1. */\nconst VOUCHER_MAGIC = [0x56, 0x01] as const;\nconst VOUCHER_LENGTH = 50;\n/** `BPS_DENOMINATOR`: one recipient takes all of it. */\nconst ALL_BPS = 10_000;\n\n/** x402's conformance bound on `withdrawDelay` / `grace_period` (SVM spec §4.1). */\nexport const MIN_GRACE_PERIOD_SECONDS = 900;\nexport const MAX_GRACE_PERIOD_SECONDS = 30 * 24 * 60 * 60;\n\nconst MAX_U64 = 2n ** 64n - 1n;\nconst CHANNEL_ACCOUNT_LENGTH = 256;\nconst CHANNEL_DISCRIMINATOR = 1;\nconst STATUSES = ['open', 'sealed', 'closing', 'distributed'] as const;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * A connector's `batch-settlement` offer on Solana: one `accepts[]` entry of its\n * greeting, in x402's `PaymentRequirements` shape (ADR 0074 decision 8).\n */\nexport interface BatchSettlementSvmOffer {\n scheme: 'batch-settlement';\n /** CAIP-2, `solana:<genesis hash prefix>`. */\n network: string;\n amount: string;\n /** The mint. */\n asset: string;\n /** The owner of the connector's receiving account — the one distribution recipient. */\n payTo: string;\n maxTimeoutSeconds: number;\n extra: {\n /** The connector's sponsor key: fee payer, `rent_payer` and zero-share `payee`. */\n feePayer: string;\n /** The connector's published MINIMUM `grace_period`, seconds. */\n withdrawDelay: number;\n /** The program that owns `asset`. */\n tokenProgram: string;\n /** When present, the `open` transaction's memo must be exactly this. */\n memo?: string;\n /**\n * The connector's own field, not x402's: the smallest deposit it will\n * sponsor an open for, atomic units (connector #1346).\n */\n minDeposit?: string;\n /**\n * The connector's own field, not x402's: the path, on the connector's\n * client edge, that co-signs and submits a sponsored `open` (connector #1357).\n */\n sponsorEndpoint?: string;\n };\n}\n\n/** x402's SVM `ChannelConfig`: what a channel's PDA and `open` are built from. */\nexport interface SvmBatchChannelConfig {\n payer: string;\n /** The channel's `authorized_signer` — the key that signs vouchers. */\n payerAuthorizer: string;\n receiver: string;\n token: string;\n withdrawDelay: number;\n salt: bigint;\n openSlot: bigint;\n}\n\n/** A signed voucher, in x402's `BatchVoucher` spelling. */\nexport interface SvmBatchVoucher {\n channelId: string;\n maxClaimableAmount: string;\n expiresAt: 0;\n /** Base58 Ed25519 signature. */\n signature: string;\n}\n\n/** The 256-byte `Channel` account, decoded. */\nexport interface SvmBatchChannelState {\n status: (typeof STATUSES)[number];\n salt: bigint;\n deposit: bigint;\n settled: bigint;\n payoutWatermark: bigint;\n closureStartedAt: bigint;\n payerWithdrawnAt: bigint;\n gracePeriod: number;\n distributionHash: Uint8Array;\n payer: string;\n payee: string;\n authorizedSigner: string;\n mint: string;\n rentPayer: string;\n openSlot: bigint;\n}\n\n// ---------------------------------------------------------------------------\n// Config and addresses\n// ---------------------------------------------------------------------------\n\n/**\n * The config of a NEW channel to the connector that made `offer`.\n *\n * x402 fixes most of it from the offer (SVM spec §4.1): the mint, the single\n * recipient `payTo`, and `grace_period`. The client chooses `payer`, the voucher\n * key, `salt`, and `openSlot` — a recent slot; the program refuses one more than\n * 1,500 slots old, so it is fetched just before the transaction is built.\n *\n * Only SPL Token mints are built for: the associated-token-account derivation\n * this client carries is SPL Token's.\n */\nexport function buildSvmBatchChannelConfig(params: {\n payer: string;\n payerAuthorizer?: string;\n offer: BatchSettlementSvmOffer;\n openSlot: bigint;\n /** Seconds; at least the offer's minimum. Defaults to that minimum. */\n withdrawDelay?: number;\n salt?: bigint;\n}): SvmBatchChannelConfig {\n const { offer } = params;\n if (offer.scheme !== 'batch-settlement') {\n throw new ConfigError(\n `offer scheme is ${String(offer.scheme)}, not batch-settlement`\n );\n }\n if (!offer.network.startsWith('solana:')) {\n throw new ConfigError(\n `batch-settlement offer names ${offer.network}, which is not a Solana network`\n );\n }\n if (offer.extra.tokenProgram !== TOKEN_PROGRAM_ID) {\n throw new ConfigError(\n `batch-settlement offer's mint is owned by ${offer.extra.tokenProgram}; only SPL Token is supported`\n );\n }\n const sponsor = offer.extra.feePayer;\n const payerAuthorizer = params.payerAuthorizer ?? params.payer;\n if (params.payer === sponsor || payerAuthorizer === sponsor) {\n throw new ConfigError(\n `the sponsor ${sponsor} cannot also be the payer or the voucher signer: it is the channel's payee`\n );\n }\n\n const minimum = offer.extra.withdrawDelay;\n const withdrawDelay = params.withdrawDelay ?? minimum;\n if (\n !Number.isInteger(withdrawDelay) ||\n withdrawDelay < MIN_GRACE_PERIOD_SECONDS ||\n withdrawDelay > MAX_GRACE_PERIOD_SECONDS\n ) {\n throw new ConfigError(\n `withdrawDelay ${withdrawDelay}s is outside x402's ${MIN_GRACE_PERIOD_SECONDS}..${MAX_GRACE_PERIOD_SECONDS}s`\n );\n }\n if (withdrawDelay < minimum) {\n throw new ConfigError(\n `withdrawDelay ${withdrawDelay}s is below the connector's published minimum of ${minimum}s`\n );\n }\n if (withdrawDelay < offer.maxTimeoutSeconds) {\n throw new ConfigError(\n `withdrawDelay ${withdrawDelay}s is below the offer's maxTimeoutSeconds ${offer.maxTimeoutSeconds}s (x402 SVM spec §4.1)`\n );\n }\n\n const salt = params.salt ?? randomU64();\n assertU64(salt, 'salt');\n assertU64(params.openSlot, 'openSlot');\n return {\n payer: params.payer,\n payerAuthorizer,\n receiver: offer.payTo,\n token: offer.asset,\n withdrawDelay,\n salt,\n openSlot: params.openSlot,\n };\n}\n\n/** The channel PDA — the `channelId` every voucher on it names. */\nexport function svmBatchChannelAddress(\n config: SvmBatchChannelConfig,\n sponsor: string\n): string {\n const { pda } = findProgramAddress(\n [\n encodeUtf8('channel'),\n key(config.payer),\n key(sponsor),\n key(config.token),\n key(config.payerAuthorizer),\n u64(config.salt),\n u64(config.openSlot),\n ],\n key(PAYMENT_CHANNELS_PROGRAM_ID)\n );\n return base58Encode(pda);\n}\n\n/** The program's event-authority PDA (`[\"event_authority\"]`), an `open` account. */\nexport function paymentChannelsEventAuthority(): string {\n const { pda } = findProgramAddress(\n [encodeUtf8('event_authority')],\n key(PAYMENT_CHANNELS_PROGRAM_ID)\n );\n return base58Encode(pda);\n}\n\n// ---------------------------------------------------------------------------\n// Instructions\n// ---------------------------------------------------------------------------\n\n/**\n * `open` (discriminator 1). Deliberately not exported from the package: it takes\n * any `sponsor`, and {@link buildSponsoredOpen} is the one path that checks the\n * sponsor is the receiving connector's before a payer signs.\n *\n * The 14 accounts, in the order x402's SVM spec\n * requires a sponsor to check, and `salt ‖ deposit ‖ grace_period ‖ open_slot ‖\n * recipients`, where the one recipient is `payTo` at 10,000 bps.\n */\nexport function buildSvmOpenInstruction(params: {\n config: SvmBatchChannelConfig;\n sponsor: string;\n deposit: bigint;\n}): RawInstruction {\n const { config, sponsor, deposit } = params;\n assertPositive(deposit, 'deposit');\n const channel = svmBatchChannelAddress(config, sponsor);\n\n const data = new Uint8Array(1 + 8 + 8 + 4 + 8 + 4 + 34);\n data[0] = IX_OPEN;\n data.set(u64(config.salt), 1);\n data.set(u64(deposit), 9);\n new DataView(data.buffer).setUint32(17, config.withdrawDelay, true);\n data.set(u64(config.openSlot), 21);\n new DataView(data.buffer).setUint32(29, 1, true);\n data.set(key(config.receiver), 33);\n new DataView(data.buffer).setUint16(65, ALL_BPS, true);\n\n return {\n programId: PAYMENT_CHANNELS_PROGRAM_ID,\n keys: [\n meta(config.payer, true, true),\n meta(sponsor, true, true),\n meta(sponsor, false, false),\n meta(config.token, false, false),\n meta(config.payerAuthorizer, false, false),\n meta(channel, false, true),\n meta(\n deriveAssociatedTokenAccount(config.payer, config.token),\n false,\n true\n ),\n meta(deriveAssociatedTokenAccount(channel, config.token), false, true),\n meta(TOKEN_PROGRAM_ID, false, false),\n meta(SYSTEM_PROGRAM_ID, false, false),\n meta(RENT_SYSVAR_ID, false, false),\n meta(ASSOCIATED_TOKEN_PROGRAM_ID, false, false),\n meta(paymentChannelsEventAuthority(), false, false),\n meta(PAYMENT_CHANNELS_PROGRAM_ID, false, false),\n ],\n data,\n };\n}\n\n/**\n * `top_up` (discriminator 3): more deposit into an Open channel. The sponsor\n * pays only the fee, so it is not among the instruction's accounts.\n */\nexport function buildSvmTopUpInstruction(params: {\n config: SvmBatchChannelConfig;\n sponsor: string;\n amount: bigint;\n}): RawInstruction {\n const { config, sponsor, amount } = params;\n assertPositive(amount, 'top-up amount');\n const channel = svmBatchChannelAddress(config, sponsor);\n const data = new Uint8Array(9);\n data[0] = IX_TOP_UP;\n data.set(u64(amount), 1);\n return {\n programId: PAYMENT_CHANNELS_PROGRAM_ID,\n keys: [\n meta(config.payer, true, true),\n meta(channel, false, true),\n meta(\n deriveAssociatedTokenAccount(config.payer, config.token),\n false,\n true\n ),\n meta(deriveAssociatedTokenAccount(channel, config.token), false, true),\n meta(config.token, false, false),\n meta(TOKEN_PROGRAM_ID, false, false),\n ],\n data,\n };\n}\n\n// ---------------------------------------------------------------------------\n// The sponsored open\n// ---------------------------------------------------------------------------\n\n/**\n * The `open` transaction for a channel the receiving connector sponsors: `[open,\n * memo]`, with the sponsor as fee payer, signed by the payer, and the sponsor's\n * slot left empty for it to fill.\n *\n * `connectorSponsor` is the sponsor key the RECEIVING connector publishes. The\n * offer's `feePayer` must be that key, or nothing is signed: a third-party\n * sponsor sits in the `payee` seat, can seal the channel before the connector\n * settles, and after the payer calls `request_close` is the only party that can\n * land a voucher — a loss to the connector, not merely a risk (ADR 0074\n * decision 5). The connector refuses such a channel, so the payer's deposit\n * would be locked for `grace_period` in a channel that buys nothing.\n *\n * The memo is the offer's when it names one, and otherwise a random 16-byte hex\n * nonce, as x402's acceptance policy requires of the transaction's suffix.\n */\nexport function buildSponsoredOpen(params: {\n payer: Signer;\n config: SvmBatchChannelConfig;\n offer: BatchSettlementSvmOffer;\n connectorSponsor: string;\n deposit: bigint;\n recentBlockhash: string;\n memo?: string;\n}): { transaction: string; channelId: string } {\n const { payer, config, offer, connectorSponsor } = params;\n const sponsor = offer.extra.feePayer;\n if (sponsor !== connectorSponsor) {\n throw new ConfigError(\n `sponsor ${sponsor} is not the receiving connector's sponsor ${connectorSponsor}; ` +\n 'a third-party sponsor can seal the channel (connector ADR 0074 decision 5)'\n );\n }\n if (base58Encode(payer.publicKey) !== config.payer) {\n throw new ValidationError(\n `signing key is not the channel payer ${config.payer}`\n );\n }\n\n const memo = offer.extra.memo ?? params.memo ?? toHex(randomBytes(16));\n const compiled = compileLegacyMessage(\n sponsor,\n [\n buildSvmOpenInstruction({ config, sponsor, deposit: params.deposit }),\n { programId: MEMO_PROGRAM_ID, keys: [], data: encodeUtf8(memo) },\n ],\n params.recentBlockhash\n );\n const unsigned = toBase64(serializeLegacyTransaction(compiled, []));\n return {\n transaction: signSolanaWireTransaction(unsigned, [payer]),\n channelId: svmBatchChannelAddress(config, sponsor),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Vouchers\n// ---------------------------------------------------------------------------\n\n/**\n * The 50 bytes a voucher signs, with `expires_at` always zero: a nonzero one is\n * value that can lapse before the connector lands it, and the connector refuses\n * it structurally (ADR 0074 decision 3). So there is no way to ask for one.\n */\nexport function buildSvmVoucherMessage(\n channelId: string,\n cumulative: bigint\n): Uint8Array {\n assertU64(cumulative, 'voucher amount');\n const message = new Uint8Array(VOUCHER_LENGTH);\n message.set(VOUCHER_MAGIC, 0);\n message.set(key(channelId), 2);\n message.set(u64(cumulative), 34);\n // bytes 42..50: expires_at, i64 LE zero.\n return message;\n}\n\n/** Sign a cumulative voucher on `channelId` with the channel's `authorized_signer`. */\nexport function signSvmVoucher(\n signer: Signer,\n channelId: string,\n cumulative: bigint\n): SvmBatchVoucher {\n const message = buildSvmVoucherMessage(channelId, cumulative);\n return {\n channelId,\n maxClaimableAmount: cumulative.toString(),\n expiresAt: 0,\n signature: base58Encode(ed25519.sign(message, signer.privateKey)),\n };\n}\n\n// ---------------------------------------------------------------------------\n// The channel account\n// ---------------------------------------------------------------------------\n\n/**\n * Decode the 256-byte `Channel` account (`state/channel.rs`), refusing anything\n * that is not a live one: the wrong length, or a discriminator other than\n * `Channel` (a `ClosedChannel` tombstone included).\n */\nexport function decodeSvmBatchChannel(\n data: Uint8Array | string\n): SvmBatchChannelState {\n const bytes = typeof data === 'string' ? fromBase64(data) : data;\n if (bytes.length !== CHANNEL_ACCOUNT_LENGTH) {\n throw new ValidationError(\n `a payment-channels Channel is ${CHANNEL_ACCOUNT_LENGTH} bytes, got ${bytes.length}`\n );\n }\n if (bytes[0] !== CHANNEL_DISCRIMINATOR) {\n throw new ValidationError(\n `account discriminator ${bytes[0]} is not a payment-channels Channel`\n );\n }\n const status = STATUSES[bytes[3] ?? 255];\n if (!status) {\n throw new ValidationError(\n `channel status byte ${bytes[3]} is not one the program writes`\n );\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const address = (offset: number) =>\n base58Encode(bytes.slice(offset, offset + 32));\n return {\n status,\n salt: view.getBigUint64(4, true),\n deposit: view.getBigUint64(12, true),\n settled: view.getBigUint64(20, true),\n payoutWatermark: view.getBigUint64(28, true),\n closureStartedAt: view.getBigInt64(36, true),\n payerWithdrawnAt: view.getBigInt64(44, true),\n gracePeriod: view.getUint32(52, true),\n distributionHash: bytes.slice(56, 88),\n payer: address(88),\n payee: address(120),\n authorizedSigner: address(152),\n mint: address(184),\n rentPayer: address(216),\n openSlot: view.getBigUint64(248, true),\n };\n}\n\n/**\n * Read the channel account at `channelId` over JSON-RPC, or `null` when it does\n * not exist (never opened, or closed and deallocated). An account that exists\n * but is not a payment-channels `Channel` — the wrong owner included — throws.\n */\nexport async function getSvmBatchChannel(\n rpc: SolanaRpcTarget,\n channelId: string\n): Promise<SvmBatchChannelState | null> {\n const result = (await solanaRpc(rpc, 'getAccountInfo', [\n channelId,\n { encoding: 'base64', commitment: 'confirmed' },\n ])) as { value: { data: [string, string]; owner: string } | null };\n if (result.value === null) return null;\n if (result.value.owner !== PAYMENT_CHANNELS_PROGRAM_ID) {\n throw new ValidationError(\n `account ${channelId} is owned by ${result.value.owner}, not payment-channels`\n );\n }\n return decodeSvmBatchChannel(result.value.data[0]);\n}\n\n/**\n * The `distribution_hash` a channel paying all of its settled value to\n * `receiver` commits to: `sha256(count u32 LE ‖ recipient ‖ bps u16 LE)`. A\n * client compares it with a decoded channel's to confirm where the money goes.\n */\nexport function singleRecipientDistributionHash(receiver: string): Uint8Array {\n const preimage = new Uint8Array(4 + 34);\n new DataView(preimage.buffer).setUint32(0, 1, true);\n preimage.set(key(receiver), 4);\n new DataView(preimage.buffer).setUint16(36, ALL_BPS, true);\n return sha256(preimage);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction key(address: string): Uint8Array {\n return padTo32(base58Decode(address));\n}\n\nfunction meta(pubkey: string, isSigner: boolean, isWritable: boolean) {\n return { pubkey, isSigner, isWritable };\n}\n\nfunction u64(value: bigint): Uint8Array {\n const out = new Uint8Array(8);\n new DataView(out.buffer).setBigUint64(0, value, true);\n return out;\n}\n\nfunction assertU64(value: bigint, what: string): void {\n if (value < 0n || value > MAX_U64) {\n throw new ValidationError(`${what} ${value} is outside u64`);\n }\n}\n\nfunction assertPositive(value: bigint, what: string): void {\n assertU64(value, what);\n if (value === 0n) throw new ValidationError(`${what} must be positive`);\n}\n\nfunction randomBytes(length: number): Uint8Array {\n return globalThis.crypto.getRandomValues(new Uint8Array(length));\n}\n\nfunction randomU64(): bigint {\n return new DataView(randomBytes(8).buffer).getBigUint64(0, true);\n}\n","/**\n * Solana over raw JSON-RPC: the program-derived-address search, associated\n * token accounts, a legacy transaction compiler and sender, and the reads a\n * payer needs — balances, blockhashes, confirmation.\n *\n * Everything here is chain plumbing shared by the x402 `batch-settlement`\n * code (`../batch-settlement/`), the wallet's transfers and the ArNS jobs, and\n * none of it knows about any channel program. TOON's own `payment-channel`\n * program — which this module was named for — left with connector ADR 0075;\n * the channel program is solana-foundation's `payment-channels`, driven from\n * `../batch-settlement/svm.ts`. No `@solana/web3.js` / `@solana/kit` runtime\n * dependency: only `@noble/curves` and `@noble/hashes`.\n */\n\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { base58Encode, base58Decode } from '../../utils/base58.js';\nimport {\n NetworkError,\n TransactionOutcomeError,\n} from '../../client/errors.js';\nimport { RECEIPT_TIMEOUT_MS } from '../evm/receipt.js';\n\n// ---------------------------------------------------------------------------\n// Constants (must match the Rust program + connector SDK exactly)\n// ---------------------------------------------------------------------------\n\n/** Well-known Solana program addresses (base58). */\nconst TOKEN_PROGRAM_ID = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\n\n/** On-chain channel-account discriminator: ASCII \"pchannel\". */\n\n/** Left-pad / trim a byte array to exactly 32 bytes. */\nexport function padTo32(bytes: Uint8Array): Uint8Array {\n if (bytes.length === 32) return bytes;\n if (bytes.length > 32) return bytes.slice(bytes.length - 32);\n const padded = new Uint8Array(32);\n padded.set(bytes, 32 - bytes.length);\n return padded;\n}\n\n/** Sort two 32-byte pubkeys lexicographically by raw bytes (matches Rust). */\n\n// ---------------------------------------------------------------------------\n// Ed25519 curve check + PDA derivation (matches Solana find_program_address)\n// ---------------------------------------------------------------------------\n\nfunction modPow(base: bigint, exp: bigint, mod: bigint): bigint {\n let result = 1n;\n base = ((base % mod) + mod) % mod;\n while (exp > 0n) {\n if (exp & 1n) result = (result * base) % mod;\n exp >>= 1n;\n base = (base * base) % mod;\n }\n return result;\n}\n\nfunction modInverse(a: bigint, m: bigint): bigint {\n return modPow(((a % m) + m) % m, m - 2n, m);\n}\n\n/** True if 32 bytes lie on the Ed25519 curve. A valid PDA must NOT be on-curve. */\nfunction isOnCurve(bytes: Uint8Array): boolean {\n const P = (1n << 255n) - 19n;\n const yBytes = new Uint8Array(32);\n yBytes.set(bytes);\n yBytes[31] = (yBytes[31] ?? 0) & 0x7f;\n\n let y = 0n;\n for (let i = 0; i < 32; i++) {\n y |= BigInt(yBytes[i] ?? 0) << BigInt(i * 8);\n }\n if (y >= P) return true;\n\n const y2 = (y * y) % P;\n const D = (P - ((121665n * modInverse(121666n, P)) % P) + P) % P;\n const numerator = (y2 - 1n + P) % P;\n const denominator = (D * y2 + 1n) % P;\n const x2 = (numerator * modInverse(denominator, P)) % P;\n if (x2 === 0n) return true;\n return modPow(x2, (P - 1n) / 2n, P) === 1n;\n}\n\nexport function findProgramAddress(\n seeds: Uint8Array[],\n programId: Uint8Array\n): { pda: Uint8Array; bump: number } {\n const PDA_MARKER = new TextEncoder().encode('ProgramDerivedAddress');\n for (let bump = 255; bump >= 0; bump--) {\n const allSeeds = [...seeds, new Uint8Array([bump])];\n let totalLen = programId.length + PDA_MARKER.length;\n for (const s of allSeeds) totalLen += s.length;\n\n const input = new Uint8Array(totalLen);\n let offset = 0;\n for (const s of allSeeds) {\n input.set(s, offset);\n offset += s.length;\n }\n input.set(programId, offset);\n offset += programId.length;\n input.set(PDA_MARKER, offset);\n\n const hash = sha256(input);\n if (!isOnCurve(hash)) return { pda: hash, bump };\n }\n throw new Error('Could not find a viable PDA bump seed');\n}\n\n/**\n * Derive the Associated Token Account (ATA) for an owner + SPL mint — the\n * standard SPL ATA PDA over seeds `[owner, TOKEN_PROGRAM_ID, mint]` under the\n * Associated-Token-Account program. Deterministic from `(owner, mint)`, so\n * callers (e.g. a Solana channel deposit) need not supply the funded token\n * account explicitly — it is always the owner's ATA for the channel's mint.\n *\n * @param owner - base58 wallet pubkey that owns the token account.\n * @param tokenMint - base58 SPL mint.\n * @returns base58 ATA address.\n */\nexport function deriveAssociatedTokenAccount(\n owner: string,\n tokenMint: string\n): string {\n // Canonical mainnet/devnet SPL program ids (same on every cluster).\n const TOKEN_PROGRAM_ID = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\n const ASSOCIATED_TOKEN_PROGRAM_ID =\n 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';\n const seeds = [\n padTo32(base58Decode(owner)),\n padTo32(base58Decode(TOKEN_PROGRAM_ID)),\n padTo32(base58Decode(tokenMint)),\n ];\n const { pda } = findProgramAddress(\n seeds,\n padTo32(base58Decode(ASSOCIATED_TOKEN_PROGRAM_ID))\n );\n return base58Encode(pda);\n}\n\n// ---------------------------------------------------------------------------\n// Balance-proof message + signing (connector-parity)\n// ---------------------------------------------------------------------------\n\n\n\n// ---------------------------------------------------------------------------\n// On-chain channel open (initialize_channel + deposit) over raw JSON-RPC\n// ---------------------------------------------------------------------------\n\n/** One account meta of an instruction, in the order the program reads them. */\nexport interface InstructionKey {\n pubkey: string;\n isSigner: boolean;\n isWritable: boolean;\n}\n\n/**\n * An unsigned Solana instruction. Exported because\n * {@link buildClaimFromChannelInstructions} returns a PAIR that must be\n * submitted in one transaction, in order — so the builder cannot also be the\n * sender.\n */\nexport interface RawInstruction {\n programId: string;\n keys: InstructionKey[];\n data: Uint8Array;\n}\n\nexport interface Signer {\n publicKey: Uint8Array;\n privateKey: Uint8Array;\n}\n\nlet rpcIdCounter = 1;\n\n/**\n * A JSON-RPC-level error — the node answered, and said no. Distinct from a\n * TRANSPORT fault (DNS, timeout, 429, 5xx, malformed body), which surfaces as\n * whatever `fetch`/`json()` threw. Callers must not conflate the two: \"the node\n * says this account does not exist\" is a fact about the chain, while \"the node\n * did not answer\" is a fact about the network, and treating the latter as the\n * former turns a transient blip into a false accusation that the user's wallet\n * is unfunded.\n */\nexport class SolanaRpcError extends Error {\n constructor(\n readonly method: string,\n readonly code: number,\n readonly rpcMessage: string\n ) {\n super(`Solana RPC error [${method}]: ${rpcMessage} (code ${code})`);\n this.name = 'SolanaRpcError';\n }\n}\n\n/**\n * True when `err` is the node reporting that the queried account does not\n * exist. Solana answers `getTokenAccountBalance` for an absent account with a\n * JSON-RPC error (`-32602 Invalid param: could not find account`) rather than a\n * zero balance, so absence is only ever observable as an error — which is\n * exactly why it must be told apart from transport faults by CONTENT, not by\n * \"something threw\".\n */\nfunction isAccountNotFoundError(err: unknown): boolean {\n if (!(err instanceof SolanaRpcError)) return false;\n return /could not find account|account not found|account does not exist/i.test(\n err.rpcMessage\n );\n}\n\n/**\n * Raw Solana JSON-RPC call.\n *\n * Exported (with {@link getLatestBlockhash} and {@link waitForConfirmation}) for\n * `../swap/solana-settlement.js`, which submits a settlement Message the SDK has\n * ALREADY compiled and so cannot go through {@link buildAndSendTransaction} —\n * that builds its own message from instructions. Sharing the transport keeps one\n * definition of \"the node answered and said no\" (see {@link SolanaRpcError})\n * across the channel and settlement paths.\n */\n/**\n * Where Solana JSON-RPC goes, and how it gets there.\n *\n * A bare URL is the ordinary case and dials the global `fetch`. The object form\n * carries a `fetch` to use instead — on a hidden-service client that is the\n * proxied one, so chain reads ride the overlay with the packets rather than\n * announcing this wallet on clearnet (ADR 0002). Every function in this module\n * that takes an RPC target passes it straight through to {@link solanaRpc}; only\n * that function ever looks inside.\n */\nexport type SolanaRpcTarget = string | { url: string; fetchImpl?: typeof fetch };\n\n/** Split a target into the URL to dial and the `fetch` to dial it with. */\nfunction resolveRpcTarget(target: SolanaRpcTarget): { url: string; fetchImpl: typeof fetch } {\n if (typeof target === 'string') return { url: target, fetchImpl: globalThis.fetch };\n return { url: target.url, fetchImpl: target.fetchImpl ?? globalThis.fetch };\n}\n\n/**\n * Delays before each retry of a Solana JSON-RPC call that failed in transit.\n *\n * Three retries, as viem does for EVM. The ADR 0073 hardening asks for this on\n * both chains: exit IPs are shared, so a public RPC reached through `anon` will\n * eventually answer 429 or 403, and a circuit can drop a request. Resending is\n * safe for every call this module makes. Reads are reads, and a resent\n * `sendTransaction` carries the same signed bytes, which the cluster\n * deduplicates by signature.\n */\nconst SOLANA_RPC_RETRY_DELAYS_MS = [250, 500, 1_000] as const;\n/** HTTP statuses worth another try: viem's list, the same on both chains. */\nconst RETRYABLE_HTTP_STATUS = new Set([403, 408, 413, 429, 500, 502, 503, 504]);\n/** A `Retry-After` longer than this is not waited on; the call fails instead. */\nconst MAX_RETRY_AFTER_MS = 10_000;\n/** Per-request timeout, as the connector's Solana client has it (ADR 0073, decision 4). */\nconst SOLANA_RPC_TIMEOUT_MS = 30_000;\n\n/**\n * A Solana JSON-RPC call that got no answer from the node: every try was lost in\n * transit, timed out, or was turned away at the HTTP layer.\n *\n * `mayHaveArrived` is `false` only when every try failed before a byte of the\n * request could have been written, because the connection or the proxy refused\n * it. That is the one case in which a failed `sendTransaction` is known not to\n * have been sent.\n */\nexport class SolanaRpcTransportError extends NetworkError {\n constructor(\n readonly method: string,\n readonly attempts: number,\n readonly mayHaveArrived: boolean,\n cause: unknown\n ) {\n super(\n `Solana RPC [${method}] got no answer after ${attempts} tries: ` +\n (cause instanceof Error ? cause.message : String(cause)),\n cause instanceof Error ? cause : undefined\n );\n this.name = 'SolanaRpcTransportError';\n }\n}\n\n/** An HTTP answer that is not a JSON-RPC one: a 429 page, a 5xx, a gateway's 403. */\nclass SolanaRpcHttpError extends Error {\n constructor(\n readonly status: number,\n readonly retryAfterMs: number | undefined\n ) {\n super(`HTTP ${status}`);\n this.name = 'SolanaRpcHttpError';\n }\n}\n\n/**\n * One JSON-RPC call, retried when it fails in transit.\n *\n * @throws {SolanaRpcError} the node answered and said no. Never retried.\n * @throws {SolanaRpcTransportError} no answer came back, after every retry.\n */\nexport async function solanaRpc(\n rpcUrl: SolanaRpcTarget,\n method: string,\n params: unknown[] = []\n): Promise<unknown> {\n const { url, fetchImpl } = resolveRpcTarget(rpcUrl);\n let mayHaveArrived = false;\n for (let attempt = 0; ; attempt++) {\n try {\n return await solanaRpcOnce(url, fetchImpl, method, params);\n } catch (err) {\n if (err instanceof SolanaRpcError) throw err;\n mayHaveArrived ||= !failedBeforeSending(err);\n const retryable =\n !(err instanceof SolanaRpcHttpError) || RETRYABLE_HTTP_STATUS.has(err.status);\n const delay =\n err instanceof SolanaRpcHttpError && err.retryAfterMs !== undefined\n ? err.retryAfterMs\n : SOLANA_RPC_RETRY_DELAYS_MS[attempt];\n if (\n !retryable ||\n attempt >= SOLANA_RPC_RETRY_DELAYS_MS.length ||\n delay === undefined ||\n delay > MAX_RETRY_AFTER_MS\n ) {\n throw new SolanaRpcTransportError(method, attempt + 1, mayHaveArrived, err);\n }\n await sleep(delay);\n }\n }\n}\n\n/** One try: the node's answer, a {@link SolanaRpcError}, or whatever the transport threw. */\nasync function solanaRpcOnce(\n url: string,\n fetchImpl: typeof fetch,\n method: string,\n params: unknown[]\n): Promise<unknown> {\n const res = await fetchImpl(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n method,\n params,\n id: rpcIdCounter++,\n }),\n signal: AbortSignal.timeout(SOLANA_RPC_TIMEOUT_MS),\n });\n if (res.ok === false) {\n throw new SolanaRpcHttpError(res.status, retryAfterMs(res.headers?.get('retry-after')));\n }\n const json = (await res.json()) as {\n result?: unknown;\n error?: { message: string; code: number };\n };\n if (json.error) {\n throw new SolanaRpcError(method, json.error.code, json.error.message);\n }\n return json.result;\n}\n\n/** `Retry-After` in whole seconds, as ms. The date form is not worth parsing here. */\nfunction retryAfterMs(header: string | null | undefined): number | undefined {\n if (header === null || header === undefined || !/^\\d+$/.test(header.trim())) return undefined;\n return Number.parseInt(header.trim(), 10) * 1000;\n}\n\n/**\n * Connection-phase failures: nothing was written, so nothing can have arrived.\n * A SOCKS error always is one, because the proxy answers before any request\n * byte is sent. Anything else (a timeout, a reset, a lost answer) may have come\n * after the request went out.\n */\nfunction failedBeforeSending(err: unknown): boolean {\n let e: unknown = err;\n for (let depth = 0; e instanceof Error && depth < 5; depth++) {\n const code = (e as { code?: unknown }).code;\n if (e.name === 'SocksClientError') return true;\n if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'EAI_AGAIN') return true;\n if (code === 'UND_ERR_CONNECT_TIMEOUT') return true;\n e = e.cause;\n }\n return false;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Latest blockhash, base58 — what `patchSolanaRecentBlockhash` accepts as-is. */\nexport async function getLatestBlockhash(rpcUrl: SolanaRpcTarget): Promise<string> {\n return (await getLatestBlockhashWithExpiry(rpcUrl)).blockhash;\n}\n\n/**\n * The latest blockhash, and the last block height at which a transaction built\n * on it can still land. After that height, it never will.\n */\nasync function getLatestBlockhashWithExpiry(\n rpcUrl: SolanaRpcTarget\n): Promise<{ blockhash: string; lastValidBlockHeight: number | undefined }> {\n const result = (await solanaRpc(rpcUrl, 'getLatestBlockhash', [\n { commitment: 'confirmed' },\n ])) as { value: { blockhash: string; lastValidBlockHeight?: number } };\n return {\n blockhash: result.value.blockhash,\n lastValidBlockHeight: result.value.lastValidBlockHeight,\n };\n}\n\n\n/**\n * Balance (base units) of an SPL token account, or `null` when the node reports\n * that the account does not exist (an owner who has never held the mint has no\n * ATA).\n *\n * ONLY that one answer becomes `null`. A transport fault — timeout, 429, 5xx,\n * DNS — propagates, because \"the RPC is unreachable\" is not evidence about the\n * user's balance, and swallowing it here would turn a transient blip into a\n * hard `ChannelFundingError` telling the user to fund an already-funded wallet.\n */\nexport async function getTokenAccountBalance(\n rpcUrl: SolanaRpcTarget,\n tokenAccount: string\n): Promise<bigint | null> {\n try {\n const result = (await solanaRpc(rpcUrl, 'getTokenAccountBalance', [\n tokenAccount,\n { commitment: 'confirmed' },\n ])) as { value?: { amount?: string } } | null;\n const amount = result?.value?.amount;\n return amount === undefined ? null : BigInt(amount);\n } catch (err) {\n if (isAccountNotFoundError(err)) return null;\n throw err;\n }\n}\n\n/** Native SOL balance (lamports) of an account; 0 for an account that does not exist. */\nexport async function getLamports(rpcUrl: SolanaRpcTarget, pubkey: string): Promise<bigint> {\n const result = (await solanaRpc(rpcUrl, 'getBalance', [\n pubkey,\n { commitment: 'confirmed' },\n ])) as { value?: number | string } | null;\n return BigInt(result?.value ?? 0);\n}\n\n/** How {@link waitForConfirmation} waits. */\nexport interface ConfirmationOptions {\n /**\n * The blockhash's `lastValidBlockHeight`. With it, the wait ends when the\n * chain says the transaction can no longer land. Without it, only the clock\n * ends the wait.\n */\n lastValidBlockHeight?: number;\n /**\n * The wall-clock bound, ms, after which the outcome is `unknown`. Default\n * {@link CONFIRM_TIMEOUT_MS} with a `lastValidBlockHeight`, which the chain\n * normally ends well before; 30s without one.\n */\n timeoutMs?: number;\n /** Between polls, ms. Default 500. */\n pollIntervalMs?: number;\n}\n\n/**\n * The wall-clock bound on a confirmation that knows its blockhash's expiry.\n * A blockhash lives ~150 slots (60–90s), so the chain decides first unless the\n * RPC stops answering. 180s is the deadline ADR 0073 gives EVM confirmation.\n */\nexport const CONFIRM_TIMEOUT_MS = RECEIPT_TIMEOUT_MS;\n\n/**\n * Poll until the transaction is `confirmed`/`finalized`, and report any other\n * ending as a {@link TransactionOutcomeError} naming the signature.\n *\n * A poll that fails in transit is not an outcome. It says nothing about the\n * transaction, so the loop keeps polling. Only the chain (confirmed, failed,\n * or past `lastValidBlockHeight`) or the wall clock ends it.\n */\nexport async function waitForConfirmation(\n rpcUrl: SolanaRpcTarget,\n signature: string,\n options: ConfirmationOptions = {}\n): Promise<void> {\n const { lastValidBlockHeight, pollIntervalMs = 500 } = options;\n const timeoutMs =\n options.timeoutMs ?? (lastValidBlockHeight !== undefined ? CONFIRM_TIMEOUT_MS : 30_000);\n const deadline = Date.now() + timeoutMs;\n let lastError: unknown;\n let failedPolls = 0;\n\n for (;;) {\n try {\n if (await isConfirmed(rpcUrl, signature)) return;\n if (lastValidBlockHeight !== undefined) {\n const height = Number(\n await solanaRpc(rpcUrl, 'getBlockHeight', [{ commitment: 'confirmed' }])\n );\n // One last look once expiry is seen: it may have landed in the very\n // block that ended its blockhash's life.\n if (height > lastValidBlockHeight && !(await isConfirmed(rpcUrl, signature))) {\n throw new TransactionOutcomeError(\n `Transaction ${signature} expired: block height ${height} is past its ` +\n `blockhash's last valid height ${lastValidBlockHeight}, and it never ` +\n 'appeared, so it cannot land. It is safe to build and send it again.',\n 'solana',\n signature,\n 'expired'\n );\n }\n }\n } catch (err) {\n if (err instanceof TransactionOutcomeError) throw err;\n lastError = err;\n failedPolls += 1;\n }\n if (Date.now() >= deadline) {\n throw new TransactionOutcomeError(\n `Transaction ${signature} was not seen confirmed within ${timeoutMs}ms, and ` +\n 'the RPC could not say whether it can still land. Look the signature up ' +\n 'before sending anything that would repeat it.' +\n (lastError instanceof Error ? ` Last RPC error: ${lastError.message}` : ''),\n 'solana',\n signature,\n 'unknown',\n lastError instanceof Error ? lastError : undefined\n );\n }\n // Back off while polls keep failing (to 8x, 4s at the default), so a\n // rate-limited RPC is not hammered; a poll that answers resets nothing\n // because the loop only continues while the answer is \"not yet\".\n await sleep(pollIntervalMs * 2 ** Math.min(failedPolls, 3));\n }\n}\n\n/**\n * Whether `signature` is `confirmed`/`finalized`. Throws a `failed`\n * {@link TransactionOutcomeError} when it landed with an execution error: a\n * settled-but-failed transaction is not a success.\n */\nasync function isConfirmed(rpcUrl: SolanaRpcTarget, signature: string): Promise<boolean> {\n const result = (await solanaRpc(rpcUrl, 'getSignatureStatuses', [[signature]])) as {\n value: ({ confirmationStatus: string; err?: unknown } | null)[];\n };\n const status = result.value[0];\n if (status?.confirmationStatus !== 'confirmed' && status?.confirmationStatus !== 'finalized') {\n return false;\n }\n if (status.err) {\n throw new TransactionOutcomeError(\n `Transaction ${signature} failed: ${JSON.stringify(status.err)}`,\n 'solana',\n signature,\n 'failed'\n );\n }\n return true;\n}\n\n/**\n * Whether a `sendTransaction` RPC error means the transaction is already on\n * chain: a resend of bytes the node took the first time. That happens exactly\n * when a first send's answer was lost and {@link solanaRpc} sent it again.\n */\nfunction isAlreadyProcessed(err: SolanaRpcError): boolean {\n return /already been processed|AlreadyProcessed/i.test(err.rpcMessage);\n}\n\nfunction compactU16Size(value: number): number {\n if (value > 0xffff) {\n throw new RangeError(`compact-u16 value ${value} exceeds u16 max (0xFFFF)`);\n }\n return value < 0x80 ? 1 : value < 0x4000 ? 2 : 3;\n}\n\nfunction writeCompactU16(\n buf: Uint8Array,\n offset: number,\n value: number\n): number {\n if (value < 0x80) {\n buf[offset++] = value;\n } else if (value < 0x4000) {\n buf[offset++] = (value & 0x7f) | 0x80;\n buf[offset++] = value >> 7;\n } else {\n buf[offset++] = (value & 0x7f) | 0x80;\n buf[offset++] = ((value >> 7) & 0x7f) | 0x80;\n buf[offset++] = value >> 14;\n }\n return offset;\n}\n\ninterface AccountEntry {\n pubkey: string;\n isSigner: boolean;\n isWritable: boolean;\n}\n\n/**\n * A compiled legacy message, and the signature slots it requires.\n *\n * `signers` is in slot order: slot `i` of a transaction over `message` carries\n * the signature of `signers[i]`, and `signers[0]` is always the fee payer.\n */\nexport interface CompiledLegacyMessage {\n message: Uint8Array;\n signers: string[];\n}\n\n/**\n * Compile a Solana legacy message: the fee payer first, then accounts ordered by\n * role (writable signers, read-only signers, writable, read-only), each account\n * once with the union of the privileges its instructions ask of it.\n *\n * Exported so a transaction whose fee payer is someone else — a sponsor who\n * co-signs later — is compiled by the same code {@link buildAndSendTransaction}\n * is connector-parity-tested on, rather than by a second copy of it.\n */\nexport function compileLegacyMessage(\n feePayer: string,\n instructions: RawInstruction[],\n recentBlockhash: string\n): CompiledLegacyMessage {\n const accountMap = new Map<string, AccountEntry>();\n accountMap.set(feePayer, {\n pubkey: feePayer,\n isSigner: true,\n isWritable: true,\n });\n for (const ix of instructions) {\n for (const key of ix.keys) {\n const existing = accountMap.get(key.pubkey);\n if (existing) {\n existing.isSigner = existing.isSigner || key.isSigner;\n existing.isWritable = existing.isWritable || key.isWritable;\n } else {\n accountMap.set(key.pubkey, { ...key });\n }\n }\n if (!accountMap.has(ix.programId)) {\n accountMap.set(ix.programId, {\n pubkey: ix.programId,\n isSigner: false,\n isWritable: false,\n });\n }\n }\n\n const accounts = [...accountMap.values()].sort((a, b) => {\n if (a.pubkey === feePayer) return -1;\n if (b.pubkey === feePayer) return 1;\n const aScore = (a.isSigner ? 2 : 0) + (a.isWritable ? 1 : 0);\n const bScore = (b.isSigner ? 2 : 0) + (b.isWritable ? 1 : 0);\n return bScore - aScore;\n });\n\n const numSigners = accounts.filter((a) => a.isSigner).length;\n const numReadonlySigners = accounts.filter(\n (a) => a.isSigner && !a.isWritable\n ).length;\n const numReadonlyNonSigners = accounts.filter(\n (a) => !a.isSigner && !a.isWritable\n ).length;\n\n const accountIndexMap = new Map<string, number>();\n accounts.forEach((a, i) => accountIndexMap.set(a.pubkey, i));\n\n const compiled = instructions.map((ix) => ({\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- programId added to accountMap above\n programIdIndex: accountIndexMap.get(ix.programId)!,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- every key added to accountMap above\n accountIndices: ix.keys.map((k) => accountIndexMap.get(k.pubkey)!),\n data: ix.data,\n }));\n\n const blockhashBytes = base58Decode(recentBlockhash);\n\n let instructionSize = compactU16Size(compiled.length);\n for (const ix of compiled) {\n instructionSize += 1;\n instructionSize +=\n compactU16Size(ix.accountIndices.length) + ix.accountIndices.length;\n instructionSize += compactU16Size(ix.data.length) + ix.data.length;\n }\n\n const messageSize =\n 3 +\n compactU16Size(accounts.length) +\n 32 * accounts.length +\n 32 +\n instructionSize;\n const message = new Uint8Array(messageSize);\n let offset = 0;\n\n message[offset++] = numSigners;\n message[offset++] = numReadonlySigners;\n message[offset++] = numReadonlyNonSigners;\n\n offset = writeCompactU16(message, offset, accounts.length);\n for (const acct of accounts) {\n message.set(padTo32(base58Decode(acct.pubkey)), offset);\n offset += 32;\n }\n\n message.set(padTo32(blockhashBytes), offset);\n offset += 32;\n\n offset = writeCompactU16(message, offset, compiled.length);\n for (const ix of compiled) {\n message[offset++] = ix.programIdIndex;\n offset = writeCompactU16(message, offset, ix.accountIndices.length);\n for (const idx of ix.accountIndices) message[offset++] = idx;\n offset = writeCompactU16(message, offset, ix.data.length);\n message.set(ix.data, offset);\n offset += ix.data.length;\n }\n\n return {\n message: message.slice(0, offset),\n signers: accounts.filter((a) => a.isSigner).map((a) => a.pubkey),\n };\n}\n\n/**\n * A wire transaction: the signature slots, then the message. A slot with no\n * signature yet is 64 zero bytes — how \"not signed\" is spelled on the wire.\n */\nexport function serializeLegacyTransaction(\n compiled: CompiledLegacyMessage,\n signatures: (Uint8Array | undefined)[]\n): Uint8Array {\n const { message, signers } = compiled;\n const txSize =\n compactU16Size(signers.length) + signers.length * 64 + message.length;\n const tx = new Uint8Array(txSize);\n let txOffset = writeCompactU16(tx, 0, signers.length);\n for (let i = 0; i < signers.length; i++) {\n const sig = signatures[i];\n if (sig) tx.set(sig, txOffset);\n txOffset += 64;\n }\n tx.set(message, txOffset);\n return tx;\n}\n\n/**\n * Build, sign, and send a Solana legacy transaction over raw JSON-RPC, then wait\n * for confirmation. Mirrors the SDK reference E2E's `buildAndSendTransaction`.\n *\n * Exported (along with {@link getLamports} and {@link getTokenAccountBalance})\n * so `../transfer.js` can build plain System/SPL-Token instructions on the\n * SAME wire-format code this module already gets connector-parity-tested\n * against, rather than re-deriving Solana's compact transaction encoding a\n * second time.\n */\nexport async function buildAndSendTransaction(\n rpcUrl: SolanaRpcTarget,\n feePayer: Signer,\n instructions: RawInstruction[],\n additionalSigners: Signer[] = [],\n confirmation: Omit<ConfirmationOptions, 'lastValidBlockHeight'> = {}\n): Promise<string> {\n const { blockhash, lastValidBlockHeight } = await getLatestBlockhashWithExpiry(rpcUrl);\n const compiled = compileLegacyMessage(\n base58Encode(feePayer.publicKey),\n instructions,\n blockhash\n );\n\n const allSigners = [feePayer, ...additionalSigners];\n const signatures = compiled.signers.map((signerPubkey) => {\n const signer = allSigners.find(\n (s) => base58Encode(s.publicKey) === signerPubkey\n );\n if (!signer) throw new Error(`Missing signer for ${signerPubkey}`);\n return ed25519.sign(compiled.message, signer.privateKey);\n });\n const tx = serializeLegacyTransaction(compiled, signatures);\n\n const txBase64 = Buffer.from(tx).toString('base64');\n let txSig: string;\n try {\n txSig = (await solanaRpc(rpcUrl, 'sendTransaction', [\n txBase64,\n {\n encoding: 'base64',\n skipPreflight: false,\n preflightCommitment: 'confirmed',\n },\n ])) as string;\n } catch (err) {\n // An RPC error is the node's answer, and a send that never left was never sent. But a\n // send whose answer was lost, or a resend the node says it already has, may\n // be on chain: it is looked up by the signature it carries rather than\n // reported as a failure (ADR 0073, decision 5). The first signature on the\n // wire, the fee payer's, IS the transaction id.\n const alreadyOnChain = err instanceof SolanaRpcError && isAlreadyProcessed(err);\n const answerLost = err instanceof SolanaRpcTransportError && err.mayHaveArrived;\n if (!alreadyOnChain && !answerLost) throw err;\n const firstSignature = compactU16Size(signatures.length);\n txSig = base58Encode(tx.subarray(firstSignature, firstSignature + 64));\n }\n await waitForConfirmation(rpcUrl, txSig, {\n ...confirmation,\n ...(lastValidBlockHeight !== undefined ? { lastValidBlockHeight } : {}),\n });\n return txSig;\n}\n\nexport const __testing = {\n padTo32,\n isOnCurve,\n TOKEN_PROGRAM_ID,\n};\n","/**\n * Waiting for an EVM transaction to be mined, over an RPC that may fail a poll.\n *\n * viem's `waitForTransactionReceipt` rejects on the first receipt poll that\n * fails in transit once the transport's own retries are spent, and the\n * transaction may be mined a block later. Over a public RPC reached through\n * `anon`, where a circuit can drop a request and a shared exit IP earns a 429,\n * that turns a transaction that landed into an error, and an error invites a\n * retry (connector ADR 0073, decision 5). So this waits again, by hash, until\n * a receipt arrives or the deadline passes. Waiting by hash is always safe: it\n * repeats nothing.\n */\nimport { TransactionOutcomeError } from '../../client/errors.js';\nimport {\n WaitForTransactionReceiptTimeoutError,\n type Hash,\n type PublicClient,\n type TransactionReceipt,\n} from 'viem';\n\n/**\n * The overall deadline for a receipt: 180s, 90 Base blocks, as ADR 0073 gives\n * EVM confirmation. It is also viem's own default for one wait.\n */\nexport const RECEIPT_TIMEOUT_MS = 180_000;\n\n/** Between a failed wait and the next one, ms. */\nconst RETRY_DELAY_MS = 1_000;\n\n/** The one method this needs, so a test can hand in any client that has it. */\ntype ReceiptSource = Pick<PublicClient, 'waitForTransactionReceipt'>;\n\n/**\n * The receipt for `hash`, however many polls fail on the way.\n *\n * @throws {TransactionOutcomeError} `unknown`: no receipt by the deadline. The\n * transaction was sent and may still be mined.\n */\nexport async function waitForReceipt(\n client: ReceiptSource,\n hash: Hash,\n options: { timeoutMs?: number; retryDelayMs?: number } = {}\n): Promise<TransactionReceipt> {\n const timeoutMs = options.timeoutMs ?? RECEIPT_TIMEOUT_MS;\n const retryDelayMs = options.retryDelayMs ?? RETRY_DELAY_MS;\n const deadline = Date.now() + timeoutMs;\n let lastError: unknown;\n\n for (;;) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) {\n throw pending(hash, timeoutMs, lastError);\n }\n try {\n return await client.waitForTransactionReceipt({\n hash,\n timeout: remaining,\n });\n } catch (err) {\n if (err instanceof WaitForTransactionReceiptTimeoutError) {\n throw pending(hash, timeoutMs, lastError);\n }\n lastError = err;\n }\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(retryDelayMs, deadline - Date.now()))\n );\n }\n}\n\n/** The deadline passed with no receipt: sent, and may still be mined. */\nfunction pending(\n hash: string,\n timeoutMs: number,\n lastError: unknown\n): TransactionOutcomeError {\n return new TransactionOutcomeError(\n `Transaction ${hash} was sent, but no receipt was seen within ${timeoutMs}ms. ` +\n 'It may still be mined. Look the hash up before sending anything that ' +\n 'would repeat it.' +\n (lastError instanceof Error\n ? ` Last RPC error: ${lastError.message}`\n : ''),\n 'evm',\n hash,\n 'unknown',\n lastError instanceof Error ? lastError : undefined\n );\n}\n","/**\n * Solana wire transactions this client did NOT build.\n *\n * {@link import('./payment-channel.js').buildAndSendTransaction} composes a\n * transaction from instructions and signs every slot it created. This module is\n * the other half: somebody else compiled the message, and the client's only job\n * is to fill in the signature slots that are its own — and, when a fee payer\n * hands back a blockhash of its choosing, to move those 32 bytes without\n * touching anything else.\n *\n * That is the shape of a brokered transaction. In the ANT spawn the store\n * composes (it is the only party with `@ar.io/sdk`), the client signs (it is\n * the only party that may own the ANT), and the gas station pays and broadcasts\n * (it is the only party with SOL). None of the three can do the other two's\n * work, and the transaction travels between them as base64 wire bytes.\n *\n * **NEVER RECOMPILE.** The signature slots are in the compiled header's account\n * order, and the message bytes are what every signature covers, so rebuilding\n * the message from a decoded view — even into something byte-identical by\n * intent — is how a transaction arrives with signatures over a message that no\n * longer exists. Everything here is an in-place overwrite at a computed offset,\n * and {@link parseSolanaWireTransaction} exists to compute those offsets, not to\n * be a step towards re-serialization.\n *\n * The wire format (`solana-sdk`'s `Transaction`):\n *\n * ```text\n * compact-u16 signature count ─┐ must equal the message's\n * 64 × count signatures, slot order │ numRequiredSignatures\n * ── message ──────────────────────────────┘\n * 1 byte 0x80 | version (VERSIONED MESSAGES ONLY)\n * 3 bytes header\n * compact-u16 static account count\n * 32 × count static account keys (slot i signs for key i)\n * 32 bytes recent blockhash ← what patching overwrites\n * … instructions, address-table lookups\n * ```\n *\n * A zero-filled 64-byte slot is how \"not signed yet\" is spelled: `@solana/kit`'s\n * decoder reads one back as `null`, and the gas station's inspector refuses such\n * a transaction as `missing_client_signature` — a diagnosis, rather than the\n * opaque signature-verification failure a stale signature would produce.\n */\n\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { base58Decode, base58Encode } from '../../utils/base58.js';\nimport { fromBase64, toBase64 } from '../../utils/binary.js';\nimport type { Signer } from './payment-channel.js';\n\n/** Bytes in one Ed25519 signature slot. */\nconst SIGNATURE_LENGTH = 64;\n/** Bytes in a pubkey, a blockhash, and an Ed25519 seed alike. */\nconst PUBKEY_LENGTH = 32;\n/** An Ed25519 seed — the private half of a keypair, and all of it that is stored. */\nconst SEED_LENGTH = 32;\n/** A stored `seed ‖ pubkey` secret key, the spelling most Solana tooling writes. */\nconst SECRET_KEY_LENGTH = 64;\n/** High bit of a message's first byte: set ⇒ versioned, clear ⇒ legacy. */\nconst VERSION_PREFIX_MASK = 0x80;\n\n/**\n * A wire transaction, read but not rebuilt.\n *\n * Every field is a view onto {@link bytes}, which is the caller's transaction\n * verbatim. Nothing here is enough to re-serialize the message, deliberately.\n */\nexport interface SolanaWireTransaction {\n /** The whole wire transaction, unmodified. */\n bytes: Uint8Array;\n /** `'legacy'` for a message with no version prefix, else the version number. */\n version: 'legacy' | number;\n /**\n * The signature slots in COMPILED ORDER — index `i` is the key whose\n * signature belongs in slot `i`. This is the order the header fixed when the\n * message was compiled; within a role it is address-sorted rather than\n * semantic, so map a signer to a slot by ADDRESS, never by position.\n */\n signers: string[];\n /** Base58 addresses of the slots that are still 64 zero bytes. */\n unsigned: string[];\n /** Every static account key, in compiled order. `signers` is its head. */\n staticAccounts: string[];\n /** The blockhash the message currently commits to, base58. */\n recentBlockhash: string;\n /** Byte offset of the first signature slot. */\n signaturesOffset: number;\n /** Byte offset of the message — the bytes a signature covers. */\n messageOffset: number;\n /** Byte offset of the 32 blockhash bytes inside {@link bytes}. */\n recentBlockhashOffset: number;\n}\n\n/** A compact-u16 read: the value, and where the next field starts. */\nfunction readCompactU16(\n bytes: Uint8Array,\n offset: number\n): { value: number; offset: number } {\n let value = 0;\n for (let shift = 0; shift < 3; shift++) {\n const byte = bytes[offset + shift];\n if (byte === undefined) {\n throw new Error('malformed Solana transaction: truncated compact-u16');\n }\n value |= (byte & 0x7f) << (shift * 7);\n if ((byte & 0x80) === 0) return { value, offset: offset + shift + 1 };\n }\n throw new Error('malformed Solana transaction: compact-u16 exceeds three bytes');\n}\n\n/** Coerce the two spellings a wire transaction travels in to bytes. */\nfunction toWireBytes(wire: string | Uint8Array): Uint8Array {\n return typeof wire === 'string' ? fromBase64(wire) : wire;\n}\n\n/** Answer in whatever spelling the caller handed in. */\nfunction likeInput(wire: string | Uint8Array, bytes: Uint8Array): string | Uint8Array {\n return typeof wire === 'string' ? toBase64(bytes) : bytes;\n}\n\n/**\n * Read a base64 (or raw) wire transaction far enough to locate its signature\n * slots and its blockhash. Legacy and v0 messages both parse; the address-table\n * lookups a v0 message may carry sit AFTER everything this needs and are not\n * decoded.\n *\n * @throws {Error} when the bytes are not a transaction of the shape above —\n * truncated, or claiming a signature count the header does not agree with.\n */\nexport function parseSolanaWireTransaction(\n wire: string | Uint8Array\n): SolanaWireTransaction {\n const bytes = toWireBytes(wire);\n\n const count = readCompactU16(bytes, 0);\n const signaturesOffset = count.offset;\n const messageOffset = signaturesOffset + count.value * SIGNATURE_LENGTH;\n if (messageOffset > bytes.length) {\n throw new Error(\n `malformed Solana transaction: ${count.value} signature slots do not fit in ${bytes.length} bytes`\n );\n }\n\n const prefix = bytes[messageOffset];\n if (prefix === undefined) {\n throw new Error('malformed Solana transaction: no message after the signatures');\n }\n const versioned = (prefix & VERSION_PREFIX_MASK) !== 0;\n const version = versioned ? prefix & ~VERSION_PREFIX_MASK : 'legacy';\n const headerOffset = messageOffset + (versioned ? 1 : 0);\n\n const numRequiredSignatures = bytes[headerOffset];\n if (numRequiredSignatures === undefined) {\n throw new Error('malformed Solana transaction: truncated message header');\n }\n if (numRequiredSignatures !== count.value) {\n throw new Error(\n `malformed Solana transaction: ${count.value} signature slots but the header requires ${numRequiredSignatures}`\n );\n }\n\n const accountCount = readCompactU16(bytes, headerOffset + 3);\n const keysOffset = accountCount.offset;\n const recentBlockhashOffset = keysOffset + accountCount.value * PUBKEY_LENGTH;\n if (recentBlockhashOffset + PUBKEY_LENGTH > bytes.length) {\n throw new Error(\n `malformed Solana transaction: ${accountCount.value} account keys and a blockhash do not fit in ${bytes.length} bytes`\n );\n }\n if (numRequiredSignatures > accountCount.value) {\n throw new Error(\n `malformed Solana transaction: header requires ${numRequiredSignatures} signatures but the message names only ${accountCount.value} accounts`\n );\n }\n\n const staticAccounts: string[] = [];\n for (let i = 0; i < accountCount.value; i++) {\n const start = keysOffset + i * PUBKEY_LENGTH;\n staticAccounts.push(base58Encode(bytes.slice(start, start + PUBKEY_LENGTH)));\n }\n\n const signers = staticAccounts.slice(0, numRequiredSignatures);\n const unsigned = signers.filter((_signer, slot) => {\n const start = signaturesOffset + slot * SIGNATURE_LENGTH;\n return bytes\n .subarray(start, start + SIGNATURE_LENGTH)\n .every((byte) => byte === 0);\n });\n\n return {\n bytes,\n version,\n signers,\n unsigned,\n staticAccounts,\n recentBlockhash: base58Encode(\n bytes.slice(recentBlockhashOffset, recentBlockhashOffset + PUBKEY_LENGTH)\n ),\n signaturesOffset,\n messageOffset,\n recentBlockhashOffset,\n };\n}\n\n/**\n * Overwrite a compiled message's recent blockhash in place, and **clear every\n * signature slot**.\n *\n * The gas station quotes a blockhash of its own and then refuses any execute\n * whose transaction does not carry it (`blockhash_mismatch`), so a client that\n * has already been handed a draft has two ways to comply: ask the composer to\n * prepare the same transaction again against the quoted blockhash, or move the\n * 32 bytes itself. This is the second, and it makes step 5 of the ceremony\n * local — one round trip fewer inside a 60-second quote TTL.\n *\n * Clearing the signatures is not a side effect, it is the point. Those 32 bytes\n * are inside the message every signature covers, so a signature made before the\n * patch is now a signature over a message that no longer exists. Left in place\n * it would fail signature verification at the validator with nothing pointing at\n * the cause; zeroed, the slot means exactly what an unsigned slot means\n * everywhere else on this path, and the gas station names it\n * (`missing_client_signature`) before spending anything. **Sign after patching,\n * never before.**\n *\n * @param wire - The transaction, base64 or raw bytes.\n * @param recentBlockhash - Base58, exactly as the quote returned it.\n * @returns The patched transaction, in the spelling `wire` arrived in.\n * @throws {Error} when `recentBlockhash` is not 32 bytes of base58.\n */\nexport function patchSolanaRecentBlockhash(wire: string, recentBlockhash: string): string;\nexport function patchSolanaRecentBlockhash(\n wire: Uint8Array,\n recentBlockhash: string\n): Uint8Array;\nexport function patchSolanaRecentBlockhash(\n wire: string | Uint8Array,\n recentBlockhash: string\n): string | Uint8Array {\n const blockhash = base58Decode(recentBlockhash);\n if (blockhash.length !== PUBKEY_LENGTH) {\n throw new Error(\n `recentBlockhash must decode to ${PUBKEY_LENGTH} bytes, got ${blockhash.length} from ${JSON.stringify(recentBlockhash)}`\n );\n }\n\n const parsed = parseSolanaWireTransaction(wire);\n const patched = new Uint8Array(parsed.bytes);\n patched.set(blockhash, parsed.recentBlockhashOffset);\n patched.fill(\n 0,\n parsed.signaturesOffset,\n parsed.signaturesOffset + parsed.signers.length * SIGNATURE_LENGTH\n );\n\n return likeInput(wire, patched);\n}\n\n/**\n * Sign a supplied wire transaction in place: for each key in `signers` that the\n * compiled header names, write its Ed25519 signature over the message bytes\n * into that key's own slot. Slots belonging to nobody in `signers` — the fee\n * payer's, above all — are left exactly as they were.\n *\n * Slots are matched by ADDRESS. A receipt's `requiredSigners` is address-sorted\n * within a role and carries no semantics, so \"the mint is second\" is a fact\n * about one particular pair of keys and not about the transaction shape.\n *\n * @param wire - The transaction, base64 or raw bytes.\n * @param signers - Keypairs to sign with; each `privateKey` is a 32-byte seed.\n * @returns The signed transaction, in the spelling `wire` arrived in.\n * @throws {Error} when a supplied signer is not one of the message's required\n * signers — signing with a key the transaction never asked for means the\n * caller built or patched the wrong thing, and silently doing nothing would\n * surface much later as `missing_client_signature`.\n */\nexport function signSolanaWireTransaction(wire: string, signers: Signer[]): string;\nexport function signSolanaWireTransaction(\n wire: Uint8Array,\n signers: Signer[]\n): Uint8Array;\nexport function signSolanaWireTransaction(\n wire: string | Uint8Array,\n signers: Signer[]\n): string | Uint8Array {\n const parsed = parseSolanaWireTransaction(wire);\n const signed = new Uint8Array(parsed.bytes);\n const message = signed.subarray(parsed.messageOffset);\n\n for (const signer of signers) {\n const address = base58Encode(signer.publicKey);\n const slot = parsed.signers.indexOf(address);\n if (slot === -1) {\n throw new Error(\n `${address} is not a required signer of this transaction (slots: ${parsed.signers.join(', ')})`\n );\n }\n signed.set(\n ed25519.sign(message, signer.privateKey),\n parsed.signaturesOffset + slot * SIGNATURE_LENGTH\n );\n }\n\n return likeInput(wire, signed);\n}\n\n/**\n * A fresh Ed25519 keypair.\n *\n * The ANT spawn needs one per attempt: its public half goes to the store as the\n * MPL Core asset address — which becomes the ANT's address, and the `processId`\n * the follow-up name purchase wants — and its private half signs one slot of one\n * transaction. Nothing needs it afterwards, so it is generated, used, and\n * dropped rather than derived from the user's phrase, where it would be one more\n * key to keep and to lose.\n */\nexport function generateSolanaKeypair(): Signer & { address: string } {\n return keypairFromSeed(randomBytes(SEED_LENGTH));\n}\n\n/**\n * The keypair a stored or derived Solana secret represents — a 32-byte seed or\n * a 64-byte `seed ‖ pubkey` secret key, as bytes or base58.\n *\n * The public half is DERIVED, never read out of the trailing 32 bytes: a\n * 64-byte input whose tail disagrees with its own seed is a corrupt file, and\n * honouring it would fill a signature slot addressed to a key that did not sign\n * it. Mirrors the rule `ToonClient`'s own config applies to `solanaSecretKey`.\n */\nexport function solanaKeypair(\n key: string | Uint8Array\n): Signer & { address: string } {\n const bytes = typeof key === 'string' ? base58Decode(key.trim()) : key;\n if (bytes.length !== SEED_LENGTH && bytes.length !== SECRET_KEY_LENGTH) {\n throw new Error(\n `a Solana secret must be a ${SEED_LENGTH}-byte seed or a ${SECRET_KEY_LENGTH}-byte ` +\n `secret key; got ${bytes.length} bytes`\n );\n }\n return keypairFromSeed(bytes.slice(0, SEED_LENGTH));\n}\n\n/** The one place a seed becomes a keypair, so both entry points agree. */\nfunction keypairFromSeed(seed: Uint8Array): Signer & { address: string } {\n const publicKey = new Uint8Array(ed25519.getPublicKey(seed));\n return { privateKey: seed, publicKey, address: base58Encode(publicKey) };\n}\n","/**\n * Leaving an x402 `batch-settlement` channel, and getting the unspent deposit\n * back (connector ADR 0074, toon-client#691).\n *\n * A connector only ever receives on these channels: it never refunds\n * cooperatively, so both exits are the payer's own, unilateral, and cost the\n * payer native gas — the one step of this scheme that does. Both give the\n * connector a window to land its latest voucher first, and it watches for\n * exactly that (decision 5).\n *\n * - **EVM** (`x402BatchSettlement.sol`): `initiateWithdraw(config, amount)`\n * by the payer or its `payerAuthorizer`, then after `withdrawDelay`\n * `finalizeWithdraw(config)`, which pays out what is still unclaimed.\n * - **Solana** (payment-channels): `request_close` by the payer moves the\n * channel to Closing; after `grace_period` anyone may `seal` it, and\n * `withdraw_payer` returns `deposit − settled` to the payer's token account.\n */\n\nimport type { Hex, TransactionReceipt } from 'viem';\nimport { ValidationError } from '../../client/errors.js';\nimport {\n X402_BATCH_SETTLEMENT_ADDRESS,\n readEvmBatchChannel,\n type BatchChannelConfig,\n type ContractReader,\n} from './evm.js';\nimport {\n PAYMENT_CHANNELS_PROGRAM_ID,\n getSvmBatchChannel,\n type SvmBatchChannelConfig,\n} from './svm.js';\nimport {\n buildAndSendTransaction,\n deriveAssociatedTokenAccount,\n type RawInstruction,\n type Signer,\n type SolanaRpcTarget,\n} from '../solana/payment-channel.js';\nimport { base58Encode } from '../../utils/base58.js';\n\nconst TOKEN_PROGRAM_ID = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\nconst IX_REQUEST_CLOSE = 5;\nconst IX_SEAL = 6;\nconst IX_WITHDRAW_PAYER = 8;\n\nconst CHANNEL_CONFIG_TUPLE = {\n name: 'config',\n type: 'tuple',\n components: [\n { name: 'payer', type: 'address' },\n { name: 'payerAuthorizer', type: 'address' },\n { name: 'receiver', type: 'address' },\n { name: 'receiverAuthorizer', type: 'address' },\n { name: 'token', type: 'address' },\n { name: 'withdrawDelay', type: 'uint40' },\n { name: 'salt', type: 'bytes32' },\n ],\n} as const;\n\n/** `initiateWithdraw` and `finalizeWithdraw`. */\nexport const X402_BATCH_SETTLEMENT_EXIT_ABI = [\n {\n type: 'function',\n name: 'initiateWithdraw',\n stateMutability: 'nonpayable',\n inputs: [CHANNEL_CONFIG_TUPLE, { name: 'amount', type: 'uint128' }],\n outputs: [],\n },\n {\n type: 'function',\n name: 'finalizeWithdraw',\n stateMutability: 'nonpayable',\n inputs: [CHANNEL_CONFIG_TUPLE],\n outputs: [],\n },\n] as const;\n\n/** The viem clients an EVM exit needs: one to write, one to read and wait. */\nexport interface EvmExitClients {\n publicClient: ContractReader & {\n waitForTransactionReceipt: (params: {\n hash: Hex;\n }) => Promise<TransactionReceipt>;\n };\n walletClient: { writeContract: (params: never) => Promise<Hex> };\n}\n\n// ---------------------------------------------------------------------------\n// EVM\n// ---------------------------------------------------------------------------\n\n/**\n * Start a timed withdrawal of everything the connector has not claimed. The\n * connector sees `WithdrawInitiated` and claims its latest voucher before the\n * delay ends, so what finally comes back is the deposit less what was spent.\n */\nexport async function initiateEvmBatchWithdraw(\n clients: EvmExitClients,\n channel: { channelId: string; config: BatchChannelConfig }\n): Promise<{ transaction: Hex; amount: bigint; finalizeAfter: bigint }> {\n const state = await readEvmBatchChannel(\n clients.publicClient,\n channel.channelId as Hex\n );\n if (state.pendingWithdrawal > 0n) {\n throw new ValidationError(\n `channel ${channel.channelId} already has a withdrawal of ${state.pendingWithdrawal} pending`\n );\n }\n const amount = state.balance - state.totalClaimed;\n if (amount <= 0n) {\n throw new ValidationError(\n `channel ${channel.channelId} holds nothing unclaimed to withdraw`\n );\n }\n const transaction = await clients.walletClient.writeContract({\n address: X402_BATCH_SETTLEMENT_ADDRESS,\n abi: X402_BATCH_SETTLEMENT_EXIT_ABI,\n functionName: 'initiateWithdraw',\n args: [channelConfigArg(channel.config), amount],\n } as never);\n assertSucceeded(\n await clients.publicClient.waitForTransactionReceipt({ hash: transaction }),\n 'initiateWithdraw'\n );\n // The chain's own start time, not this machine's clock.\n const started = await readEvmBatchChannel(\n clients.publicClient,\n channel.channelId as Hex\n );\n return {\n transaction,\n amount,\n finalizeAfter:\n BigInt(started.withdrawalInitiatedAt) +\n BigInt(channel.config.withdrawDelay),\n };\n}\n\n/** Finish a timed withdrawal once `withdrawDelay` has passed. */\nexport async function finalizeEvmBatchWithdraw(\n clients: EvmExitClients,\n channel: { channelId: string; config: BatchChannelConfig },\n now = BigInt(Math.floor(Date.now() / 1000))\n): Promise<{ transaction: Hex }> {\n const state = await readEvmBatchChannel(\n clients.publicClient,\n channel.channelId as Hex\n );\n if (state.withdrawalInitiatedAt === 0) {\n throw new ValidationError(\n `channel ${channel.channelId} has no withdrawal pending`\n );\n }\n const finalizeAfter = BigInt(\n state.withdrawalInitiatedAt + channel.config.withdrawDelay\n );\n if (now < finalizeAfter) {\n throw new ValidationError(\n `channel ${channel.channelId}'s withdrawal can be finalized at ${finalizeAfter} (unix seconds), not yet`\n );\n }\n const transaction = await clients.walletClient.writeContract({\n address: X402_BATCH_SETTLEMENT_ADDRESS,\n abi: X402_BATCH_SETTLEMENT_EXIT_ABI,\n functionName: 'finalizeWithdraw',\n args: [channelConfigArg(channel.config)],\n } as never);\n assertSucceeded(\n await clients.publicClient.waitForTransactionReceipt({ hash: transaction }),\n 'finalizeWithdraw'\n );\n return { transaction };\n}\n\nfunction channelConfigArg(config: BatchChannelConfig) {\n return {\n payer: config.payer as Hex,\n payerAuthorizer: config.payerAuthorizer as Hex,\n receiver: config.receiver as Hex,\n receiverAuthorizer: config.receiverAuthorizer as Hex,\n token: config.token as Hex,\n withdrawDelay: config.withdrawDelay,\n salt: config.salt,\n };\n}\n\nfunction assertSucceeded(receipt: TransactionReceipt, what: string): void {\n if (receipt.status !== 'success') {\n throw new ValidationError(`${what} reverted in ${receipt.transactionHash}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Solana\n// ---------------------------------------------------------------------------\n\n/** `request_close` (5): the payer starts the grace period. */\nexport function buildSvmRequestCloseInstruction(\n channelId: string,\n payer: string\n): RawInstruction {\n return {\n programId: PAYMENT_CHANNELS_PROGRAM_ID,\n keys: [\n { pubkey: payer, isSigner: true, isWritable: false },\n { pubkey: channelId, isSigner: false, isWritable: true },\n ],\n data: new Uint8Array([IX_REQUEST_CLOSE]),\n };\n}\n\n/** `seal` (6): permissionless, once the grace period has elapsed. */\nexport function buildSvmSealInstruction(channelId: string): RawInstruction {\n return {\n programId: PAYMENT_CHANNELS_PROGRAM_ID,\n keys: [{ pubkey: channelId, isSigner: false, isWritable: true }],\n data: new Uint8Array([IX_SEAL]),\n };\n}\n\n/** `withdraw_payer` (8): `deposit − settled` back to the payer, from a Sealed channel. */\nexport function buildSvmWithdrawPayerInstruction(\n channelId: string,\n config: Pick<SvmBatchChannelConfig, 'payer' | 'token'>\n): RawInstruction {\n return {\n programId: PAYMENT_CHANNELS_PROGRAM_ID,\n keys: [\n { pubkey: config.payer, isSigner: true, isWritable: false },\n { pubkey: channelId, isSigner: false, isWritable: true },\n {\n pubkey: deriveAssociatedTokenAccount(channelId, config.token),\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: deriveAssociatedTokenAccount(config.payer, config.token),\n isSigner: false,\n isWritable: true,\n },\n { pubkey: config.token, isSigner: false, isWritable: false },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n ],\n data: new Uint8Array([IX_WITHDRAW_PAYER]),\n };\n}\n\n/**\n * The payer's `request_close`. From here the channel accepts no new voucher,\n * and the connector lands its latest one with `settle_and_seal` before the\n * grace period ends.\n */\nexport async function requestSvmBatchClose(\n rpc: SolanaRpcTarget,\n payer: Signer,\n channelId: string\n): Promise<{ transaction: string; settleableAt: bigint }> {\n const state = await getSvmBatchChannel(rpc, channelId);\n if (state === null)\n throw new ValidationError(`channel ${channelId} does not exist`);\n if (state.status !== 'open') {\n throw new ValidationError(\n `channel ${channelId} is ${state.status}, not open`\n );\n }\n const transaction = await buildAndSendTransaction(rpc, payer, [\n buildSvmRequestCloseInstruction(channelId, base58Encode(payer.publicKey)),\n ]);\n return {\n transaction,\n settleableAt:\n BigInt(Math.floor(Date.now() / 1000)) + BigInt(state.gracePeriod),\n };\n}\n\n/**\n * Take the unspent deposit back: `seal` a Closing channel whose grace period\n * has passed (unless the connector already sealed it), then `withdraw_payer`,\n * in one transaction.\n */\nexport async function withdrawSvmBatchChannel(\n rpc: SolanaRpcTarget,\n payer: Signer,\n channelId: string,\n config: Pick<SvmBatchChannelConfig, 'payer' | 'token'>,\n now = BigInt(Math.floor(Date.now() / 1000))\n): Promise<{ transaction: string }> {\n const state = await getSvmBatchChannel(rpc, channelId);\n if (state === null)\n throw new ValidationError(`channel ${channelId} does not exist`);\n if (state.payerWithdrawnAt !== 0n) {\n throw new ValidationError(\n `channel ${channelId}'s deposit was already withdrawn`\n );\n }\n const instructions: RawInstruction[] = [];\n if (state.status === 'closing') {\n const deadline = state.closureStartedAt + BigInt(state.gracePeriod);\n if (now < deadline) {\n throw new ValidationError(\n `channel ${channelId} can be sealed at ${deadline} (unix seconds), not yet`\n );\n }\n instructions.push(buildSvmSealInstruction(channelId));\n } else if (state.status !== 'sealed') {\n throw new ValidationError(\n `channel ${channelId} is ${state.status}; request its close first`\n );\n }\n instructions.push(buildSvmWithdrawPayerInstruction(channelId, config));\n return {\n transaction: await buildAndSendTransaction(rpc, payer, instructions),\n };\n}\n","/**\n * The one place viem is told to send chain RPC through the hidden-service proxy.\n *\n * viem's HTTP transport calls the **global** `fetch` and accepts no injected one.\n * Its only opening is `fetchOptions`, which it merges into the `fetch` init — and\n * Node's `fetch` reads a `dispatcher` from there. So a dispatcher is how, and the\n * only how, chain traffic joins the packet traffic inside the overlay (ADR 0002).\n *\n * Browser-safe: this module imports nothing but viem. The dispatcher itself is\n * built in `./socks.js`, which is Node-only and dynamically imported; here it is\n * an opaque `unknown` that is either present or not.\n */\nimport { http } from 'viem';\n\n/** Options a caller already wanted, independent of any proxy. */\nexport interface RpcTransportOptions {\n timeout?: number;\n retryCount?: number;\n retryDelay?: number;\n}\n\n/**\n * What a proxied RPC request gets when its caller names nothing else, sized\n * from connector ADR 0073's measurements through `anon` (decisions 4 and 5).\n *\n * - `timeout` 30s, not viem's 10s. The worst call measured that needed a new\n * circuit took 13s. Under 10s that one would have been reported as a failure,\n * and retried on another new circuit.\n * - `retryDelay` 500ms, not viem's 150ms. viem already retries 403, 408, 429,\n * 5xx and dropped connections. Exit IPs are shared, so a 429 is the error to\n * expect, and retrying it at 150ms mostly earns another one.\n * - `retryCount` 3, viem's own.\n */\nexport const PROXIED_RPC_DEFAULTS = {\n timeout: 30_000,\n retryCount: 3,\n retryDelay: 500,\n} as const satisfies Required<RpcTransportOptions>;\n\n/**\n * A viem HTTP transport for `url`, bound to `dispatcher` when there is one.\n *\n * `undefined` dispatcher means clearnet, and produces exactly the transport this\n * package built before hidden services existed. A dispatcher also brings\n * {@link PROXIED_RPC_DEFAULTS}, under anything the caller set explicitly.\n */\nexport function rpcTransport(\n url: string,\n dispatcher: unknown | undefined,\n options: RpcTransportOptions = {}\n): ReturnType<typeof http> {\n const { timeout, retryCount, retryDelay } =\n dispatcher === undefined ? options : { ...PROXIED_RPC_DEFAULTS, ...definedOnly(options) };\n return http(url, {\n ...(timeout !== undefined ? { timeout } : {}),\n ...(retryCount !== undefined ? { retryCount } : {}),\n ...(retryDelay !== undefined ? { retryDelay } : {}),\n ...(dispatcher !== undefined ? { fetchOptions: { dispatcher } as RequestInit } : {}),\n });\n}\n\n/** `options` without its `undefined` members, so a spread cannot erase a default. */\nfunction definedOnly(options: RpcTransportOptions): RpcTransportOptions {\n return Object.fromEntries(\n Object.entries(options).filter(([, value]) => value !== undefined)\n ) as RpcTransportOptions;\n}\n\n/**\n * `fetch` bound to `dispatcher`, for a JSON-RPC path that calls `fetch` itself\n * rather than going through viem — Solana's, in practice.\n */\nexport function rpcFetch(dispatcher: unknown | undefined, fetchImpl: typeof fetch = globalThis.fetch): typeof fetch {\n if (dispatcher === undefined) return fetchImpl;\n return ((input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) =>\n fetchImpl(input, { ...init, dispatcher } as unknown as RequestInit)) as typeof fetch;\n}\n","/**\n * Read-only on-chain wallet balances.\n *\n * Reports what your OWN wallet holds on each configured chain — the native coin\n * and the settlement token — as a free read: no signing, no transaction, no\n * money moved. It has nothing to do with a payment channel's balance, which is\n * collateral already locked on chain and is reported by the channel facade.\n *\n * Each per-chain reader is independent and injectable (viem for EVM, raw\n * JSON-RPC `fetch` for Solana, mirroring the channel modules) so they unit-test\n * without a live chain. The caller treats each chain best-effort: a chain whose\n * RPC is unreachable degrades to `unreadable` rather than failing the others.\n */\nimport { createPublicClient, defineChain } from 'viem';\nimport { PROXIED_RPC_DEFAULTS, rpcTransport } from '../transport/rpc.js';\n\n/** One on-chain wallet token balance. `amount` is base-unit integer, decimal. */\nexport interface WalletBalance {\n chain: 'evm' | 'solana';\n address: string;\n amount: string;\n /** Token symbol, when resolved (e.g. `'USDC'`). */\n asset?: string;\n /** Token decimals, when resolved. */\n assetScale?: number;\n}\n\n/**\n * One asset amount within a chain's wallet view — the native coin or one token.\n * `amount` is a base-unit integer, decimal string.\n */\nexport interface WalletTokenAmount {\n /** Asset symbol (e.g. `'ETH'`, `'SOL'`, `'USDC'`), when known. */\n symbol?: string;\n /** Base-unit integer, decimal string. */\n amount: string;\n /** Decimals for formatting (ETH 18, SOL 9, USDC 6). */\n decimals?: number;\n /** Token contract / SPL mint address. Absent for the native coin. */\n address?: string;\n}\n\n/**\n * The full wallet view for ONE chain the identity is configured for: the native\n * coin plus every configured token, keyed by the chain's full key (e.g.\n * `'evm:84532'`). `unreadable` marks a chain whose RPC could not be reached at\n * all — the caller renders a per-chain notice rather than crashing.\n */\nexport interface WalletChainBalances {\n chain: 'evm' | 'solana';\n /** Full chain key, e.g. `'evm:base-sepolia:84532'`, `'solana'`. */\n chainKey: string;\n address: string;\n /** Native-coin balance, when readable. */\n native?: WalletTokenAmount;\n /** Configured token balances (e.g. USDC), each best-effort. */\n tokens: WalletTokenAmount[];\n /** True when nothing on this chain could be read (RPC unreachable). */\n unreadable?: boolean;\n /** First read error, when any read failed (for diagnostics). */\n error?: string;\n}\n\n/** Minimal ERC-20 read ABI (balance + metadata). */\nconst ERC20_READ_ABI = [\n { name: 'balanceOf', type: 'function', stateMutability: 'view', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }] },\n { name: 'decimals', type: 'function', stateMutability: 'view', inputs: [], outputs: [{ type: 'uint8' }] },\n { name: 'symbol', type: 'function', stateMutability: 'view', inputs: [], outputs: [{ type: 'string' }] },\n] as const;\n\n/** Extract the numeric chainId from an `evm:{network}:{chainId}` / `evm:{chainId}` key. */\nexport function parseEvmChainId(chainKey: string): number {\n const parts = chainKey.split(':');\n const idStr = parts.length >= 3 ? parts[2] : parts[1];\n const id = Number.parseInt(idStr ?? '', 10);\n if (!Number.isFinite(id)) throw new Error(`Invalid EVM chain key \"${chainKey}\".`);\n return id;\n}\n\n/**\n * Per-request network timeout (ms) for ONE wallet-balance RPC/GraphQL call.\n * Node's global `fetch` has NO default timeout, so a single stalled socket would\n * otherwise hang the entire multi-chain read until the caller's outer bound —\n * making one flaky endpoint hide the balances of every chain. Bounding each call\n * (viem's own `timeout` for EVM; an AbortSignal for the Solana `fetch`)\n * lets a slow endpoint degrade only its own chain to `unreadable`. Env override\n * `TOON_WALLET_RPC_TIMEOUT_MS` (`0` disables).\n */\nconst RPC_TIMEOUT_ENV = 'TOON_WALLET_RPC_TIMEOUT_MS';\nconst DEFAULT_RPC_TIMEOUT_MS = 8_000;\n/**\n * The default through the SOCKS5h proxy: a read that needs a fresh circuit took\n * up to 13s in connector ADR 0073's measurements, so 8s would report a healthy\n * chain `unreadable` on a cold daemon.\n */\nconst DEFAULT_PROXIED_RPC_TIMEOUT_MS = PROXIED_RPC_DEFAULTS.timeout;\n\nfunction rpcTimeoutMs(proxied = false): number {\n const raw =\n typeof process !== 'undefined' ? process.env?.[RPC_TIMEOUT_ENV] : undefined;\n const n = raw === undefined || raw === '' ? NaN : Number(raw);\n if (Number.isFinite(n) && n >= 0) return n;\n return proxied ? DEFAULT_PROXIED_RPC_TIMEOUT_MS : DEFAULT_RPC_TIMEOUT_MS;\n}\n\n/** AbortSignal firing after {@link rpcTimeoutMs}; undefined when disabled (`0`). */\nfunction rpcAbortSignal(proxied = false): AbortSignal | undefined {\n const ms = rpcTimeoutMs(proxied);\n return ms > 0 ? AbortSignal.timeout(ms) : undefined;\n}\n\n/** Read an ERC-20 token balance (balance + decimals + symbol) for `owner`. */\nexport async function readEvmTokenBalance(opts: {\n rpcUrl: string;\n chainKey: string;\n tokenAddress: string;\n owner: string;\n /** Send this read through the hidden-service proxy, when there is one (ADR 0002). */\n rpcDispatcher?: unknown;\n}): Promise<WalletBalance> {\n const chainId = parseEvmChainId(opts.chainKey);\n const client = createPublicClient({\n transport: rpcTransport(opts.rpcUrl, opts.rpcDispatcher, {\n ...(rpcTimeoutMs(opts.rpcDispatcher !== undefined)\n ? { timeout: rpcTimeoutMs(opts.rpcDispatcher !== undefined) }\n : {}),\n retryCount: 1,\n }),\n chain: defineChain({\n id: chainId,\n name: opts.chainKey,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [opts.rpcUrl] } },\n }),\n });\n const token = opts.tokenAddress as `0x${string}`;\n const owner = opts.owner as `0x${string}`;\n const [amount, decimals, symbol] = await Promise.all([\n client.readContract({ address: token, abi: ERC20_READ_ABI, functionName: 'balanceOf', args: [owner] }),\n client.readContract({ address: token, abi: ERC20_READ_ABI, functionName: 'decimals' }).catch(() => undefined),\n client.readContract({ address: token, abi: ERC20_READ_ABI, functionName: 'symbol' }).catch(() => undefined),\n ]);\n const out: WalletBalance = { chain: 'evm', address: opts.owner, amount: (amount as bigint).toString() };\n if (typeof symbol === 'string' && symbol) out.asset = symbol;\n if (decimals !== undefined) out.assetScale = Number(decimals);\n return out;\n}\n\n/** Read the native ETH balance (wei) for `owner` via `eth_getBalance`. */\nexport async function readEvmNativeBalance(opts: {\n rpcUrl: string;\n chainKey: string;\n owner: string;\n /** Send this read through the hidden-service proxy, when there is one (ADR 0002). */\n rpcDispatcher?: unknown;\n}): Promise<WalletTokenAmount> {\n const chainId = parseEvmChainId(opts.chainKey);\n const client = createPublicClient({\n transport: rpcTransport(opts.rpcUrl, opts.rpcDispatcher, {\n ...(rpcTimeoutMs(opts.rpcDispatcher !== undefined)\n ? { timeout: rpcTimeoutMs(opts.rpcDispatcher !== undefined) }\n : {}),\n retryCount: 1,\n }),\n chain: defineChain({\n id: chainId,\n name: opts.chainKey,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [opts.rpcUrl] } },\n }),\n });\n const wei = await client.getBalance({ address: opts.owner as `0x${string}` });\n return { symbol: 'ETH', amount: wei.toString(), decimals: 18 };\n}\n\n/** Read the native SOL balance (lamports) for `owner` via the `getBalance` RPC. */\nexport async function readSolanaNativeBalance(opts: {\n rpcUrl: string;\n owner: string;\n fetchImpl?: typeof fetch;\n /** The fetch rides the SOCKS5h proxy: allow a circuit's latency. */\n proxied?: boolean;\n}): Promise<WalletTokenAmount> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const res = await fetchImpl(opts.rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'getBalance',\n params: [opts.owner, { commitment: 'confirmed' }],\n }),\n signal: rpcAbortSignal(opts.proxied),\n });\n if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);\n const json = (await res.json()) as {\n result?: { value?: number | string };\n error?: { message?: string };\n };\n if (json.error) throw new Error(`Solana RPC error: ${json.error.message ?? 'unknown'}`);\n const lamports = BigInt(json.result?.value ?? 0);\n return { symbol: 'SOL', amount: lamports.toString(), decimals: 9 };\n}\n\n/** Read the SPL-token balance for `owner`'s token account(s) of `mint`. */\nexport async function readSolanaTokenBalance(opts: {\n rpcUrl: string;\n mint: string;\n owner: string;\n fetchImpl?: typeof fetch;\n /** The fetch rides the SOCKS5h proxy: allow a circuit's latency. */\n proxied?: boolean;\n}): Promise<WalletBalance> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const res = await fetchImpl(opts.rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'getTokenAccountsByOwner',\n params: [opts.owner, { mint: opts.mint }, { encoding: 'jsonParsed', commitment: 'confirmed' }],\n }),\n signal: rpcAbortSignal(opts.proxied),\n });\n if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);\n const json = (await res.json()) as {\n result?: { value?: { account?: { data?: { parsed?: { info?: { tokenAmount?: { amount?: string; decimals?: number } } } } } }[] };\n error?: { message?: string };\n };\n if (json.error) throw new Error(`Solana RPC error: ${json.error.message ?? 'unknown'}`);\n let amount = 0n;\n let decimals: number | undefined;\n for (const acc of json.result?.value ?? []) {\n const ta = acc.account?.data?.parsed?.info?.tokenAmount;\n if (ta?.amount) amount += BigInt(ta.amount);\n if (ta?.decimals !== undefined) decimals = ta.decimals;\n }\n const out: WalletBalance = { chain: 'solana', address: opts.owner, amount: amount.toString() };\n if (decimals !== undefined) out.assetScale = decimals;\n return out;\n}\n\n/**\n * Per-chain inputs for {@link readWalletBalances}: the resolved RPC URL, the\n * identity's address on that chain, and the configured token (USDC) — sourced by\n * the caller from the network topology / presets, never hardcoded here. A chain\n * key absent from the object is simply not read.\n */\nexport interface WalletBalanceSources {\n evm?: {\n chainKey: string;\n rpcUrl: string;\n owner: string;\n tokenAddress?: string;\n /**\n * Send the EVM reads through the hidden-service proxy (ADR 0002). The Solana\n * reads need no equivalent: they go through {@link WalletBalanceSources.fetchImpl},\n * which is already the proxied `fetch` on a hidden-service client.\n */\n rpcDispatcher?: unknown;\n };\n solana?: { chainKey?: string; rpcUrl: string; owner: string; tokenMint?: string };\n /** Injectable fetch (the Solana JSON-RPC calls) for tests. */\n fetchImpl?: typeof fetch;\n /** `fetchImpl` rides the SOCKS5h proxy, so the Solana reads allow a circuit's latency. */\n solanaProxied?: boolean;\n}\n\nconst errText = (e: unknown): string => (e instanceof Error ? e.message : String(e));\n\n/** Fold a settled native read into the chain view, recording any failure. */\nfunction foldNative(\n out: WalletChainBalances,\n settled: PromiseSettledResult<WalletTokenAmount>,\n errors: string[]\n): void {\n if (settled.status === 'fulfilled') out.native = settled.value;\n else errors.push(errText(settled.reason));\n}\n\n/** Fold a settled token read (a `WalletBalance`) into the chain view. */\nfunction foldToken(\n out: WalletChainBalances,\n settled: PromiseSettledResult<WalletBalance | undefined>,\n tokenAddress: string | undefined,\n errors: string[]\n): void {\n if (settled.status === 'rejected') {\n errors.push(errText(settled.reason));\n return;\n }\n const bal = settled.value;\n if (!bal) return;\n out.tokens.push({\n symbol: bal.asset,\n amount: bal.amount,\n decimals: bal.assetScale,\n ...(tokenAddress ? { address: tokenAddress } : {}),\n });\n}\n\n/** Mark a chain unreadable when nothing could be read; attach the first error. */\nfunction finalizeChain(out: WalletChainBalances, errors: string[]): void {\n if (errors.length > 0) out.error = errors[0];\n if (out.native === undefined && out.tokens.length === 0) out.unreadable = true;\n}\n\n/**\n * Read the full wallet view — native coin + configured tokens — for every chain\n * in `sources`, keyed per chain. FREE: read-only RPC, no signing. Each chain is\n * read independently and in parallel; a chain whose RPC is unreachable degrades\n * to `{ unreadable: true, error }` instead of failing the others. Within a chain\n * the native and token reads are independent, so a native read can succeed even\n * if the token read fails (and vice versa).\n */\nexport async function readWalletBalances(\n sources: WalletBalanceSources\n): Promise<WalletChainBalances[]> {\n const { fetchImpl, solanaProxied: proxied } = sources;\n const tasks: Promise<WalletChainBalances>[] = [];\n\n if (sources.evm) {\n const { chainKey, rpcUrl, owner, tokenAddress, rpcDispatcher } = sources.evm;\n tasks.push(\n (async () => {\n const out: WalletChainBalances = { chain: 'evm', chainKey, address: owner, tokens: [] };\n const errors: string[] = [];\n const [nativeR, tokenR] = await Promise.allSettled([\n readEvmNativeBalance({ rpcUrl, chainKey, owner, rpcDispatcher }),\n tokenAddress\n ? readEvmTokenBalance({ rpcUrl, chainKey, tokenAddress, owner, rpcDispatcher })\n : Promise.resolve<WalletBalance | undefined>(undefined),\n ]);\n foldNative(out, nativeR, errors);\n foldToken(out, tokenR, tokenAddress, errors);\n finalizeChain(out, errors);\n return out;\n })()\n );\n }\n\n if (sources.solana) {\n const { chainKey = 'solana', rpcUrl, owner, tokenMint } = sources.solana;\n tasks.push(\n (async () => {\n const out: WalletChainBalances = { chain: 'solana', chainKey, address: owner, tokens: [] };\n const errors: string[] = [];\n const [nativeR, tokenR] = await Promise.allSettled([\n readSolanaNativeBalance({ rpcUrl, owner, fetchImpl, proxied }),\n tokenMint\n ? readSolanaTokenBalance({ rpcUrl, mint: tokenMint, owner, fetchImpl, proxied })\n : Promise.resolve<WalletBalance | undefined>(undefined),\n ]);\n foldNative(out, nativeR, errors);\n // Solana SPL reads carry no symbol from `getTokenAccountsByOwner`; the\n // negotiated settlement token is USDC on every configured chain.\n if (tokenR.status === 'fulfilled' && tokenR.value && tokenR.value.asset === undefined) {\n tokenR.value.asset = 'USDC';\n }\n foldToken(out, tokenR, tokenMint, errors);\n finalizeChain(out, errors);\n return out;\n })()\n );\n }\n\n return Promise.all(tasks);\n}\n","/**\n * Plain token transfer — send the settlement token or native gas from your own\n * key to an ARBITRARY address, on either chain this client supports. This is\n * the primitive underneath provisioning a second wallet: before a derived\n * address can open a payment channel, something has to send it USDC and native\n * gas.\n *\n * It has nothing to do with paying a connector. A paid request moves value by\n * signing a claim on a channel; this moves value by signing a chain\n * transaction, straight to `to`, non-custodially.\n *\n * Every send is confirmed by an OBSERVED balance delta at the destination,\n * never by the send call merely returning. The devnet faucet's Solana leg has\n * been seen returning success with a real transaction signature while\n * delivering 0 lamports (connector#691) — a send that trusted its own receipt\n * would report a funded wallet that in fact holds nothing.\n * {@link TransferNotDeliveredError} is exactly that failure mode, made loud\n * instead of silent.\n */\n\nimport {\n createPublicClient,\n createWalletClient,\n defineChain,\n type Hex,\n} from 'viem';\nimport { rpcTransport } from '../transport/rpc.js';\nimport { waitForReceipt } from '../channel/evm/receipt.js';\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { base58Decode, base58Encode } from '../utils/base58.js';\nimport type { EvmSigner } from '../signing/evm-signer.js';\nimport {\n InsufficientBalanceError,\n InvalidAddressError,\n TransferNotDeliveredError,\n TransferUnsupportedError,\n UnknownChainError,\n ValidationError,\n} from '../client/errors.js';\nimport {\n parseEvmChainId,\n} from './balances.js';\nimport {\n buildAndSendTransaction,\n getLamports,\n getTokenAccountBalance,\n deriveAssociatedTokenAccount,\n type SolanaRpcTarget,\n} from '../channel/solana/payment-channel.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/** Chains this client can send a plain transfer on. */\nexport type TransferChain = 'evm' | 'solana';\n\n/** `'native'` — the chain's own gas token. `'token'` — the settlement token. */\nexport type TransferAssetKind = 'native' | 'token';\n\nexport interface SendTransferParams {\n chain: TransferChain;\n asset: TransferAssetKind;\n /** Destination address, in the target chain's native format. */\n to: string;\n /** Amount to send, in the asset's base units (wei, lamports, or the token's). */\n amount: string | bigint;\n /**\n * How long to wait for the destination's observed balance to reflect the\n * transfer before giving up with {@link TransferNotDeliveredError}. Default\n * 30 seconds on both chains.\n */\n confirmTimeoutMs?: number;\n /** Poll interval (ms) while waiting for the balance delta. Default 2000. */\n confirmPollIntervalMs?: number;\n}\n\nexport interface SendTransferResult {\n chain: TransferChain;\n asset: TransferAssetKind;\n to: string;\n /** Base units actually requested (echoed back as a decimal string). */\n amount: string;\n /** Transaction hash / signature of the send. */\n txHash: string;\n /** Destination's observed balance immediately before the send. */\n balanceBefore: string;\n /** Destination's observed balance once the delta was confirmed. */\n balanceAfter: string;\n}\n\n/** Per-chain config a caller supplies to {@link sendTransfer}. */\nexport interface EvmTransferConfig {\n /** Chain key, e.g. `'evm:base-sepolia:84532'` (used for chainId + RPC). */\n chainKey: string;\n rpcUrl: string;\n signer: EvmSigner;\n /** ERC-20 settlement-token address. Required only for `asset: 'token'`. */\n tokenAddress?: string;\n /** Send this transfer's RPC through the hidden-service proxy (ADR 0002). */\n rpcDispatcher?: unknown;\n}\n\nexport interface SolanaTransferConfig {\n rpcUrl: string;\n /** `fetch` for Solana JSON-RPC — the proxied one on a hidden-service client (ADR 0002). */\n rpcFetch?: typeof fetch;\n /** Ed25519 signing seed (32 bytes) or a 64-byte seed||pubkey keypair. */\n keypair: Uint8Array;\n /** SPL settlement-token mint. Required only for `asset: 'token'`. */\n tokenMint?: string;\n}\n\nexport interface TransferConfig {\n evm?: EvmTransferConfig;\n solana?: SolanaTransferConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Address validation — checked BEFORE any transaction is built, so a typo\n// never costs gas/fees or risks sending funds into a black hole.\n// ---------------------------------------------------------------------------\n\nfunction assertValidEvmAddress(address: string): void {\n if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {\n throw new InvalidAddressError(\n `\"${address}\" is not a valid EVM address (expected 0x + 40 hex chars).`\n );\n }\n}\n\nfunction assertValidSolanaAddress(address: string): void {\n let decoded: Uint8Array;\n try {\n decoded = base58Decode(address);\n } catch (err) {\n throw new InvalidAddressError(\n `\"${address}\" is not valid base58 for a Solana address.`,\n err instanceof Error ? err : undefined\n );\n }\n if (decoded.length !== 32) {\n throw new InvalidAddressError(\n `\"${address}\" decodes to ${decoded.length} bytes, not the 32 a Solana address requires.`\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// Balance-delta confirmation — the core guarantee of this module. Never trust\n// the send call returning; re-read the destination and wait for it to move.\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_POLL_INTERVAL_MS = 2000;\n\n/**\n * Poll `readBalance` until it reports at least `before + minDelta`, or\n * `timeoutMs` elapses. Returns the last-observed balance either way — the\n * caller decides whether the final delta was enough (see each chain's\n * sender, which throws {@link TransferNotDeliveredError} when it wasn't).\n */\nasync function waitForBalanceDelta(opts: {\n readBalance: () => Promise<bigint>;\n before: bigint;\n minDelta: bigint;\n timeoutMs: number;\n pollIntervalMs?: number;\n}): Promise<bigint> {\n const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const deadline = Date.now() + opts.timeoutMs;\n for (;;) {\n const current = await opts.readBalance();\n if (current - opts.before >= opts.minDelta) return current;\n if (Date.now() >= deadline) return current;\n await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));\n }\n}\n\n/**\n * {@link waitForBalanceDelta}, then throw {@link TransferNotDeliveredError}\n * if the final observed balance still doesn't reflect the transfer — the\n * shared tail end of every chain's send path below.\n */\nasync function confirmDelivered(opts: {\n readBalance: () => Promise<bigint>;\n before: bigint;\n amount: bigint;\n timeoutMs: number;\n pollIntervalMs?: number;\n notDeliveredMessage: (observedDelta: bigint) => string;\n}): Promise<bigint> {\n const after = await waitForBalanceDelta({\n readBalance: opts.readBalance,\n before: opts.before,\n minDelta: opts.amount,\n timeoutMs: opts.timeoutMs,\n pollIntervalMs: opts.pollIntervalMs,\n });\n if (after - opts.before < opts.amount) {\n throw new TransferNotDeliveredError(\n opts.notDeliveredMessage(after - opts.before)\n );\n }\n return after;\n}\n\nfunction buildResult(\n chain: TransferChain,\n asset: TransferAssetKind,\n to: string,\n amount: bigint,\n txHash: string,\n before: bigint,\n after: bigint\n): SendTransferResult {\n return {\n chain,\n asset,\n to,\n amount: amount.toString(),\n txHash,\n balanceBefore: before.toString(),\n balanceAfter: after.toString(),\n };\n}\n\n// ---------------------------------------------------------------------------\n// EVM\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_EVM_CONFIRM_TIMEOUT_MS = 30_000;\n\nconst ERC20_TRANSFER_ABI = [\n {\n name: 'balanceOf',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'account', type: 'address' }],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'transfer',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'to', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ type: 'bool' }],\n },\n] as const;\n\n/** The RPC target for a Solana transfer: the URL, plus a proxied `fetch` if configured. */\nfunction solanaRpcTarget(cfg: SolanaTransferConfig): SolanaRpcTarget {\n return cfg.rpcFetch === undefined ? cfg.rpcUrl : { url: cfg.rpcUrl, fetchImpl: cfg.rpcFetch };\n}\n\nfunction evmClients(cfg: EvmTransferConfig) {\n const chainId = parseEvmChainId(cfg.chainKey);\n const viemChain = defineChain({\n id: chainId,\n name: cfg.chainKey,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [cfg.rpcUrl] } },\n });\n const publicClient = createPublicClient({\n transport: rpcTransport(cfg.rpcUrl, cfg.rpcDispatcher),\n chain: viemChain,\n });\n const walletClient = createWalletClient({\n account: cfg.signer.account,\n transport: rpcTransport(cfg.rpcUrl, cfg.rpcDispatcher),\n chain: viemChain,\n });\n return { publicClient, walletClient };\n}\n\nasync function sendEvmTransfer(\n cfg: EvmTransferConfig,\n params: SendTransferParams,\n amount: bigint\n): Promise<SendTransferResult> {\n const { publicClient, walletClient } = evmClients(cfg);\n const from = cfg.signer.address as Hex;\n const to = params.to as Hex;\n const timeoutMs = params.confirmTimeoutMs ?? DEFAULT_EVM_CONFIRM_TIMEOUT_MS;\n\n if (params.asset === 'native') {\n const senderBalance = await publicClient.getBalance({ address: from });\n if (senderBalance < amount) {\n throw new InsufficientBalanceError(\n `EVM wallet ${from} holds ${senderBalance} wei, short of the ${amount} wei transfer (before gas).`\n );\n }\n const readDest = () => publicClient.getBalance({ address: to });\n const before = await readDest();\n const txHash = await walletClient.sendTransaction({ to, value: amount });\n const receipt = await waitForReceipt(publicClient, txHash);\n if (receipt.status === 'reverted') {\n throw new TransferNotDeliveredError(\n `EVM native transfer ${txHash} reverted on-chain — no funds reached ${to}.`\n );\n }\n const after = await confirmDelivered({\n readBalance: readDest,\n before,\n amount,\n timeoutMs,\n pollIntervalMs: params.confirmPollIntervalMs,\n notDeliveredMessage: (delta) =>\n `EVM native transfer ${txHash} confirmed on-chain, but ${to}'s balance only rose by ` +\n `${delta} wei (expected ${amount}) within the wait window.`,\n });\n return buildResult('evm', 'native', params.to, amount, txHash, before, after);\n }\n\n // Settlement token (ERC-20).\n if (!cfg.tokenAddress) {\n throw new TransferUnsupportedError(\n `No settlement-token address configured for EVM chain \"${cfg.chainKey}\" — cannot send the token leg.`\n );\n }\n const tokenAddr = cfg.tokenAddress as Hex;\n const readSenderBalance = () =>\n publicClient.readContract({\n address: tokenAddr,\n abi: ERC20_TRANSFER_ABI,\n functionName: 'balanceOf',\n args: [from],\n }) as Promise<bigint>;\n const readDest = () =>\n publicClient.readContract({\n address: tokenAddr,\n abi: ERC20_TRANSFER_ABI,\n functionName: 'balanceOf',\n args: [to],\n }) as Promise<bigint>;\n\n const senderBalance = await readSenderBalance();\n if (senderBalance < amount) {\n throw new InsufficientBalanceError(\n `EVM wallet ${from} holds ${senderBalance} base units of ${tokenAddr}, short of the ${amount} transfer.`\n );\n }\n const before = await readDest();\n const txHash = await walletClient.writeContract({\n address: tokenAddr,\n abi: ERC20_TRANSFER_ABI,\n functionName: 'transfer',\n args: [to, amount],\n });\n const receipt = await waitForReceipt(publicClient, txHash);\n if (receipt.status === 'reverted') {\n throw new TransferNotDeliveredError(\n `EVM token transfer ${txHash} reverted on-chain — no funds reached ${to}.`\n );\n }\n const after = await confirmDelivered({\n readBalance: readDest,\n before,\n amount,\n timeoutMs,\n pollIntervalMs: params.confirmPollIntervalMs,\n notDeliveredMessage: (delta) =>\n `EVM token transfer ${txHash} confirmed on-chain, but ${to}'s balance only rose by ` +\n `${delta} base units (expected ${amount}) within the wait window.`,\n });\n return buildResult('evm', 'token', params.to, amount, txHash, before, after);\n}\n\n// ---------------------------------------------------------------------------\n// Solana — raw System/SPL-Token instructions over the same connector-parity\n// transaction wire format `solana-payment-channel.ts` already builds and\n// tests against (`buildAndSendTransaction`).\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_SOLANA_CONFIRM_TIMEOUT_MS = 30_000;\nconst SOLANA_SYSTEM_PROGRAM_ID = '11111111111111111111111111111111';\nconst SOLANA_TOKEN_PROGRAM_ID = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\nconst SOLANA_ASSOCIATED_TOKEN_PROGRAM_ID =\n 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';\n/** Base fee per signature (lamports) — every tx here carries exactly one. */\nconst SOLANA_LAMPORTS_PER_SIGNATURE = 5_000n;\n\nfunction writeU64LE(buf: Uint8Array, offset: number, value: bigint): void {\n for (let i = 0; i < 8; i++) {\n buf[offset + i] = Number((value >> BigInt(i * 8)) & 0xffn);\n }\n}\n\nasync function sendSolanaTransfer(\n cfg: SolanaTransferConfig,\n params: SendTransferParams,\n amount: bigint\n): Promise<SendTransferResult> {\n const payerSeed = cfg.keypair.slice(0, 32);\n const payerPubkey = base58Encode(\n new Uint8Array(ed25519.getPublicKey(payerSeed))\n );\n const payer = { publicKey: base58Decode(payerPubkey), privateKey: payerSeed };\n const timeoutMs =\n params.confirmTimeoutMs ?? DEFAULT_SOLANA_CONFIRM_TIMEOUT_MS;\n // Bound ONCE, and used for every call below — the sends and the balance reads\n // alike. A read left on the bare URL would be the one chain-touching operation\n // that still announced this wallet on clearnet, beside a transfer that did not\n // (ADR 0002), which is exactly the correlation the overlay exists to prevent.\n const rpc = solanaRpcTarget(cfg);\n\n if (params.asset === 'native') {\n const lamports = await getLamports(rpc, payerPubkey);\n const need = amount + SOLANA_LAMPORTS_PER_SIGNATURE;\n if (lamports < need) {\n throw new InsufficientBalanceError(\n `Solana wallet ${payerPubkey} holds ${lamports} lamports, short of the ${amount}-lamport ` +\n `transfer plus the ${SOLANA_LAMPORTS_PER_SIGNATURE}-lamport signature fee.`\n );\n }\n const readDest = () => getLamports(rpc, params.to);\n const before = await readDest();\n\n // SystemProgram::Transfer — Borsh enum: u32 LE variant(2) + u64 LE lamports.\n const data = new Uint8Array(12);\n new DataView(data.buffer).setUint32(0, 2, true);\n writeU64LE(data, 4, amount);\n\n const txHash = await buildAndSendTransaction(rpc, payer, [\n {\n programId: SOLANA_SYSTEM_PROGRAM_ID,\n keys: [\n { pubkey: payerPubkey, isSigner: true, isWritable: true },\n { pubkey: params.to, isSigner: false, isWritable: true },\n ],\n data,\n },\n ]);\n\n const after = await confirmDelivered({\n readBalance: readDest,\n before,\n amount,\n timeoutMs,\n pollIntervalMs: params.confirmPollIntervalMs,\n notDeliveredMessage: (delta) =>\n `Solana native transfer ${txHash} confirmed on-chain, but ${params.to}'s balance only rose by ` +\n `${delta} lamports (expected ${amount}) within the wait window — the devnet ` +\n `faucet's Solana leg has shown exactly this shape (connector#691): a real transaction ` +\n `signature with 0 lamports delivered.`,\n });\n return buildResult(\n 'solana',\n 'native',\n params.to,\n amount,\n txHash,\n before,\n after\n );\n }\n\n // Settlement token (SPL).\n if (!cfg.tokenMint) {\n throw new TransferUnsupportedError(\n 'No settlement-token mint configured for Solana — cannot send the token leg.'\n );\n }\n const senderAta = deriveAssociatedTokenAccount(payerPubkey, cfg.tokenMint);\n const senderBalance = await getTokenAccountBalance(rpc, senderAta);\n if (senderBalance === null || senderBalance < amount) {\n throw new InsufficientBalanceError(\n `Solana token account ${senderAta} holds ${senderBalance ?? 0n} base units of ${cfg.tokenMint}, ` +\n `short of the ${amount} transfer.`\n );\n }\n const lamports = await getLamports(rpc, payerPubkey);\n if (lamports < SOLANA_LAMPORTS_PER_SIGNATURE) {\n throw new InsufficientBalanceError(\n `Solana wallet ${payerPubkey} holds ${lamports} lamports, below the ` +\n `${SOLANA_LAMPORTS_PER_SIGNATURE}-lamport fee this token transfer needs.`\n );\n }\n\n const destAta = deriveAssociatedTokenAccount(params.to, cfg.tokenMint);\n const readDest = async () =>\n (await getTokenAccountBalance(rpc, destAta)) ?? 0n;\n const before = await readDest();\n\n // Associated-Token-Account \"CreateIdempotent\" (variant 1, no-op if it\n // already exists) — a freshly-derived agent address has no token account\n // yet, so the destination ATA must be created before it can receive SPL\n // tokens. Idempotent so this never fails on an already-funded destination.\n const createAtaIx = {\n programId: SOLANA_ASSOCIATED_TOKEN_PROGRAM_ID,\n keys: [\n { pubkey: payerPubkey, isSigner: true, isWritable: true },\n { pubkey: destAta, isSigner: false, isWritable: true },\n { pubkey: params.to, isSigner: false, isWritable: false },\n { pubkey: cfg.tokenMint, isSigner: false, isWritable: false },\n { pubkey: SOLANA_SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: SOLANA_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n ],\n data: new Uint8Array([1]),\n };\n\n // SPL Token \"Transfer\" (variant 3): u8 tag + u64 LE amount.\n const transferData = new Uint8Array(9);\n transferData[0] = 3;\n writeU64LE(transferData, 1, amount);\n const transferIx = {\n programId: SOLANA_TOKEN_PROGRAM_ID,\n keys: [\n { pubkey: senderAta, isSigner: false, isWritable: true },\n { pubkey: destAta, isSigner: false, isWritable: true },\n { pubkey: payerPubkey, isSigner: true, isWritable: false },\n ],\n data: transferData,\n };\n\n const txHash = await buildAndSendTransaction(rpc, payer, [\n createAtaIx,\n transferIx,\n ]);\n\n const after = await confirmDelivered({\n readBalance: readDest,\n before,\n amount,\n timeoutMs,\n pollIntervalMs: params.confirmPollIntervalMs,\n notDeliveredMessage: (delta) =>\n `Solana token transfer ${txHash} confirmed on-chain, but ${destAta}'s balance only rose by ` +\n `${delta} base units (expected ${amount}) within the wait window (connector#691 shape).`,\n });\n return buildResult('solana', 'token', params.to, amount, txHash, before, after);\n}\n\n// ---------------------------------------------------------------------------\n// Dispatch\n// ---------------------------------------------------------------------------\n\n/**\n * Send `params.amount` base units of `params.asset` to `params.to` on\n * `params.chain`, using whichever chain config in `config` matches. Confirms\n * delivery by re-reading the destination's balance (see module docs) rather\n * than trusting the send call's own success signal.\n *\n * @throws {UnknownChainError} `params.chain` is unrecognized, or this client\n * has no configuration for it.\n * @throws {InvalidAddressError} `params.to` is malformed for the chain.\n * @throws {InsufficientBalanceError} the sender cannot cover the amount\n * (plus fees, where applicable) — checked before anything is submitted.\n * @throws {TransferNotDeliveredError} the send was accepted (a landed,\n * non-reverted transaction / a node-accepted payment) but the destination\n * balance never reflected it within the wait window.\n * @throws {TransferUnsupportedError} this chain/asset combination has no\n * configuration on this client — an `asset: 'token'` send with no token\n * address or mint given for the chain.\n */\nexport async function sendTransfer(\n config: TransferConfig,\n params: SendTransferParams\n): Promise<SendTransferResult> {\n const amount =\n typeof params.amount === 'string' ? BigInt(params.amount) : params.amount;\n if (amount <= 0n) {\n throw new ValidationError('sendTransfer: amount must be positive.');\n }\n\n switch (params.chain) {\n case 'evm': {\n if (!config.evm) {\n throw new UnknownChainError(\n 'sendTransfer: no EVM chain configured on this client (no RPC URL or no EVM key).'\n );\n }\n assertValidEvmAddress(params.to);\n return sendEvmTransfer(config.evm, params, amount);\n }\n case 'solana': {\n if (!config.solana) {\n throw new UnknownChainError(\n 'sendTransfer: no Solana chain configured on this client (no RPC URL, or no Solana key ' +\n '— construct the client from a mnemonic or pass solanaSecretKey).'\n );\n }\n assertValidSolanaAddress(params.to);\n return sendSolanaTransfer(config.solana, params, amount);\n }\n default:\n throw new UnknownChainError(\n `sendTransfer: unknown chain \"${String(params.chain)}\". Supported: evm, solana.`\n );\n }\n}\n","/**\n * Devnet faucet helper.\n *\n * The public TOON devnet runs a faucet that drips the settlement token (USDC)\n * to an address so a client can open a payment channel and pay for requests.\n * Both legs are USDC-only: they fund the token and assume the wallet already\n * holds enough native gas to transact.\n *\n * EVM `POST {faucetUrl}/api/base-sepolia/request` body `{ address }`\n * Solana `POST {faucetUrl}/api/solana/usdc-request` body `{ address }`\n *\n * The request shape is identical on both; only the path differs. The EVM leg\n * mints devnet USDC (Circle FiatToken v2.2; the faucet key is its minter) on\n * Base Sepolia and best-effort tops up gas; the\n * **Solana leg drips USDC and no SOL**, so a Solana wallet needs devnet SOL\n * from somewhere else (`solana airdrop`) before it can pay for a transaction.\n *\n * Devnet edge today: `https://faucet.devnet.toonprotocol.dev`. `GET /api/info`\n * on the same host reports what it is configured to drip.\n */\n\nimport { NetworkError } from '../client/errors.js';\nimport { trimTrailingSlashes } from '../utils/url.js';\n\n/** Supported faucet chains. */\nexport type FaucetChain = 'evm' | 'solana';\n\n/** Result of a successful faucet drip. */\nexport interface FundWalletResult {\n /** The chain that was funded. */\n chain: FaucetChain;\n /** The funded address (echoed back). */\n address: string;\n /** Raw parsed JSON body from the faucet (shape is faucet-defined). */\n response: unknown;\n}\n\n/** Options for {@link fundWallet}. */\nexport interface FundWalletOptions {\n /** Custom fetch implementation (for testing / custom transports). */\n fetchImpl?: typeof fetch;\n /**\n * Request timeout in milliseconds. Defaults to {@link defaultFaucetTimeout}\n * for the chain.\n */\n timeout?: number;\n}\n\n/**\n * Default faucet request timeout (ms) for a chain. Both legs mint or transfer\n * on a fast chain and answer in a few seconds, so 30s is ample; the parameter\n * stays per-chain so a slower leg can be given its own budget without changing\n * a caller.\n */\nexport function defaultFaucetTimeout(_chain: FaucetChain): number {\n return 30000;\n}\n\n/**\n * Map a chain to its USDC-only faucet request path. Each leg funds USDC and\n * assumes the address already holds native gas (the EVM leg still best-effort\n * tops up Base Sepolia ETH, but does not depend on it).\n */\nfunction faucetPath(chain: FaucetChain): string {\n switch (chain) {\n case 'evm':\n return '/api/base-sepolia/request';\n case 'solana':\n return '/api/solana/usdc-request';\n }\n}\n\n/**\n * Drip test funds to `address` on `chain` from the devnet `faucetUrl`.\n *\n * @param faucetUrl - Faucet base URL, e.g. `https://faucet.devnet.toonprotocol.dev`.\n * A trailing `/` is tolerated.\n * @param address - The chain address to fund (EVM `0x…`, or Solana base58).\n * @param chain - `'evm'` or `'solana'`. Both live on the devnet faucet.\n * @throws {Error} If `faucetUrl` or `address` is missing.\n * @throws {NetworkError} On transport failure or a non-2xx faucet response.\n */\nexport async function fundWallet(\n faucetUrl: string,\n address: string,\n chain: FaucetChain,\n options: FundWalletOptions = {}\n): Promise<FundWalletResult> {\n if (!faucetUrl) {\n throw new Error('fundWallet: faucetUrl is required');\n }\n if (!address) {\n throw new Error('fundWallet: address is required');\n }\n\n const base = trimTrailingSlashes(faucetUrl);\n const url = `${base}${faucetPath(chain)}`;\n const fetchImpl = options.fetchImpl ?? fetch;\n const timeout = options.timeout ?? defaultFaucetTimeout(chain);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n let response: Response;\n try {\n response = await fetchImpl(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ address }),\n signal: controller.signal,\n });\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new NetworkError(\n `Faucet request timed out after ${timeout}ms (${url})`,\n error\n );\n }\n throw new NetworkError(\n `Faucet request failed (${url}): ${\n error instanceof Error ? error.message : String(error)\n }`,\n error instanceof Error ? error : undefined\n );\n } finally {\n clearTimeout(timeoutId);\n }\n\n if (!response.ok) {\n const detail = await response.text().catch(() => '');\n throw new NetworkError(\n `Faucet responded ${response.status} ${response.statusText}${\n detail ? `: ${detail}` : ''\n } (${url})`\n );\n }\n\n // The faucet returns JSON; tolerate an empty/non-JSON body (some faucets\n // return `204`/plain text on success).\n const body = await response.text().catch(() => '');\n let parsed: unknown = body;\n if (body) {\n try {\n parsed = JSON.parse(body);\n } catch {\n parsed = body;\n }\n }\n\n return { chain, address, response: parsed };\n}\n","import { privateKeyToAccount, type PrivateKeyAccount } from 'viem/accounts';\nimport { type Hex, toHex } from 'viem';\n\n/**\n * An EVM key, held as a viem account: what signs this client's vouchers,\n * challenges, deposit authorizations and on-chain transactions.\n *\n * Encapsulates the private key — no getPrivateKey() method is exposed. What it\n * signs is decided elsewhere (`../channel/batch-settlement/`); since connector\n * ADR 0075 there is no balance proof left for it to sign.\n */\nexport class EvmSigner {\n readonly chainType = 'evm' as const;\n private readonly _account: PrivateKeyAccount;\n\n /**\n * @param privateKey - EVM private key as hex string (with or without 0x prefix) or Uint8Array\n */\n constructor(privateKey: string | Uint8Array) {\n let hexKey: Hex;\n if (privateKey instanceof Uint8Array) {\n hexKey = toHex(privateKey);\n } else {\n hexKey = (privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`) as Hex;\n }\n this._account = privateKeyToAccount(hexKey);\n }\n\n /** Derived 0x EVM address */\n get address(): string {\n return this._account.address;\n }\n\n /** Viem PrivateKeyAccount — usable with walletClient for on-chain transactions, and to sign typed data */\n get account(): PrivateKeyAccount {\n return this._account;\n }\n}\n","/**\n * Chain reads and transfers that have nothing to do with paying a connector.\n *\n * A payment channel is collateralised from an ordinary wallet, so a client that\n * could pay a connector but could not tell you what it holds, or move funds to\n * the address that needs them, is missing the half of the job the user does. None\n * of this touches the client edge: no connector is asked, nothing is sealed, and\n * no claim is signed.\n *\n * The settlement facts each read needs — which token, at what address, on which\n * chain — come from the connector's own `GET /ilp` rather than from a preset,\n * for the same reason everything else does: the node proved them against a live\n * chain at boot (`self-description-spec.md` ND-07), and a preset that disagreed\n * would report a balance in the wrong token without saying so.\n */\nimport { readWalletBalances, type WalletChainBalances } from '../wallet/balances.js';\nimport { sendTransfer, type SendTransferParams, type SendTransferResult } from '../wallet/transfer.js';\nimport { fundWallet, type FundWalletResult } from '../wallet/faucet.js';\nimport type { ChainKind, WalletFacade } from './types.js';\nimport type { NodeSelfDescription } from '../connector/self-description.js';\nimport { EvmSigner } from '../signing/evm-signer.js';\nimport { ChainUnavailableError, ConfigError, chainUnavailableMessage } from './errors.js';\nimport type { ResolvedConfig } from './config.js';\n\nexport interface WalletFacadeDeps {\n config: ResolvedConfig;\n /** The node's `GET /ilp`, cached — the source of every token address read here. */\n describe: () => Promise<NodeSelfDescription>;\n}\n\n/**\n * The `fetch` this client's SOLANA JSON-RPC should dial through.\n *\n * With no proxy that is `config.fetch`: the caller's own if they injected one,\n * and otherwise the global. With one, `chainRpc` is the single signal for \"chain\n * RPC rides the proxy\" (ADR 0002), on Solana's own circuit. `proxyRpc: false`\n * clears it, and the Solana reads then leave the proxy with the EVM ones. A\n * payer who opted out because their node is on loopback would otherwise still\n * be dialling it through a circuit that cannot reach loopback at all.\n */\nfunction solanaRpcFetch(config: ResolvedConfig): typeof fetch {\n if (config.socksProxy === undefined) return config.fetch;\n return config.chainRpc?.solana.fetch ?? globalThis.fetch;\n}\n\n/** The EVM dispatcher chain RPC rides, when it rides the proxy at all. */\nfunction evmRpcDispatcher(config: ResolvedConfig): { rpcDispatcher: unknown } | Record<string, never> {\n return config.chainRpc !== undefined ? { rpcDispatcher: config.chainRpc.evm.dispatcher } : {};\n}\n\n/** One chain's settlement token, as the node's x402 terms name it. */\ninterface SettlementToken {\n kind: ChainKind;\n chain: string;\n tokenAddress: string;\n}\n\nexport class ClientWalletFacade implements WalletFacade {\n private readonly deps: WalletFacadeDeps;\n private evmSigner: EvmSigner | undefined;\n\n constructor(deps: WalletFacadeDeps) {\n this.deps = deps;\n }\n\n /**\n * Native coin plus the connector's settlement token, per chain.\n *\n * Best effort per chain and per asset: a chain whose RPC is unreachable comes\n * back `unreadable` rather than failing the others, because a user with a\n * flaky Solana endpoint should still be told their EVM balance. `chain` narrows\n * the read to one.\n */\n async balances(chain?: ChainKind): Promise<WalletChainBalances[]> {\n const { config } = this.deps;\n const settlements = await this.settlements();\n\n const wanted: ChainKind[] = chain !== undefined ? [chain] : ['evm', 'solana'];\n const sources: Parameters<typeof readWalletBalances>[0] = {\n fetchImpl: solanaRpcFetch(config),\n ...(config.chainRpc !== undefined ? { solanaProxied: true } : {}),\n };\n\n for (const kind of wanted) {\n const entry = settlements.get(kind);\n if (kind === 'evm' && config.identity.evm) {\n sources.evm = {\n chainKey: entry?.chain ?? 'evm',\n rpcUrl: config.rpcUrls.evm,\n owner: config.identity.evm.address,\n ...evmRpcDispatcher(config),\n ...(entry?.tokenAddress ? { tokenAddress: entry.tokenAddress } : {}),\n };\n }\n if (kind === 'solana' && config.identity.solana) {\n sources.solana = {\n ...(entry?.chain ? { chainKey: entry.chain } : {}),\n rpcUrl: config.rpcUrls.solana,\n owner: config.identity.solana.publicKey,\n ...(entry?.tokenAddress ? { tokenMint: entry.tokenAddress } : {}),\n };\n }\n }\n\n if (sources.evm === undefined && sources.solana === undefined) {\n throw new ChainUnavailableError(\n chainUnavailableMessage(chain, [...settlements.keys()], 'no-key'),\n [...settlements.keys()]\n );\n }\n return readWalletBalances(sources);\n }\n\n /**\n * Move funds to another address.\n *\n * Delivery is CONFIRMED, not assumed: the destination's balance is polled until\n * it rises by the sent amount, because a landed transaction is not the same\n * fact as a delivered one — the devnet faucet's Solana leg has been observed\n * returning a real signature while delivering nothing\n * (toon-protocol/connector#691).\n */\n async transfer(params: SendTransferParams): Promise<SendTransferResult> {\n const { config } = this.deps;\n const settlements = await this.settlements();\n const entry = settlements.get(params.chain);\n\n return sendTransfer(\n {\n ...(config.identity.evm\n ? {\n evm: {\n chainKey: entry?.kind === 'evm' ? entry.chain : 'evm',\n rpcUrl: config.rpcUrls.evm,\n signer: this.signer(),\n ...evmRpcDispatcher(config),\n ...(entry?.tokenAddress ? { tokenAddress: entry.tokenAddress } : {}),\n },\n }\n : {}),\n ...(config.identity.solana\n ? {\n solana: {\n rpcUrl: config.rpcUrls.solana,\n ...(config.chainRpc !== undefined ? { rpcFetch: config.chainRpc.solana.fetch } : {}),\n keypair: config.identity.solana.secretKey,\n ...(entry?.tokenAddress ? { tokenMint: entry.tokenAddress } : {}),\n },\n }\n : {}),\n },\n params\n );\n }\n\n /**\n * Ask the devnet faucet for test funds. **Devnet only** — there is no mainnet\n * equivalent and there never will be.\n *\n * Defaults to the chain the client settles on, so `faucet()` funds the wallet\n * that is about to open a channel rather than an unrelated one.\n */\n async faucet(chain?: ChainKind): Promise<FundWalletResult> {\n const { config } = this.deps;\n const target = chain ?? (await this.defaultChain());\n const address =\n target === 'evm' ? config.identity.evm?.address : config.identity.solana?.publicKey;\n if (address === undefined) {\n throw new ChainUnavailableError(\n `This client holds no ${target} key, so there is no address to fund.`,\n []\n );\n }\n return fundWallet(config.faucetUrl, address, target, { fetchImpl: config.fetch });\n }\n\n // ─── Private ──────────────────────────────────────────────────────────────\n\n /**\n * The node's settlement token per chain family, from its x402 terms: the\n * chain key (`evm:<chainId>` / `solana`, the spelling the balance and\n * transfer code key an RPC by) and the token address or mint.\n */\n private async settlements(): Promise<Map<ChainKind, SettlementToken>> {\n const description = await this.deps.describe();\n const byKind = new Map<ChainKind, SettlementToken>();\n for (const terms of description.batchSettlements) {\n if (byKind.has(terms.chain)) continue;\n byKind.set(terms.chain, {\n kind: terms.chain,\n chain:\n terms.chain === 'evm' ? `evm:${terms.network.slice('eip155:'.length)}` : 'solana',\n tokenAddress: terms.asset,\n });\n }\n return byKind;\n }\n\n /** The chain this client would settle on, for a `faucet()` with no argument. */\n private async defaultChain(): Promise<ChainKind> {\n const { config } = this.deps;\n if (config.chain !== undefined) return config.chain;\n const settlements = await this.settlements();\n for (const kind of settlements.keys()) {\n if (config.identity[kind] !== undefined) return kind;\n }\n if (config.identity.evm) return 'evm';\n if (config.identity.solana) return 'solana';\n throw new ChainUnavailableError(\n chainUnavailableMessage(undefined, [...settlements.keys()], 'no-key'),\n [...settlements.keys()]\n );\n }\n\n /** The EVM transaction signer, built once and only when a transfer needs one. */\n private signer(): EvmSigner {\n if (this.evmSigner) return this.evmSigner;\n const key = this.deps.config.identity.evm?.privateKey;\n if (key === undefined) {\n throw new ConfigError('This client holds no EVM key, so it cannot sign an EVM transaction.');\n }\n this.evmSigner = new EvmSigner(key);\n return this.evmSigner;\n }\n}\n","/**\n * The client: one object that knows a connector, holds the keys, and pays.\n *\n * Deliberately thin. It wires — {@link ./send.js!send} performs a request,\n * {@link ./channel-facade.js!ClientChannelFacade} owns the channels and\n * {@link ./wallet-facade.js!ClientWalletFacade} owns the wallet — and what it\n * contributes is the small set of decisions that must be made once and shared:\n * which chain, which carriage, which key labels a claim, and where the cached\n * self-description lives.\n *\n * ## What `create` does, and what it refuses to do\n *\n * It resolves the configuration, derives the keys, opens the channel store, and\n * makes exactly **one** free network call: `GET /ilp`, the node's\n * self-description. That call is the whole of bootstrapping — there is no\n * discovery, no relay and no peer list (connector ADR 0050) — and it is what\n * settles the chain to pay on, since the node's own `batchSettlements[]` is the\n * authority (`self-description-spec.md` ND-07) and a preset is not.\n *\n * It does **not** touch a chain. No RPC connection is opened, no channel is read\n * and certainly none is opened: a deposit locks the user's money, and a\n * constructor is not where that belongs. The first chain access happens when\n * something explicitly asks for it — `channel.open()`, or a `send()` on a client\n * left with the default `autoOpenChannel: true`.\n */\nimport { ConnectorEdgeClient, decodeConnectorPublicKey } from '../connector/ConnectorEdgeClient.js';\nimport type {\n ClaimStateOk,\n ClaimStateResult,\n ConnectorRoutePrice,\n} from '../connector/ConnectorEdgeClient.js';\nimport {\n defaultDestinationFor,\n requiredTransportFor,\n type NodeSelfDescription,\n} from '../connector/self-description.js';\nimport { selectTransport } from '../btp/transport-select.js';\nimport { isHiddenServiceUrl } from '../transport/hs-hostname.js';\nimport { HttpIlpClient } from '../http/HttpIlpClient.js';\nimport { BtpRuntimeClient, type BtpChannelDeclaration } from '../btp/BtpRuntimeClient.js';\nimport { BtpPaidWriteTransport } from '../btp/BtpPaidWriteTransport.js';\n\nimport { sealExchange } from '../wire/sealed-exchange.js';\nimport { toBase64 } from '../utils/binary.js';\nimport { resolveConfig, addressFor, type ResolvedConfig } from './config.js';\nimport { ClientChannelFacade } from './channel-facade.js';\nimport { ClientWalletFacade } from './wallet-facade.js';\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { createPublicClient, toHex } from 'viem';\nimport { rpcTransport } from '../transport/rpc.js';\nimport type { ContractReader } from '../channel/batch-settlement/evm.js';\nimport { evmWalletAccess } from '../channel/batch-settlement/deposit-gas.js';\nimport { BatchSettlementPayer } from '../channel/batch-settlement/payer.js';\nimport { base58Decode } from '../utils/base58.js';\nimport { BatchChannelManager } from '../channel/batch-settlement/manager.js';\nimport { send, type PaidWriteTransport, type SendContext } from './send.js';\nimport {\n ChainUnavailableError,\n ChannelNotOpenError,\n ConfigError,\n chainUnavailableMessage,\n} from './errors.js';\nimport type {\n ChainKind,\n ChannelFacade,\n SendOptions,\n SendRequest,\n SendResult,\n ToonClientConfig,\n ToonClientLike,\n ToonIdentity,\n WalletFacade,\n} from './types.js';\n\n/**\n * How long a voucher claim-state challenge stays valid, in seconds: well inside\n * the 300 s a connector allows a BTP `channelChallenge`.\n */\nconst CHALLENGE_TTL_SECONDS = 120;\n\nexport class ToonClient implements ToonClientLike {\n readonly connector: string;\n readonly chain: ChainKind;\n readonly identity: ToonIdentity;\n readonly channel: ChannelFacade;\n readonly wallet: WalletFacade;\n\n private readonly config: ResolvedConfig;\n private readonly edge: ConnectorEdgeClient;\n private readonly manager: BatchChannelManager;\n /** Where every paid packet's voucher comes from. */\n private readonly payer: BatchSettlementPayer;\n private description: NodeSelfDescription;\n /**\n * One live carriage per kind, not one per client.\n *\n * A node pins carriages **per route** (connector ADR 0072), so one client can\n * legitimately owe one destination a BTP session and another an HTTP one-shot.\n * Keying by kind keeps each carriage chosen once and reused — which is the\n * point of caching at all — without letting the first destination decide for\n * every later one.\n */\n private carriages: Partial<\n Record<'http' | 'btp', { kind: 'http' | 'btp'; transport: PaidWriteTransport }>\n > = {};\n private btpSession: BtpRuntimeClient | undefined;\n private readonly hiddenService: { close(): Promise<void> } | undefined;\n private closed = false;\n\n private constructor(init: {\n config: ResolvedConfig;\n edge: ConnectorEdgeClient;\n description: NodeSelfDescription;\n chain: ChainKind;\n senderId: string;\n /** The proxy-bound transport, when this client talks to a hidden service. */\n hiddenService?: { close(): Promise<void> };\n }) {\n this.config = init.config;\n this.hiddenService = init.hiddenService;\n this.edge = init.edge;\n this.description = init.description;\n this.chain = init.chain;\n this.connector = init.config.connector;\n this.identity = {\n ...(init.config.identity.evm ? { evmAddress: init.config.identity.evm.address } : {}),\n ...(init.config.identity.solana\n ? { solanaPublicKey: init.config.identity.solana.publicKey }\n : {}),\n senderId: init.senderId,\n };\n\n this.manager = new BatchChannelManager(init.config.channelStore);\n const chains = chainAccess(init.config);\n this.payer = new BatchSettlementPayer({\n connector: init.config.connector,\n manager: this.manager,\n deposit: init.config.deposit,\n ...(chains.evm !== undefined\n ? {\n evm: {\n account: chains.evm.account,\n ...(init.config.facilitatorUrl !== undefined\n ? { facilitatorUrl: init.config.facilitatorUrl }\n : {}),\n ...(init.config.depositMethod !== undefined\n ? { depositMethod: init.config.depositMethod }\n : {}),\n depositGas: init.config.depositGas,\n reader: lazyEvmReader(init.config),\n wallet: evmWalletAccess({\n rpcUrl: init.config.rpcUrls.evm,\n account: chains.evm.account,\n dispatcher: init.config.chainRpc?.evm.dispatcher,\n }),\n },\n }\n : {}),\n ...(chains.solana !== undefined ? { solana: chains.solana } : {}),\n fetch: init.config.fetch,\n autoOpen: init.config.autoOpenChannel,\n connectorWatermark: (entry) => this.connectorWatermark(entry),\n });\n this.channel = new ClientChannelFacade({\n connector: init.config.connector,\n payer: this.payer,\n chain: init.chain,\n manager: this.manager,\n describe: () => this.describe(),\n ...(chains.evm !== undefined\n ? {\n evm: {\n privateKey: chains.evm.privateKey,\n rpcUrl: init.config.rpcUrls.evm,\n rpcDispatcher: init.config.chainRpc?.evm.dispatcher,\n },\n }\n : {}),\n ...(chains.solana !== undefined ? { solana: chains.solana } : {}),\n });\n this.wallet = new ClientWalletFacade({\n config: init.config,\n describe: () => this.describe(),\n });\n }\n\n /**\n * Build a client: resolve the configuration, derive the keys, read the node's\n * self-description, and settle which chain to pay on.\n *\n * @throws {ConfigError} the configuration cannot produce a working client.\n * @throws {ChainUnavailableError} the node settles on no chain this client\n * holds a key for — checked here rather than at the first `send`, because it\n * is a permanent fact about this pairing and finding it out mid-request is\n * strictly worse.\n * @throws {NetworkError} the connector could not be reached.\n */\n static async create(config: ToonClientConfig): Promise<ToonClient> {\n const base = resolveConfig(config);\n // Before the first `GET`: a hidden-service connector is unreachable without\n // its proxy, and the very first thing this method does is dial. Building the\n // transport here also means `describe()` below already rides the overlay —\n // asking a node what it is must not be the request that exposes the asking.\n const hiddenService = await openHiddenService(base, config);\n const resolved = hiddenService?.config ?? base;\n const edge = new ConnectorEdgeClient({\n fetch: resolved.fetch,\n timeout: resolved.timeoutMs,\n });\n const description = await edge.describe(resolved.connector);\n const chain = pickChain(resolved, description);\n\n const senderId = resolved.senderId ?? addressFor(resolved.identity, chain);\n if (senderId === undefined) {\n throw new ConfigError(\n `This client holds no ${chain} key, so it has no address to label its ` +\n 'vouchers with. Supply a `mnemonic`, the raw key for that chain, or an ' +\n 'explicit `senderId`.'\n );\n }\n\n return new ToonClient({\n config: resolved,\n edge,\n description,\n chain,\n senderId,\n ...(hiddenService ? { hiddenService: hiddenService.transport } : {}),\n });\n }\n\n /**\n * The node's `GET /ilp`, cached for the life of this client.\n *\n * Cached because it is a description of a deployment, not a reading: the\n * settlement facts in it were proved against a live chain when the node booted\n * and do not change while it runs. `fresh` re-reads, which is what an operator\n * reconfiguring a node needs.\n */\n async describe(options: { fresh?: boolean } = {}): Promise<NodeSelfDescription> {\n if (options.fresh === true) {\n this.description = await this.edge.describe(this.connector, { forceRefresh: true });\n }\n return this.description;\n }\n\n /**\n * What `destination` costs at this node **before any per-size charge**, or\n * `null` when it prices no matching route.\n *\n * `null` is an ANSWER — \"I do not terminate that\" — and not a failure; a\n * connector that could not be asked throws instead, so the two are never\n * confused.\n *\n * A base price is flat per handler, but it is not always the whole bill: a\n * route may also publish a `pricePerKib` and meter by the size of the sealed\n * payload, in which case every packet costs strictly more than this figure.\n * {@link ToonClient.routePrice} reports both, and {@link ToonClient.send}\n * always pays the full charge without being asked.\n */\n async price(destination: string): Promise<bigint | null> {\n const result = await this.edge.getRoutePrice(this.connector, destination);\n return result === null ? null : result.price;\n }\n\n /**\n * The full terms for `destination` — base price and, when the route meters by\n * size, its per-kibibyte rate — or `null` when this node prices no matching\n * route.\n *\n * The counterpart to {@link ToonClient.price} for a caller who needs to know\n * what a packet will actually cost:\n * {@link ../connector/self-description.js!chargeFor} turns these terms plus a\n * sealed payload size into the figure that goes on the claim.\n */\n async routePrice(destination: string): Promise<ConnectorRoutePrice | null> {\n return this.edge.getRoutePrice(this.connector, destination);\n }\n\n /**\n * Learn what a path costs without buying the work behind it\n * (`client-edge-spec.md` §1.6, connector ADR 0011).\n *\n * A probe is free to traverse but not free to make: it must be identified by\n * a voucher on a channel this connector recognises, because free traversal\n * offered to anyone is an amplifier. It **identifies rather than pays**: the\n * latest voucher on the channel, resent byte for byte, is a retransmission\n * the connector accepts and records nothing for.\n *\n * @throws {ChannelNotOpenError} this client has not yet paid on a channel it\n * could identify with.\n */\n async probe(\n destination: string\n ): Promise<{ accumulatedCost: bigint; code: string; message: string }> {\n const current = await this.channel.current();\n const latest = current && this.manager.lastVoucher(current.channel.channelId);\n if (latest === undefined) {\n throw new ChannelNotOpenError(\n `a probe identifies with the latest voucher on a channel, and this client has not yet ` +\n `paid ${this.connector} on one — pay for one request first`\n );\n }\n\n const key = await this.sealKey(this.description);\n const exchange = sealExchange({ method: 'GET', target: '', headers: [], body: new Uint8Array(0) }, key);\n\n const result = await this.edge.probe(\n this.connector,\n {\n destination,\n amount: '0',\n data: toBase64(exchange.data),\n expectedFulfillment: exchange.fulfillment,\n timeout: this.config.timeoutMs,\n },\n JSON.parse(latest) as Record<string, unknown>\n );\n return {\n accumulatedCost: result.accumulatedCost ?? 0n,\n code: result.code ?? (result.accepted ? 'FULFILL' : 'F00'),\n message: result.message ?? '',\n };\n }\n\n /**\n * Pay for one HTTP request through this connector, and return what the app\n * said.\n *\n * The destination is **optional**: omit it and the packet goes to\n * {@link ToonClient.defaultDestination}, the address this node published for\n * itself. Configuring a client is then just a URL — the thing a person\n * actually has — and the route comes from the node rather than from a string\n * the caller copied out of a document.\n *\n * ```ts\n * const client = await ToonClient.create({ connector: 'https://…', mnemonic });\n * await client.send({ body: 'hello' }); // the node's own address\n * await client.send('g.toon.relay.store', { … }); // or name one yourself\n * ```\n *\n * A REJECT comes back as `{ fulfilled: false }` and is never thrown — see\n * {@link ./types.js!SendRefused}.\n *\n * @throws {ConfigError} the destination was omitted and this node published no\n * address to fall back on.\n */\n async send(request?: SendRequest, options?: SendOptions): Promise<SendResult>;\n async send(\n destination: string,\n request?: SendRequest,\n options?: SendOptions\n ): Promise<SendResult>;\n async send(\n destinationOrRequest?: string | SendRequest,\n requestOrOptions?: SendRequest | SendOptions,\n maybeOptions?: SendOptions\n ): Promise<SendResult> {\n // A destination is always a string and a request is always an object, so the\n // two forms are told apart without a sentinel.\n const named = typeof destinationOrRequest === 'string';\n const destination = named ? destinationOrRequest : this.defaultDestination;\n if (destination === undefined) {\n throw new ConfigError(\n `The connector at ${this.connector} published no \\`ilpAddresses\\`, so ` +\n 'there is no route to send to. Name one explicitly: ' +\n \"`send('g.example.route', { … })`.\"\n );\n }\n const request = (named ? requestOrOptions : destinationOrRequest) as SendRequest | undefined;\n const options = (named ? maybeOptions : requestOrOptions) as SendOptions | undefined;\n return send(this.sendContext(), destination, request ?? {}, options ?? {});\n }\n\n /**\n * Where {@link ToonClient.send} goes when the caller names no route: the first\n * address this node published for itself that it also prices.\n *\n * Read off the cached self-description, so it follows a\n * `describe({ fresh: true })`. `undefined` only from a node that claims no\n * address at all.\n */\n get defaultDestination(): string | undefined {\n return defaultDestinationFor(this.description);\n }\n\n /**\n * The connector's OWN watermark for channels this client controls\n * (`POST /ilp/claim-state`, `client-edge-spec.md` §1.10).\n *\n * The counterpart to `channel.channels()`, which reports what this client has\n * signed. The two agree unless a voucher was signed and never accepted, and\n * this is how a caller finds that out — the connector's figure is the one\n * that decides, so it is asked rather than derived.\n *\n * Control is proved with a voucher claim-state challenge: a signature by the\n * channel's voucher signer over a message DISTINCT from a voucher, so it\n * moves no value and can never be replayed as a payment.\n *\n * @param channelIds which channels to ask about; every channel this client\n * holds with the connector when omitted.\n */\n async claimState(channelIds?: string[]): Promise<ClaimStateResult[]> {\n const held = this.manager\n .channels(this.connector)\n .map((c) => c.channel)\n .filter((c) => channelIds === undefined || channelIds.includes(c.channelId));\n if (held.length === 0) return [];\n const expires = BigInt(Math.floor(Date.now() / 1000) + CHALLENGE_TTL_SECONDS);\n const entries = await Promise.all(held.map((c) => this.payer.challenge(c, expires)));\n return this.edge.getClaimState(this.connector, entries);\n }\n\n /**\n * Release the BTP session and stop using this client.\n *\n * Does **not** touch the channel: leaving a channel is an on-chain\n * transaction that starts a withdrawal window measured in hours, and\n * conflating it with releasing a socket would pull a user's deposit because\n * their script ended. `channel.close()` is that operation, and it is\n * deliberately spelled differently.\n *\n * The channel store is written through on every voucher, so there is no flush\n * to perform here — the watermark is already durable when this is called.\n */\n async close(): Promise<void> {\n this.closed = true;\n const session = this.btpSession;\n this.btpSession = undefined;\n this.carriages = {};\n if (session) await session.disconnect();\n // The dispatcher pools connections; without this a hidden-service client\n // holds circuits open and the process does not exit.\n if (this.hiddenService) await this.hiddenService.close();\n }\n\n // ─── Private ──────────────────────────────────────────────────────────────\n\n /**\n * Refuse an endpoint this client has no way to dial.\n *\n * A node's endpoints are its own strings, and a hidden-service node may publish\n * absolute `.anyone` ones. The configured client edge always wins on *whether*\n * we can reach the node — but a carriage resolved from the description can\n * still point somewhere the configured transport cannot go. Without a proxy\n * that address does not merely fail: the hostname goes out in a plaintext DNS\n * query first, which is precisely what a hidden service exists to prevent. So\n * this fails loudly, naming the proxy, before anything dials.\n */\n private assertEndpointReachable(endpoint: string): void {\n if (this.config.socksProxy !== undefined) return;\n if (!isHiddenServiceUrl(endpoint)) return;\n throw new ConfigError(\n `The connector published the endpoint ${JSON.stringify(endpoint)}, which is a ` +\n 'hidden service, but this client has no `socksProxy` to reach it through. ' +\n 'Set one to a running Anyone Protocol `anon` daemon (e.g. ' +\n '\"socks5h://127.0.0.1:9050\"), or ask the operator for a clearnet endpoint.'\n );\n }\n\n /** The port {@link send} runs against. */\n private sendContext(): SendContext {\n return {\n describe: () => this.describe(),\n sealKey: (description) => this.sealKey(description),\n sealKeyAt: (endpoint) => this.sealKeyAt(endpoint),\n routePrice: (destination) => this.routePrice(destination),\n vouchers: this.payer,\n transport: (description, destination) => this.transportFor(description, destination),\n chain: this.chain,\n timeoutMs: this.config.timeoutMs,\n };\n }\n\n /**\n * The key to seal a payload to.\n *\n * The self-description carries it (`edgeIdentity.publicKey`), which is one\n * fewer round trip; `GET /ilp/identity` is the fallback for a node whose\n * document omits it. Without a key a packet cannot be formed at all\n * (`self-description-spec.md` ND-06), so a node that publishes neither is\n * unusable rather than degraded.\n */\n private async sealKey(description: NodeSelfDescription): Promise<Uint8Array> {\n const published = description.edgeIdentity?.publicKey;\n if (published !== undefined) return decodeConnectorPublicKey(published);\n return this.sealKeyAt(this.connector);\n }\n\n /** The sealing key of a node named by its client-edge URL. */\n private async sealKeyAt(endpoint: string): Promise<Uint8Array> {\n const identity = await this.edge.getIdentity(endpoint);\n return identity.publicKey;\n }\n\n /**\n * The connector's own watermark for one channel, asked with its voucher\n * claim-state challenge — `undefined` when the connector cannot verify it\n * (`\"unverified\"` covers \"no such channel\" and \"bad signature\" alike, and\n * neither is a watermark).\n */\n private async connectorWatermark(entry: Record<string, unknown>): Promise<bigint | undefined> {\n const [answer] = await this.edge.getClaimState(this.connector, [entry]);\n return answer?.ok === true ? BigInt((answer as ClaimStateOk).cumulativeClaimed) : undefined;\n }\n\n /**\n * The carriage for `destination`, chosen once per kind and then reused.\n *\n * Reuse matters for BTP specifically: the whole reason to prefer it is that one\n * ordered socket cannot race its own claim nonces into `F01 NonceNotAdvancing`\n * (`client-edge-spec.md` §1.9), and a session rebuilt per request would give\n * that up while paying for the handshake.\n *\n * `destination` is what lets the node's **per-route** pin decide, rather than\n * only its node-wide summary — which is silent on any node that pins one of\n * its own addresses and not another (TOON_Network#111). The choice is made\n * before the first packet, so a pinned route is dialled correctly on the first\n * attempt and never learns its carriage from a refusal.\n */\n private async transportFor(\n description: NodeSelfDescription,\n destination?: string\n ): Promise<{\n kind: 'http' | 'btp';\n transport: PaidWriteTransport;\n }> {\n if (this.closed) {\n throw new ConfigError('This client has been closed; construct a new one to send again.');\n }\n\n const choice = selectTransport(description, this.config.transport, undefined, destination);\n const cached = this.carriages[choice.kind];\n if (cached) return cached;\n const httpEndpoint =\n choice.kind === 'http' ? choice.url : httpEndpointOf(description, this.connector);\n this.assertEndpointReachable(choice.url);\n this.assertEndpointReachable(httpEndpoint);\n const http = new HttpIlpClient({\n httpEndpoint,\n timeout: this.config.timeoutMs,\n httpClient: this.config.fetch,\n ...(this.config.createWebSocket\n ? { createWebSocket: this.config.createWebSocket as (url: string) => WebSocket }\n : {}),\n });\n\n if (choice.kind === 'http') {\n const carriage = { kind: 'http' as const, transport: http };\n this.carriages.http = carriage;\n return carriage;\n }\n\n const session = new BtpRuntimeClient({\n btpUrl: choice.url,\n // The client edge resolves a PRESENTED identity before it looks at the\n // route and answers `401` when it cannot authenticate one, so an anonymous\n // peer plus a valid claim is the supported permissionless path.\n peerId: this.identity.senderId,\n authToken: '',\n ...(this.config.btp.maxReconnectAttempts !== undefined\n ? { maxRetries: this.config.btp.maxReconnectAttempts }\n : {}),\n ...(this.config.btp.reconnectDelay !== undefined\n ? { retryDelay: this.config.btp.reconnectDelay }\n : {}),\n ...(this.config.createWebSocket\n ? { createWebSocket: this.config.createWebSocket as (url: string) => WebSocket }\n : {}),\n ...(this.config.btp.declareChannel\n ? { getChannelDeclaration: () => this.channelDeclaration() }\n : {}),\n });\n this.btpSession = session;\n\n const carriage = {\n kind: 'btp' as const,\n transport: new BtpPaidWriteTransport({\n session,\n // HTTP fallback only where the node did not REQUIRE btp *for this\n // destination*: falling back onto a carriage the route refuses would\n // turn a recoverable socket outage into a `402` per request. Read\n // through the same per-route resolution the choice above was made with,\n // so the fallback cannot be enabled against a route the node-wide field\n // happens not to describe (TOON_Network#111).\n ...(requiredTransportFor(description, destination) === 'btp' ? {} : { fallback: http }),\n ...(this.config.btp.maxReconnectAttempts !== undefined\n ? { maxReconnectAttempts: this.config.btp.maxReconnectAttempts }\n : {}),\n ...(this.config.btp.reconnectDelay !== undefined\n ? { reconnectDelay: this.config.btp.reconnectDelay }\n : {}),\n }),\n };\n this.carriages.btp = carriage;\n return carriage;\n }\n\n /**\n * Declare the channel this client pays from on the BTP auth frame, as a\n * voucher claim-state challenge (`channelChallenge`, ADR 0075), binding the\n * session to it before it has presented a voucher. `undefined` — no channel\n * yet — leaves the auth frame without one.\n */\n private async channelDeclaration(): Promise<BtpChannelDeclaration | undefined> {\n const current = await this.channel.current();\n if (current === undefined) return undefined;\n const expires = BigInt(Math.floor(Date.now() / 1000) + CHALLENGE_TTL_SECONDS);\n return this.payer.challenge(current.channel, expires);\n }\n}\n\n/**\n * Which chain this client will pay on: the caller's choice when they made one,\n * else the first chain the node offers an x402 channel on that this client\n * holds a key for.\n *\n * The node's ORDER is the preference order — it published these, and the first\n * one it lists is the one it expects to be paid on.\n */\nfunction pickChain(config: ResolvedConfig, description: NodeSelfDescription): ChainKind {\n const offers = description.batchSettlements;\n const offered = offers.map((t) => t.network);\n if (offers.length === 0) {\n throw new ChainUnavailableError(chainUnavailableMessage(config.chain, offered, 'none'), offered);\n }\n if (config.chain !== undefined) {\n if (!offers.some((t) => t.chain === config.chain)) {\n throw new ChainUnavailableError(\n chainUnavailableMessage(config.chain, offered, 'not-offered'),\n offered\n );\n }\n return config.chain;\n }\n const match = offers.find((t) => config.identity[t.chain] !== undefined);\n if (!match) {\n throw new ChainUnavailableError(chainUnavailableMessage(undefined, offered, 'no-key'), offered);\n }\n return match.chain;\n}\n\n/**\n * The `POST /ilp` URL, for the HTTP fallback beneath a BTP session.\n *\n * Falls back to the client-edge base plus `/ilp` when the node published no\n * `httpEndpoint`: the fallback is only ever *tried* when BTP has already failed,\n * so a guess that turns out to be wrong costs one failed request rather than\n * suppressing a working carriage.\n */\nfunction httpEndpointOf(description: NodeSelfDescription, connector: string): string {\n const published = description.httpEndpoint;\n if (published === undefined) return `${connector}/ilp`;\n return /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(published)\n ? published\n : new URL(published, connector).toString();\n}\n\n/**\n * Builds everything that rides the proxy, or returns `undefined` when there is\n * no proxy.\n *\n * That is the client edge (`fetch`), the BTP socket (`createWebSocket`) and,\n * unless `proxyRpc` is `false`, each chain's RPC on a circuit of its own. It is\n * the same whether the connector is a `.anyone` hidden service or a clearnet\n * host. In the second case the payer is the one hiding, and a single byte sent\n * around the proxy would name it (TOON_Network#167).\n *\n * The import is dynamic on purpose: `../transport/socks.js` reaches for\n * `node:module` on its first line, and this module is bundled for browsers too.\n *\n * An explicitly injected `fetch` or `createWebSocket` wins over the proxy's for\n * the client edge. A caller who supplied their own transport has said something\n * specific about how bytes leave this process, and silently replacing it would\n * be a worse surprise than an unproxied request they chose. Chain RPC never\n * uses an injected `fetch` under a proxy: it rides its own circuit, or dials\n * directly only because `proxyRpc: false` said so.\n */\nasync function openHiddenService(\n resolved: ResolvedConfig,\n config: ToonClientConfig\n): Promise<{ config: ResolvedConfig; transport: { close(): Promise<void> } } | undefined> {\n const socksProxy = resolved.socksProxy;\n if (socksProxy === undefined) return undefined;\n\n const { createChainRpcTransport, createHiddenServiceTransport, probeSocks5Proxy } =\n await import('../transport/socks.js');\n // Fail closed, and fail now. A missing daemon discovered at packet time costs\n // a signed claim; discovered here it costs nothing.\n await probeSocks5Proxy(socksProxy);\n const edge = createHiddenServiceTransport(socksProxy);\n const rpc = resolved.proxyRpc\n ? {\n evm: createChainRpcTransport(socksProxy, 'evm'),\n solana: createChainRpcTransport(socksProxy, 'solana'),\n }\n : undefined;\n\n return {\n transport: {\n async close(): Promise<void> {\n await Promise.all([edge.close(), rpc?.evm.close(), rpc?.solana.close()]);\n },\n },\n config: {\n ...resolved,\n fetch: config.fetch ?? edge.fetch,\n createWebSocket: config.createWebSocket ?? edge.createWebSocket,\n chainRpc:\n rpc === undefined\n ? undefined\n : {\n evm: { dispatcher: rpc.evm.dispatcher, fetch: rpc.evm.fetch },\n solana: { dispatcher: rpc.solana.dispatcher, fetch: rpc.solana.fetch },\n },\n },\n };\n}\n\n/**\n * This client's keys, in the shapes the x402 channel code signs with: a viem\n * account on EVM, and on Solana a keypair plus the JSON-RPC it reads the chain\n * through. Chain RPC rides the proxy under the same condition everywhere: there\n * is one, and the caller has not opted RPC out of it.\n */\nfunction chainAccess(config: ResolvedConfig): {\n evm?: { account: ReturnType<typeof privateKeyToAccount>; privateKey: Uint8Array };\n solana?: {\n signer: { privateKey: Uint8Array; publicKey: Uint8Array };\n rpc: { url: string; fetchImpl?: typeof fetch };\n };\n} {\n const evmKey = config.identity.evm?.privateKey;\n const solanaKey = config.identity.solana;\n return {\n ...(evmKey !== undefined\n ? { evm: { account: privateKeyToAccount(toHex(evmKey)), privateKey: evmKey } }\n : {}),\n ...(solanaKey !== undefined\n ? {\n solana: {\n signer: {\n privateKey: solanaKey.secretKey.slice(0, 32),\n publicKey: base58Decode(solanaKey.publicKey),\n },\n rpc: {\n url: config.rpcUrls.solana,\n ...(config.chainRpc !== undefined ? { fetchImpl: config.chainRpc.solana.fetch } : {}),\n },\n },\n }\n : {}),\n };\n}\n\n/**\n * A `readContract` over the client's EVM RPC, built on first use so a client\n * that never needs to read a batch-settlement channel back opens no connection.\n */\nfunction lazyEvmReader(config: ResolvedConfig): ContractReader {\n let client: ReturnType<typeof createPublicClient> | undefined;\n return {\n readContract: (params: never) => {\n client ??= createPublicClient({\n transport: rpcTransport(config.rpcUrls.evm, config.chainRpc?.evm.dispatcher),\n });\n return client.readContract(params);\n },\n };\n}\n","/**\n * Who pays the gas for a deposit into an x402 `batch-settlement` channel on\n * EVM, and how (connector ADR 0074; toon-client#695).\n *\n * The contract's `deposit(config, amount, collector, collectorData)` is\n * callable by anyone: the payer's one signature — an ERC-3009 authorization or\n * a Permit2 witness transfer — binds the deposit to its channel. So the same\n * signed payload can be put on chain two ways:\n *\n * - **by a facilitator**, which pays the gas (`facilitator.ts`); or\n * - **by the payer itself**, from its own ETH ({@link depositDirectly}).\n *\n * Both spend the one authorization, and its nonce is single-use on chain — the\n * ERC-3009 nonce is `keccak256(channelId, salt)`, a Permit2 nonce is\n * unordered and random — so a direct deposit after a facilitator's answer was\n * lost can never land twice: whichever arrives second reverts.\n *\n * A token without ERC-3009 deposits through Permit2, which first needs the\n * payer's `approve(Permit2, …)`. That approval is gas too, and x402 defines\n * two extensions for a facilitator to cover it:\n *\n * - `eip2612GasSponsoring`, for a token with an EIP-2612 permit: the payer\n * signs a permit for Permit2 and the facilitator folds it into the deposit;\n * - `erc20ApprovalGasSponsoring`, for a token with neither: the payer signs\n * the `approve` transaction without sending it, and the facilitator funds\n * its gas and broadcasts it before the deposit.\n *\n * A payer holding ETH can instead send the approval itself\n * ({@link approvePermit2}). The encodings below are x402's own\n * (`@x402/evm` 2.27.0, `batch-settlement/encoding.ts` and\n * `shared/extensions`), so a facilitator and a direct deposit read the same\n * bytes.\n */\n\nimport {\n createPublicClient,\n createWalletClient,\n defineChain,\n encodeAbiParameters,\n encodeFunctionData,\n getAddress,\n maxUint256,\n parseErc6492Signature,\n parseSignature,\n type Hex,\n type LocalAccount,\n} from 'viem';\nimport { rpcTransport } from '../../transport/rpc.js';\nimport {\n ERC3009_DEPOSIT_COLLECTOR_ADDRESS,\n PERMIT2_ADDRESS,\n PERMIT2_DEPOSIT_COLLECTOR_ADDRESS,\n X402_BATCH_SETTLEMENT_ADDRESS,\n type BatchChannelConfig,\n type BatchDepositPayload,\n type ContractReader,\n type Eip3009DepositPayload,\n type Permit2DepositPayload,\n type TypedDataSigner,\n} from './evm.js';\nimport { NetworkError, TransactionOutcomeError } from '../../client/errors.js';\n\nexport const EIP2612_GAS_SPONSORING = 'eip2612GasSponsoring';\nexport const ERC20_APPROVAL_GAS_SPONSORING = 'erc20ApprovalGasSponsoring';\n\n/** x402's approval gas limit and fallback fee cap (`@x402/evm` 2.27.0). */\nexport const ERC20_APPROVE_GAS_LIMIT = 70_000n;\nconst DEFAULT_MAX_FEE_PER_GAS = 1_000_000_000n;\nconst DEFAULT_MAX_PRIORITY_FEE_PER_GAS = 100_000_000n;\n\nconst CHANNEL_CONFIG_COMPONENTS = [\n { name: 'payer', type: 'address' },\n { name: 'payerAuthorizer', type: 'address' },\n { name: 'receiver', type: 'address' },\n { name: 'receiverAuthorizer', type: 'address' },\n { name: 'token', type: 'address' },\n { name: 'withdrawDelay', type: 'uint40' },\n { name: 'salt', type: 'bytes32' },\n] as const;\n\n/** `x402BatchSettlement.deposit`. */\nexport const X402_BATCH_SETTLEMENT_DEPOSIT_ABI = [\n {\n type: 'function',\n name: 'deposit',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'config', type: 'tuple', components: CHANNEL_CONFIG_COMPONENTS },\n { name: 'amount', type: 'uint128' },\n { name: 'collector', type: 'address' },\n { name: 'collectorData', type: 'bytes' },\n ],\n outputs: [],\n },\n] as const;\n\nconst ERC20_PERMIT2_ABI = [\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n ],\n outputs: [{ type: 'uint256' }],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'spender', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ type: 'bool' }],\n },\n {\n type: 'function',\n name: 'nonces',\n stateMutability: 'view',\n inputs: [{ name: 'owner', type: 'address' }],\n outputs: [{ type: 'uint256' }],\n },\n] as const;\n\nconst EIP2612_PERMIT_TYPES = {\n Permit: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'nonce', type: 'uint256' },\n { name: 'deadline', type: 'uint256' },\n ],\n} as const;\n\n// ---------------------------------------------------------------------------\n// The payer's own chain access\n// ---------------------------------------------------------------------------\n\n/**\n * What paying gas from the payer's own wallet needs of the chain, bound to the\n * payer's account. A viem wallet client extended with public actions provides\n * all of it; `ToonClient` builds one lazily.\n */\nexport interface EvmWalletAccess {\n /** The payer's native balance, wei. */\n getBalance(): Promise<bigint>;\n /** The payer's next transaction nonce. */\n getTransactionCount(): Promise<number>;\n estimateFeesPerGas(): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }>;\n /** Sign, without sending, a transaction from the payer's account. */\n signTransaction(transaction: never): Promise<Hex>;\n /** Send a contract call from the payer's account. */\n writeContract(params: never): Promise<Hex>;\n waitForTransactionReceipt(params: { hash: Hex }): Promise<{ status: string }>;\n}\n\n/**\n * {@link EvmWalletAccess} for `account` over `rpcUrl`, on whichever chain the\n * RPC reports. Nothing connects until it is first used.\n */\nexport function evmWalletAccess(params: {\n rpcUrl: string;\n account: LocalAccount;\n /** The proxy-bound dispatcher a hidden payer's RPC rides, if any. */\n dispatcher?: unknown;\n}): EvmWalletAccess {\n const { account } = params;\n const transport = rpcTransport(params.rpcUrl, params.dispatcher);\n const reader = createPublicClient({ transport });\n let writer: Promise<ReturnType<typeof createWalletClient>> | undefined;\n const wallet = () =>\n (writer ??= reader.getChainId().then((id) =>\n createWalletClient({\n account,\n transport,\n chain: defineChain({\n id,\n name: `eip155:${id}`,\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [params.rpcUrl] } },\n }),\n })\n ));\n return {\n getBalance: () => reader.getBalance({ address: account.address }),\n getTransactionCount: () =>\n reader.getTransactionCount({ address: account.address, blockTag: 'pending' }),\n estimateFeesPerGas: () => reader.estimateFeesPerGas(),\n signTransaction: (tx: never) => account.signTransaction(tx),\n writeContract: async (q: never) => (await wallet()).writeContract(q),\n waitForTransactionReceipt: ({ hash }) => reader.waitForTransactionReceipt({ hash }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Reading the token\n// ---------------------------------------------------------------------------\n\n/** How much of `token` Permit2 may move for `owner`. */\nexport async function permit2Allowance(\n reader: ContractReader,\n token: string,\n owner: string\n): Promise<bigint> {\n return (await reader.readContract({\n address: getAddress(token),\n abi: ERC20_PERMIT2_ABI,\n functionName: 'allowance',\n args: [getAddress(owner), PERMIT2_ADDRESS],\n } as never)) as bigint;\n}\n\n/**\n * `owner`'s EIP-2612 nonce on `token`, or `undefined` when the token has no\n * `nonces(address)` — and so, for this purpose, no permit.\n */\nexport async function eip2612Nonce(\n reader: ContractReader,\n token: string,\n owner: string\n): Promise<bigint | undefined> {\n try {\n return (await reader.readContract({\n address: getAddress(token),\n abi: ERC20_PERMIT2_ABI,\n functionName: 'nonces',\n args: [getAddress(owner)],\n } as never)) as bigint;\n } catch {\n return undefined;\n }\n}\n\n/** The extensions a facilitator's `GET /supported` advertises. */\nexport async function facilitatorExtensions(\n facilitatorUrl: string,\n fetchImpl: typeof fetch = fetch\n): Promise<string[]> {\n const url = `${facilitatorUrl.replace(/\\/+$/, '')}/supported`;\n let body: unknown;\n try {\n const response = await fetchImpl(url);\n body = await response.json();\n } catch (err) {\n throw new NetworkError(\n `facilitator ${url} did not answer`,\n err instanceof Error ? err : undefined\n );\n }\n const extensions = (body as { extensions?: unknown } | null)?.extensions;\n return Array.isArray(extensions)\n ? extensions.filter((e): e is string => typeof e === 'string')\n : [];\n}\n\n// ---------------------------------------------------------------------------\n// The two gas-sponsoring extensions, in x402's own shape\n// ---------------------------------------------------------------------------\n\n/** `paymentPayload.extensions`, as a facilitator reads them. */\nexport type DepositExtensions = Record<string, { info: Record<string, unknown> }>;\n\n/**\n * An EIP-2612 permit letting Permit2 move `amount` of the token, for the\n * facilitator to fold into the deposit (`eip2612GasSponsoring`).\n */\nexport async function signEip2612GasSponsoring(params: {\n payer: TypedDataSigner;\n token: string;\n /** The token's own EIP-712 domain. */\n name: string;\n version: string;\n chainId: number;\n nonce: bigint;\n amount: bigint;\n /** The Permit2 authorization's own deadline, unix seconds. */\n deadline: string;\n}): Promise<DepositExtensions> {\n const owner = getAddress(params.payer.address);\n const asset = getAddress(params.token);\n const signature = await params.payer.signTypedData({\n domain: {\n name: params.name,\n version: params.version,\n chainId: params.chainId,\n verifyingContract: asset,\n },\n types: EIP2612_PERMIT_TYPES,\n primaryType: 'Permit',\n message: {\n owner,\n spender: PERMIT2_ADDRESS,\n value: params.amount,\n nonce: params.nonce,\n deadline: BigInt(params.deadline),\n },\n } as never);\n return {\n [EIP2612_GAS_SPONSORING]: {\n info: {\n from: owner,\n asset,\n spender: PERMIT2_ADDRESS,\n amount: params.amount.toString(),\n nonce: params.nonce.toString(),\n deadline: params.deadline,\n signature,\n version: '1',\n },\n },\n };\n}\n\n/**\n * The payer's signed-but-unsent `approve(Permit2, max)`, for the facilitator\n * to fund and broadcast (`erc20ApprovalGasSponsoring`).\n */\nexport async function signErc20ApprovalGasSponsoring(params: {\n payerAddress: string;\n wallet: Pick<EvmWalletAccess, 'getTransactionCount' | 'estimateFeesPerGas' | 'signTransaction'>;\n token: string;\n chainId: number;\n}): Promise<DepositExtensions> {\n const asset = getAddress(params.token);\n let maxFeePerGas = DEFAULT_MAX_FEE_PER_GAS;\n let maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE_PER_GAS;\n try {\n ({ maxFeePerGas, maxPriorityFeePerGas } = await params.wallet.estimateFeesPerGas());\n } catch {\n // x402's own client falls back to its defaults too.\n }\n const signedTransaction = await params.wallet.signTransaction({\n to: asset,\n data: encodeFunctionData({\n abi: ERC20_PERMIT2_ABI,\n functionName: 'approve',\n args: [PERMIT2_ADDRESS, maxUint256],\n }),\n nonce: await params.wallet.getTransactionCount(),\n gas: ERC20_APPROVE_GAS_LIMIT,\n maxFeePerGas,\n maxPriorityFeePerGas,\n chainId: params.chainId,\n type: 'eip1559',\n } as never);\n return {\n [ERC20_APPROVAL_GAS_SPONSORING]: {\n info: {\n from: getAddress(params.payerAddress),\n asset,\n spender: PERMIT2_ADDRESS,\n amount: maxUint256.toString(),\n signedTransaction,\n version: '1',\n },\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Paying the gas yourself\n// ---------------------------------------------------------------------------\n\n/** How long a landed approval may take to show on the RPC, and how often to look. */\nconst VISIBLE_WITHIN_MS = 30_000;\nconst POLL_INTERVAL_MS = 1_000;\n\n/**\n * Approve Permit2 for `token`, for the maximum, from the payer's own ETH.\n *\n * With `seen`, it also waits until the RPC shows the allowance: a public RPC is\n * load-balanced, and a receipt from one backend says nothing about the next.\n * On Base Sepolia, a deposit estimated straight after the receipt reverted\n * `TRANSFER_FROM_FAILED` (#695).\n */\nexport async function approvePermit2(\n wallet: EvmWalletAccess,\n token: string,\n seen?: { reader: ContractReader; owner: string; atLeast: bigint }\n): Promise<Hex> {\n const hash = await wallet.writeContract({\n address: getAddress(token),\n abi: ERC20_PERMIT2_ABI,\n functionName: 'approve',\n args: [PERMIT2_ADDRESS, maxUint256],\n } as never);\n await landed(wallet, hash, 'the Permit2 approval');\n if (seen) {\n const deadline = Date.now() + VISIBLE_WITHIN_MS;\n while ((await permit2Allowance(seen.reader, token, seen.owner)) < seen.atLeast) {\n if (Date.now() >= deadline) {\n throw new NetworkError(\n `the Permit2 approval ${hash} landed, but the RPC did not show it within ${VISIBLE_WITHIN_MS / 1000} s`\n );\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n }\n return hash;\n}\n\n/** `collectorData` for the ERC-3009 deposit collector. */\nexport function erc3009CollectorData(payload: Eip3009DepositPayload): Hex {\n const auth = payload.deposit.authorization.erc3009Authorization;\n const { signature } = parseErc6492Signature(auth.signature);\n return encodeAbiParameters(\n [{ type: 'uint256' }, { type: 'uint256' }, { type: 'uint256' }, { type: 'bytes' }],\n [BigInt(auth.validAfter), BigInt(auth.validBefore), BigInt(auth.salt), signature]\n );\n}\n\n/**\n * `collectorData` for the Permit2 deposit collector, optionally carrying an\n * EIP-2612 permit for Permit2 (`eip2612PermitData`, else empty).\n */\nexport function permit2CollectorData(\n payload: Permit2DepositPayload,\n eip2612PermitData: Hex = '0x'\n): Hex {\n const auth = payload.deposit.authorization.permit2Authorization;\n const { signature } = parseErc6492Signature(auth.signature as Hex);\n return encodeAbiParameters(\n [{ type: 'uint256' }, { type: 'uint256' }, { type: 'bytes' }, { type: 'bytes' }],\n [BigInt(auth.nonce), BigInt(auth.deadline), signature, eip2612PermitData]\n );\n}\n\n/** An EIP-2612 permit as the Permit2 collector reads it. */\nexport function eip2612PermitData(info: {\n amount: string;\n deadline: string;\n signature: string;\n}): Hex {\n const { v, r, s, yParity } = parseSignature(info.signature as Hex);\n return encodeAbiParameters(\n [\n { type: 'uint256' },\n { type: 'uint256' },\n { type: 'uint8' },\n { type: 'bytes32' },\n { type: 'bytes32' },\n ],\n [BigInt(info.amount), BigInt(info.deadline), Number(v ?? BigInt(27 + (yParity ?? 0))), r, s]\n );\n}\n\n/**\n * Put a signed deposit on chain from the payer's own wallet: the same call a\n * facilitator makes, with the payer paying the gas.\n */\nexport async function depositDirectly(\n wallet: EvmWalletAccess,\n payload: BatchDepositPayload<unknown>,\n method: 'eip3009' | 'permit2'\n): Promise<Hex> {\n const config: BatchChannelConfig = payload.channelConfig;\n const collectorData =\n method === 'eip3009'\n ? erc3009CollectorData(payload as Eip3009DepositPayload)\n : permit2CollectorData(payload as Permit2DepositPayload);\n const hash = await wallet.writeContract({\n address: X402_BATCH_SETTLEMENT_ADDRESS,\n abi: X402_BATCH_SETTLEMENT_DEPOSIT_ABI,\n functionName: 'deposit',\n args: [\n {\n payer: getAddress(config.payer),\n payerAuthorizer: getAddress(config.payerAuthorizer),\n receiver: getAddress(config.receiver),\n receiverAuthorizer: getAddress(config.receiverAuthorizer),\n token: getAddress(config.token),\n withdrawDelay: config.withdrawDelay,\n salt: config.salt,\n },\n BigInt((payload.deposit as { amount: string }).amount),\n method === 'eip3009'\n ? ERC3009_DEPOSIT_COLLECTOR_ADDRESS\n : PERMIT2_DEPOSIT_COLLECTOR_ADDRESS,\n collectorData,\n ],\n } as never);\n await landed(wallet, hash, 'the deposit');\n return hash;\n}\n\nasync function landed(wallet: EvmWalletAccess, hash: Hex, what: string): Promise<void> {\n const receipt = await wallet.waitForTransactionReceipt({ hash });\n if (receipt.status !== 'success') {\n throw new TransactionOutcomeError(`${what} ${hash} reverted`, 'evm', hash, 'failed');\n }\n}\n","/**\n * Handing an x402 `batch-settlement` deposit to a facilitator, which submits it\n * and pays its gas (connector ADR 0074, prerequisite 2).\n *\n * This is the one step of paying from an x402 channel that leaves the packet\n * path: the deposit goes to a stock x402 facilitator's `/settle`, exactly as an\n * x402 resource server would send it, and every voucher afterwards travels\n * inside ILP. The body is x402 v2's settle request (`@x402/core`'s\n * `HTTPFacilitatorClient.settle`): the payload, wrapped with the requirements it\n * answers, which here are the connector's own `accepts[]` offer.\n */\n\nimport type { BatchDepositPayload, BatchSettlementEvmOffer } from './evm.js';\nimport { FacilitatorError, NetworkError } from '../../client/errors.js';\n\n/** The deposit as the chain now holds it. */\nexport interface SettledDeposit {\n /** The deposit's transaction hash, sent from the facilitator's signer. */\n transaction: string;\n network: string;\n}\n\n/**\n * POST a deposit to `<facilitatorUrl>/settle`, and return its transaction.\n *\n * The requirements sent are the offer with `extra.withdrawDelay` set to the\n * channel's own: the offer publishes a MINIMUM, a channel may choose longer, and\n * a stock facilitator requires the two to be equal (x402 EVM spec, rule 5).\n *\n * @throws {FacilitatorError} when the facilitator refuses it — its `errorReason`\n * is carried as `reason` — or answers with something that is not a settle\n * result (`reason` `unreadable_response`).\n * @throws {NetworkError} when it does not answer at all.\n */\nexport async function settleDeposit(params: {\n facilitatorUrl: string;\n offer: BatchSettlementEvmOffer;\n payload: BatchDepositPayload<unknown>;\n /**\n * x402 extensions for the facilitator — a gas-sponsored Permit2 approval\n * (`deposit-gas.ts`) — carried as `paymentPayload.extensions`.\n */\n extensions?: Record<string, { info: Record<string, unknown> }>;\n fetchImpl?: typeof fetch;\n}): Promise<SettledDeposit> {\n const { payload } = params;\n const offer: BatchSettlementEvmOffer = {\n ...params.offer,\n extra: {\n ...params.offer.extra,\n withdrawDelay: payload.channelConfig.withdrawDelay,\n },\n };\n const fetchImpl = params.fetchImpl ?? fetch;\n const url = `${params.facilitatorUrl.replace(/\\/+$/, '')}/settle`;\n\n let response: Response;\n let text: string;\n try {\n response = await fetchImpl(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n x402Version: 2,\n paymentPayload: {\n x402Version: 2,\n accepted: offer,\n payload,\n ...(params.extensions ? { extensions: params.extensions } : {}),\n },\n paymentRequirements: offer,\n }),\n });\n text = await response.text();\n } catch (err) {\n throw new NetworkError(\n `facilitator ${url} did not answer`,\n err instanceof Error ? err : undefined\n );\n }\n\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch {\n throw new FacilitatorError(\n `facilitator ${url} answered HTTP ${response.status} with a body that is not JSON: ${text.slice(0, 200)}`,\n 'unreadable_response'\n );\n }\n if (typeof body !== 'object' || body === null || !('success' in body)) {\n throw new FacilitatorError(\n `facilitator ${url} answered HTTP ${response.status} with no settle result: ${text.slice(0, 200)}`,\n 'unreadable_response'\n );\n }\n\n const result = body as {\n success: unknown;\n errorReason?: unknown;\n errorMessage?: unknown;\n transaction?: unknown;\n network?: unknown;\n };\n if (\n result.success !== true ||\n typeof result.transaction !== 'string' ||\n !result.transaction\n ) {\n const reason =\n typeof result.errorReason === 'string' ? result.errorReason : 'unknown';\n const detail =\n typeof result.errorMessage === 'string' ? `: ${result.errorMessage}` : '';\n throw new FacilitatorError(\n `facilitator refused the deposit (${reason})${detail}`,\n reason\n );\n }\n return {\n transaction: result.transaction,\n network:\n typeof result.network === 'string' ? result.network : offer.network,\n };\n}\n","/**\n * A voucher as it rides the wire: a client-edge claim under `scheme:\n * \"batch-settlement\"` (connector ADR 0074 decision 4, pinned by the vectors'\n * `claim_voucher.*.json`).\n *\n * It rides in the `ILP-Payment-Channel-Claim` header on `POST /ilp`, and in\n * the `payment-channel-claim` protocolData entry on BTP.\n *\n * Keys are written in the vectors' order (sorted) and EVM hex in lowercase, so\n * `JSON.stringify` of a claim built from a vector's fields reproduces that\n * vector's `json` byte for byte. The connector parses JSON, so neither is load\n * bearing on the wire; matching the vector is what makes the replay exact.\n */\n\nimport type { BatchChannelConfig, BatchVoucher } from './evm.js';\nimport type { SvmBatchVoucher } from './svm.js';\n\n/** The envelope fields every client-edge claim carries. Drawn fresh unless given. */\nexport interface VoucherClaimEnvelope {\n messageId?: string;\n timestamp?: string;\n}\n\n/**\n * An EVM voucher claim. `channelConfig` is carried on every voucher: the\n * connector needs it on the first one it sees for a channel, because the\n * contract stores channels by id and never gives the config back, and carrying\n * it always costs a few hundred bytes and survives a connector that lost its\n * journal.\n */\nexport function evmVoucherClaim(\n voucher: BatchVoucher,\n config: BatchChannelConfig,\n envelope: VoucherClaimEnvelope = {}\n): Record<string, unknown> {\n return {\n blockchain: 'evm',\n channelConfig: {\n payer: config.payer.toLowerCase(),\n payerAuthorizer: config.payerAuthorizer.toLowerCase(),\n receiver: config.receiver.toLowerCase(),\n receiverAuthorizer: config.receiverAuthorizer.toLowerCase(),\n salt: config.salt.toLowerCase(),\n token: config.token.toLowerCase(),\n withdrawDelay: config.withdrawDelay,\n },\n channelId: voucher.channelId.toLowerCase(),\n maxClaimableAmount: voucher.maxClaimableAmount,\n messageId: envelope.messageId ?? crypto.randomUUID(),\n scheme: 'batch-settlement',\n senderId: config.payerAuthorizer.toLowerCase(),\n signature: voucher.signature.toLowerCase(),\n timestamp: envelope.timestamp ?? claimTimestamp(),\n version: '1.0',\n };\n}\n\n/**\n * A Solana voucher claim. `senderId` is the voucher signer — the channel's\n * `authorized_signer` — in base58, as the connector's vector names it.\n */\nexport function solanaVoucherClaim(\n voucher: SvmBatchVoucher,\n signer: string,\n envelope: VoucherClaimEnvelope = {}\n): Record<string, unknown> {\n return {\n blockchain: 'solana',\n channelId: voucher.channelId,\n expiresAt: voucher.expiresAt,\n maxClaimableAmount: voucher.maxClaimableAmount,\n messageId: envelope.messageId ?? crypto.randomUUID(),\n scheme: 'batch-settlement',\n senderId: signer,\n signature: voucher.signature,\n timestamp: envelope.timestamp ?? claimTimestamp(),\n version: '1.0',\n };\n}\n\n/**\n * The cumulative amount the next voucher on a channel signs for, given what\n * this client has signed on it so far and the packet's charge — or `undefined`\n * when the packet should carry no voucher at all.\n *\n * A voucher has no nonce, so the connector accepts one only if its amount\n * strictly exceeds the channel's watermark, and by at least the route's charge\n * (ADR 0074 decision 3). Hence:\n *\n * - a charge of zero sends **no** voucher. An explicitly free route admits an\n * unpaid packet, and a voucher that did not advance would be refused as\n * `amount_not_advancing`;\n * - otherwise the voucher is exactly `signedSoFar + charge`: advancing by\n * more pays more than the route asked, and by less is underpayment.\n */\nexport function nextVoucherAmount(\n signedSoFar: bigint,\n charge: bigint\n): bigint | undefined {\n if (charge < 0n)\n throw new RangeError(`a charge cannot be negative, got ${charge}`);\n return charge === 0n ? undefined : signedSoFar + charge;\n}\n\n/** The claim envelope's timestamp: ISO-8601, milliseconds zeroed, as `EvmSigner` writes it. */\nfunction claimTimestamp(): string {\n return new Date().toISOString().replace(/\\.\\d{3}Z$/, '.000Z');\n}\n","/**\n * Asking the receiving connector to sponsor a Solana `open` (connector ADR 0074\n * decision 9; connector #1346).\n *\n * `POST <connector><sponsorEndpoint>` with `{ \"transaction\": \"<base64>\" }` — the\n * payer-signed `open` {@link ./svm.js!buildSponsoredOpen} built. The connector\n * vets it against x402's acceptance policy and its own published minimums,\n * co-signs it as fee payer and `rent_payer`, submits it and waits for it to\n * land, then answers `{ channelId, transaction, payer, deposit }`. It never\n * hands the co-signed bytes back, so the client never holds a transaction that\n * decides when the connector's rent is spent.\n *\n * A refusal is `{ error, detail }` with a status by class (400 malformed, 422\n * refused, 503 unavailable, 502 failed on chain), and the name is what a\n * client acts on.\n */\n\nimport { NetworkError, SponsorRefusedError } from '../../client/errors.js';\n\n/** The channel the connector opened. */\nexport interface SponsoredOpen {\n /** The channel PDA, base58. */\n channelId: string;\n /** The open's transaction signature. */\n transaction: string;\n payer: string;\n /** Atomic units, decimal. */\n deposit: string;\n}\n\n/**\n * Post a payer-signed `open` to the connector's sponsor endpoint.\n *\n * @param connector the connector's client-edge base URL.\n * @param sponsorEndpoint the path its greeting publishes.\n * @throws {SponsorRefusedError} the connector answered and did not open it.\n * @throws {NetworkError} it did not answer, or not in a shape this client reads.\n */\nexport async function requestSponsoredOpen(params: {\n connector: string;\n sponsorEndpoint: string;\n transaction: string;\n fetchImpl?: typeof fetch;\n}): Promise<SponsoredOpen> {\n const url = new URL(\n params.sponsorEndpoint,\n `${params.connector.replace(/\\/+$/, '')}/`\n ).toString();\n const fetchImpl = params.fetchImpl ?? fetch;\n\n let response: Response;\n let text: string;\n try {\n response = await fetchImpl(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ transaction: params.transaction }),\n });\n text = await response.text();\n } catch (err) {\n throw new NetworkError(\n `sponsor endpoint ${url} did not answer`,\n err instanceof Error ? err : undefined\n );\n }\n\n let body: Record<string, unknown>;\n try {\n body = JSON.parse(text) as Record<string, unknown>;\n } catch {\n throw new NetworkError(\n `sponsor endpoint ${url} answered HTTP ${response.status} with a body that is not JSON: ${text.slice(0, 200)}`\n );\n }\n\n if (!response.ok || typeof body['error'] === 'string') {\n const reason =\n typeof body['error'] === 'string'\n ? body['error']\n : `http_${response.status}`;\n const detail =\n typeof body['detail'] === 'string' ? `: ${body['detail']}` : '';\n throw new SponsorRefusedError(\n `the connector refused to sponsor the open (${reason})${detail}`,\n reason,\n response.status\n );\n }\n\n const { channelId, transaction, payer, deposit } = body;\n if (\n typeof channelId !== 'string' ||\n typeof transaction !== 'string' ||\n typeof payer !== 'string' ||\n typeof deposit !== 'string'\n ) {\n throw new NetworkError(\n `sponsor endpoint ${url} answered with no opened channel: ${text.slice(0, 200)}`\n );\n }\n return { channelId, transaction, payer, deposit };\n}\n","/**\n * The voucher claim-state challenge: a read-only \"I control this channel's\n * voucher signer, until `expires`\", distinct from a voucher (connector\n * `connector-signer`'s `claim_state_challenge`, ADR 0075; pinned by the\n * vectors' `voucher_claim_state_challenge` and `client_auth_channel_challenge`).\n *\n * One message serves every place a client proves control without moving value:\n *\n * - `POST /ilp/claim-state`, which answers with the connector's own watermark\n * for the channel;\n * - the BTP `auth` frame's `channelChallenge`, which binds the session to the\n * channel before it has presented a voucher.\n *\n * It must never verify as a voucher, so it signs a domain-separated message:\n *\n * - **EVM** — `ClaimStateChallenge(bytes32 channelId,uint256 expires)` under\n * `x402BatchSettlement`'s EIP-712 domain: the voucher's domain, a\n * different type hash;\n * - **Solana** — Ed25519 over `\"toon-voucher-claim-state-challenge-v1\" ‖\n * channel account ‖ expires u64 LE`, which does not begin with a\n * voucher's `0x56 0x01`.\n *\n * Replay protection is `expires` alone, so a challenge is signed fresh each\n * time and never lives long: BTP auth refuses one more than 300 s ahead.\n */\n\nimport { hashTypedData, type Hex } from 'viem';\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { base58Decode } from '../../utils/base58.js';\nimport { encodeUtf8, toBase64 } from '../../utils/binary.js';\nimport type { Signer } from '../solana/payment-channel.js';\nimport {\n X402_BATCH_SETTLEMENT_ADDRESS,\n type BatchChannelConfig,\n type TypedDataSigner,\n} from './evm.js';\n\nconst CLAIM_STATE_CHALLENGE_TYPES = {\n ClaimStateChallenge: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'expires', type: 'uint256' },\n ],\n} as const;\n\nconst SOLANA_CHALLENGE_TAG = encodeUtf8(\n 'toon-voucher-claim-state-challenge-v1'\n);\n\n/** How far ahead a BTP `channelChallenge` may expire and still bind a session. */\nexport const CHANNEL_CHALLENGE_MAX_LIFETIME_SECONDS = 300;\n\nfunction domain(chainId: number) {\n return {\n name: 'x402 Batch Settlement',\n version: '1',\n chainId,\n verifyingContract: X402_BATCH_SETTLEMENT_ADDRESS as Hex,\n } as const;\n}\n\n/** The EIP-712 digest an EVM voucher signer signs to prove control of `channelId`. */\nexport function evmChallengeDigest(\n chainId: number,\n channelId: Hex,\n expires: bigint\n): Hex {\n return hashTypedData({\n domain: domain(chainId),\n types: CLAIM_STATE_CHALLENGE_TYPES,\n primaryType: 'ClaimStateChallenge',\n message: { channelId, expires },\n });\n}\n\n/** The bytes a Solana `authorized_signer` signs to prove control of `channelAccount`. */\nexport function solanaChallengeMessage(\n channelAccount: string,\n expires: bigint\n): Uint8Array {\n const out = new Uint8Array(SOLANA_CHALLENGE_TAG.length + 32 + 8);\n out.set(SOLANA_CHALLENGE_TAG, 0);\n out.set(base58Decode(channelAccount), SOLANA_CHALLENGE_TAG.length);\n new DataView(out.buffer).setBigUint64(\n SOLANA_CHALLENGE_TAG.length + 32,\n expires,\n true\n );\n return out;\n}\n\n/**\n * An EVM challenge entry, in the vectors' key order. It carries the channel's\n * `channelConfig`, so a connector that has not yet seen a voucher on the\n * channel can still resolve its signer.\n */\nexport async function signEvmChallenge(\n signer: TypedDataSigner,\n chainId: number,\n config: BatchChannelConfig,\n channelId: Hex,\n expires: bigint\n): Promise<Record<string, unknown>> {\n const signature = await signer.signTypedData({\n domain: domain(chainId),\n types: CLAIM_STATE_CHALLENGE_TYPES,\n primaryType: 'ClaimStateChallenge',\n message: { channelId, expires },\n } as never);\n return {\n blockchain: 'evm',\n channelConfig: {\n payer: config.payer.toLowerCase(),\n payerAuthorizer: config.payerAuthorizer.toLowerCase(),\n receiver: config.receiver.toLowerCase(),\n receiverAuthorizer: config.receiverAuthorizer.toLowerCase(),\n salt: config.salt.toLowerCase(),\n token: config.token.toLowerCase(),\n withdrawDelay: config.withdrawDelay,\n },\n channelId: channelId.toLowerCase(),\n expires: Number(expires),\n scheme: 'batch-settlement',\n signature: signature.toLowerCase(),\n };\n}\n\n/** A Solana challenge entry, in the vectors' key order; the signature is base64. */\nexport function signSolanaChallenge(\n signer: Signer,\n channelAccount: string,\n expires: bigint\n): Record<string, unknown> {\n const signature = ed25519.sign(\n solanaChallengeMessage(channelAccount, expires),\n signer.privateKey\n );\n return {\n blockchain: 'solana',\n channelAccount,\n expires: Number(expires),\n scheme: 'batch-settlement',\n signature: toBase64(signature),\n };\n}\n","/**\n * Paying a connector from an x402 `batch-settlement` channel: the one object\n * {@link ../../client/send.js!send} asks for a voucher — the only way this\n * client pays (connector ADRs 0074, 0075; toon-client#689, #690, #692).\n *\n * For each paid packet it:\n *\n * 1. finds the node's `batch-settlement` terms on the chain this client pays\n * from — none, and it steps aside: the node cannot be paid there;\n * 2. resolves the channel it holds with this node there — settling any\n * deposit whose answer was lost, and rebuilding a lost or doubtful\n * watermark from the chain and the connector's `claim-state` — or onboards one with no native gas: on EVM a deposit through an\n * x402 facilitator, on Solana an open the connector sponsors;\n * 3. tops the channel up when its deposit cannot cover the next voucher: a\n * further deposit on EVM, a fresh sponsored channel on Solana;\n * 4. reserves the next cumulative amount — persisted before anything is\n * signed — and signs the voucher;\n * 5. hands back the claim, and learns the packet's fate from the caller.\n *\n * **Nothing leaves before it is recorded.** A deposit or sponsored open is\n * written down as pending first, because the facilitator or sponsor may land\n * it and then fail to answer: on EVM the contract never gives a config back,\n * and a Solana PDA cannot be recomputed without its salt and slot, so a\n * channel not recorded first is a deposit lost. The next use reads the chain\n * and settles the pending deposit either way.\n */\n\nimport type { Hex } from 'viem';\nimport type { NodeSelfDescription } from '../../connector/self-description.js';\nimport {\n ChannelNotOpenError,\n ConfigError,\n FacilitatorError,\n InsufficientBalanceError,\n NetworkError,\n SponsorRefusedError,\n ValidationError,\n} from '../../client/errors.js';\nimport {\n batchChannelId,\n buildBatchChannelConfig,\n buildEip3009Deposit,\n buildPermit2Deposit,\n evmChainIdOf,\n readEvmBatchChannel,\n signBatchVoucher,\n type BatchSettlementEvmOffer,\n type ContractReader,\n type TypedDataSigner,\n} from './evm.js';\nimport { settleDeposit } from './facilitator.js';\nimport {\n ERC20_APPROVAL_GAS_SPONSORING,\n EIP2612_GAS_SPONSORING,\n approvePermit2,\n depositDirectly,\n eip2612Nonce,\n facilitatorExtensions,\n permit2Allowance,\n signEip2612GasSponsoring,\n signErc20ApprovalGasSponsoring,\n type DepositExtensions,\n type EvmWalletAccess,\n} from './deposit-gas.js';\nimport { chooseBatchSettlement, offerFromTerms } from './offers.js';\nimport { evmVoucherClaim, solanaVoucherClaim } from './claim.js';\nimport {\n buildSponsoredOpen,\n buildSvmBatchChannelConfig,\n getSvmBatchChannel,\n signSvmVoucher,\n type BatchSettlementSvmOffer,\n} from './svm.js';\nimport { requestSponsoredOpen } from './sponsor.js';\nimport { signEvmChallenge, signSolanaChallenge } from './challenge.js';\nimport { defaultFacilitatorFor } from '../../presets.js';\nimport {\n deriveAssociatedTokenAccount,\n getLatestBlockhash,\n getTokenAccountBalance,\n solanaRpc,\n type Signer,\n type SolanaRpcTarget,\n} from '../solana/payment-channel.js';\nimport { base58Encode } from '../../utils/base58.js';\nimport type { BatchChannel, BatchChannelManager } from './manager.js';\n\n/** What became of a packet that carried a voucher. */\nexport type VoucherOutcome =\n | { kind: 'banked' }\n /** A transport error or timeout: it may or may not have arrived. */\n | { kind: 'unknown' }\n /** The connector refused the voucher; `message` is its reject's own text. */\n | { kind: 'refused'; message?: string };\n\n/** A voucher ready to ride one packet. */\nexport interface PreparedVoucher {\n chain: 'evm' | 'solana';\n channelId: string;\n /** The client-edge claim, for the carriage to attach. */\n claim: Record<string, unknown>;\n /** The cumulative amount it signs for. */\n cumulative: bigint;\n /** Report the packet's fate, so the watermark follows it. */\n settle(outcome: VoucherOutcome): void;\n}\n\nexport interface BatchSettlementPayerConfig {\n /** The connector's client-edge URL — what channels are bound to. */\n connector: string;\n manager: BatchChannelManager;\n /** Atomic units deposited on onboarding, and again on each top-up. */\n deposit: bigint;\n evm?: {\n /** The funding wallet; also signs vouchers unless `voucherSigner` is set. */\n account: TypedDataSigner;\n /** Signs vouchers as the channel's `payerAuthorizer`. */\n voucherSigner?: TypedDataSigner;\n /**\n * The x402 facilitator that relays deposits and pays their gas. Defaults\n * to the devnet's own on Base Sepolia (`defaultFacilitatorFor`).\n */\n facilitatorUrl?: string;\n /**\n * How a deposit moves the token: `eip3009` for a token with ERC-3009,\n * `permit2` for any other ERC-20. Defaults to what the connector's offer\n * names (`assetTransferMethod`), and to `eip3009` when it names nothing.\n */\n depositMethod?: 'eip3009' | 'permit2';\n /**\n * Who pays a deposit's gas, and a Permit2 token's one-time approval's:\n *\n * - `auto` (the default): the facilitator, when there is one and it will;\n * otherwise the payer, when it holds ETH;\n * - `facilitator`: only ever the facilitator — the payer's ETH is never\n * spent;\n * - `self`: always the payer, and no facilitator is contacted at all.\n */\n depositGas?: 'auto' | 'facilitator' | 'self';\n /**\n * The payer's own chain access: what a self-paid deposit or approval, and\n * an approval the facilitator sponsors, are signed and sent with. Without\n * it the payer can only use a facilitator, and only for tokens it needs no\n * approval for.\n */\n wallet?: EvmWalletAccess;\n /**\n * Reads the escrow back, to settle a deposit whose answer was lost and to\n * rebuild a lost watermark. Without one, either of those is an error\n * rather than a guess.\n */\n reader?: ContractReader;\n };\n solana?: {\n /** The funding wallet; also the channel's `authorized_signer`, which signs vouchers. */\n signer: Signer;\n /** The Solana JSON-RPC to read the slot, the blockhash and the accounts from. */\n rpc: SolanaRpcTarget;\n };\n /** How the connector's sponsor endpoint and the facilitator are reached. */\n fetch?: typeof fetch;\n /**\n * The connector's own watermark for a channel (`POST /ilp/claim-state`),\n * asked with the voucher challenge this payer signs. It recovers a lost\n * watermark, and settles one a refusal left in doubt. Without it, the chain's\n * landed figure — a floor — is all there is.\n */\n connectorWatermark?: (entry: Record<string, unknown>) => Promise<bigint | undefined>;\n /**\n * Whether a paid packet may open, top up or replace a channel on its own.\n * Default `true`. `false` leaves every such step to {@link BatchSettlementPayer.open}\n * and {@link BatchSettlementPayer.topUp}, and a packet that needs one throws\n * {@link ChannelNotOpenError} instead.\n */\n autoOpen?: boolean;\n}\n\n/**\n * What a voucher's refusal says about the connector's watermark, read from its\n * reject message (`connector-client-edge`'s `ClaimIngestRejection::message`):\n *\n * - `advances value by A, less than this route's price` — an underpayment,\n * which names how far the voucher for `voucherAmount` advanced the\n * watermark, so the watermark is `voucherAmount − A`;\n * - `cumulative amount goes backwards` — the connector holds at least\n * `voucherAmount`, and says no more.\n */\nexport function readVoucherRefusal(\n message: string | undefined,\n voucherAmount: bigint\n): { notAdvancing: boolean; connectorWatermark?: bigint } {\n if (message === undefined) return { notAdvancing: false };\n const advancedBy = /advances value by (\\d+),/.exec(message)?.[1];\n if (advancedBy !== undefined) {\n const advanced = BigInt(advancedBy);\n const watermark = voucherAmount > advanced ? voucherAmount - advanced : 0n;\n return { notAdvancing: advanced === 0n, connectorWatermark: watermark };\n }\n return { notAdvancing: message.includes('cumulative amount goes backwards') };\n}\n\ntype EvmPayerConfig = NonNullable<BatchSettlementPayerConfig['evm']>;\ntype SolanaPayerConfig = NonNullable<BatchSettlementPayerConfig['solana']>;\n\nexport class BatchSettlementPayer {\n /** Onboardings in flight, so concurrent first sends open one channel, not two. */\n private readonly onboarding = new Map<string, Promise<BatchChannel>>();\n /** Channels whose last refusal said the connector holds more, without saying how much. */\n private readonly inDoubt = new Set<string>();\n\n constructor(private readonly config: BatchSettlementPayerConfig) {\n if (config.deposit <= 0n) {\n throw new ConfigError(\n `a batch-settlement deposit must be positive, got ${config.deposit}`\n );\n }\n }\n\n /**\n * A voucher for one packet charging `amount` on `chain`, or `undefined` when\n * this node offers no `batch-settlement` there — and so cannot be paid on\n * `chain` at all.\n */\n async claimFor(\n description: NodeSelfDescription,\n chain: 'evm' | 'solana',\n amount: bigint\n ): Promise<PreparedVoucher | undefined> {\n const terms = chooseBatchSettlement(description, chain);\n if (terms === undefined) return undefined;\n const priced = offerFromTerms(terms, amount);\n const channel =\n priced.chain === 'evm'\n ? await this.evmChannelFor(this.requireEvm(), priced.offer, amount)\n : await this.solanaChannelFor(\n this.requireSolana(),\n priced.offer,\n amount\n );\n return this.voucher(channel, amount);\n }\n\n /**\n * Open a channel to this node on `chain` now, rather than on the first paid\n * packet — or return the one already open there. `undefined` when the node\n * offers no `batch-settlement` on `chain`.\n *\n * On EVM the deposit must carry a voucher of at least one unit (ADR 0074\n * prerequisite 1). It is signed for one unit and handed only to the\n * facilitator, which cannot claim it — `receiverAuthorizer` is the\n * connector's — and the first real voucher supersedes it.\n */\n async open(\n description: NodeSelfDescription,\n chain: 'evm' | 'solana'\n ): Promise<BatchChannel | undefined> {\n const terms = chooseBatchSettlement(description, chain);\n if (terms === undefined) return undefined;\n const priced = offerFromTerms(terms, 1n);\n const live = await this.live(priced.offer.network, priced.offer.asset);\n if (live !== undefined) return live;\n return priced.chain === 'evm'\n ? this.onboard(priced.offer, () =>\n this.evmOnboard(this.requireEvm(), priced.offer, 1n)\n )\n : this.onboard(priced.offer, () =>\n this.solanaOnboard(this.requireSolana(), priced.offer, 1n)\n );\n }\n\n /**\n * Deposit `amount` more into the Base channel this client pays the node\n * from. A Solana channel has no top-up that costs no SOL, so it is replaced\n * by a fresh sponsored one instead, and this refuses.\n */\n async topUp(\n description: NodeSelfDescription,\n chain: 'evm' | 'solana',\n amount: bigint\n ): Promise<BatchChannel> {\n if (chain !== 'evm') {\n throw new ConfigError(\n 'a Solana batch-settlement channel is not topped up: the next payment it cannot cover opens a fresh sponsored one'\n );\n }\n const terms = chooseBatchSettlement(description, 'evm');\n if (terms === undefined) {\n throw new ConfigError(\n `${this.config.connector} offers no batch-settlement channel on evm`\n );\n }\n const priced = offerFromTerms(terms, 1n);\n if (priced.chain !== 'evm') throw new Error('unreachable');\n const channel = await this.live(priced.offer.network, priced.offer.asset);\n if (channel === undefined || channel.chain !== 'evm') {\n throw new ChannelNotOpenError(\n `no batch-settlement channel to ${this.config.connector} is open to top up`\n );\n }\n const manager = this.config.manager;\n await this.evmDeposit(\n this.requireEvm(),\n channel,\n priced.offer,\n amount,\n manager.signedSoFar(channel.channelId) + 1n\n );\n return channel;\n }\n\n // ─── The channel for a packet ────────────────────────────────────────────\n\n private async evmChannelFor(\n evm: EvmPayerConfig,\n offer: BatchSettlementEvmOffer,\n charge: bigint\n ): Promise<BatchChannel> {\n const manager = this.config.manager;\n let channel = await this.live(offer.network, offer.asset);\n if (channel === undefined) {\n this.assertMayOpen('a batch-settlement channel', 'channel open');\n channel = await this.onboard(offer, () =>\n this.evmOnboard(evm, offer, charge)\n );\n } else {\n const needed = manager.signedSoFar(channel.channelId) + charge;\n if (needed > manager.depositTotal(channel.channelId)) {\n this.assertMayOpen(\n 'a top-up of its batch-settlement channel',\n 'channel deposit'\n );\n const shortfall = needed - manager.depositTotal(channel.channelId);\n const amount =\n this.config.deposit > shortfall ? this.config.deposit : shortfall;\n await this.evmDeposit(evm, channel, offer, amount, needed);\n }\n }\n return channel;\n }\n\n private async solanaChannelFor(\n solana: SolanaPayerConfig,\n offer: BatchSettlementSvmOffer,\n charge: bigint\n ): Promise<BatchChannel> {\n const manager = this.config.manager;\n const channel = await this.live(offer.network, offer.asset);\n // The sponsor endpoint opens channels and nothing else, so a Solana top-up\n // would cost the payer SOL. A channel its deposit cannot cover is instead\n // replaced by a fresh sponsored one, and its binding archived: it stays\n // listed, and `close` / `settle` take what is left in it back.\n if (\n channel !== undefined &&\n manager.signedSoFar(channel.channelId) + charge <=\n manager.depositTotal(channel.channelId)\n ) {\n return channel;\n }\n this.assertMayOpen(\n 'a fresh sponsored batch-settlement channel',\n // `open` returns the live channel however little is left in it; leaving\n // it first is what makes the next open a fresh one, and takes back the rest.\n channel === undefined ? 'channel open' : 'channel close`, then `toon-client channel open'\n );\n return this.onboard(\n offer,\n () => this.solanaOnboard(solana, offer, charge),\n channel?.channelId\n );\n }\n\n /**\n * The channel this client pays the node from on `network` in `asset`, once\n * any deposit whose answer was lost is settled and any lost watermark is\n * rebuilt — or `undefined` when there is none it can still pay from.\n */\n private async live(\n network: string,\n asset: string\n ): Promise<BatchChannel | undefined> {\n const manager = this.config.manager;\n const channel = manager.resolve(this.config.connector, network, asset);\n if (channel === undefined) return undefined;\n if (manager.pendingDeposit(channel.channelId) !== undefined) {\n await this.reconcile(channel);\n if (manager.resolve(this.config.connector, network, asset) === undefined)\n return undefined;\n }\n if (!manager.hasWatermark(channel.channelId)) {\n // The chain's figure is a floor; the connector's, when it will say, is\n // the one that decides — and with the local record gone, it may exceed\n // anything this client can still show it signed.\n manager.restoreWatermark(\n channel.channelId,\n (await this.readChain(channel)).landed\n );\n await this.resync(channel, { recovering: true });\n } else if (this.inDoubt.has(channel.channelId)) {\n await this.resync(channel);\n }\n if (manager.isClosing(channel.channelId)) return undefined;\n return channel;\n }\n\n /**\n * Ask the connector where it stands on `channel` and adopt its figure — the\n * one that decides. Best effort: a connector that cannot answer leaves the\n * local figure as it was, and the doubt standing.\n */\n private async resync(channel: BatchChannel, options: { recovering?: boolean } = {}): Promise<void> {\n const ask = this.config.connectorWatermark;\n if (!ask) return;\n let watermark: bigint | undefined;\n try {\n const expires = BigInt(Math.floor(Date.now() / 1000) + 60);\n watermark = await ask(await this.challenge(channel, expires));\n } catch {\n return;\n }\n if (watermark === undefined) return;\n this.config.manager.adoptConnectorWatermark(channel.channelId, watermark, options);\n this.inDoubt.delete(channel.channelId);\n }\n\n /**\n * The voucher claim-state challenge for `channel`, signed by its voucher\n * signer: what `POST /ilp/claim-state` and BTP auth's `channelChallenge`\n * take to prove this client controls the channel (ADR 0075).\n */\n async challenge(channel: BatchChannel, expires: bigint): Promise<Record<string, unknown>> {\n if (channel.chain === 'evm') {\n const evm = this.requireEvm();\n return signEvmChallenge(\n evm.voucherSigner ?? evm.account,\n evmChainIdOf(channel.network),\n channel.config,\n channel.channelId as Hex,\n expires\n );\n }\n return signSolanaChallenge(this.requireSolana().signer, channel.channelId, expires);\n }\n\n /** Settle a pending deposit against the chain: kept if it landed, dropped if not. */\n private async reconcile(channel: BatchChannel): Promise<void> {\n const manager = this.config.manager;\n const onChain = await this.readChain(channel);\n if (onChain.escrow === undefined) {\n // Never landed, and nothing else was ever deposited: forget the channel.\n manager.abandon(channel.channelId);\n if (manager.pendingDeposit(channel.channelId) !== undefined) {\n manager.confirmDeposit(\n channel.channelId,\n manager.depositTotal(channel.channelId)\n );\n }\n return;\n }\n manager.confirmDeposit(channel.channelId, onChain.escrow);\n }\n\n /**\n * What the chain holds for `channel`: its escrow (`undefined` when there is\n * no such channel yet), and what has landed — a floor under the connector's\n * watermark.\n */\n private async readChain(\n channel: BatchChannel\n ): Promise<{ escrow: bigint | undefined; landed: bigint }> {\n if (channel.chain === 'evm') {\n const reader = this.config.evm?.reader;\n if (!reader) {\n throw new ConfigError(\n `channel ${channel.channelId} needs reading back from the chain, and this payer has no EVM reader`\n );\n }\n const state = await readEvmBatchChannel(reader, channel.channelId as Hex);\n return {\n escrow:\n state.balance > 0n || state.totalClaimed > 0n\n ? state.balance\n : undefined,\n landed: state.totalClaimed,\n };\n }\n const state = await getSvmBatchChannel(\n this.requireSolana().rpc,\n channel.channelId\n );\n return { escrow: state?.deposit, landed: state?.settled ?? 0n };\n }\n\n /** Run one onboarding per network and asset at a time; concurrent callers share it. */\n private async onboard(\n offer: { network: string; asset: string },\n run: () => Promise<BatchChannel>,\n replacing?: string\n ): Promise<BatchChannel> {\n const key = `${offer.network}|${offer.asset}|${replacing ?? ''}`;\n const inFlight = this.onboarding.get(key);\n if (inFlight) return inFlight;\n const started = run().finally(() => this.onboarding.delete(key));\n this.onboarding.set(key, started);\n return started;\n }\n\n // ─── Vouchers ────────────────────────────────────────────────────────────\n\n private async voucher(\n channel: BatchChannel,\n charge: bigint\n ): Promise<PreparedVoucher> {\n const manager = this.config.manager;\n const cumulative = manager.reserve(channel.channelId, charge);\n if (cumulative === undefined) {\n throw new ValidationError(\n 'a free route carries no voucher; send it unpaid'\n );\n }\n const channelId = channel.channelId;\n let claim: Record<string, unknown>;\n if (channel.chain === 'evm') {\n const evm = this.requireEvm();\n const voucher = await signBatchVoucher(\n evm.voucherSigner ?? evm.account,\n evmChainIdOf(channel.network),\n channelId as Hex,\n cumulative\n );\n claim = evmVoucherClaim(voucher, channel.config);\n } else {\n const solana = this.requireSolana();\n claim = solanaVoucherClaim(\n signSvmVoucher(solana.signer, channelId, cumulative),\n base58Encode(solana.signer.publicKey)\n );\n }\n return {\n chain: channel.chain,\n channelId,\n claim,\n cumulative,\n settle: (outcome) => {\n if (outcome.kind !== 'refused') {\n // Possibly — or certainly — the connector's latest: what a probe resends.\n manager.recordVoucher(channelId, JSON.stringify(claim), cumulative);\n if (outcome.kind === 'banked') manager.banked(channelId, cumulative);\n return;\n }\n const reading = readVoucherRefusal(outcome.message, cumulative);\n manager.refused(channelId, cumulative, charge, reading);\n if (reading.notAdvancing && reading.connectorWatermark === undefined) {\n this.inDoubt.add(channelId);\n }\n },\n };\n }\n\n // ─── EVM ─────────────────────────────────────────────────────────────────\n\n /**\n * Open a channel by depositing into it through the facilitator. The deposit's\n * own voucher is the first packet's charge, so the first packet can carry the\n * very same voucher (ADR 0074 prerequisite 1).\n */\n private async evmOnboard(\n evm: EvmPayerConfig,\n offer: BatchSettlementEvmOffer,\n charge: bigint\n ): Promise<BatchChannel> {\n const config = buildBatchChannelConfig({\n payer: evm.account.address,\n payerAuthorizer: (evm.voucherSigner ?? evm.account).address,\n offer,\n });\n const channel: BatchChannel = {\n chain: 'evm',\n channelId: batchChannelId(config, evmChainIdOf(offer.network)),\n network: offer.network,\n config,\n };\n const deposit = this.config.deposit > charge ? this.config.deposit : charge;\n const manager = this.config.manager;\n manager.adoptPending(this.config.connector, channel, deposit);\n try {\n await this.evmSettle(evm, offer, channel, deposit, charge);\n } catch (err) {\n if (isDefinitiveRefusal(err)) manager.abandon(channel.channelId);\n throw err;\n }\n manager.confirmDeposit(channel.channelId, deposit);\n return channel;\n }\n\n /** Deposit `amount` more into `channel`, carrying the running cumulative `voucherAmount`. */\n private async evmDeposit(\n evm: EvmPayerConfig,\n channel: BatchChannel,\n offer: BatchSettlementEvmOffer,\n amount: bigint,\n voucherAmount: bigint\n ): Promise<void> {\n const manager = this.config.manager;\n const before = manager.depositTotal(channel.channelId);\n manager.setPendingDeposit(channel.channelId, amount);\n try {\n // The deposit carries the running cumulative: a voucher at or below\n // what the chain has claimed would be refused by the facilitator.\n await this.evmSettle(evm, offer, channel, amount, voucherAmount);\n } catch (err) {\n if (isDefinitiveRefusal(err))\n manager.confirmDeposit(channel.channelId, before);\n throw err;\n }\n manager.confirmDeposit(channel.channelId, before + amount);\n }\n\n /**\n * Put a deposit of `amount`, carrying the voucher for `voucherAmount`, on\n * chain — through the facilitator, or from the payer's own ETH, as\n * `depositGas` and what is available decide (toon-client#695).\n */\n private async evmSettle(\n evm: EvmPayerConfig,\n offer: BatchSettlementEvmOffer,\n channel: BatchChannel,\n amount: bigint,\n voucherAmount: bigint\n ): Promise<void> {\n if (channel.chain !== 'evm') throw new Error('unreachable');\n const mode = evm.depositGas ?? 'auto';\n const method = evm.depositMethod ?? offer.extra.assetTransferMethod ?? 'eip3009';\n // An empty `facilitatorUrl` is the caller saying \"none\", not \"the default\".\n const facilitatorUrl =\n mode === 'self' || evm.facilitatorUrl === ''\n ? undefined\n : (evm.facilitatorUrl ?? offer.extra.facilitator ?? defaultFacilitatorFor(offer.network));\n if (facilitatorUrl === undefined && mode === 'facilitator') {\n throw new ConfigError(\n `depositing into a channel on ${offer.network} needs \\`facilitatorUrl\\`: the x402 ` +\n 'facilitator that relays the deposit and pays its gas. This connector names none.'\n );\n }\n\n const build = method === 'permit2' ? buildPermit2Deposit : buildEip3009Deposit;\n const payload = await build({\n payer: evm.account,\n ...(evm.voucherSigner ? { voucherSigner: evm.voucherSigner } : {}),\n offer: {\n ...offer,\n extra: { ...offer.extra, withdrawDelay: channel.config.withdrawDelay },\n },\n config: channel.config,\n amount,\n voucherAmount,\n });\n\n // A Permit2 token needs Permit2 approved for the amount first.\n let extensions: DepositExtensions | undefined;\n // Without a reader the allowance is unknown, and the facilitator decides.\n if (method === 'permit2' && evm.reader) {\n const allowance = await permit2Allowance(evm.reader, offer.asset, evm.account.address);\n if (allowance < amount) {\n extensions = facilitatorUrl\n ? await this.sponsoredApproval(evm, offer, facilitatorUrl, amount, payload)\n : undefined;\n if (extensions === undefined) {\n if (mode === 'facilitator') {\n throw new FacilitatorError(\n `${offer.asset} has no ERC-3009, so its deposit goes through Permit2, which needs ` +\n `a one-time approval from ${evm.account.address}; the facilitator sponsors none, ` +\n \"and depositGas 'facilitator' will not spend this wallet's ETH on it.\",\n 'permit2_allowance_required'\n );\n }\n await this.payOwnGas(evm, `a one-time Permit2 approval of ${offer.asset}`, facilitatorUrl);\n await approvePermit2(this.requireWallet(evm), offer.asset, {\n reader: evm.reader,\n owner: evm.account.address,\n atLeast: amount,\n });\n }\n }\n }\n\n if (facilitatorUrl === undefined) {\n await this.payOwnGas(evm, 'the deposit', facilitatorUrl, offer.network);\n await depositDirectly(this.requireWallet(evm), payload, method);\n return;\n }\n try {\n await settleDeposit({\n facilitatorUrl,\n // The facilitator checks the payload against the requirements' method,\n // so they name the one signed, which the caller may have overridden.\n offer: { ...offer, extra: { ...offer.extra, assetTransferMethod: method } },\n payload,\n ...(extensions ? { extensions } : {}),\n ...(this.config.fetch ? { fetchImpl: this.config.fetch } : {}),\n });\n } catch (err) {\n // The same signed payload can go on chain from the payer's own wallet,\n // and its nonce is single-use: if the facilitator's did land after all,\n // this one reverts rather than depositing twice. An approval the\n // facilitator was to fund is not ours to redo, so that case rethrows.\n const retry =\n mode === 'auto' &&\n extensions === undefined &&\n facilitatorCannotHandle(err) &&\n (await holdsEth(evm.wallet));\n if (!retry) throw explainPermit2(err, offer, evm);\n await depositDirectly(this.requireWallet(evm), payload, method);\n }\n }\n\n /**\n * One of x402's gas-sponsoring extensions for a Permit2 approval, when the\n * facilitator offers one this token can use; `undefined` otherwise.\n */\n private async sponsoredApproval(\n evm: EvmPayerConfig,\n offer: BatchSettlementEvmOffer,\n facilitatorUrl: string,\n amount: bigint,\n payload: { deposit: unknown }\n ): Promise<DepositExtensions | undefined> {\n let offered: string[];\n try {\n offered = await facilitatorExtensions(facilitatorUrl, this.config.fetch);\n } catch {\n return undefined;\n }\n const chainId = evmChainIdOf(offer.network);\n if (offered.includes(EIP2612_GAS_SPONSORING) && offer.extra.name && offer.extra.version) {\n const nonce = await eip2612Nonce(this.requireReader(evm), offer.asset, evm.account.address);\n if (nonce !== undefined) {\n const auth = (payload.deposit as {\n authorization: { permit2Authorization: { deadline: string } };\n }).authorization.permit2Authorization;\n return signEip2612GasSponsoring({\n payer: evm.account,\n token: offer.asset,\n name: offer.extra.name,\n version: offer.extra.version,\n chainId,\n nonce,\n amount,\n deadline: auth.deadline,\n });\n }\n }\n if (offered.includes(ERC20_APPROVAL_GAS_SPONSORING) && evm.wallet) {\n return signErc20ApprovalGasSponsoring({\n payerAddress: evm.account.address,\n wallet: evm.wallet,\n token: offer.asset,\n chainId,\n });\n }\n return undefined;\n }\n\n /** Refuse, naming what would work, unless the payer holds ETH to pay `what` with. */\n private async payOwnGas(\n evm: EvmPayerConfig,\n what: string,\n facilitatorUrl: string | undefined,\n network?: string\n ): Promise<void> {\n const wallet = evm.wallet;\n const eth = wallet ? await wallet.getBalance() : 0n;\n if (eth > 0n) return;\n if (network !== undefined && facilitatorUrl === undefined && evm.depositGas !== 'self') {\n throw new ConfigError(\n `depositing into a channel on ${network} needs either \\`facilitatorUrl\\` — an x402 ` +\n 'facilitator that pays the gas, which this connector names none of — or ETH in ' +\n `${evm.account.address} to deposit directly.`\n );\n }\n throw new InsufficientBalanceError(\n `${what} costs gas, ${\n facilitatorUrl ? 'the facilitator does not sponsor it, ' : ''\n }and ${evm.account.address} holds no ETH to pay for it. Send it a little ETH, or use a ` +\n (what.includes('Permit2')\n ? 'facilitator that sponsors Permit2 approvals.'\n : 'facilitator.')\n );\n }\n\n private requireReader(evm: EvmPayerConfig): ContractReader {\n if (!evm.reader) {\n throw new ConfigError('this payer has no EVM reader to read the token with');\n }\n return evm.reader;\n }\n\n private requireWallet(evm: EvmPayerConfig): EvmWalletAccess {\n if (!evm.wallet) {\n throw new ConfigError(\"paying a deposit's gas from this wallet needs its EVM chain access\");\n }\n return evm.wallet;\n }\n\n // ─── Solana ──────────────────────────────────────────────────────────────\n\n /**\n * Open a channel the receiving connector sponsors: the connector pays the fee\n * and the rent, and the payer needs no SOL at all.\n *\n * The sponsor key is the one THIS connector published — the offer is read off\n * its own `GET /ilp` — so the refusal of any other sponsor that\n * {@link buildSponsoredOpen} enforces holds by construction here.\n */\n private async solanaOnboard(\n solana: SolanaPayerConfig,\n offer: BatchSettlementSvmOffer,\n charge: bigint\n ): Promise<BatchChannel> {\n const { sponsorEndpoint, minDeposit, feePayer, tokenProgram } = offer.extra;\n if (!sponsorEndpoint) {\n throw new ConfigError(\n `the connector's Solana batch-settlement offer names no sponsorEndpoint to open a channel through`\n );\n }\n const payer = base58Encode(solana.signer.publicKey);\n const floor = minDeposit !== undefined ? BigInt(minDeposit) : 0n;\n const deposit = [this.config.deposit, charge, floor].reduce((a, b) =>\n a > b ? a : b\n );\n\n // x402 SVM spec §4.1: the client confirms the token program against the\n // mint's on-chain owner rather than trusting the offer.\n const mintOwner = await accountOwner(solana.rpc, offer.asset);\n if (mintOwner !== tokenProgram) {\n throw new ConfigError(\n `mint ${offer.asset} is owned by ${mintOwner ?? 'nothing'}, not the offer's tokenProgram ${tokenProgram}`\n );\n }\n const ata = deriveAssociatedTokenAccount(payer, offer.asset);\n const balance = await getTokenAccountBalance(solana.rpc, ata);\n if (balance === null) {\n throw new InsufficientBalanceError(\n `${payer} has no token account for ${offer.asset} (${ata}); the channel's deposit is drawn from it, and it must exist before the connector will sponsor an open`\n );\n }\n if (balance < deposit) {\n throw new InsufficientBalanceError(\n `${payer} holds ${balance} of ${offer.asset}; a sponsored open deposits ${deposit}`\n );\n }\n\n const [openSlot, recentBlockhash] = await Promise.all([\n currentSlot(solana.rpc),\n getLatestBlockhash(solana.rpc),\n ]);\n const config = buildSvmBatchChannelConfig({ payer, offer, openSlot });\n const { transaction, channelId } = buildSponsoredOpen({\n payer: solana.signer,\n config,\n offer,\n connectorSponsor: feePayer,\n deposit,\n recentBlockhash,\n });\n const channel: BatchChannel = {\n chain: 'solana',\n channelId,\n network: offer.network,\n sponsor: feePayer,\n config,\n };\n\n const manager = this.config.manager;\n manager.adoptPending(this.config.connector, channel, deposit);\n let opened;\n try {\n opened = await requestSponsoredOpen({\n connector: this.config.connector,\n sponsorEndpoint,\n transaction,\n ...(this.config.fetch ? { fetchImpl: this.config.fetch } : {}),\n });\n } catch (err) {\n if (isDefinitiveRefusal(err)) manager.abandon(channelId);\n throw err;\n }\n if (opened.channelId !== channelId) {\n // Left pending: the chain, not the sponsor's word, decides whether ours exists.\n throw new ValidationError(\n `the sponsor reports opening ${opened.channelId}, not the channel ${channelId} the payer signed for`\n );\n }\n manager.confirmDeposit(channelId, deposit);\n return channel;\n }\n\n // ─── Keys and rules ──────────────────────────────────────────────────────\n\n private requireEvm(): EvmPayerConfig {\n if (!this.config.evm) {\n throw new ConfigError(\n 'this client holds no EVM key to pay a batch-settlement channel with'\n );\n }\n return this.config.evm;\n }\n\n private requireSolana(): SolanaPayerConfig {\n if (!this.config.solana) {\n throw new ConfigError(\n 'this client holds no Solana key to pay a batch-settlement channel with'\n );\n }\n return this.config.solana;\n }\n\n /** Refuse an open, top-up or replacement a packet needs, when that is not its to do. */\n private assertMayOpen(what: string, command: string): void {\n if (this.config.autoOpen === false) {\n throw new ChannelNotOpenError(\n `paying ${this.config.connector} needs ${what} first, and this client does not ` +\n `open channels on its own; run \\`toon-client ${command}\\``\n );\n }\n }\n}\n\n/**\n * Whether a failed deposit or sponsored open is KNOWN not to have landed: the\n * facilitator or sponsor answered, readably, with a refusal. A transport\n * failure, an unreadable answer, or a sponsor's `502` (sent and not confirmed)\n * proves nothing, and leaves the deposit pending for the chain to decide.\n */\nfunction isDefinitiveRefusal(err: unknown): boolean {\n // `settlement_pending`: x402's \"I broadcast it; the receipt timed out\". It\n // may well land, so the channel is kept and settled against the chain.\n if (err instanceof FacilitatorError)\n return err.reason !== 'unreadable_response' && err.reason !== 'settlement_pending';\n if (err instanceof SponsorRefusedError) return err.status !== 502;\n return false;\n}\n\n/** The program that owns `address`, or `null` when there is no such account. */\nasync function accountOwner(\n rpc: SolanaRpcTarget,\n address: string\n): Promise<string | null> {\n const result = (await solanaRpc(rpc, 'getAccountInfo', [\n address,\n { encoding: 'base64', commitment: 'confirmed' },\n ])) as { value: { owner: string } | null };\n return result.value?.owner ?? null;\n}\n\n/**\n * The cluster's current confirmed slot: the channel's `open_slot`, which the\n * program refuses once it is more than 1,500 slots old.\n */\nasync function currentSlot(rpc: SolanaRpcTarget): Promise<bigint> {\n const slot = (await solanaRpc(rpc, 'getSlot', [\n { commitment: 'confirmed' },\n ])) as number;\n return BigInt(slot);\n}\n\n/** A facilitator's Permit2-allowance refusal, explained; any other error as it was. */\nfunction explainPermit2(\n err: unknown,\n offer: BatchSettlementEvmOffer,\n evm: { account: { address: string } }\n): unknown {\n if (err instanceof FacilitatorError && err.reason.includes('permit2_allowance')) {\n return new FacilitatorError(\n `${offer.asset} has no Permit2 allowance from ${evm.account.address}. A Permit2 ` +\n 'deposit needs a one-time `approve(Permit2, …)` from the payer, which costs ' +\n 'native gas unless the facilitator sponsors it; hold a little ETH, use a ' +\n 'facilitator that sponsors approvals, or use a token with ERC-3009.',\n err.reason,\n err\n );\n }\n return err;\n}\n\n/**\n * Whether a failed facilitator call leaves the deposit for the payer to send\n * itself: the facilitator did not answer, answered with something that is not\n * a settle result (a 500 — x402's \"no facilitator registered for this scheme\n * and network\"), or said it cannot handle this kind of deposit. A refusal of\n * the deposit itself (a balance, a voucher, a deadline) would fail on chain\n * just the same, and `settlement_pending` means the facilitator's own\n * transaction may yet land.\n */\nfunction facilitatorCannotHandle(err: unknown): boolean {\n if (err instanceof NetworkError) return true;\n if (!(err instanceof FacilitatorError)) return false;\n return err.reason === 'unreadable_response' || err.reason.startsWith('unsupported_');\n}\n\n/** Whether the payer holds any ETH; an unreadable balance counts as none. */\nasync function holdsEth(wallet: EvmWalletAccess | undefined): Promise<boolean> {\n if (!wallet) return false;\n try {\n return (await wallet.getBalance()) > 0n;\n } catch {\n return false;\n }\n}\n","/**\n * The watermark and the config of this client's x402 `batch-settlement`\n * channels (connector ADRs 0074, 0075; toon-client#688), persisted in a\n * {@link ChannelStore}.\n *\n * A voucher is not a balance proof, so the bookkeeping is its own:\n *\n * - **There is no nonce.** The connector orders vouchers by amount alone and\n * accepts one only if it strictly exceeds the channel's watermark by at\n * least the charge, so the one number to keep is the cumulative amount.\n * - **Nothing is derived.** The channel id travels in every voucher, so the\n * whole config is what must survive a restart: on EVM the contract stores a\n * channel by id and never gives the config back.\n * - **More than one channel to one connector is legal** (decision 2), so a\n * newer channel on the same connector, network and asset retires the older\n * binding into the archive rather than overwriting it — whatever that\n * channel still holds on chain stays findable.\n *\n * ## Resynchronization\n *\n * `POST /ilp/claim-state` answers for a voucher channel (connector#1364,\n * ADR 0075), but only when asked with a signed challenge, and a refusal names\n * the connector's watermark only sometimes. So the rules are built to need it\n * rarely:\n *\n * - the amount is persisted BEFORE a voucher is signed, so a crash never\n * re-signs below something already handed out;\n * - a voucher whose fate is unknown stays counted, so the next one exceeds it\n * whether or not it arrived — at the cost of at most one charge if it did\n * not;\n * - only a definite refusal gives a charge back, and `amount_not_advancing`\n * is not one: it says the connector already holds at least that amount;\n * where its message names the figure, that figure is adopted, and where it\n * does not, the payer asks `claim-state` before the next voucher;\n * - a lost store is recovered from what the chain has landed, a LOWER bound,\n * and then from `claim-state`, the connector's own figure.\n */\n\nimport type { Hex } from 'viem';\nimport type {\n BatchSettlementBinding,\n ChannelStore,\n ChannelStoreEntry,\n} from '../ChannelStore.js';\nimport { InMemoryChannelStore } from '../ChannelStore.js';\nimport type { BatchChannelConfig } from './evm.js';\nimport { evmChainIdOf, X402_BATCH_SETTLEMENT_ADDRESS } from './evm.js';\nimport type { SvmBatchChannelConfig } from './svm.js';\nimport { PAYMENT_CHANNELS_PROGRAM_ID } from './svm.js';\nimport { nextVoucherAmount } from './claim.js';\nimport { ValidationError } from '../../client/errors.js';\n\n/** One batch-settlement channel this client holds. */\nexport type BatchChannel =\n | {\n chain: 'evm';\n channelId: string;\n network: string;\n config: BatchChannelConfig;\n }\n | {\n chain: 'solana';\n channelId: string;\n network: string;\n /** The receiving connector's sponsor key. */\n sponsor: string;\n config: SvmBatchChannelConfig;\n };\n\nconst KEY_PREFIX = 'batch|';\n\nexport class BatchChannelManager {\n private readonly store: ChannelStore;\n\n constructor(store: ChannelStore = new InMemoryChannelStore()) {\n this.store = store;\n }\n\n /** Where the binding for `connector`'s channel on `network` in `asset` lives. */\n static bindingKey(connector: string, network: string, asset: string): string {\n // EVM addresses are case-insensitive, base58 is not.\n const a = network.startsWith('eip155:') ? asset.toLowerCase() : asset;\n return `${KEY_PREFIX}${connector}|${network}|${a}`;\n }\n\n /**\n * Record a channel this client just opened or deposited into (and so owns),\n * with the deposit it holds. A new channel starts at a watermark of zero; a\n * channel already known keeps its own.\n */\n adopt(connector: string, channel: BatchChannel, depositTotal: bigint): void {\n this.bind(connector, channel, { depositTotal });\n }\n\n /**\n * Record a channel BEFORE its first deposit or sponsored open leaves, with\n * that deposit pending. A facilitator or sponsor that times out after the\n * transaction landed must not lose the channel: on EVM the contract never\n * gives a config back, and a Solana PDA cannot be recomputed without its\n * salt and slot. {@link confirmDeposit} or {@link abandon} settles it.\n */\n adoptPending(\n connector: string,\n channel: BatchChannel,\n pendingDeposit: bigint\n ): void {\n this.bind(connector, channel, { depositTotal: 0n, pendingDeposit });\n }\n\n private bind(\n connector: string,\n channel: BatchChannel,\n deposit: { depositTotal: bigint; pendingDeposit?: bigint }\n ): void {\n const key = BatchChannelManager.bindingKey(\n connector,\n channel.network,\n channel.config.token\n );\n const existing = this.store.loadBinding?.(key);\n if (existing && existing.channelId !== channel.channelId) {\n this.store.supersedeBinding?.(key);\n }\n this.store.saveBinding?.(key, {\n channelId: channel.channelId,\n context: {\n chainType: channel.chain,\n chainId: channel.chain === 'evm' ? evmChainIdOf(channel.network) : 0,\n tokenNetworkAddress:\n channel.chain === 'evm'\n ? X402_BATCH_SETTLEMENT_ADDRESS\n : PAYMENT_CHANNELS_PROGRAM_ID,\n tokenAddress: channel.config.token,\n recipient: channel.config.receiver,\n },\n depositTotal: deposit.depositTotal,\n ...(deposit.pendingDeposit !== undefined\n ? { pendingDeposit: deposit.pendingDeposit }\n : {}),\n batchSettlement: toBinding(channel),\n });\n if (!this.store.load(channel.channelId)) {\n this.store.save(channel.channelId, {\n nonce: 0,\n cumulativeAmount: 0n,\n signedCeiling: 0n,\n });\n }\n }\n\n /** A deposit on `channelId` whose fate is not yet known, if there is one. */\n pendingDeposit(channelId: string): bigint | undefined {\n return this.findBinding(channelId)?.binding.pendingDeposit;\n }\n\n /** Record a top-up about to leave, before it does. */\n setPendingDeposit(channelId: string, amount: bigint): void {\n const found = this.requireBinding(channelId);\n this.store.saveBinding?.(found.key, {\n ...found.binding,\n pendingDeposit: amount,\n });\n }\n\n /**\n * Settle a pending deposit against what the chain holds: `onChain` is the\n * channel's escrow as the chain reports it (EVM `channels(id).balance`,\n * Solana `deposit`), which is the deposit from here on.\n */\n confirmDeposit(channelId: string, onChain: bigint): void {\n const found = this.requireBinding(channelId);\n const { pendingDeposit: _settled, ...rest } = found.binding;\n this.store.saveBinding?.(found.key, { ...rest, depositTotal: onChain });\n }\n\n /**\n * Forget a channel whose first deposit definitely did not land: nothing is\n * on chain under it, so there is nothing to keep.\n */\n abandon(channelId: string): void {\n const found = this.findBinding(channelId);\n if (!found || (found.binding.depositTotal ?? 0n) > 0n) return;\n this.store.deleteBinding?.(found.key);\n this.store.delete(channelId);\n }\n\n /** The channel this client pays `connector` from on `network` in `asset`, if it holds one. */\n resolve(\n connector: string,\n network: string,\n asset: string\n ): BatchChannel | undefined {\n const binding = this.store.loadBinding?.(\n BatchChannelManager.bindingKey(connector, network, asset)\n );\n if (!binding?.batchSettlement) return undefined;\n return fromBinding(binding.channelId, binding.batchSettlement);\n }\n\n /** The deposit recorded for `channelId`. */\n depositTotal(channelId: string): bigint {\n return this.findBinding(channelId)?.binding.depositTotal ?? 0n;\n }\n\n /** Record a top-up of `amount` on `channelId`. */\n addDeposit(channelId: string, amount: bigint): void {\n const found = this.requireBinding(channelId);\n this.store.saveBinding?.(found.key, {\n ...found.binding,\n depositTotal: (found.binding.depositTotal ?? 0n) + amount,\n });\n }\n\n /** The cumulative amount this client counts as signed on `channelId`. */\n signedSoFar(channelId: string): bigint {\n return this.entry(channelId).cumulativeAmount;\n }\n\n /**\n * Reserve the next voucher on `channelId` for a packet charging `charge`, and\n * persist it before anything is signed. Returns the cumulative amount to sign,\n * or `undefined` when the packet should carry no voucher (a free route).\n *\n * @throws {ValidationError} when the channel's deposit cannot cover it — the\n * connector would refuse it, so the caller tops up first.\n */\n reserve(channelId: string, charge: bigint): bigint | undefined {\n const entry = this.entry(channelId);\n const amount = nextVoucherAmount(entry.cumulativeAmount, charge);\n if (amount === undefined) return undefined;\n const deposit = this.depositTotal(channelId);\n if (amount > deposit) {\n throw new ValidationError(\n `a voucher for ${amount} exceeds channel ${channelId}'s deposit of ${deposit}; top it up first`\n );\n }\n this.store.save(channelId, {\n ...entry,\n cumulativeAmount: amount,\n signedCeiling:\n entry.signedCeiling === undefined || amount > entry.signedCeiling\n ? amount\n : entry.signedCeiling,\n });\n return amount;\n }\n\n /**\n * The connector refused the voucher for `voucherAmount`, reserved for\n * `charge`. What the refusal says about the connector's watermark decides:\n *\n * - **it named the watermark** — an underpayment says how far the voucher\n * advanced it, so the watermark is `voucherAmount − advanced`. That is\n * adopted exactly (never above what this client ever signed), and the\n * next voucher is priced from it rather than refused the same way again;\n * - **it did not advance** — the connector holds at least this much, and\n * can hold no more than this client ever signed, so the count moves to\n * that ceiling and the next voucher clears whatever it holds;\n * - **anything else** banked nothing, and the charge is given back — but\n * only if no later voucher has already superseded this one, since a\n * concurrent send may have been banked above it.\n */\n refused(\n channelId: string,\n voucherAmount: bigint,\n charge: bigint,\n reason: { notAdvancing: boolean; connectorWatermark?: bigint }\n ): void {\n const entry = this.entry(channelId);\n const ceiling = entry.signedCeiling ?? entry.cumulativeAmount;\n let cumulative = entry.cumulativeAmount;\n let floor = entry.provenFloor;\n if (reason.connectorWatermark !== undefined) {\n cumulative =\n reason.connectorWatermark > ceiling\n ? ceiling\n : reason.connectorWatermark;\n floor = max(floor, cumulative);\n } else if (reason.notAdvancing) {\n cumulative = ceiling > cumulative ? ceiling : cumulative;\n // The connector already holds at least this voucher's amount.\n floor = max(floor, voucherAmount);\n } else if (entry.cumulativeAmount === voucherAmount && charge > 0n) {\n cumulative = voucherAmount > charge ? voucherAmount - charge : 0n;\n }\n if (floor !== undefined && cumulative < floor) cumulative = floor;\n if (cumulative === entry.cumulativeAmount && floor === entry.provenFloor) return;\n this.store.save(channelId, {\n ...entry,\n cumulativeAmount: cumulative,\n ...(floor !== undefined ? { provenFloor: floor } : {}),\n });\n }\n\n /** The connector banked the voucher for `voucherAmount`: it holds at least that. */\n banked(channelId: string, voucherAmount: bigint): void {\n const entry = this.entry(channelId);\n if (entry.provenFloor !== undefined && entry.provenFloor >= voucherAmount) return;\n this.store.save(channelId, { ...entry, provenFloor: voucherAmount });\n }\n\n /**\n * Record a voucher that went out on `channelId`, for a probe to resend — only\n * if it is the highest yet. Answers come back in any order, and a probe must\n * retransmit the connector's latest, never an older voucher it superseded.\n */\n recordVoucher(channelId: string, claimJson: string, amount: bigint): void {\n const found = this.findBinding(channelId);\n if (!found) return;\n const recorded = found.binding.lastVoucherAmount;\n if (recorded !== undefined && recorded > amount) return;\n this.store.saveBinding?.(found.key, {\n ...found.binding,\n lastVoucher: claimJson,\n lastVoucherAmount: amount,\n });\n }\n\n /** The last voucher this client sent on `channelId`, exactly as it travelled. */\n lastVoucher(channelId: string): string | undefined {\n return this.findBinding(channelId)?.binding.lastVoucher;\n }\n\n /**\n * Adopt the connector's own watermark for `channelId`, as `POST\n * /ilp/claim-state` reported it: the figure the next voucher must exceed.\n * Never above what this client ever signed — a connector can only hold a\n * voucher it was given — unless `recovering` says this client's own record\n * was lost, when the connector's figure is the only one there is. And never\n * below what the connector is proven to hold: a figure under that is a\n * connector that lost or has not caught up on its own state, and adopting it\n * would sign vouchers it refuses as going backwards.\n */\n adoptConnectorWatermark(\n channelId: string,\n cumulativeClaimed: bigint,\n options: { recovering?: boolean } = {}\n ): void {\n const entry = this.entry(channelId);\n const ceiling = entry.signedCeiling ?? entry.cumulativeAmount;\n let adopted =\n options.recovering !== true && cumulativeClaimed > ceiling ? ceiling : cumulativeClaimed;\n if (entry.provenFloor !== undefined && adopted < entry.provenFloor) {\n adopted = entry.provenFloor;\n }\n this.store.save(channelId, {\n ...entry,\n cumulativeAmount: adopted,\n signedCeiling: adopted > ceiling ? adopted : ceiling,\n });\n }\n\n /** Whether this client still holds the watermark for `channelId`. */\n hasWatermark(channelId: string): boolean {\n return this.store.load(channelId) !== undefined;\n }\n\n /**\n * Rebuild a lost watermark for a channel whose binding survived — the two\n * live in separate files — from what the chain shows landed. The connector\n * holds at least that much; the payer then asks `claim-state` for the\n * connector's own figure (connector#1364), which replaces this floor.\n */\n restoreWatermark(channelId: string, landed: bigint): void {\n if (this.store.load(channelId)) return;\n this.store.save(channelId, {\n nonce: 0,\n cumulativeAmount: landed,\n signedCeiling: landed,\n provenFloor: landed,\n });\n }\n\n /**\n * Raise the watermark to what the chain shows landed on `channelId` — EVM\n * `channels(id).totalClaimed`, Solana `settled` — when the store lost it. The\n * connector has banked at least that much, so it is a floor, never a ceiling:\n * a figure below what this client counts moves nothing.\n */\n recoverFromChain(channelId: string, landed: bigint): void {\n const entry = this.entry(channelId);\n if (landed <= entry.cumulativeAmount) return;\n this.store.save(channelId, {\n ...entry,\n cumulativeAmount: landed,\n provenFloor: max(entry.provenFloor, landed),\n signedCeiling:\n entry.signedCeiling === undefined || landed > entry.signedCeiling\n ? landed\n : entry.signedCeiling,\n });\n }\n\n /**\n * Record that this client started leaving `channelId` at `closedAt`, and can\n * take its deposit back from `settleableAt` (unix seconds). A closing channel\n * takes no more vouchers: the connector stops accepting them the moment the\n * chain says the payer is leaving.\n */\n markClosing(channelId: string, closedAt: bigint, settleableAt: bigint): void {\n this.store.save(channelId, {\n ...this.entry(channelId),\n closedAt,\n settleableAt,\n });\n }\n\n /** Record that `channelId`'s unspent deposit is back with the payer. */\n markSettled(channelId: string, settledAt: bigint): void {\n this.store.save(channelId, { ...this.entry(channelId), settledAt });\n }\n\n /** Whether this client has started leaving `channelId`. */\n isClosing(channelId: string): boolean {\n return this.store.load(channelId)?.closedAt !== undefined;\n }\n\n /**\n * Every channel this client holds on `connector`, live or archived, with its\n * exit state — what `toon-client channel settle` walks to take deposits back.\n */\n channels(connector: string): {\n channel: BatchChannel;\n depositTotal: bigint;\n signed: bigint;\n closedAt?: bigint;\n settleableAt?: bigint;\n settledAt?: bigint;\n }[] {\n const prefix = `${KEY_PREFIX}${connector}|`;\n return (this.store.listBindings?.() ?? [])\n .filter(\n ({ key, binding }) => key.startsWith(prefix) && binding.batchSettlement\n )\n .map(({ binding }) => {\n const entry = this.store.load(binding.channelId);\n return {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- filtered above\n channel: fromBinding(binding.channelId, binding.batchSettlement!),\n depositTotal: binding.depositTotal ?? 0n,\n signed: entry?.cumulativeAmount ?? 0n,\n ...(entry?.closedAt !== undefined\n ? { closedAt: entry.closedAt }\n : {}),\n ...(entry?.settleableAt !== undefined\n ? { settleableAt: entry.settleableAt }\n : {}),\n ...(entry?.settledAt !== undefined\n ? { settledAt: entry.settledAt }\n : {}),\n };\n });\n }\n\n /**\n * The channels on `connector` this client can still pay from or leave: not\n * yet closing, whether live or archived by a newer one.\n */\n openChannels(connector: string): BatchChannel[] {\n return this.channels(connector)\n .filter((c) => c.closedAt === undefined && c.settledAt === undefined)\n .map((c) => c.channel);\n }\n\n private requireBinding(channelId: string) {\n const found = this.findBinding(channelId);\n if (!found)\n throw new ValidationError(\n `no batch-settlement channel ${channelId} is held`\n );\n return found;\n }\n\n private entry(channelId: string): ChannelStoreEntry {\n const entry = this.store.load(channelId);\n if (!entry)\n throw new ValidationError(\n `no batch-settlement channel ${channelId} is held`\n );\n return entry;\n }\n\n /**\n * The binding that records `channelId`, live or archived: a channel retired by\n * a newer one on the same connector still holds its deposit, and still needs\n * its watermark to exit.\n */\n private findBinding(channelId: string) {\n return this.store\n .listBindings?.()\n .find(\n ({ key, binding }) =>\n key.startsWith(KEY_PREFIX) &&\n binding.batchSettlement !== undefined &&\n binding.channelId === channelId\n );\n }\n}\n\nfunction toBinding(channel: BatchChannel): BatchSettlementBinding {\n if (channel.chain === 'evm') {\n return {\n chain: 'evm',\n network: channel.network,\n config: { ...channel.config },\n };\n }\n return {\n chain: 'solana',\n network: channel.network,\n sponsor: channel.sponsor,\n config: {\n ...channel.config,\n salt: channel.config.salt.toString(),\n openSlot: channel.config.openSlot.toString(),\n },\n };\n}\n\nfunction fromBinding(\n channelId: string,\n b: BatchSettlementBinding\n): BatchChannel {\n if (b.chain === 'evm') {\n return {\n chain: 'evm',\n channelId,\n network: b.network,\n config: { ...b.config, salt: b.config.salt as Hex },\n };\n }\n return {\n chain: 'solana',\n channelId,\n network: b.network,\n sponsor: b.sponsor,\n config: {\n ...b.config,\n salt: BigInt(b.config.salt),\n openSlot: BigInt(b.config.openSlot),\n },\n };\n}\n\nfunction max(a: bigint | undefined, b: bigint): bigint {\n return a === undefined || b > a ? b : a;\n}\n","/**\n * One paid request, end to end.\n *\n * This is the composition the whole package exists to perform, and it is written\n * as one readable function plus its helpers because the ORDER is the contract:\n *\n * 1. **Describe the node** (`GET /ilp`). Everything else reads off this one\n * document — the sealing key, the settlement chains, the endpoints.\n * 2. **Get the sealing key.** The payload is sealed to the connector that\n * TERMINATES the route (`client-edge-spec.md` §1.8, ADR 0018), so a forwarded\n * destination needs {@link SendOptions.sealTo} naming that node; sealing to a\n * forwarder is a confidentiality failure the wire can only report as an\n * undeliverable packet.\n * 3. **Seal.** {@link sealExchange} mints the gift wrap, the execution condition\n * and the shared secret together, so they cannot drift: the condition is\n * `sha256` of the fulfilment derived from the secret inside the wrap, and the\n * answer is sealed back with that same secret.\n * 4. **Ask the price**, and charge it against the sealed payload. A route's base\n * price is flat per handler — the route table IS the price list — but a route\n * MAY also publish a `pricePerKib` and meter by the size of the sealed\n * payload, which is why this step follows the seal rather than preceding it.\n * The rate is the connector's; the arithmetic\n * ({@link ../connector/self-description.js!chargeFor}) is the only thing\n * computed locally, and a wrong answer is refused `F03` with the real figure\n * attached rather than silently overpaid.\n * 5. **Get a voucher** for that amount: the payer resolves the x402 channel it\n * holds with this node — opening one with no native gas when there is none —\n * and signs the next cumulative voucher on it (connector ADRs 0074, 0075).\n * 6. **Choose a carriage and send.**\n * 7. **Read the answer** with the secret from step 4.\n *\n * ## How a voucher's fate moves the watermark\n *\n * A voucher has no nonce: the connector orders vouchers by amount alone, and\n * accepts one only if it strictly exceeds the channel's watermark by at least\n * the charge. So:\n *\n * - **a transport error leaves the voucher counted.** It may have been\n * banked, and the next voucher exceeds it either way — being one charge\n * over is the only cost, where being under would be refused;\n * - **a refusal hands the payer the reject's own text,** which says where the\n * connector's watermark stands (`readVoucherRefusal`); one that says the\n * connector holds more without saying how much sends the payer to\n * `POST /ilp/claim-state` before the next voucher.\n *\n * **`refusedBy` is honest about what is actually known.** A sealed reject is\n * proof: only the terminating connector could recover the secret needed to seal\n * one, so `'destination'` is a fact rather than an inference. A plaintext reject\n * identifies nobody — any hop can raise one, and so can a termination that could\n * not open the wrap — so it is `'path'`. A greeting is `'edge'`: the connector we\n * are attached to refused before routing at all.\n */\nimport {\n readExchangeOutcome,\n sealExchange,\n type SealedExchange,\n} from '../wire/sealed-exchange.js';\nimport type { EnvelopeRequest } from '../wire/envelope.js';\nimport {\n chargeFor,\n type NodeSelfDescription,\n type RouteCharge,\n} from '../connector/self-description.js';\nimport { decodeConnectorPublicKey } from '../connector/ConnectorEdgeClient.js';\nimport { parsePaymentTerms } from '../connector/x402.js';\nimport type { IlpSendResult } from '../ilp/types.js';\nimport type { IlpSendParams } from '../ilp/ilp-send.js';\nimport type { PreparedVoucher } from '../channel/batch-settlement/payer.js';\nimport { toBase64, fromBase64, encodeUtf8, decodeUtf8 } from '../utils/binary.js';\nimport {\n BeforePayRefusedError,\n ChainUnavailableError,\n PaymentRequiredError,\n RouteNotPricedError,\n TransportRequiredError,\n ValidationError,\n} from './errors.js';\nimport type {\n ChainKind,\n ClaimSummary,\n PaymentTerms,\n SendOptions,\n SendRequest,\n SendResult,\n} from './types.js';\n\n/**\n * The narrowest thing that can carry a paid packet: one method.\n *\n * Deliberately narrower than {@link ../ilp/types.js!ClaimSendingTransport}, which\n * also requires the unpaid `sendIlpPacket`. Nothing in this pipeline ever sends\n * an unpaid packet — a request with no claim is answered with terms rather than\n * performed — and requiring the wider port would exclude\n * {@link ../btp/BtpPaidWriteTransport.js!BtpPaidWriteTransport}, whose whole\n * subject is paid writes.\n */\nexport interface PaidWriteTransport {\n sendIlpPacketWithClaim(\n params: IlpSendParams,\n claim: Record<string, unknown>\n ): Promise<IlpSendResult>;\n /**\n * The same packet with no claim attached, for a route priced at zero. Both\n * carriages have always offered it; only a free route uses it.\n */\n sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;\n}\n\n/**\n * Everything {@link send} needs from the client around it.\n *\n * A port rather than the `ToonClient` itself, so the composition can be tested\n * against a fake connector with no sockets, no chain and no keys beyond the ones\n * the claim actually needs — and so the carriage, which is the one part that\n * genuinely differs between deployments, stays behind one method.\n */\nexport interface SendContext {\n /** The node's `GET /ilp`, cached per client. */\n describe(): Promise<NodeSelfDescription>;\n /**\n * The key to seal to for the node described by `description`. Falls back to\n * `GET /ilp/identity` when the self-description carries no `edgeIdentity`.\n */\n sealKey(description: NodeSelfDescription): Promise<Uint8Array>;\n /** The sealing key of a DIFFERENT node, by its client-edge URL. */\n sealKeyAt(endpoint: string): Promise<Uint8Array>;\n /**\n * `GET /ilp/routes/price`; `null` when this node prices no matching route.\n *\n * The whole terms rather than one figure, because a route may meter by size\n * and the base price alone would under-pay it.\n */\n routePrice(destination: string): Promise<RouteCharge | null>;\n /**\n * The carriage for one destination, chosen and connected.\n *\n * `destination` is passed because a node pins a carriage **per route**\n * (connector ADR 0072): the pin covering the prefix this packet is addressed\n * to is the one that will be enforced, and a node-wide summary is silent on\n * any node that pins one of its own addresses and not another.\n */\n transport(\n description: NodeSelfDescription,\n destination: string\n ): Promise<{\n kind: 'http' | 'btp';\n transport: PaidWriteTransport;\n }>;\n /**\n * Where a paid packet's voucher comes from (connector ADRs 0074, 0075).\n * `undefined` from it means the node offers no x402 channel on this client's\n * chain, and the packet cannot be paid.\n */\n vouchers: {\n claimFor(\n description: NodeSelfDescription,\n chain: ChainKind,\n amount: bigint\n ): Promise<PreparedVoucher | undefined>;\n };\n /** The chain claims are signed on, for {@link ClaimSummary}. */\n chain: ChainKind;\n /** Per-packet timeout, in milliseconds. */\n timeoutMs: number;\n /** Where an operational warning goes. Defaults to `console.warn`. */\n warn?: (message: string) => void;\n}\n\n/**\n * Pay for one HTTP request through a connector, and return what the app said.\n *\n * @throws {RouteNotPricedError} the node prices no route covering `destination`\n * and no explicit {@link SendOptions.amount} was given.\n * @throws {BeforePayRefusedError} the caller's own\n * {@link SendOptions.beforePay} returned a reason, having seen the resolved\n * price. Nothing was signed and no packet went out.\n * @throws Anything the chain or the network throws while opening a channel.\n * A REJECT is never thrown — see {@link SendResult}.\n */\nexport async function send(\n context: SendContext,\n destination: string,\n request: SendRequest = {},\n options: SendOptions = {}\n): Promise<SendResult> {\n const description = await context.describe();\n const sealingKey = await resolveSealingKey(context, description, options.sealTo);\n // Seal BEFORE pricing: a metered route charges by the size of the sealed\n // payload, which does not exist until `sealExchange` has run.\n const exchange = sealExchange(toEnvelopeRequest(request), sealingKey);\n const amount = await resolveAmount(\n context,\n destination,\n options.amount,\n exchange.data.length\n );\n // The caller's last look, between step 4 and step 5: the price is known and\n // nothing has been signed. Here and only here can a refusal be guaranteed to\n // cost nothing — one line later `attempt` may open a channel and signs a\n // voucher, and a signed voucher cannot be unsigned.\n refuseIfCallerSaysSo(options.beforePay, destination, amount, request);\n const carriage = await context.transport(description, destination);\n\n return attempt(context, {\n destination,\n amount,\n exchange,\n carriage,\n description,\n timeoutMs: options.timeoutMs ?? context.timeoutMs,\n });\n}\n\n/**\n * Give {@link SendOptions.beforePay} the resolved price, and stop here if it\n * says no.\n *\n * Synchronous on purpose. The hook's guarantee is \"this runs while nothing has\n * been signed yet\", and an `await` here would hold that window open across the\n * event loop for a check whose whole job is to be a last, local look at facts\n * this client already has in hand. A caller needing a network round trip to\n * decide has a different question, and should ask it before calling `send`.\n *\n * A returned string becomes a {@link BeforePayRefusedError}; a throw from the\n * callback is left exactly as it is, because re-wrapping a caller's own error\n * hides the stack that says where the rule actually lives.\n *\n * Runs for a free route as well as a paid one. `amount === 0n` means no claim is\n * signed, but the answer is not the only thing a wrong request spends: it still\n * costs the round trip and whatever the app does with it before saying no.\n */\nfunction refuseIfCallerSaysSo(\n beforePay: SendOptions['beforePay'],\n destination: string,\n amount: bigint,\n request: SendRequest\n): void {\n if (beforePay === undefined) return;\n const reason = beforePay({ destination, amount, request });\n if (typeof reason !== 'string') return;\n throw new BeforePayRefusedError(reason, destination, amount);\n}\n\n// ─── One attempt ────────────────────────────────────────────────────────────\n\ninterface AttemptParams {\n destination: string;\n amount: bigint;\n exchange: SealedExchange;\n carriage: { kind: 'http' | 'btp'; transport: PaidWriteTransport };\n description: NodeSelfDescription;\n timeoutMs: number;\n}\n\nasync function attempt(context: SendContext, params: AttemptParams): Promise<SendResult> {\n // A route priced at zero is deliberately free, and free means no voucher.\n //\n // The connector states this rather than leaving it implied: a terminated\n // route MUST carry a price, and `price = 0` is how an operator writes down\n // that they meant it, \"because it is never silently free\". Such a route is\n // not greeted and no claim gate runs on it — an unpaid request to an unpriced\n // destination is simply routed. So a free route must be usable by a client\n // that holds no channel and no funds at all.\n if (params.amount === 0n) return attemptUnpaid(params);\n\n const voucher = await context.vouchers.claimFor(params.description, context.chain, params.amount);\n if (voucher === undefined) {\n throw new ChainUnavailableError(\n `The connector offers no x402 channel on ${context.chain}, so this client has no way to ` +\n 'pay it. Pick a chain it publishes in `GET /ilp` `batchSettlements`.',\n params.description.batchSettlements.map((t) => t.network)\n );\n }\n return attemptWithVoucher(context, params, voucher);\n}\n\n/**\n * One attempt, paid by a voucher: the packet on its carriage, and its fate\n * reported back to the payer so the watermark follows it (see this module's\n * docs).\n */\nasync function attemptWithVoucher(\n context: SendContext,\n params: AttemptParams,\n voucher: PreparedVoucher\n): Promise<SendResult> {\n const summary: ClaimSummary = {\n channelId: voucher.channelId,\n chain: context.chain,\n cumulative: voucher.cumulative,\n amount: params.amount,\n };\n\n let result: IlpSendResult;\n try {\n result = await params.carriage.transport.sendIlpPacketWithClaim(\n {\n destination: params.destination,\n amount: params.amount.toString(),\n data: toBase64(params.exchange.data),\n expectedFulfillment: params.exchange.fulfillment,\n timeout: params.timeoutMs,\n },\n voucher.claim\n );\n } catch (error) {\n const greeting = asGreeting(error, params.carriage.kind, summary);\n if (greeting) {\n // The connector answered before routing: nothing was banked.\n voucher.settle({ kind: 'refused' });\n return greeting;\n }\n voucher.settle({ kind: 'unknown' });\n throw error;\n }\n\n if (claimWasRefused(result)) {\n // The reject's own text says where the connector's watermark stands.\n voucher.settle({\n kind: 'refused',\n ...(result.message !== undefined ? { message: result.message } : {}),\n });\n } else {\n voucher.settle({ kind: 'banked' });\n }\n return toSendResult(result, params, summary);\n}\n\n/**\n * One attempt at a free route: the same sealed packet, with no claim attached.\n *\n * Everything else is identical — the envelope, the gift wrap, the fulfilment\n * derived from the secret inside it, and the sealed answer read back with that\n * same secret. Only the payment is absent, because there is nothing to pay.\n */\nasync function attemptUnpaid(params: AttemptParams): Promise<SendResult> {\n const result = await params.carriage.transport.sendIlpPacket({\n destination: params.destination,\n amount: params.amount.toString(),\n data: toBase64(params.exchange.data),\n expectedFulfillment: params.exchange.fulfillment,\n timeout: params.timeoutMs,\n });\n return toSendResult(result, params, undefined);\n}\n\n// ─── Reading the outcome ────────────────────────────────────────────────────\n\n/**\n * Did the connector refuse the CLAIM, as opposed to refusing the packet after\n * banking it?\n *\n * The distinction decides whether the local watermark is repaid, and getting it\n * backwards is expensive in both directions: repaying a claim the connector\n * banked leaves the next one short (refused `F03`), while not repaying one it\n * refused leaves every later claim overpaying.\n *\n * An explicit `claimAck` settles it outright — the connector's own verdict on the\n * claim, independent of the packet's. Without one, only the codes the claim gate\n * itself raises count: `F03` (underpaid, or over the deposit), `F01` (malformed,\n * a non-advancing nonce, or an unknown channel) and `F06` (no claim was seen at\n * all). A reject from further along the path — `F02` no route, `T0x`, `R00`\n * expiry — arrives *after* a valid claim advanced the watermark, so it must not\n * be repaid.\n */\nfunction claimWasRefused(result: IlpSendResult): boolean {\n if (result.claimAck?.result === 'rejected') return true;\n if (result.claimAck?.result === 'accepted') return false;\n if (result.accepted) return false;\n return result.code === 'F03' || result.code === 'F01' || result.code === 'F06';\n}\n\nfunction toSendResult(\n result: IlpSendResult,\n params: AttemptParams,\n claim: ClaimSummary | undefined\n): SendResult {\n const data = result.data === undefined ? undefined : fromBase64(result.data);\n const outcome = readExchangeOutcome(result, data, params.exchange.sharedSecret);\n const transport = params.carriage.kind;\n\n if (outcome.kind === 'answered') {\n const body = Uint8Array.from(outcome.response.body);\n return {\n fulfilled: true,\n transport,\n status: outcome.response.status,\n headers: outcome.response.headers.map(([name, value]): [string, string] => [name, value]),\n body,\n text: () => decodeUtf8(body),\n json: <T = unknown,>(): T => JSON.parse(decodeUtf8(body)) as T,\n fulfillment:\n result.fulfillment !== undefined\n ? fromBase64(result.fulfillment)\n : params.exchange.fulfillment,\n ...(claim !== undefined ? { claim } : {}),\n ...(result.claimAck !== undefined ? { claimAck: result.claimAck } : {}),\n };\n }\n\n // A greeting that arrived as a REJECT rather than an HTTP status: BTP answers\n // an unpaid or wrong-carriage request with `F06`/`F02` carrying the same terms\n // document a `402` would have. Terms are the tell, not the code.\n const terms = readTerms(result);\n\n return {\n fulfilled: false,\n transport,\n refusedBy:\n terms !== undefined\n ? 'edge'\n : outcome.kind === 'destination-refused'\n ? 'destination'\n : 'path',\n code: outcome.code,\n message: outcome.message,\n ...(result.accumulatedCost !== undefined ? { accumulatedCost: result.accumulatedCost } : {}),\n ...(result.claimAck !== undefined ? { claimAck: result.claimAck } : {}),\n ...(terms !== undefined ? { terms } : {}),\n ...(outcome.kind === 'destination-refused' && outcome.detail.length > 0\n ? { detail: outcome.detail }\n : {}),\n ...(claim !== undefined ? { claim } : {}),\n };\n}\n\n/**\n * The terms a reject carried, when it carried any.\n *\n * `paymentRequired` is the raw x402 document the connector attached beside the\n * packet — the `payment-required` protocolData entry on BTP. It is projected onto\n * {@link PaymentTerms} by the same parser the HTTP `402` path uses, so the two\n * carriages cannot come to different conclusions about one greeting.\n */\nfunction readTerms(result: IlpSendResult): PaymentTerms | undefined {\n if (result.paymentRequired === undefined) return undefined;\n return parsePaymentTerms(result.paymentRequired);\n}\n\n/**\n * A refusal the transport threw because the connector answered with a status\n * rather than a packet — `402 Payment Required`, or a `402`/`401` naming a\n * carriage this route does not accept.\n *\n * Converted to a {@link SendResult} rather than propagated, because from\n * {@link send}'s contract these are refusals like any other: the packet did not\n * travel, nothing was paid, and the caller wants the terms, not a stack trace.\n * `refusedBy: 'edge'` — the connector we are attached to made this decision\n * before routing anything.\n */\nfunction asGreeting(\n error: unknown,\n transport: 'http' | 'btp',\n claim: ClaimSummary\n): SendResult | undefined {\n if (error instanceof PaymentRequiredError) {\n return {\n fulfilled: false,\n transport,\n refusedBy: 'edge',\n code: 'PAYMENT_REQUIRED',\n message: error.message,\n terms: error.terms,\n claim,\n };\n }\n if (error instanceof TransportRequiredError) {\n return {\n fulfilled: false,\n transport,\n refusedBy: 'edge',\n code: 'TRANSPORT_REQUIRED',\n message: error.message,\n ...(error.terms !== undefined ? { terms: error.terms } : {}),\n claim,\n };\n }\n return undefined;\n}\n\n// ─── Inputs ─────────────────────────────────────────────────────────────────\n\n/**\n * The key this packet's payload is sealed to.\n *\n * `sealTo` accepts the raw uncompressed key or the client-edge URL of the node\n * to seal to — the second because the caller of a *forwarded* route knows which\n * node terminates it but has no reason to hold that node's key, and no hop may\n * name it on the terminator's behalf (`self-description-spec.md` ND-13/ND-14).\n */\nasync function resolveSealingKey(\n context: SendContext,\n description: NodeSelfDescription,\n sealTo: Uint8Array | string | undefined\n): Promise<Uint8Array> {\n if (sealTo === undefined) return context.sealKey(description);\n if (sealTo instanceof Uint8Array) return sealTo;\n const trimmed = sealTo.trim();\n if (/^0x[0-9a-fA-F]+$/.test(trimmed)) return decodeConnectorPublicKey(trimmed);\n return context.sealKeyAt(trimmed);\n}\n\n/**\n * What to put on the packet.\n *\n * The terms are ASKED for rather than computed: nothing local could derive a\n * price, and anything local that tried could disagree with what the connector\n * will charge. What IS computed is the arithmetic the connector states — a route\n * that publishes a `pricePerKib` charges its base plus that rate per kibibyte of\n * `sealedBytes`, and {@link ../connector/self-description.js!chargeFor} is the\n * one place that rule lives.\n *\n * An explicit amount overrides and skips the lookup entirely, which is how a\n * forwarded destination — priced at a node this one only routes towards — is\n * paid for. It is taken literally, per-KiB rate and all: the caller who supplies\n * one is the caller who knows the far node's terms.\n */\nasync function resolveAmount(\n context: SendContext,\n destination: string,\n explicit: bigint | undefined,\n sealedBytes: number\n): Promise<bigint> {\n if (explicit !== undefined) {\n if (explicit < 0n) {\n throw new ValidationError('`amount` cannot be negative — a claim advances, never retreats.');\n }\n return explicit;\n }\n const terms = await context.routePrice(destination);\n if (terms === null) {\n throw new RouteNotPricedError(\n `This connector prices no route covering \"${destination}\", so there is no ` +\n 'amount to put on the packet. If the destination terminates elsewhere and ' +\n 'this node only routes towards it, pass an explicit `amount` (and `sealTo`, ' +\n 'naming the node that terminates it).'\n );\n }\n return chargeFor(terms, sealedBytes);\n}\n\n/**\n * A {@link SendRequest} as the envelope the wire carries.\n *\n * `target` defaults to `''` — the route's own handler path, which is the whole\n * answer for a route terminating at exactly one endpoint, and the only value\n * that cannot be refused: ADR 0025 resolves a target strictly BENEATH the\n * handler path, so an absolute `'/write'` is an escape attempt (`F00`) rather\n * than a shortcut.\n *\n * A plain object body is JSON, and says so: the connector hands the app the\n * headers this envelope carries, so a JSON body with no `content-type` reaches\n * an app that cannot tell what it is.\n */\nexport function toEnvelopeRequest(request: SendRequest): EnvelopeRequest {\n const headers = normalizeHeaders(request.headers);\n const { body, contentType } = normalizeBody(request.body);\n if (contentType !== undefined && !hasHeader(headers, 'content-type')) {\n headers.push(['content-type', contentType]);\n }\n return {\n method: request.method ?? 'POST',\n target: request.target ?? '',\n headers,\n body,\n };\n}\n\nfunction normalizeHeaders(\n headers: Record<string, string> | [string, string][] | undefined\n): [string, string][] {\n if (headers === undefined) return [];\n // An array is a SEQUENCE, duplicates and order preserved — the wire's own\n // shape. An object cannot express either, which is why both are accepted.\n if (Array.isArray(headers)) return headers.map(([name, value]) => [name, value]);\n return Object.entries(headers).map(([name, value]): [string, string] => [name, value]);\n}\n\nfunction hasHeader(headers: [string, string][], name: string): boolean {\n return headers.some(([header]) => header.toLowerCase() === name);\n}\n\nfunction normalizeBody(body: SendRequest['body']): {\n body: Uint8Array;\n contentType?: string;\n} {\n if (body === undefined) return { body: new Uint8Array(0) };\n if (body instanceof Uint8Array) return { body };\n if (typeof body === 'string') return { body: encodeUtf8(body) };\n return {\n body: encodeUtf8(JSON.stringify(body)),\n contentType: 'application/json',\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgCO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,MAChB,OACA;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAHR;AAIhB,SAAK,OAAO;AAAA,EACd;AAAA,EALkB;AAMpB;AAMO,IAAM,eAAN,cAA2B,gBAAgB;AAAA,EAChD,YAAY,SAAiB,OAAe;AAC1C,UAAM,SAAS,iBAAiB,KAAK;AACrC,SAAK,OAAO;AAAA,EACd;AACF;AAYO,IAAM,iBAAN,cAA6B,gBAAgB;AAAA,EAClD,YAAY,SAAiB,OAAe;AAC1C,UAAM,SAAS,mBAAmB,KAAK;AACvC,SAAK,OAAO;AAAA,EACd;AACF;AAMO,IAAM,kBAAN,cAA8B,gBAAgB;AAAA,EACnD,YAAY,SAAiB,OAAe;AAC1C,UAAM,SAAS,oBAAoB,KAAK;AACxC,SAAK,OAAO;AAAA,EACd;AACF;AAkBO,IAAM,cAAN,cAA0B,gBAAgB;AAAA,EAC/C,YAAY,SAAiB,OAAe;AAC1C,UAAM,SAAS,UAAU,KAAK;AAC9B,SAAK,OAAO;AAAA,EACd;AACF;AAWO,IAAM,wBAAN,cAAoC,gBAAgB;AAAA;AAAA,EAEhD;AAAA,EAET,YAAY,SAAiB,SAAmB,OAAe;AAC7D,UAAM,SAAS,qBAAqB,KAAK;AACzC,SAAK,OAAO;AACZ,SAAK,UAAU,CAAC,GAAG,OAAO;AAAA,EAC5B;AACF;AAUO,IAAM,sBAAN,cAAkC,gBAAgB;AAAA,EACvD,YAAY,SAAiB,OAAe;AAC1C,UAAM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","key","str","textEncoder","pending","attempt","readResponseMeta","key","require","key","readResponseMeta","http","resolveEndpoint","isConnectionError","attempt","OerErrorKind","encodeVarOctetString","decodeVarOctetString","EnvelopeErrorKind","decodeVarOctetString","concat","encodeVarOctetString","GiftWrapErrorKind","concat","key","key","DEFAULT_TIMEOUT_MS","key","toHex","toHex","pending","ed25519","sha256","ed25519","sha256","sha256","TOKEN_PROGRAM_ID","ASSOCIATED_TOKEN_PROGRAM_ID","retryAfterMs","attempt","sleep","key","ed25519","ed25519","randomBytes","ed25519","randomBytes","key","randomBytes","ed25519","sha256","TOKEN_PROGRAM_ID","state","started","transaction","key","createPublicClient","defineChain","createPublicClient","defineChain","createPublicClient","createWalletClient","defineChain","ed25519","defineChain","createPublicClient","createWalletClient","senderBalance","readDest","before","txHash","receipt","after","ed25519","lamports","privateKeyToAccount","toHex","key","privateKeyToAccount","createPublicClient","toHex","createPublicClient","createWalletClient","defineChain","encodeAbiParameters","getAddress","createPublicClient","createWalletClient","defineChain","getAddress","encodeAbiParameters","eip2612PermitData","hashTypedData","ed25519","hashTypedData","ed25519","state","key","key","toBinding","landed","key","http","carriage","privateKeyToAccount","toHex","createPublicClient"]}
|