@toon-protocol/client 3.1.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-M54FLOSJ.js → chunk-ZHWYFPOP.js} +74 -20
- package/dist/chunk-ZHWYFPOP.js.map +1 -0
- package/dist/cli/main.js +9 -2
- package/dist/cli/main.js.map +1 -1
- package/dist/{client-WC6UGT6C.js → client-SCEP67S5.js} +4 -2
- package/dist/index.d.ts +147 -15
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-M54FLOSJ.js.map +0 -1
- /package/dist/{client-WC6UGT6C.js.map → client-SCEP67S5.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client/errors.ts","../src/btp/protocol.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/connector/x402.ts","../src/http/HttpIlpClient.ts","../src/utils/url.ts","../src/connector/ConnectorEdgeClient.ts","../src/btp/transport-select.ts","../src/btp/BtpPaidWriteTransport.ts","../src/signing/evm-signer.ts","../src/channel/counterparty.ts","../src/channel/ChannelManager.ts","../src/channel/OnChainChannelClient.ts","../src/transport/rpc.ts","../src/channel/evm/TokenNetworkClient.ts","../src/channel/evm/abi.ts","../src/channel/evm/channel-id.ts","../src/channel/solana/payment-channel.ts","../src/channel/solana/SolanaChannelClient.ts","../src/signing/solana-signer.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/wallet/balances.ts","../src/wallet/transfer.ts","../src/wallet/faucet.ts","../src/client/wallet-facade.ts","../src/channel/stale-channel.ts","../src/client/send.ts","../src/client/ToonClient.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 chains the node *does* publish in its\n * `settlements[]`, 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 chain keys the node publishes, exactly as it spells them (`evm:84532`, `solana`). */\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 balance proof was signed — which is the\n * whole point of the hook, since a signed claim is a bearer instrument that\n * cannot be recalled (see\n * {@link ../channel/ChannelManager.js!ChannelManager.signBalanceProof}).\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// ─── 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 one of those, or leave it unset to take the ` +\n '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","/* 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 * 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 * - **`settlements`** — per chain, what opening a channel takes. Each entry was\n * *proved against a live chain* when the node booted (ND-07), which is why\n * this is the source for channel opening and claim signing rather than any\n * preset this package ships.\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 type {\n ConnectorChainSettlementTerms,\n ConnectorSettlementTerms,\n ConnectorSolanaSettlementTerms,\n} from './ConnectorEdgeClient.js';\n\nexport type {\n ConnectorChainSettlementTerms,\n ConnectorSettlementTerms,\n ConnectorSolanaSettlementTerms,\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 */\nexport function chargeFor(terms: RouteCharge, sealedBytes: number): bigint {\n const perKib = terms.pricePerKib;\n if (perKib === undefined || perKib === 0n) return 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 terms.price + perKib * units;\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 /** One entry per chain the node settles on. Absent — not empty — when it settles on none. */\n settlements: ConnectorChainSettlementTerms[];\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 * Read one `settlements[]` entry.\n *\n * The wire is **untagged** — the two shapes are told apart structurally, by\n * which contract-ish field they carry (`tokenNetworkRegistry` names EVM,\n * `programId` names Solana), exactly as the connector's own `#[serde(untagged)]`\n * enum does it. `kind` is this parser's addition and never appears on the wire.\n *\n * Note what is *not* here: a Solana entry publishes no `cluster`. The connector\n * knows its own cluster (it reads the genesis hash) and cross-checks the one a\n * claim declares, but it does not publish it — so a client must never expect to\n * learn the cluster from this document.\n */\nexport function parseSettlementEntry(raw: unknown): ConnectorChainSettlementTerms | undefined {\n if (typeof raw !== 'object' || raw === null) return undefined;\n const e = raw as Record<string, unknown>;\n const chain = readString(e, 'chain');\n const settlementAddress = readString(e, 'settlementAddress');\n const tokenAddress = readString(e, 'tokenAddress');\n const decimals = typeof e['decimals'] === 'number' ? (e['decimals'] as number) : undefined;\n if (!chain || !settlementAddress || !tokenAddress || decimals === undefined) return undefined;\n\n const programId = readString(e, 'programId');\n if (programId !== undefined) {\n const solana: ConnectorSolanaSettlementTerms = {\n chain,\n settlementAddress,\n programId,\n tokenAddress,\n decimals,\n };\n return { kind: 'solana', ...solana };\n }\n\n const tokenNetworkRegistry = readString(e, 'tokenNetworkRegistry');\n const tokenNetwork = readString(e, 'tokenNetwork');\n if (tokenNetworkRegistry !== undefined && tokenNetwork !== undefined) {\n const evm: ConnectorSettlementTerms = {\n chain,\n settlementAddress,\n tokenNetworkRegistry,\n tokenNetwork,\n tokenAddress,\n decimals,\n };\n return { kind: 'evm', ...evm };\n }\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 const settlements = Array.isArray(b['settlements'])\n ? (b['settlements'] as unknown[])\n .map(parseSettlementEntry)\n .filter((s): s is ConnectorChainSettlementTerms => s !== undefined)\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 settlements,\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 payment channel, declared on the BTP auth greeting so a\n * connector that credits earned increments knows which channel to pay\n * (toon-client#513, connector#790). `signature` is a\n * `signClaimStateChallenge` signature over `(channelId, expires)` —\n * deliberately the SAME domain-separated scheme `POST /ilp/claim-state`\n * already uses to prove channel ownership, never a real balance proof, so it\n * can never be replayed as a payment.\n */\nexport type BtpChannelDeclaration =\n | { blockchain: 'evm'; channelId: string; expires: number; signature: string }\n | {\n blockchain: 'solana';\n channelAccount: string;\n expires: number;\n signature: string;\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 = JSON.stringify({\n peerId: this.config.peerId,\n secret: this.config.authToken,\n ...(declaration ?? {}),\n });\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 contentType: 0,\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 balance proof 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 * 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 * 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 * Carved out of the retired `Http402Client` (the h402 paid-fetch engine),\n * which is the only part of it 1.0 keeps.\n */\n\nimport type { PaymentTerms } from '../client/types.js';\nimport type { ConnectorChainSettlementTerms } from './ConnectorEdgeClient.js';\nimport { parseSettlementEntry } from './self-description.js';\n\n// ─── x402 challenge types (documented wire contract above) ──────────────────\n\n/**\n * The `extra` bag of an `accepts` entry — an open set of terms from the peer,\n * not a fixed contract. `session_lease_ttl_ms` (connector#722,\n * `session_registry::SESSION_LEASE_BACKSTOP_TTL`) is the one member this\n * client currently reads by name; everything else is preserved untouched\n * (issue #506) rather than stripped by a narrower type, so a future field\n * survives the round trip even before this package knows its name.\n */\nexport interface X402ChannelExtra {\n /**\n * The connector's session lease TTL in milliseconds — the value\n * `connector_client_edge::session_registry::SESSION_LEASE_BACKSTOP_TTL`\n * enforces, published so a consumer reads it instead of hardcoding a guess\n * (client-edge-spec §1.4). The connector spells it `sessionLeaseTtlMs`;\n * `session_lease_ttl_ms` is accepted too because this client asked for that\n * spelling for a while and a fixture may still carry it.\n */\n sessionLeaseTtlMs?: number;\n /** @deprecated snake_case alias — the wire spelling is `sessionLeaseTtlMs`. */\n session_lease_ttl_ms?: number;\n [key: string]: unknown;\n}\n\n/** A single parsed `accepts` entry that offers the `toon-channel` scheme. */\nexport interface ToonChannelAccept {\n /** Always `'toon-channel'` for a matched entry. */\n scheme: 'toon-channel';\n /** Optional chain key, e.g. `evm:base:8453` — informational. */\n network?: string;\n /** ILP destination address to pay (the connector route fronting the URL). */\n destination: string;\n /** Price in ILP base units. */\n amount: bigint;\n /** The connector's `POST /ilp` URL. */\n httpEndpoint: string;\n /** Whether the host accepts the BTP upgrade over the HTTP endpoint. */\n supportsUpgrade: boolean;\n /**\n * The carriage this route actually requires, when the greeting is the\n * wrong-transport refusal (`extra.requiredTransport`, `client-edge-spec.md`\n * §1.4 \"Transport policy\", issue #701).\n *\n * Present **only** on that refusal: a route whose transport policy is the\n * default `both` never sets it, and neither does an ordinary unpaid-request\n * greeting. So its presence is the signal — \"the route exists, you reached\n * it over the wrong carriage\" — and its absence is not a default of `http`.\n * The BTP mirror (an `F02` REJECT with the same terms as `payment-required`\n * protocolData, §1.9 step 3) carries the identical field.\n */\n requiredTransport?: 'http' | 'btp';\n /**\n * The entry's raw `extra` bag, preserved as-is. `undefined` when the entry\n * carried no `extra` at all — distinct from an `extra` that merely omits a\n * given key (issue #506).\n */\n extra?: X402ChannelExtra;\n}\n\n/** The parsed x402 402 body, with the selected `toon-channel` entry (if any). */\nexport interface ParsedX402Challenge {\n x402Version?: number;\n /** The first usable `toon-channel` accepts entry, or `undefined`. */\n toonChannel?: ToonChannelAccept;\n}\n\n// ─── x402 challenge parsing (defensive) ─────────────────────────────────────\n\n/** First defined string among the given keys on `obj`. */\nfunction readString(\n obj: Record<string, unknown>,\n keys: string[]\n): 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/** First parseable bigint among the given keys (string|number) on `obj`. */\nfunction readAmount(\n obj: Record<string, unknown>,\n keys: string[]\n): bigint | undefined {\n for (const k of keys) {\n const v = obj[k];\n if (typeof v === 'bigint') return v;\n if (typeof v === 'number' && Number.isFinite(v))\n return BigInt(Math.trunc(v));\n if (typeof v === 'string' && /^\\d+$/.test(v.trim()))\n return BigInt(v.trim());\n }\n return undefined;\n}\n\n/**\n * Turn an `httpEndpoint` into something fetchable.\n *\n * The Rust connector emits a RELATIVE endpoint (`\"/ilp\"`), because the terms\n * describe an endpoint on the origin that answered. Resolved against the\n * resource URL it becomes the absolute `POST /ilp` URL this adapter needs. An\n * already-absolute endpoint is returned unchanged; a relative one with no base\n * to resolve against is passed through as before, so nothing that worked\n * previously stops working.\n */\nfunction resolveEndpoint(\n endpoint: string | undefined,\n baseUrl: string | undefined\n): 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/**\n * Parse a 402 `Response` body into a {@link ParsedX402Challenge}, selecting the\n * first usable `toon-channel` entry. Reads every field defensively; a malformed\n * body, a non-JSON body, or an entry missing its `destination`/`httpEndpoint`\n * yields `{ toonChannel: undefined }` so the caller falls back to the vanilla\n * 402 rather than throwing.\n */\nexport async function parseX402Challenge(\n response: Response\n): Promise<ParsedX402Challenge> {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n return {};\n }\n // `response.url` is the resource that answered 402 — the base a relative\n // `httpEndpoint` (which is what the Rust connector actually emits: `/ilp`)\n // has to be resolved against.\n return parseX402Body(body, response.url || undefined);\n}\n\n/**\n * Pure parser over an already-decoded x402 body (testable without a Response).\n *\n * `baseUrl`, when given, is the absolute URL of the resource that answered\n * `402`; a relative `httpEndpoint` is resolved against it. Omitting it keeps\n * the old behaviour of passing the endpoint through verbatim.\n */\nexport function parseX402Body(\n body: unknown,\n baseUrl?: string\n): ParsedX402Challenge {\n if (typeof body !== 'object' || body === null) return {};\n const b = body as Record<string, unknown>;\n\n const version =\n typeof b['x402Version'] === 'number'\n ? (b['x402Version'] as number)\n : undefined;\n\n const accepts = Array.isArray(b['accepts'])\n ? (b['accepts'] as unknown[])\n : [];\n\n for (const raw of accepts) {\n if (typeof raw !== 'object' || raw === null) continue;\n const entry = raw as Record<string, unknown>;\n const scheme = readString(entry, ['scheme']);\n if (scheme !== 'toon-channel') continue;\n\n // The Rust connector puts the ILP address, the endpoint and the price\n // under `extra` (`crates/connector-client-edge/src/lib.rs`, client-edge-spec\n // §1.4) — NOT at the entry's top level. `extra` is therefore read as a\n // first-class source, not a fallback: reading `payTo` instead only ever\n // worked because that connector happens to set it to the destination too,\n // which is a coincidence of today's code and not part of the contract.\n const rawExtra = entry['extra'];\n // Preserved verbatim on the returned entry below (issue #506) — `extra`\n // stays a first-class read source for the fields this adapter already\n // knows (destination/endpoint/price), via `extraForReads`.\n const extra: X402ChannelExtra | undefined =\n typeof rawExtra === 'object' && rawExtra !== null\n ? (rawExtra as X402ChannelExtra)\n : undefined;\n const extraForReads = extra ?? {};\n\n const destination =\n readString(extraForReads, ['ilpAddress', 'destination']) ??\n readString(entry, ['destination', 'ilpAddress', 'payTo']);\n const rawEndpoint =\n readString(entry, ['httpEndpoint', 'ilpEndpoint']) ??\n readString(extraForReads, ['httpEndpoint', 'endpoint']) ??\n readString(entry, ['endpoint']);\n const httpEndpoint = resolveEndpoint(rawEndpoint, baseUrl);\n const amount =\n readAmount(extraForReads, ['price', 'amount']) ??\n readAmount(entry, ['amount', 'price', 'maxAmountRequired']);\n\n // A usable entry MUST carry where to pay, how much, and how to reach /ilp.\n if (!destination || !httpEndpoint || amount === undefined) continue;\n\n const network = readString(entry, ['network', 'chain']);\n const supportsUpgrade =\n entry['supportsUpgrade'] === true || entry['upgradable'] === true;\n\n // `extra` is where the connector actually writes it\n // (`connector_domain::x402::X402ChannelExtra::required_transport`); the\n // entry's top level is read as a fallback only, matching how every other\n // field here tolerates the two placements. Anything other than the two\n // documented spellings is dropped rather than carried: a transport this\n // client cannot name is one it cannot select.\n const rawRequired =\n readString(extraForReads, ['requiredTransport']) ??\n readString(entry, ['requiredTransport']);\n const requiredTransport =\n rawRequired === 'http' || rawRequired === 'btp' ? rawRequired : undefined;\n\n return {\n ...(version !== undefined ? { x402Version: version } : {}),\n toonChannel: {\n scheme: 'toon-channel',\n ...(network !== undefined ? { network } : {}),\n destination,\n amount,\n httpEndpoint,\n supportsUpgrade,\n ...(requiredTransport !== undefined ? { requiredTransport } : {}),\n ...(extra !== undefined ? { extra } : {}),\n },\n };\n }\n\n return version !== undefined ? { x402Version: version } : {};\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 (`connector_domain::x402::terms_body` takes\n * the node), so the two can never disagree (`self-description-spec.md` ND-11).\n * That is why `settlements` here is the SAME per-chain list `GET /ilp` carries\n * and is parsed by the same {@link parseSettlementEntry}: a caller that opens a\n * channel off a greeting and one that opens it off the self-description must\n * open the same channel.\n *\n * `undefined` when the body carries no usable `toon-channel` option at all —\n * a vanilla x402 challenge from something that is not a TOON connector.\n *\n * @param body the already-decoded `402` JSON (or the same bytes carried as a\n * `payment-required` protocolData entry on the BTP carriage).\n * @param baseUrl the URL that answered, for resolving a relative `httpEndpoint`.\n */\nexport function parsePaymentTerms(\n body: unknown,\n baseUrl?: string\n): PaymentTerms | undefined {\n const parsed = parseX402Body(body, baseUrl);\n const option = parsed.toonChannel;\n if (!option) return undefined;\n\n const extra = option.extra ?? {};\n const btpEndpoint = readString(extra, ['btpEndpoint']);\n const rawSettlements = extra['settlements'];\n const settlements = Array.isArray(rawSettlements)\n ? rawSettlements\n .map(parseSettlementEntry)\n .filter((s): s is ConnectorChainSettlementTerms => s !== undefined)\n : [];\n // The connector spells it `sessionLeaseTtlMs`; the snake_case alias is\n // accepted because this client asked for that spelling for a while.\n const ttl = extra.sessionLeaseTtlMs ?? extra.session_lease_ttl_ms;\n\n return {\n destination: option.destination,\n price: option.amount,\n httpEndpoint: option.httpEndpoint,\n ...(btpEndpoint !== undefined ? { btpEndpoint } : {}),\n ...(option.requiredTransport !== undefined\n ? { requiredTransport: option.requiredTransport }\n : {}),\n settlements,\n ...(typeof ttl === 'number' ? { sessionLeaseTtlMs: ttl } : {}),\n raw: body,\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-channel 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 type { X402ChannelExtra } from './x402.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 * The channel-opening facts a settling connector carries in its x402\n * greeting (connector #617): everything a buyer needs to OPEN a channel\n * with the node, learned by ASKING (ADR 0022) rather than from a\n * kind:10032 announce the Rust fleet never makes.\n */\nexport interface ConnectorSettlementTerms {\n /** `evm:<chainId>` — the chain the node's settlement backend runs on. */\n chain: string;\n /** The on-chain counterparty a buyer opens a channel WITH. */\n settlementAddress: string;\n /** The stable TokenNetworkRegistry factory address. */\n tokenNetworkRegistry: string;\n /** The resolved TokenNetwork — the EIP-712 verifyingContract. */\n tokenNetwork: string;\n tokenAddress: string;\n /** Informational; claims are already in base units. */\n decimals: number;\n}\n\n/**\n * The Solana twin of {@link ConnectorSettlementTerms} (connector #632): what\n * an unaffiliated buyer needs to open a channel against a Solana settlement\n * backend's deployed `payment-channel` program instance.\n */\nexport interface ConnectorSolanaSettlementTerms {\n /** Always `'solana'` — unlike EVM there is no chain id to append. */\n chain: string;\n /** The on-chain counterparty a buyer opens a channel WITH, base58. */\n settlementAddress: string;\n /** The deployed `payment-channel` program instance, base58. */\n programId: string;\n /** The SPL mint every channel this backend opens settles in, base58. */\n tokenAddress: string;\n /** Informational; claims are already in base units. */\n decimals: number;\n}\n\n/**\n * One chain's entry in the x402 greeting's per-chain `settlements` list\n * (connector #632). `kind` is added by this parser, not present on the wire\n * — the wire is untagged, disambiguated structurally (`tokenNetworkRegistry`\n * names EVM, `programId` names Solana).\n */\nexport type ConnectorChainSettlementTerms =\n | ({ kind: 'evm' } & ConnectorSettlementTerms)\n | ({ kind: 'solana' } & ConnectorSolanaSettlementTerms);\n\n/**\n * A route's terms as the x402 greeting states them: the price, plus (from a\n * settling node) the channel-opening facts. `settlement` is absent exactly\n * when the node has no settlement backend — the wire's own shape. `settlements`\n * is the additive per-chain list (connector #632): one entry per chain the\n * node settles on, including the same EVM entry `settlement` already carries.\n * Absent — not an empty array — on a node with no settlement backend, or one\n * still answering the pre-#632 greeting shape.\n */\nexport interface ConnectorRouteTerms {\n destination: string;\n price: string;\n settlement?: ConnectorSettlementTerms;\n settlements?: ConnectorChainSettlementTerms[];\n /**\n * The `toon-channel` accepts entry's raw `extra` bag, preserved as-is\n * (issue #509 — the same posture #506/#507 established for\n * `Http402Client`'s parser, e.g. `extra.session_lease_ttl_ms`,\n * connector#722). `undefined` when the entry carried no `extra` at all —\n * distinct from an `extra` that merely omits a given key.\n */\n extra?: X402ChannelExtra;\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: proof of ownership of a channel\n * this client controls, via a signature over a challenge distinct from a\n * real claim's balance-proof (never reusable as one). `signature` is\n * `EvmSigner.signClaimStateChallenge`'s `0x`-prefixed 65-byte hex for `evm`,\n * `SolanaSigner.signClaimStateChallenge`'s base64 64-byte Ed25519 for\n * `solana`.\n */\nexport type ClaimStateRequestEntry =\n | { blockchain: 'evm'; channelId: string; expires: number; signature: string }\n | {\n blockchain: 'solana';\n channelAccount: string;\n expires: number;\n signature: string;\n };\n\n/**\n * The credited/spendable position of one channel this client asked about —\n * the runway source of truth (toon-meta#261/#262 decision 9). Money fields\n * are decimal strings (never a bare JS number, which cannot represent a\n * value past 2^53 exactly).\n */\nexport interface ClaimStateOk {\n blockchain: 'evm' | 'solana';\n channelId?: string;\n channelAccount?: string;\n ok: true;\n /** On-chain deposit, or `null` for a channel this connector only DECLARED. */\n depositTotal: string | null;\n /** The channel's watermark; `\"0\"` if this connector has never accepted a claim. */\n cumulativeClaimed: string;\n /** `depositTotal - cumulativeClaimed`; `null` exactly when `depositTotal` is. */\n available: string | null;\n nonce: number;\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 collapsed to two\n * causes (unlike a claim's own refusal taxonomy) so a caller learns nothing\n * about a channel it does not control: `\"unverified\"` covers \"no such\n * channel\" and \"bad signature\" identically.\n */\nexport interface ClaimStateFailed {\n blockchain: 'evm' | 'solana';\n channelId?: string;\n channelAccount?: string;\n ok: false;\n error: 'expired' | 'unverified';\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/** A nullable-string reader: `null` passes through, anything else must be a string. */\nfunction claimNullableStr(\n e: Record<string, unknown>,\n key: string,\n entryIndex: number\n): string | null {\n const value = e[key];\n if (value === null) return null;\n if (typeof value !== 'string') {\n throw new ConnectorEdgeError(\n `claim-state channel entry ${entryIndex}'s '${key}' is neither a string nor null`,\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 = typeof e['channelId'] === 'string' ? e['channelId'] : undefined;\n const channelAccount =\n typeof e['channelAccount'] === 'string' ? e['channelAccount'] : undefined;\n const identity = {\n ...(channelId !== undefined ? { channelId } : {}),\n ...(channelAccount !== undefined ? { channelAccount } : {}),\n };\n\n if (e['ok'] === false) {\n const error = e['error'];\n if (error !== 'expired' && error !== 'unverified') {\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, ...identity, 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\n const nonce = e['nonce'];\n if (typeof nonce !== 'number' || !Number.isInteger(nonce) || nonce < 0) {\n throw new ConnectorEdgeError(\n `claim-state channel entry ${entryIndex} has a non-integer nonce`,\n 'CLAIM_STATE_MALFORMED'\n );\n }\n const lastClaimTime = e['lastClaimTime'];\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\n return {\n blockchain,\n ...identity,\n ok: true,\n depositTotal: claimNullableStr(e, 'depositTotal', entryIndex),\n cumulativeClaimed: claimStr(e, 'cumulativeClaimed', entryIndex),\n available: claimNullableStr(e, 'available', entryIndex),\n nonce,\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/** A required-string reader over a raw settlement-facts record, refusing a missing/empty field. */\nfunction settlementStr(s: Record<string, unknown>, key: string): string {\n const value = s[key];\n if (typeof value !== 'string' || value.length === 0) {\n throw new ConnectorEdgeError(\n `x402 greeting settlement facts lack '${key}'`,\n 'TERMS_MALFORMED'\n );\n }\n return value;\n}\n\n/** A required-`decimals` reader, shared by every chain's settlement-facts shape. */\nfunction settlementDecimals(s: Record<string, unknown>): number {\n const decimals = s['decimals'];\n if (typeof decimals !== 'number') {\n throw new ConnectorEdgeError(\n \"x402 greeting settlement facts lack 'decimals'\",\n 'TERMS_MALFORMED'\n );\n }\n return decimals;\n}\n\n/** Parse one already-object-checked EVM settlement-facts record (legacy `settlement` shape). */\nfunction parseEvmSettlementTerms(\n s: Record<string, unknown>\n): ConnectorSettlementTerms {\n return {\n chain: settlementStr(s, 'chain'),\n settlementAddress: settlementStr(s, 'settlementAddress'),\n tokenNetworkRegistry: settlementStr(s, 'tokenNetworkRegistry'),\n tokenNetwork: settlementStr(s, 'tokenNetwork'),\n tokenAddress: settlementStr(s, 'tokenAddress'),\n decimals: settlementDecimals(s),\n };\n}\n\n/** Parse one already-object-checked Solana settlement-facts record (connector #632). */\nfunction parseSolanaSettlementTerms(\n s: Record<string, unknown>\n): ConnectorSolanaSettlementTerms {\n return {\n chain: settlementStr(s, 'chain'),\n settlementAddress: settlementStr(s, 'settlementAddress'),\n programId: settlementStr(s, 'programId'),\n tokenAddress: settlementStr(s, 'tokenAddress'),\n decimals: settlementDecimals(s),\n };\n}\n\n/**\n * Parse one entry of the greeting's `extra.settlements` list (connector\n * #632). The wire is untagged — serde on the connector side, and this parser\n * on the client side, both disambiguate structurally: `programId` names a\n * Solana entry, `tokenNetworkRegistry` names an EVM one. Anything else (both\n * fields present, neither present, or a field of the wrong shape) is refused\n * rather than guessed at.\n */\nfunction parseChainSettlementEntry(\n raw: unknown\n): ConnectorChainSettlementTerms {\n if (typeof raw !== 'object' || raw === null) {\n throw new ConnectorEdgeError(\n 'x402 greeting settlements entry is not an object',\n 'TERMS_MALFORMED'\n );\n }\n const s = raw as Record<string, unknown>;\n if (typeof s['programId'] === 'string') {\n return { kind: 'solana', ...parseSolanaSettlementTerms(s) };\n }\n if (typeof s['tokenNetworkRegistry'] === 'string') {\n return { kind: 'evm', ...parseEvmSettlementTerms(s) };\n }\n throw new ConnectorEdgeError(\n \"x402 greeting settlements entry names neither an EVM ('tokenNetworkRegistry') nor a Solana ('programId') chain\",\n 'TERMS_MALFORMED'\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 * that is not the documented greeting; a malformed OPTIONAL `settlement`\n * object (or `settlements` entry) is also a refusal rather than a silent\n * drop — half-understood channel-opening facts would be opened AGAINST.\n */\nexport function parseConnectorRouteTerms(body: unknown): ConnectorRouteTerms {\n if (typeof body !== 'object' || body === null) {\n throw new ConnectorEdgeError(\n 'x402 greeting is not an object',\n 'TERMS_MALFORMED'\n );\n }\n const greeting = body as {\n resource?: { url?: unknown };\n accepts?: unknown;\n };\n const accepts = Array.isArray(greeting.accepts) ? greeting.accepts : [];\n const option = accepts.find(\n (entry): entry is Record<string, unknown> =>\n typeof entry === 'object' &&\n entry !== null &&\n (entry as { scheme?: unknown }).scheme === 'toon-channel'\n );\n if (!option || typeof option['amount'] !== 'string') {\n throw new ConnectorEdgeError(\n 'x402 greeting carries no toon-channel option',\n 'TERMS_MALFORMED'\n );\n }\n const destination =\n typeof greeting.resource?.url === 'string' ? greeting.resource.url : '';\n const rawExtra = option['extra'];\n // Preserved verbatim on the returned terms below (issue #509, mirroring\n // #506's `Http402Client` posture) — `extraForReads` stays the source for\n // the fields this parser already knows (settlement/settlements) without\n // narrowing the bag a caller sees.\n const extra: X402ChannelExtra | undefined =\n typeof rawExtra === 'object' && rawExtra !== null\n ? (rawExtra as X402ChannelExtra)\n : undefined;\n const extraForReads = extra ?? {};\n\n const rawSettlements = extraForReads['settlements'];\n let settlements: ConnectorChainSettlementTerms[] | undefined;\n if (rawSettlements !== undefined) {\n if (!Array.isArray(rawSettlements)) {\n throw new ConnectorEdgeError(\n 'x402 greeting settlements is not an array',\n 'TERMS_MALFORMED'\n );\n }\n settlements = rawSettlements.map(parseChainSettlementEntry);\n }\n\n const rawSettlement = extraForReads['settlement'];\n if (rawSettlement === undefined) {\n return {\n destination,\n price: option['amount'],\n ...(settlements ? { settlements } : {}),\n ...(extra !== undefined ? { extra } : {}),\n };\n }\n if (typeof rawSettlement !== 'object' || rawSettlement === null) {\n throw new ConnectorEdgeError(\n 'x402 greeting settlement facts are malformed',\n 'TERMS_MALFORMED'\n );\n }\n return {\n destination,\n price: option['amount'],\n settlement: parseEvmSettlementTerms(\n rawSettlement as Record<string, unknown>\n ),\n ...(settlements ? { settlements } : {}),\n ...(extra !== undefined ? { extra } : {}),\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","import { privateKeyToAccount, type PrivateKeyAccount } from 'viem/accounts';\nimport { type Hex, toHex } from 'viem';\nimport type { BalanceProofParams, SignedBalanceProof } from '../client/types.js';\n// Types re-exported for convenience\nexport type { ClaimMessage } from './types.js';\n\n/**\n * EVM claim message for BTP protocol data.\n * Matches @toon-protocol/connector's EVMClaimMessage interface.\n *\n * The connector's validateClaimMessage() requires envelope fields\n * (version, messageId, timestamp) plus EVM claim fields, and optionally\n * chainId + tokenNetworkAddress for self-describing signature verification.\n */\nexport interface EVMClaimMessage {\n version: '1.0';\n blockchain: 'evm';\n messageId: string;\n timestamp: string;\n senderId: string;\n channelId: string;\n nonce: number;\n transferredAmount: string;\n lockedAmount: string;\n locksRoot: string;\n signature: string;\n signerAddress: string;\n /** Chain ID for self-describing EIP-712 verification */\n chainId: number;\n /** TokenNetwork address for self-describing EIP-712 verification */\n tokenNetworkAddress: string;\n /** ERC-20 token address for self-describing claim verification */\n tokenAddress?: string;\n}\n\n/**\n * EIP-712 domain for TokenNetwork balance proofs.\n * Must match connector's eip712-helper.js getDomainSeparator().\n */\nfunction getBalanceProofDomain(chainId: number, tokenNetworkAddress: string) {\n return {\n name: 'TokenNetwork' as const,\n version: '1' as const,\n chainId,\n verifyingContract: tokenNetworkAddress as Hex,\n };\n}\n\n/**\n * EIP-712 types for balance proofs.\n * Must match connector's eip712-helper.js getBalanceProofTypes().\n */\nconst BALANCE_PROOF_TYPES = {\n BalanceProof: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'nonce', type: 'uint256' },\n { name: 'transferredAmount', type: 'uint256' },\n { name: 'lockedAmount', type: 'uint256' },\n { name: 'locksRoot', type: 'bytes32' },\n ],\n} as const;\n\n/**\n * EIP-712 types for a claim-state challenge (client-edge-spec.md §1.10,\n * connector issue #693) — a message DISTINCT from {@link BALANCE_PROOF_TYPES}\n * so a captured challenge can never be replayed as a payment or vice versa.\n * Signed under the SAME domain as a real claim (`getBalanceProofDomain`).\n */\nconst CLAIM_STATE_CHALLENGE_TYPES = {\n ClaimStateChallenge: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'expires', type: 'uint256' },\n ],\n} as const;\n\n/**\n * EVM signer for EIP-712 balance proofs and on-chain transactions.\n *\n * Encapsulates the private key — no getPrivateKey() method is exposed.\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 = (\n privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`\n ) 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 /** ChainSigner identifier — EVM address */\n get signerIdentifier(): string {\n return this._account.address;\n }\n\n /** Viem PrivateKeyAccount — usable with walletClient for on-chain transactions */\n get account(): PrivateKeyAccount {\n return this._account;\n }\n\n /**\n * Signs a balance proof using EIP-712 typed data.\n *\n * @param params - Balance proof parameters plus chain context\n * @returns Signed balance proof with signature\n */\n async signBalanceProof(\n params: BalanceProofParams & {\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n }\n ): Promise<SignedBalanceProof> {\n const domain = getBalanceProofDomain(\n params.chainId,\n params.tokenNetworkAddress\n );\n\n const signature = await this._account.signTypedData({\n domain,\n types: BALANCE_PROOF_TYPES,\n primaryType: 'BalanceProof',\n message: {\n channelId: params.channelId as Hex,\n nonce: BigInt(params.nonce),\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot as Hex,\n },\n });\n\n return {\n channelId: params.channelId,\n nonce: params.nonce,\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot,\n signature,\n signerAddress: this._account.address,\n chainId: params.chainId,\n tokenNetworkAddress: params.tokenNetworkAddress,\n ...(params.tokenAddress && { tokenAddress: params.tokenAddress }),\n };\n }\n\n /**\n * Signs a `POST /ilp/claim-state` claim-state challenge (client-edge-spec.md\n * §1.10): proves ownership of `channelId` without moving any value or\n * advancing the channel's nonce — this is a READ, not a claim. Read the\n * connector's answer for the actual credited/available balance (toon-meta#262\n * decision 9); this signature only unlocks the read.\n *\n * @param params.expires - Unix seconds the signature stops verifying.\n * Reissue with a fresh value whenever an outstanding one should stop\n * being trusted — the endpoint has no other replay bound.\n */\n async signClaimStateChallenge(params: {\n chainId: number;\n tokenNetworkAddress: string;\n channelId: string;\n expires: number;\n }): Promise<string> {\n const domain = getBalanceProofDomain(\n params.chainId,\n params.tokenNetworkAddress\n );\n return this._account.signTypedData({\n domain,\n types: CLAIM_STATE_CHALLENGE_TYPES,\n primaryType: 'ClaimStateChallenge',\n message: {\n channelId: params.channelId as Hex,\n expires: BigInt(params.expires),\n },\n });\n }\n\n /**\n * Builds an EVMClaimMessage from a signed balance proof.\n * Static so it can be called without an EvmSigner instance.\n *\n * @param proof - Signed balance proof (includes chainId and tokenNetworkAddress)\n * @param senderId - Nostr pubkey or identifier of the sender\n * @returns EVMClaimMessage compatible with BTP_CLAIM_PROTOCOL\n */\n static buildClaimMessage(\n proof: SignedBalanceProof,\n senderId: string\n ): EVMClaimMessage {\n return {\n version: '1.0',\n blockchain: 'evm',\n messageId: crypto.randomUUID(),\n timestamp: new Date().toISOString().replace(/\\.\\d{3}Z$/, '.000Z'),\n senderId,\n channelId: proof.channelId,\n nonce: proof.nonce,\n transferredAmount: proof.transferredAmount.toString(),\n lockedAmount: proof.lockedAmount.toString(),\n locksRoot: proof.locksRoot,\n signature: proof.signature,\n signerAddress: proof.signerAddress,\n chainId: proof.chainId,\n tokenNetworkAddress: proof.tokenNetworkAddress,\n ...(proof.tokenAddress && { tokenAddress: proof.tokenAddress }),\n };\n }\n}\n","/**\n * Is a channel this client already holds still held with the node that\n * terminates its destination TODAY?\n *\n * Every persisted channel record in this codebase is keyed by a ROUTE — the\n * daemon's peer→channel bindings by `peer|chain|tokenNetwork`, its apex store\n * by `destination|chain`, rig's map by `identity|destination|chain|tokenNetwork`\n * — and none of those key fields names the counterparty. An ILP name can change\n * hands: the devnet apex `g.toon` was retired 2026-08-14 and other nodes took\n * over the names under it. Every key field kept matching, so the client resumed\n * a channel opened against the retired node and signed balance proofs against\n * it. The node now answering holds no record of that channel and refuses every\n * packet with `F01 - claim rejected: names a channel this connector has no\n * record of` — until the record was deleted by hand.\n *\n * The records already carry the counterparty they were opened against\n * (`recipient`), so the check is available wherever a record is about to be\n * reused: compare it against the settlement address the destination announces\n * now. This module is the ONE definition of that comparison, shared by the\n * daemon's two stores (and mirroring rig's own copy in\n * `packages/rig/src/standalone/channel-map.ts`, which cannot import it — the\n * standalone repo publishes that package separately).\n */\n\n/**\n * Compare two settlement addresses. EVM addresses travel in mixed checksum\n * case (an announce may say `0xF29f…` where the record says `0xf29f…`) and are\n * compared case-insensitively; anything else (base58 Solana, base58check Mina)\n * is case-SIGNIFICANT and compared verbatim.\n */\nexport function sameSettlementAddress(a: string, b: string): boolean {\n const normalize = (v: string): string =>\n /^0x[0-9a-fA-F]+$/.test(v) ? v.toLowerCase() : v;\n return normalize(a) === normalize(b);\n}\n\n/**\n * The three answers a stored record can give about its counterparty:\n *\n * - `'match'` — same counterparty, safe to reuse.\n * - `'mismatch'` — the counterparty rotated: the record must be retired and the\n * channel re-resolved against the address announced now.\n * - `'unrecorded'` — nothing to compare (a record written before this field was\n * validated, or a peer that announced no settlement address). Reuse is\n * ALLOWED — an unverifiable record is not a stale one, and refusing it would\n * open (and fund) a second on-chain channel for no evidence at all — and the\n * caller should back-fill the record with what the announce says so the NEXT\n * run is verifiable.\n */\nexport type CounterpartyVerdict = 'match' | 'mismatch' | 'unrecorded';\n\n/**\n * Does a recorded channel still belong to the counterparty its destination\n * announces TODAY? See {@link CounterpartyVerdict} for what each answer\n * obliges the caller to do.\n *\n * @param record - the stored channel context, of any shape that carries the\n * `recipient` it was opened against.\n * @param announced - the settlement address the destination advertises now\n * (a negotiation's `settlementAddress`).\n */\nexport function counterpartyMatch(\n record: { recipient?: string } | undefined,\n announced: string | undefined\n): CounterpartyVerdict {\n const recorded = record?.recipient;\n if (!recorded || !announced) return 'unrecorded';\n return sameSettlementAddress(recorded, announced) ? 'match' : 'mismatch';\n}\n","/**\n * The claim watermark: which channel this client holds with a connector, what\n * nonce and cumulative amount it has signed on that channel, and how to sign the\n * next one.\n *\n * ## What a watermark is, and why losing one is fatal\n *\n * A claim is cumulative and its nonce must strictly advance the figure the\n * connector has already banked (`client-edge-spec.md` §1.3 steps 2 and 3). The\n * connector keeps its own copy; this class keeps ours, and the two agree exactly\n * as long as every claim we sign is either accepted or rolled back. So the\n * watermark is not a cache — it is the only thing standing between a restart and\n * a channel whose every future claim is refused, which is why an in-memory store\n * is a footgun and {@link ../client/config.js!resolveConfig} warns about it.\n *\n * ## Signing advances it, and a refusal must put it back\n *\n * {@link ChannelManager.signBalanceProof} advances and PERSISTS the nonce and the\n * cumulative amount before the packet goes out, because a claim that is signed\n * and then sent must never be signable again at the same nonce. That ordering is\n * correct and the alternative is worse — but it leaves a debt: when the connector\n * then refuses the claim (an underpayment, an unknown channel, a rejected\n * `claimAck`), nothing was banked on its side, and our cumulative is now inflated\n * by value it never admitted. Every later claim would then overpay by that amount\n * against a deposit that is being spent down for nothing.\n * {@link ChannelManager.rollbackAmount} is the repayment, and\n * {@link ../client/send.js} calls it on every refusal path — including a thrown\n * transport error, where nothing is known to have arrived at all.\n *\n * ## And a refusal that never arrives\n *\n * Rolling back on a thrown transport error assumes nothing arrived, which is\n * the safer guess but is sometimes simply wrong: a request that times out on a\n * long path can have been delivered and banked anyway, and then our figure is\n * one claim BEHIND the connector's rather than level with it. Every later claim\n * under-advances and is refused (toon-client#671). So the assumption is no\n * longer left standing: {@link ChannelManager.markWatermarkUncertain} records\n * the doubt, and the next claim on that channel resolves it against the\n * connector's own watermark through\n * {@link ChannelManager.adoptConnectorWatermark} before it is signed.\n *\n * ## The binding\n *\n * A binding says \"this is the channel I hold with THAT connector, on THAT chain,\n * at THAT settlement contract\", keyed by all three: the same connector on a\n * second chain, or at a redeployed token network, is a different channel. It is\n * persisted so a restart resumes the channel it already funded instead of locking\n * a second lot of collateral.\n */\nimport { EvmSigner } from '../signing/evm-signer.js';\nimport type { ChainSigner, ChainMetadata } from '../signing/types.js';\nimport type { SignedBalanceProof } from '../client/types.js';\nimport { ChannelResumeError } from '../client/errors.js';\nimport type { ChannelStore } from './ChannelStore.js';\nimport { counterpartyMatch } from './counterparty.js';\nimport type { ChannelClient, ChannelTerms } from './types.js';\n\ninterface ChannelTracking {\n nonce: number;\n cumulativeAmount: bigint;\n chainType: string;\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n /**\n * The counterparty's settlement address on this channel's chain. Carried\n * through signing so it reaches the claim message; neither chain's signed\n * bytes fold it in, because which side gets paid is fixed by the channel's own\n * participants rather than by the proof.\n */\n recipient?: string;\n /**\n * On-chain `depositTotal` (base units), as captured at open or deposit time.\n * The spendable balance is `depositTotal - cumulativeAmount`, and the connector\n * refuses a cumulative above the deposit outright (`client-edge-spec.md` §1.3\n * step 5), so this is what a caller should show as runway.\n */\n depositTotal?: bigint;\n /**\n * The highest cumulative ever SIGNED on this channel — advanced by\n * {@link ChannelManager.signBalanceProof} and deliberately NOT lowered by\n * {@link ChannelManager.rollbackAmount}. The connector can only have banked a\n * claim it holds a signature for, so this is the ceiling on any figure it\n * reports, and the clamp {@link ChannelManager.adoptConnectorWatermark}\n * applies to one.\n */\n signedCeiling?: bigint;\n /**\n * \"Our watermark and the connector's may disagree.\" Set whenever a signed\n * claim's fate is unknown or bad — see\n * {@link ChannelManager.markWatermarkUncertain} — and cleared either by\n * adopting the connector's figure\n * ({@link ChannelManager.adoptConnectorWatermark}) or by a later claim it\n * banks ({@link ChannelManager.markWatermarkCertain}).\n */\n watermarkUncertain?: boolean;\n /** Withdraw flow (unix SECONDS): set when close is initiated / becomes settleable / settled. */\n closedAt?: bigint;\n settleableAt?: bigint;\n settledAt?: bigint;\n}\n\n/**\n * What {@link ChannelManager.adoptConnectorWatermark} did.\n *\n * `moved` is signed: positive when the connector had banked MORE than we had\n * recorded (the timed-out packet was delivered after all), negative when it had\n * banked less (a claim we signed never reached it). `clampedTo` is present only\n * when the connector reported a figure above anything we ever signed — which it\n * cannot have a claim for, and which was therefore not adopted.\n */\nexport type WatermarkAdoption =\n | { adopted: false; moved: bigint }\n | {\n adopted: true;\n moved: bigint;\n cumulative: bigint;\n nonce: number;\n clampedTo?: bigint;\n };\n\nexport interface ChannelManagerConfig {\n /**\n * Collateral (base units) {@link ChannelManager.ensureChannel} locks when it\n * opens a channel. Default `'100000'` (0.1 USDC at 6 decimals); a per-call\n * `initialDeposit` wins over it.\n */\n initialDeposit?: string;\n settlementTimeout?: number;\n}\n\n/** Per-open overrides, when a caller wants something other than the defaults. */\nexport interface EnsureChannelOptions {\n initialDeposit?: bigint;\n settlementTimeout?: number;\n}\n\n/**\n * The settlement contract a channel lives at: the `TokenNetwork` on EVM, the\n * settlement program on Solana. One field in the binding key, because they play\n * the same role — a channel at a redeployed one is a different channel.\n */\nfunction settlementNetwork(terms: ChannelTerms): string {\n return (terms.kind === 'evm' ? terms.tokenNetwork : terms.programId) ?? '';\n}\n\n/** The persisted context a resumed channel is re-tracked from. */\nfunction trackingContext(terms: ChannelTerms): {\n chainType: string;\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n recipient?: string;\n} {\n return {\n chainType: terms.kind,\n chainId: terms.chainId ?? 0,\n tokenNetworkAddress: settlementNetwork(terms),\n ...(terms.token ? { tokenAddress: terms.token } : {}),\n ...(terms.counterparty ? { recipient: terms.counterparty } : {}),\n };\n}\n\nexport class ChannelManager {\n private readonly channels = new Map<string, ChannelTracking>();\n private readonly chainSigners = new Map<string, ChainSigner>();\n private readonly connectorChannels = new Map<string, string>();\n private readonly pendingOpens = new Map<string, Promise<string>>();\n private readonly store?: ChannelStore;\n private readonly defaultInitialDeposit: string;\n private readonly defaultSettlementTimeout: number;\n private channelClient?: ChannelClient;\n private readonly evmSigner?: EvmSigner;\n\n constructor(\n evmSigner?: EvmSigner,\n store?: ChannelStore,\n config?: ChannelManagerConfig\n ) {\n this.evmSigner = evmSigner;\n this.store = store;\n this.defaultInitialDeposit = config?.initialDeposit ?? '100000';\n this.defaultSettlementTimeout = config?.settlementTimeout ?? 86400;\n }\n\n /** Register a chain-specific signer (`'solana'`; EVM is wrapped from `EvmSigner`). */\n registerChainSigner(chainType: string, signer: ChainSigner): void {\n this.chainSigners.set(chainType, signer);\n }\n\n /** Set the on-chain channel client used for lazy channel opening. */\n setChannelClient(client: ChannelClient): void {\n this.channelClient = client;\n }\n\n /**\n * The signer for a tracked channel's chain. EVM is adapted from\n * {@link EvmSigner} rather than registered, because that class predates the\n * {@link ChainSigner} port and is also the on-chain transaction signer.\n */\n getSignerForChannel(channelId: string): ChainSigner {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n\n const signer = this.chainSigners.get(tracking.chainType);\n if (signer) return signer;\n\n if (tracking.chainType === 'evm' && this.evmSigner) {\n const evmSigner = this.evmSigner;\n return {\n chainType: 'evm' as const,\n signerIdentifier: evmSigner.address,\n async signBalanceProof(params) {\n if (params.metadata.chainType !== 'evm') {\n throw new Error('Expected EVM metadata');\n }\n return evmSigner.signBalanceProof({\n channelId: params.channelId,\n nonce: params.nonce,\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot,\n chainId: params.metadata.chainId,\n tokenNetworkAddress: params.metadata.tokenNetworkAddress,\n tokenAddress: params.metadata.tokenAddress,\n });\n },\n buildClaimMessage(proof, senderId) {\n return EvmSigner.buildClaimMessage(proof, senderId);\n },\n };\n }\n\n throw new Error(`No signer registered for chain type: ${tracking.chainType}`);\n }\n\n /**\n * The key a connector's channel binding is persisted under: the connector, the\n * chain, and the settlement contract the channel lives at. All three matter —\n * the same connector on a second chain, or at a redeployed token network, is a\n * DIFFERENT channel.\n */\n private static bindingKey(connector: string, terms: ChannelTerms): string {\n return `${connector}|${terms.chain}|${settlementNetwork(terms)}`;\n }\n\n /**\n * The channel this client holds with `connector` on these terms, opening one on\n * chain only if there is none.\n *\n * Resolution order, cheapest first: an in-memory binding, an open already in\n * flight (so concurrent sends share one), the persisted binding, and only then\n * the chain. Nothing here forces a fresh open — the on-chain opener adopts an\n * already-open channel where one exists (ADR 0059), so even a client with no\n * store at all normally lands on the channel it already funded.\n */\n async ensureChannel(\n connector: string,\n terms: ChannelTerms,\n options: EnsureChannelOptions = {}\n ): Promise<string> {\n const key = ChannelManager.bindingKey(connector, terms);\n\n const pending = this.pendingOpens.get(key);\n if (pending) return pending;\n\n const existing = this.resolveChannel(connector, terms);\n if (existing) return existing;\n\n if (!this.channelClient) {\n throw new Error('No channel client configured — cannot open a payment channel');\n }\n const channelClient = this.channelClient;\n\n const openPromise = (async () => {\n try {\n const result = await channelClient.openChannel({\n terms,\n initialDeposit: options.initialDeposit ?? BigInt(this.defaultInitialDeposit),\n settlementTimeout: options.settlementTimeout ?? this.defaultSettlementTimeout,\n });\n\n const context = trackingContext(terms);\n this.trackChannel(result.channelId, {\n ...context,\n ...(result.depositTotal !== undefined\n ? { depositTotal: result.depositTotal }\n : {}),\n });\n this.connectorChannels.set(key, result.channelId);\n this.bindChannel(key, result.channelId, context, {\n ...(result.depositTotal !== undefined\n ? { depositTotal: result.depositTotal }\n : {}),\n });\n // A channel that was ADOPTED rather than opened has an on-chain history\n // this process did not write, so hand the chain client its context back\n // exactly as the resume path does.\n this.adoptOnChainContext(result.channelId, terms);\n return result.channelId;\n } finally {\n this.pendingOpens.delete(key);\n }\n })();\n\n this.pendingOpens.set(key, openPromise);\n return openPromise;\n }\n\n /**\n * The channel already held with `connector` on these terms — from memory, or\n * resumed from the store — WITHOUT opening anything.\n *\n * Exists because \"open one if there is none\" is a policy a caller may not\n * want: a consumer running with `autoOpenChannel: false` needs to know that\n * paying would lock collateral on chain, and needs to know it without a chain\n * round trip and without the side effect it is trying to avoid. This is the\n * whole of {@link ChannelManager.ensureChannel} up to the point where it would\n * transact.\n *\n * @throws {ChannelResumeError} when a binding names a channel whose watermark\n * is missing — the same hard failure `ensureChannel` raises, because the\n * answer \"there is no channel\" would be a lie that opens a second one.\n */\n resolveChannel(connector: string, terms: ChannelTerms): string | undefined {\n const key = ChannelManager.bindingKey(connector, terms);\n return this.connectorChannels.get(key) ?? this.resumeChannel(connector, terms);\n }\n\n /**\n * Adopt an ALREADY-OPEN channel as this connector's channel: track it\n * (rehydrating its watermark from the store), bind it so later opens resume it\n * rather than opening a second one, and hand the on-chain client its context.\n *\n * For a host that persisted the channel id itself before this client could.\n * Tracking alone is not enough: the lazy-open path keys off the binding, so a\n * host that only re-tracked its saved channel still opened a second one on the\n * first paid request.\n */\n adoptChannel(connector: string, terms: ChannelTerms, channelId: string): void {\n const key = ChannelManager.bindingKey(connector, terms);\n const context = trackingContext(terms);\n // Carry the collateral the binding already recorded: adopting is a RESTART\n // path, so the deposit was locked in a previous process and without this a\n // funded channel reports zero spendable until something re-reads the chain.\n const bound = this.store?.loadBinding?.(key);\n const deposited = bound?.channelId === channelId ? bound.depositTotal : undefined;\n this.trackChannel(channelId, {\n ...context,\n ...(deposited !== undefined ? { depositTotal: deposited } : {}),\n });\n this.connectorChannels.set(key, channelId);\n this.bindChannel(key, channelId, context, {\n ...(deposited !== undefined ? { depositTotal: deposited } : {}),\n });\n this.adoptOnChainContext(channelId, terms);\n }\n\n /**\n * Re-attach to the channel this identity already holds with `connector`, from\n * the store's binding. `undefined` when there is nothing to resume — no store,\n * no binding, or a binding whose channel is closing/settled, since a spent\n * channel must not be reused.\n *\n * COUNTERPARTY: the binding key names a connector URL and a chain, and a URL\n * can change hands. All three key fields keep matching while the node behind\n * them is replaced, so a resume would sign claims on a channel the node now\n * answering holds no record of and every write would be refused `F01`. The\n * recorded counterparty is therefore re-checked against the address the node\n * publishes TODAY ({@link counterpartyMatch}) before anything is resumed.\n *\n * @throws {ChannelResumeError} when the binding's watermark is missing —\n * resuming would restart the nonce and every later claim would be refused,\n * so the caller is told loudly instead.\n */\n private resumeChannel(connector: string, terms: ChannelTerms): string | undefined {\n const store = this.store;\n if (!store?.loadBinding) return undefined;\n\n const key = ChannelManager.bindingKey(connector, terms);\n const binding = store.loadBinding(key);\n if (!binding) return undefined;\n\n // The counterparty rotated: retire the binding and let the caller re-resolve.\n // ARCHIVED, not dropped — the old channel may still hold an on-chain deposit.\n const announced = terms.counterparty;\n const counterparty = counterpartyMatch(binding.context, announced);\n if (counterparty === 'mismatch') {\n console.warn(\n `[ChannelManager] channel ${binding.channelId} bound to \"${connector}\" on ` +\n `${terms.chain} was opened against counterparty ` +\n `${binding.context.recipient}, but that connector now publishes ` +\n `${announced} — the node terminating that URL was replaced. Re-resolving ` +\n 'the channel; the old binding is kept (superseded) so its on-chain ' +\n 'deposit stays reclaimable.'\n );\n store.supersedeBinding?.(key);\n return undefined;\n }\n\n const watermark = store.load(binding.channelId);\n if (!watermark) {\n throw new ChannelResumeError(\n `Payment channel \"${binding.channelId}\" is bound to \"${connector}\" on ` +\n `${terms.chain}, but its claim watermark is missing from the channel ` +\n 'store. Resuming would restart the nonce at 0 and the connector would ' +\n 'refuse every claim; opening a new channel would strand the collateral ' +\n 'already locked in this one. Restore the channel store file, or settle ' +\n `the channel on chain and remove its binding (key \"${key}\") before retrying.`\n );\n }\n\n // A channel in the withdraw flow is spent, not resumable: its collateral is\n // being released, so bind nothing and let the caller open a fresh channel.\n if (watermark.closedAt !== undefined || watermark.settledAt !== undefined) {\n store.deleteBinding?.(key);\n return undefined;\n }\n\n // MIGRATION: bindings written before the counterparty was validated carry no\n // `context.recipient`. There is nothing to contradict, so the resume\n // proceeds — but with the published address filled in, both for this run\n // (a Solana proof needs a recipient) and written back, so the NEXT run is\n // verifiable rather than unverifiable forever.\n const context =\n counterparty === 'unrecorded' && announced\n ? { ...binding.context, recipient: announced }\n : binding.context;\n\n this.trackChannel(binding.channelId, {\n ...context,\n ...(binding.depositTotal !== undefined ? { depositTotal: binding.depositTotal } : {}),\n });\n if (context !== binding.context) {\n store.saveBinding?.(key, { ...binding, context });\n }\n this.connectorChannels.set(key, binding.channelId);\n this.adoptOnChainContext(binding.channelId, terms);\n return binding.channelId;\n }\n\n /**\n * Retire the binding that produced `channelId`, because the connector answered\n * a claim drawn on it with `F01 — names a channel this connector has no record\n * of`.\n *\n * This is the GROUND-TRUTH counterpart to {@link resumeChannel}'s counterparty\n * check. That check is a prediction and only catches a record that visibly\n * disagrees with what is published; a node that keeps its settlement address\n * but loses its channel state (a wiped connector, a restored-from-backup box, a\n * redeployed contract) passes the prediction and fails on the wire. The reject\n * IS the answer, so the binding it names is retired and the caller re-resolves.\n *\n * SUPERSEDED, NOT DELETED — the channel may still hold an on-chain deposit, and\n * an archived record keeps it reclaimable. The channel also stays TRACKED (its\n * watermark is untouched) so close/settle still work on it; only the binding is\n * dropped.\n *\n * Refuses to act when the binding names a DIFFERENT channel than the one that\n * failed — a concurrent request may already have re-resolved it, and retiring\n * the replacement would open a third channel.\n *\n * @returns true when a binding was retired.\n */\n evictBinding(connector: string, terms: ChannelTerms, channelId: string): boolean {\n const key = ChannelManager.bindingKey(connector, terms);\n const inMemory = this.connectorChannels.get(key);\n if (inMemory !== undefined && inMemory !== channelId) return false;\n const persisted = this.store?.loadBinding?.(key);\n if (persisted && persisted.channelId !== channelId) return false;\n if (inMemory === undefined && !persisted) return false;\n\n this.connectorChannels.delete(key);\n this.pendingOpens.delete(key);\n this.store?.supersedeBinding?.(key);\n return true;\n }\n\n /**\n * Persist a freshly bound channel, and SEED its watermark entry (`nonce 0`) so\n * a later resume can tell \"never claimed against\" apart from \"watermark lost\",\n * which is a hard {@link ChannelResumeError}.\n */\n private bindChannel(\n key: string,\n channelId: string,\n context: {\n chainType: string;\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n recipient?: string;\n },\n extra: { depositTotal?: bigint }\n ): void {\n const store = this.store;\n if (!store?.saveBinding) return;\n if (!store.load(channelId)) {\n const tracking = this.channels.get(channelId);\n store.save(channelId, {\n nonce: tracking?.nonce ?? 0,\n cumulativeAmount: tracking?.cumulativeAmount ?? 0n,\n });\n }\n store.saveBinding(key, {\n channelId,\n context,\n ...(extra.depositTotal !== undefined ? { depositTotal: extra.depositTotal } : {}),\n });\n }\n\n /**\n * Re-seed the on-chain client's per-channel context for a channel it did not\n * open in this process. `OnChainChannelClient` caches the chain, settlement\n * contract and token per channel, so without this a resumed channel can be paid\n * on but not deposited into, closed or read. Optional capability — a channel\n * client that does not implement `adoptChannel` is simply left alone.\n */\n private adoptOnChainContext(channelId: string, terms: ChannelTerms): void {\n const client = this.channelClient as\n | (ChannelClient & {\n adoptChannel?: (\n channelId: string,\n ctx: { chain: string; tokenNetworkAddress: string; tokenAddress?: string }\n ) => void;\n })\n | undefined;\n const network = settlementNetwork(terms);\n if (!client?.adoptChannel || !network) return;\n client.adoptChannel(channelId, {\n chain: terms.chain,\n tokenNetworkAddress: network,\n ...(terms.token ? { tokenAddress: terms.token } : {}),\n });\n }\n\n /**\n * The channel bound to `connector`, if any — the first one tracked for it, since\n * a connector settled with on two chains has two.\n */\n getChannelForConnector(connector: string): string | undefined {\n for (const [key, channelId] of this.connectorChannels) {\n if (key === connector || key.startsWith(`${connector}|`)) return channelId;\n }\n return undefined;\n }\n\n /**\n * Start tracking a channel, resuming its watermark from the store when one is\n * persisted. `initialNonce`/`initialAmount` seed a channel the store has never\n * seen — never a channel it has, because a store entry is by definition ahead\n * of any figure a caller could pass.\n */\n trackChannel(\n channelId: string,\n chainContext?: {\n chainType?: string;\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n recipient?: string;\n depositTotal?: bigint;\n },\n initialNonce = 0,\n initialAmount = 0n\n ): void {\n const cId = chainContext?.chainId ?? 0;\n const tnAddr = chainContext?.tokenNetworkAddress ?? '';\n\n if (this.store) {\n const persisted = this.store.load(channelId);\n if (persisted) {\n this.channels.set(channelId, {\n nonce: persisted.nonce,\n cumulativeAmount: persisted.cumulativeAmount,\n chainType: chainContext?.chainType ?? 'evm',\n chainId: cId,\n tokenNetworkAddress: tnAddr,\n tokenAddress: chainContext?.tokenAddress,\n recipient: chainContext?.recipient,\n depositTotal: chainContext?.depositTotal,\n // A timeout in one process desyncs the next one, so the doubt — and\n // the ceiling that bounds how it may be settled — is resumed with the\n // watermark it is about.\n ...(persisted.signedCeiling !== undefined\n ? { signedCeiling: persisted.signedCeiling }\n : {}),\n ...(persisted.watermarkUncertain ? { watermarkUncertain: true } : {}),\n // Resume the withdraw-flow timers so a restart mid-grace doesn't\n // strand funds (the settle gate can't be evaluated without them).\n ...(persisted.closedAt !== undefined ? { closedAt: persisted.closedAt } : {}),\n ...(persisted.settleableAt !== undefined\n ? { settleableAt: persisted.settleableAt }\n : {}),\n ...(persisted.settledAt !== undefined ? { settledAt: persisted.settledAt } : {}),\n });\n return;\n }\n }\n\n this.channels.set(channelId, {\n nonce: initialNonce,\n cumulativeAmount: initialAmount,\n chainType: chainContext?.chainType ?? 'evm',\n chainId: cId,\n tokenNetworkAddress: tnAddr,\n tokenAddress: chainContext?.tokenAddress,\n recipient: chainContext?.recipient,\n depositTotal: chainContext?.depositTotal,\n });\n }\n\n /**\n * Sign the next claim on `channelId`, advancing the nonce by one and the\n * cumulative amount by `additionalAmount`.\n *\n * **The advance is persisted BEFORE the signature is returned**, and therefore\n * before the packet goes out. That ordering is deliberate: a signed claim is a\n * bearer instrument, and re-issuing one at a nonce already spent is how a client\n * double-spends against itself. The cost is that a refusal leaves the local\n * figure ahead of the connector's — see {@link ChannelManager.rollbackAmount},\n * which every refusal path must call.\n *\n * @throws {Error} if the channel is not tracked.\n */\n async signBalanceProof(\n channelId: string,\n additionalAmount: bigint\n ): Promise<SignedBalanceProof> {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(\n `Channel \"${channelId}\" is not being tracked. Call trackChannel() first.`\n );\n }\n\n tracking.nonce += 1;\n tracking.cumulativeAmount += additionalAmount;\n if (\n tracking.signedCeiling === undefined ||\n tracking.cumulativeAmount > tracking.signedCeiling\n ) {\n tracking.signedCeiling = tracking.cumulativeAmount;\n }\n this.persist(channelId);\n\n const signer = this.chainSigners.get(tracking.chainType);\n if (signer && tracking.chainType !== 'evm') {\n if (!tracking.recipient) {\n throw new Error(\n `Channel \"${channelId}\" (${tracking.chainType}) has no counterparty ` +\n 'settlement address recorded, so its balance proof cannot be built.'\n );\n }\n return signer.signBalanceProof({\n channelId,\n nonce: tracking.nonce,\n transferredAmount: tracking.cumulativeAmount,\n lockedAmount: 0n,\n locksRoot: '0x0000000000000000000000000000000000000000000000000000000000000000',\n recipient: tracking.recipient,\n metadata: this.buildMetadata(tracking),\n });\n }\n\n if (!this.evmSigner) {\n throw new Error('No EVM signer configured for EVM channel signing.');\n }\n return this.evmSigner.signBalanceProof({\n channelId,\n nonce: tracking.nonce,\n transferredAmount: tracking.cumulativeAmount,\n lockedAmount: 0n,\n locksRoot: '0x0000000000000000000000000000000000000000000000000000000000000000',\n chainId: tracking.chainId,\n tokenNetworkAddress: tracking.tokenNetworkAddress,\n tokenAddress: tracking.tokenAddress,\n });\n }\n\n /**\n * Give back cumulative amount the connector never admitted.\n *\n * Call this on EVERY path where a signed claim did not become value the\n * connector banked: a refused claim (`F03` underpayment or over-deposit, `F01`\n * unknown channel or non-advancing nonce), a `claimAck.result === 'rejected'`\n * riding beside any verdict, and a transport error where nothing is known to\n * have arrived. Without it the local cumulative runs permanently ahead of the\n * connector's watermark and every subsequent claim overpays by the difference —\n * spending the channel's deposit down for nothing, and eventually breaching the\n * deposit ceiling of `client-edge-spec.md` §1.3 step 5.\n *\n * **The nonce is deliberately NOT rolled back.** Only the amount is. A nonce is\n * a strictly-increasing sequence number, not a resource: the connector accepts\n * any claim whose nonce is above its watermark, so a gap costs nothing, whereas\n * reusing a nonce risks presenting two different claims under one number.\n * Re-signing at the next nonce with the restored cumulative is exactly what the\n * spec's own remedy for an over-deposit refusal describes.\n *\n * **The signed ceiling is not rolled back either.** What was signed was\n * signed, and the ceiling exists to remember exactly that — it bounds what\n * {@link ChannelManager.adoptConnectorWatermark} will believe the connector\n * when it reports having banked.\n *\n * Clamped at zero, and a no-op for an untracked channel: this runs on error\n * paths, and an error path that throws its own error hides the original.\n */\n rollbackAmount(channelId: string, amount: bigint): void {\n const tracking = this.channels.get(channelId);\n if (!tracking || amount <= 0n) return;\n tracking.cumulativeAmount =\n tracking.cumulativeAmount > amount ? tracking.cumulativeAmount - amount : 0n;\n this.persist(channelId);\n }\n\n /**\n * Record that this channel's watermark is in DOUBT: the last claim signed on\n * it was either sent into a transport error or a timeout — where the packet\n * may have been delivered and banked regardless of what this end saw — or was\n * refused by the connector. Either way our figure and the connector's may no\n * longer agree, and guessing which way costs a refused claim per request\n * (toon-client#671).\n *\n * The doubt is recorded rather than resolved, because resolving it here would\n * mean a second network round trip bolted onto a request that has already\n * failed, to a connector that may be exactly what is unreachable. It is\n * resolved instead at the one moment the answer is actually needed — before\n * the NEXT claim is signed — by {@link ChannelManager.adoptConnectorWatermark}\n * with what `POST /ilp/claim-state` reports.\n *\n * Persisted, and a no-op for an untracked channel: this runs on error paths.\n */\n markWatermarkUncertain(channelId: string): void {\n const tracking = this.channels.get(channelId);\n if (!tracking || tracking.watermarkUncertain === true) return;\n tracking.watermarkUncertain = true;\n this.persist(channelId);\n }\n\n /**\n * Record that this channel's watermark is known good again: the connector\n * banked the claim we signed, at the figure we signed it at, so the two agree\n * by construction.\n *\n * The cheap half of the reconciliation — a banked claim is proof, and proof\n * costs nothing, where {@link ChannelManager.adoptConnectorWatermark} costs a\n * round trip. Without it a channel that once timed out would re-read the\n * connector's watermark before every later claim.\n */\n markWatermarkCertain(channelId: string): void {\n const tracking = this.channels.get(channelId);\n if (!tracking || tracking.watermarkUncertain !== true) return;\n tracking.watermarkUncertain = false;\n this.persist(channelId);\n }\n\n /** Whether the next claim on `channelId` must reconcile before it is signed. */\n isWatermarkUncertain(channelId: string): boolean {\n return this.channels.get(channelId)?.watermarkUncertain === true;\n }\n\n /**\n * Adopt the connector's OWN watermark for a channel, and clear the doubt\n * {@link ChannelManager.markWatermarkUncertain} recorded.\n *\n * The connector's figure is the one that decides — a claim is validated\n * against what IT has banked (`client-edge-spec.md` §1.3) — so on a\n * disagreement it is adopted rather than argued with. Two guards make that\n * safe to do with a number that arrived over the network:\n *\n * - **The cumulative is clamped to {@link ChannelTracking.signedCeiling}**,\n * the highest figure this client has ever signed. A connector can only bank\n * a claim it holds our signature for, so a report above that ceiling is not\n * a fact about this channel and must not become one: adopting it would sign\n * away value that was never spent. The clamp is the whole reason the ceiling\n * is tracked.\n * - **The nonce only ever rises.** A claim is a bearer instrument and a nonce\n * is the only thing that stops one being re-issued, so the local nonce moves\n * to whichever of the two figures is higher — never down to the connector's,\n * even when the connector's is lower because a claim we signed never reached\n * it.\n *\n * @returns what was adopted, and how far the cumulative moved (negative when\n * the connector had banked LESS than we had recorded), so a caller can say\n * so out loud.\n */\n adoptConnectorWatermark(\n channelId: string,\n connector: { nonce: number; cumulativeClaimed: bigint }\n ): WatermarkAdoption {\n const tracking = this.channels.get(channelId);\n if (!tracking) return { adopted: false, moved: 0n };\n\n const ceiling = tracking.signedCeiling ?? tracking.cumulativeAmount;\n const cumulative =\n connector.cumulativeClaimed > ceiling ? ceiling : connector.cumulativeClaimed;\n const moved = cumulative - tracking.cumulativeAmount;\n\n tracking.cumulativeAmount = cumulative;\n tracking.nonce = Math.max(tracking.nonce, connector.nonce);\n tracking.watermarkUncertain = false;\n this.persist(channelId);\n\n return {\n adopted: true,\n moved,\n cumulative,\n nonce: tracking.nonce,\n ...(connector.cumulativeClaimed > ceiling ? { clampedTo: ceiling } : {}),\n };\n }\n\n private buildMetadata(tracking: ChannelTracking): ChainMetadata {\n if (tracking.chainType === 'solana') {\n return { chainType: 'solana', programId: tracking.tokenNetworkAddress };\n }\n return {\n chainType: 'evm',\n chainId: tracking.chainId,\n tokenNetworkAddress: tracking.tokenNetworkAddress,\n tokenAddress: tracking.tokenAddress,\n };\n }\n\n /** The last nonce signed on a tracked channel. */\n getNonce(channelId: string): number {\n return this.require(channelId).nonce;\n }\n\n /** The cumulative transferred amount signed on a tracked channel. */\n getCumulativeAmount(channelId: string): bigint {\n return this.require(channelId).cumulativeAmount;\n }\n\n /**\n * The on-chain deposit total, or `0n` when none was captured. The spendable\n * balance is this minus {@link getCumulativeAmount}.\n */\n getDepositTotal(channelId: string): bigint {\n return this.require(channelId).depositTotal ?? 0n;\n }\n\n /**\n * Record new collateral after a deposit. Written through to the BINDING too:\n * the deposit is an on-chain fact, so a restart must resume with the collateral\n * that is actually locked rather than the amount recorded at open.\n */\n setDepositTotal(channelId: string, total: bigint): void {\n this.require(channelId).depositTotal = total;\n this.persistDepositTotal(channelId, total);\n }\n\n /** Write `total` into whichever binding names `channelId`. */\n private persistDepositTotal(channelId: string, total: bigint): void {\n const store = this.store;\n if (!store?.saveBinding || !store.loadBinding) return;\n for (const [key, bound] of this.connectorChannels) {\n if (bound !== channelId) continue;\n const binding = store.loadBinding(key);\n if (!binding) continue;\n store.saveBinding(key, { ...binding, depositTotal: total });\n return;\n }\n }\n\n /** Persist a channel's watermark and withdraw timers. */\n private persist(channelId: string): void {\n if (!this.store) return;\n const t = this.channels.get(channelId);\n if (!t) return;\n this.store.save(channelId, {\n nonce: t.nonce,\n cumulativeAmount: t.cumulativeAmount,\n ...(t.signedCeiling !== undefined ? { signedCeiling: t.signedCeiling } : {}),\n ...(t.watermarkUncertain ? { watermarkUncertain: true } : {}),\n ...(t.closedAt !== undefined ? { closedAt: t.closedAt } : {}),\n ...(t.settleableAt !== undefined ? { settleableAt: t.settleableAt } : {}),\n ...(t.settledAt !== undefined ? { settledAt: t.settledAt } : {}),\n });\n }\n\n /**\n * Record that a channel was closed: `closedAt` + `settleableAt` (unix SECONDS),\n * persisted so the challenge timer survives a restart.\n */\n setChannelClosed(channelId: string, closedAt: bigint, settleableAt: bigint): void {\n const tracking = this.require(channelId);\n tracking.closedAt = closedAt;\n tracking.settleableAt = settleableAt;\n this.persist(channelId);\n }\n\n /** Record that a channel was settled (collateral released). */\n setChannelSettled(channelId: string, settledAt: bigint): void {\n this.require(channelId).settledAt = settledAt;\n this.persist(channelId);\n }\n\n /** The `settleableAt` timestamp (unix seconds) for a closed channel, if set. */\n getSettleableAt(channelId: string): bigint | undefined {\n return this.channels.get(channelId)?.settleableAt;\n }\n\n /**\n * Where a channel sits in the withdraw journey, from the tracked timers:\n * `open` → `closing` → `settleable` → `settled`. `nowSec` is injectable.\n */\n getChannelCloseState(\n channelId: string,\n nowSec = BigInt(Math.floor(Date.now() / 1000))\n ): 'open' | 'closing' | 'settleable' | 'settled' {\n const t = this.channels.get(channelId);\n if (!t || t.closedAt === undefined) return 'open';\n if (t.settledAt !== undefined) return 'settled';\n if (t.settleableAt !== undefined && nowSec >= t.settleableAt) return 'settleable';\n return 'closing';\n }\n\n /** Every channel id this manager is tracking. */\n getTrackedChannels(): string[] {\n return Array.from(this.channels.keys());\n }\n\n /** Whether `channelId` is tracked. */\n isTracking(channelId: string): boolean {\n return this.channels.has(channelId);\n }\n\n /**\n * The chain context a tracked channel was opened or resumed with — what a\n * caller needs to build a `POST /ilp/claim-state` request without re-deriving\n * it. `undefined` when the channel is not tracked.\n */\n getChannelContext(channelId: string):\n | {\n chainType: string;\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n recipient?: string;\n }\n | undefined {\n const tracking = this.channels.get(channelId);\n if (!tracking) return undefined;\n return {\n chainType: tracking.chainType,\n chainId: tracking.chainId,\n tokenNetworkAddress: tracking.tokenNetworkAddress,\n ...(tracking.tokenAddress !== undefined ? { tokenAddress: tracking.tokenAddress } : {}),\n ...(tracking.recipient !== undefined ? { recipient: tracking.recipient } : {}),\n };\n }\n\n private require(channelId: string): ChannelTracking {\n const tracking = this.channels.get(channelId);\n if (!tracking) throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n return tracking;\n }\n}\n","/**\n * One {@link ChannelClient} over both settlement chains: a dispatcher, and\n * nothing else.\n *\n * The lifecycle itself lives per chain — {@link ./evm/TokenNetworkClient.js} for\n * EVM, {@link ./solana/SolanaChannelClient.js} for Solana — because the two have almost\n * nothing in common beyond the shape of this interface: one is a contract call\n * against a deployment shared by every pair, the other is a program instruction\n * against a PDA that only ever belongs to one pair. What they DO share is that\n * every method here is the client's own transaction, signed with the client's own\n * key and paid for with the client's own gas. A connector has no endpoint that\n * opens a channel (`self-description-spec.md` ND-03); it reads the chain\n * ([ADR 0052](https://github.com/toon-protocol/connector/blob/main/docs/adr/0052-permissionless-payment-is-guaranteed-and-a-claim-is-what-authorises.md)),\n * which is what makes paying it permissionless.\n *\n * This class holds one piece of state, and it is worth naming: a per-channel\n * record of WHICH chain, token network/program and token a channel was opened\n * under. Deposit, close, settle and read all need it, and none of them can\n * re-derive it from a channel id alone — so a channel resumed from the store\n * (rather than opened in this process) must be handed that context back through\n * {@link OnChainChannelClient.adoptChannel} before anything but paying works on\n * it.\n */\nimport type { EvmSigner } from '../signing/evm-signer.js';\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { base58Encode } from '../utils/base58.js';\nimport { ChannelNotOpenError, ConfigError } from '../client/errors.js';\nimport type {\n ChannelClient,\n ChannelStatus,\n ChannelTerms,\n OnChainChannelStatus,\n OpenChannelParams,\n OpenChannelResult,\n} from './types.js';\nimport {\n TokenNetworkClient,\n type EvmReadConsistencyConfig,\n} from './evm/TokenNetworkClient.js';\nimport { SolanaChannelClient } from './solana/SolanaChannelClient.js';\n\nexport type { EvmReadConsistencyConfig };\n\nexport interface SolanaChannelConfig {\n rpcUrl: string;\n /** `fetch` for Solana JSON-RPC — the proxied one on a hidden-service client. */\n rpcFetch?: typeof fetch;\n /**\n * Ed25519 keypair material. Accepts either a 32-byte seed or a 64-byte\n * `secretKey` (seed ‖ pubkey, as produced by `deriveFullIdentity`). The first\n * 32 bytes are the signing seed; the public key is derived from it.\n */\n keypair: Uint8Array;\n /**\n * DEFAULT settlement program id (base58). The channel's own negotiated program\n * — the `programId` the connector published for this chain — takes precedence\n * whenever there is one, because ADR 0053 binds that program into the signed\n * balance proof: opening against one program and signing under another\n * produces claims no channel of ours lives under.\n */\n programId: string;\n /** DEFAULT SPL mint for PDA derivation. The negotiated token wins when present. */\n tokenMint?: string;\n /** Challenge-period duration in seconds. Defaults to the caller's, else 86400. */\n challengeDuration?: number;\n /**\n * OVERRIDE for the deposit made at open time: `amount` in base units and/or\n * `payerTokenAccount`, the payer's funded SPL token account (derived from\n * owner + mint when left empty). Normally unset — the open deposits the\n * negotiated collateral, the same amount the EVM opener locks.\n */\n deposit?: { amount: string; payerTokenAccount: string };\n}\n\nexport interface OnChainChannelClientConfig {\n evmSigner: EvmSigner;\n /** Chain key → RPC URL. A chain absent from this map cannot be transacted on. */\n chainRpcUrls: Record<string, string>;\n solanaConfig?: SolanaChannelConfig;\n /** How hard the EVM opener works to survive a stale-read RPC (#489). */\n readConsistency?: EvmReadConsistencyConfig;\n /**\n * An undici dispatcher to send chain RPC through, when this client is talking\n * to a hidden service. Reaching the connector inside the overlay while reading\n * chain state on clearnet would announce, from this IP and beside every paid\n * request, the settlement address the overlay exists to keep unlinked (ADR 0002).\n */\n rpcDispatcher?: unknown;\n}\n\n/** What this class remembers about a channel it opened or adopted. */\ninterface ChannelContext {\n chain: string;\n /** The `TokenNetwork` on EVM; the settlement program id on Solana. */\n tokenNetworkAddress: string;\n tokenAddress?: string;\n}\n\nexport class OnChainChannelClient implements ChannelClient {\n private readonly evmSigner: EvmSigner;\n private readonly chainRpcUrls: Record<string, string>;\n private solanaConfig?: SolanaChannelConfig;\n private readonly readConsistency: EvmReadConsistencyConfig | undefined;\n private readonly rpcDispatcher: unknown;\n private readonly channelContext = new Map<string, ChannelContext>();\n private readonly evmClients = new Map<string, TokenNetworkClient>();\n private readonly solanaClients = new Map<string, SolanaChannelClient>();\n\n constructor(config: OnChainChannelClientConfig) {\n this.evmSigner = config.evmSigner;\n this.chainRpcUrls = config.chainRpcUrls;\n this.solanaConfig = config.solanaConfig;\n this.readConsistency = config.readConsistency;\n this.rpcDispatcher = config.rpcDispatcher;\n }\n\n /**\n * Late-bind the Solana config. The Ed25519 keypair is derived asynchronously\n * from the mnemonic after this client is constructed, and it must be the SAME\n * keypair the Solana signer holds — the channel-open key and the claim-signing\n * key are one key or the channel is not ours.\n */\n setSolanaConfig(config: SolanaChannelConfig): void {\n this.solanaConfig = config;\n }\n\n /**\n * Give a channel this process did NOT open its on-chain context back — the\n * restart path (#489), where the chain, token network and token came from the\n * channel store rather than from an `openChannel` call. Without it a resumed\n * channel can be paid on but not deposited into, closed or read.\n */\n adoptChannel(channelId: string, ctx: ChannelContext): void {\n this.channelContext.set(channelId, {\n chain: ctx.chain,\n tokenNetworkAddress: ctx.tokenNetworkAddress,\n ...(ctx.tokenAddress ? { tokenAddress: ctx.tokenAddress } : {}),\n });\n }\n\n /** The chain/token-network/token a channel is tracked under, if any. */\n getChannelContext(channelId: string): ChannelContext | undefined {\n return this.channelContext.get(channelId);\n }\n\n /**\n * The `TokenNetworkClient` for one chain key, built once and reused.\n *\n * @throws {ConfigError} when no RPC URL is configured for that chain — a\n * condition no retry fixes, and one that must be reported before a caller\n * believes it has an on-chain client that works.\n */\n evmClientFor(chain: string): TokenNetworkClient {\n const existing = this.evmClients.get(chain);\n if (existing) return existing;\n const rpcUrl = this.chainRpcUrls[chain];\n if (!rpcUrl) {\n throw new ConfigError(\n `No RPC URL configured for chain \"${chain}\". Configured: ` +\n `${Object.keys(this.chainRpcUrls).join(', ') || '(none)'}.`\n );\n }\n const client = new TokenNetworkClient({\n chain,\n rpcUrl,\n signer: this.evmSigner,\n ...(this.readConsistency ? { readConsistency: this.readConsistency } : {}),\n ...(this.rpcDispatcher !== undefined ? { rpcDispatcher: this.rpcDispatcher } : {}),\n });\n this.evmClients.set(chain, client);\n return client;\n }\n\n // ─── ChannelClient ────────────────────────────────────────────────────────\n\n /**\n * Open a channel with the connector, or adopt the one already open with it.\n *\n * Adoption is the normal case on both chains and comes free from the id\n * derivation each uses: EVM derives `keccak256(p1, p2, epoch)` over the sorted\n * pair (ADR 0059), Solana derives the channel PDA from the same sorted pair\n * plus the mint. Neither needs a local record of what was opened before.\n */\n async openChannel(params: OpenChannelParams): Promise<OpenChannelResult> {\n const { terms } = params;\n if (terms.kind === 'solana') return this.openSolanaChannel(params);\n\n const client = this.evmClientFor(terms.chain);\n const result = await client.openOrAdopt({\n terms,\n ...(params.initialDeposit !== undefined\n ? { initialDeposit: params.initialDeposit }\n : {}),\n ...(params.settlementTimeout !== undefined\n ? { settlementTimeout: params.settlementTimeout }\n : {}),\n });\n this.rememberEvm(result.channelId, terms);\n return result;\n }\n\n /**\n * Add collateral. `amount` is the DELTA; `currentDeposit` is what the channel\n * already holds, which EVM needs because `setTotalDeposit` takes the new\n * cumulative figure rather than a delta.\n */\n async depositToChannel(\n channelId: string,\n amount: bigint,\n opts: { currentDeposit: bigint }\n ): Promise<{ txHash?: string; depositTotal: bigint }> {\n if (amount <= 0n) throw new RangeError('Deposit amount must be positive.');\n const ctx = this.requireContext(channelId, 'deposit into');\n if (isSolanaChain(ctx.chain)) {\n // Incremental on chain (the program adds `amount`), so the new total is\n // the caller-tracked current plus the delta.\n const { txSignature } = await this.solanaClientForChannel(ctx).deposit(channelId, amount);\n return { txHash: txSignature, depositTotal: opts.currentDeposit + amount };\n }\n return this.evmClientFor(ctx.chain).deposit(ctx.tokenNetworkAddress, channelId, amount, {\n currentDeposit: opts.currentDeposit,\n ...(ctx.tokenAddress ? { token: ctx.tokenAddress } : {}),\n });\n }\n\n /** Start the challenge period. */\n async closeChannel(channelId: string): Promise<{\n txHash?: string;\n closedAt: bigint;\n settlementTimeout: bigint;\n settleableAt: bigint;\n }> {\n const ctx = this.requireContext(channelId, 'close');\n if (isSolanaChain(ctx.chain)) {\n const client = this.solanaClientForChannel(ctx);\n const { txSignature } = await client.close(channelId);\n // The deadline comes from the account the program just stamped, never\n // from this process's clock: `settle` is gated on the chain's own\n // `close_timestamp + challenge_duration`.\n const after = await client.read(channelId);\n const closedAt = after.closeTimestamp ?? 0n;\n const challenge = after.challengeDuration ?? 0n;\n return {\n txHash: txSignature,\n closedAt,\n settlementTimeout: challenge,\n settleableAt: after.settleableAt ?? closedAt + challenge,\n };\n }\n return this.evmClientFor(ctx.chain).close(ctx.tokenNetworkAddress, channelId);\n }\n\n /** Pay out and finish. Only permitted once the challenge period has elapsed. */\n async settleChannel(channelId: string): Promise<{ txHash?: string }> {\n const ctx = this.requireContext(channelId, 'settle');\n if (isSolanaChain(ctx.chain)) {\n const { txSignature } = await this.solanaClientForChannel(ctx).settle(channelId);\n return { txHash: txSignature };\n }\n return this.evmClientFor(ctx.chain).settle(ctx.tokenNetworkAddress, channelId);\n }\n\n /** The channel's lifecycle position, as the chain reports it. */\n async getChannelState(channelId: string): Promise<OnChainChannelStatus> {\n const ctx = this.requireContext(channelId, 'read');\n if (isSolanaChain(ctx.chain)) {\n const account = await this.solanaClientForChannel(ctx).read(channelId);\n // A SETTLED channel's account is zeroed by the program, so `!exists` is\n // reported as `missing`: \"there is nothing there\" is what was read, and\n // claiming to know it settled would be inventing a fact.\n const status: ChannelStatus = !account.exists\n ? 'missing'\n : account.state === 'opened'\n ? 'open'\n : account.state === 'closed'\n ? 'closed'\n : 'settled';\n return {\n channelId,\n status,\n chain: ctx.chain,\n // Our OWN collateral, not the vault's balance: the program bounds a\n // claim by the claimer's own deposit, so a peer-funded vault can look\n // amply funded while this client's headroom is nil.\n deposit: account.ownDeposit,\n ...(account.closeTimestamp !== undefined && account.closeTimestamp > 0n\n ? { closedAt: account.closeTimestamp }\n : {}),\n ...(account.settleableAt !== undefined ? { settleableAt: account.settleableAt } : {}),\n };\n }\n return this.evmClientFor(ctx.chain).getChannelState(ctx.tokenNetworkAddress, channelId);\n }\n\n /**\n * Read the EVM channel's close-relevant fields from chain, so a restarted\n * process recomputes the grace timer from the authority rather than from a\n * remembered number.\n */\n async getChannelCloseInfo(channelId: string): Promise<{\n status: ChannelStatus;\n closedAt: bigint;\n settlementTimeout: bigint;\n settleableAt: bigint;\n }> {\n const ctx = this.requireContext(channelId, 'read');\n if (isSolanaChain(ctx.chain)) {\n const account = await this.solanaClientForChannel(ctx).read(channelId);\n if (!account.exists) {\n throw new ChannelNotOpenError(\n `Solana channel ${channelId} does not exist on chain — a settled ` +\n \"channel's account is zeroed by the program, so there is nothing left to read.\"\n );\n }\n const closedAt = account.closeTimestamp ?? 0n;\n const challenge = account.challengeDuration ?? 0n;\n return {\n status:\n account.state === 'opened' ? 'open' : account.state === 'closed' ? 'closed' : 'settled',\n closedAt,\n settlementTimeout: challenge,\n settleableAt: account.settleableAt ?? closedAt + challenge,\n };\n }\n const record = await this.evmClientFor(ctx.chain).readChannel(\n ctx.tokenNetworkAddress,\n channelId\n );\n return {\n status: record.status,\n closedAt: record.closedAt,\n settlementTimeout: record.settlementTimeout,\n settleableAt: record.closedAt + record.settlementTimeout,\n };\n }\n\n /**\n * A participant's on-chain `deposit`/`nonce`/`transferredAmount`. Takes the\n * chain and token network explicitly so it works for a channel that was resumed\n * from disk and has no in-memory context yet — which is exactly when a caller\n * needs to re-hydrate the collateral it did not persist.\n */\n async readEvmParticipantState(opts: {\n chain: string;\n tokenNetworkAddress: string;\n channelId: string;\n participant: string;\n }): Promise<{ deposit: bigint; nonce: bigint; transferredAmount: bigint }> {\n return this.evmClientFor(opts.chain).readParticipant(\n opts.tokenNetworkAddress,\n opts.channelId,\n opts.participant\n );\n }\n\n // ─── Private ──────────────────────────────────────────────────────────────\n\n private requireContext(channelId: string, verb: string): ChannelContext {\n const ctx = this.channelContext.get(channelId);\n if (!ctx) {\n throw new ConfigError(\n `No on-chain context for channel \"${channelId}\" — this client cannot ` +\n `${verb} a channel it neither opened nor adopted. Call adoptChannel() ` +\n 'with the chain and token network it lives on.'\n );\n }\n return ctx;\n }\n\n private rememberEvm(channelId: string, terms: ChannelTerms): void {\n this.channelContext.set(channelId, {\n chain: terms.chain,\n tokenNetworkAddress: terms.tokenNetwork ?? '',\n ...(terms.token ? { tokenAddress: terms.token } : {}),\n });\n }\n\n /**\n * Open (or re-derive) the Solana channel PDA and collateralise it.\n *\n * Both PDA seeds are NEGOTIATED rather than configured: the mint is the\n * connector's published `tokenAddress` and the program its published\n * `programId`, each falling back to the config default only when the node named\n * none. That is what keeps the channel this opens and the channel the signed\n * claim asserts the same object — ADR 0053 binds the program into the signed\n * message, so a stale preset silently overriding it would produce claims that\n * verify against nothing.\n *\n * Idempotent by construction: the PDA is a pure function of the sorted pair and\n * the mint, so re-opening re-derives the same account and the on-chain\n * initialisation is skipped when it already exists.\n */\n private async openSolanaChannel(params: OpenChannelParams): Promise<OpenChannelResult> {\n const { terms } = params;\n const cfg = this.requireSolanaConfig();\n const client = this.solanaClientFor(terms.programId, terms.token, params.settlementTimeout);\n // The collateral an open locks is ONE policy for every settlement chain: the\n // negotiated `initialDeposit`, the same figure the EVM opener locks.\n // `solanaConfig.deposit` remains an explicit operator override of the amount\n // and/or the funded token account it is pulled from.\n const deposit = BigInt(cfg.deposit?.amount ?? params.initialDeposit ?? 0n);\n const result = await client.open({\n counterparty: terms.counterparty,\n deposit,\n ...(cfg.deposit?.payerTokenAccount\n ? { payerTokenAccount: cfg.deposit.payerTokenAccount }\n : {}),\n });\n\n // Record BOTH seeds the channel was actually opened with, so a later deposit\n // addresses THIS channel's vault and THIS channel's payer ATA rather than\n // re-deriving either from config.\n this.channelContext.set(result.channelId, {\n chain: terms.chain,\n tokenNetworkAddress: terms.programId ?? cfg.programId,\n tokenAddress: terms.token || cfg.tokenMint || '',\n });\n\n return {\n channelId: result.channelId,\n // Deliberately conservative rather than asserted: this call submitted (or\n // adopted) a channel account, and its lifecycle position is a fact only a\n // read establishes. `getChannelState` is that read.\n status: 'opening',\n ...(result.depositTotal !== undefined ? { depositTotal: result.depositTotal } : {}),\n };\n }\n\n /**\n * The Solana lifecycle client for one (program, mint) pair, built once.\n *\n * Keyed by both because both are PDA seeds: the same connector on a second\n * mint is a different channel account, and a redeployed program is a different\n * channel entirely.\n */\n private solanaClientFor(\n programId: string | undefined,\n tokenMint: string | undefined,\n settlementTimeout?: number\n ): SolanaChannelClient {\n const cfg = this.requireSolanaConfig();\n const program = programId ?? cfg.programId;\n const mint = tokenMint || cfg.tokenMint;\n if (!mint) {\n throw new ConfigError(\n 'A Solana channel PDA is seeded on the SPL mint, and neither the ' +\n 'connector nor this config named one.'\n );\n }\n const key = `${program}|${mint}`;\n const existing = this.solanaClients.get(key);\n if (existing) return existing;\n\n const payerSeed = cfg.keypair.slice(0, 32);\n const client = new SolanaChannelClient({\n rpcUrl: cfg.rpcUrl,\n ...(cfg.rpcFetch ? { rpcFetch: cfg.rpcFetch } : {}),\n programId: program,\n tokenMint: mint,\n payerSeed,\n payerPubkey: base58Encode(new Uint8Array(ed25519.getPublicKey(payerSeed))),\n challengeDuration: BigInt(cfg.challengeDuration ?? settlementTimeout ?? 86400),\n });\n this.solanaClients.set(key, client);\n return client;\n }\n\n /** The Solana client for a channel already tracked, from its recorded seeds. */\n private solanaClientForChannel(ctx: ChannelContext): SolanaChannelClient {\n return this.solanaClientFor(ctx.tokenNetworkAddress, ctx.tokenAddress);\n }\n\n private requireSolanaConfig(): SolanaChannelConfig {\n if (!this.solanaConfig) {\n throw new ConfigError(\n 'Solana channel config not provided — cannot act on a Solana channel. ' +\n 'Supply a mnemonic or a solanaSecretKey.'\n );\n }\n return this.solanaConfig;\n }\n}\n\n/** `solana`, `solana:devnet`, … — the family, not the network. */\nfunction isSolanaChain(chain: string): boolean {\n return chain.split(':')[0] === 'solana';\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}\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.\n */\nexport function rpcTransport(\n url: string,\n dispatcher: unknown | undefined,\n options: RpcTransportOptions = {}\n): ReturnType<typeof http> {\n const { timeout, retryCount } = options;\n return http(url, {\n ...(timeout !== undefined ? { timeout } : {}),\n ...(retryCount !== undefined ? { retryCount } : {}),\n ...(dispatcher !== undefined ? { fetchOptions: { dispatcher } as RequestInit } : {}),\n });\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 * The EVM half of the channel lifecycle: open (or adopt), fund, close, settle,\n * read.\n *\n * Everything here is a transaction or a read the **client** makes, on its own\n * gas, directly against a `TokenNetwork`. A connector has no endpoint that opens\n * a channel (`self-description-spec.md` ND-03); it discovers the channel by\n * reading the chain\n * ([ADR 0052](https://github.com/toon-protocol/connector/blob/main/docs/adr/0052-permissionless-payment-is-guaranteed-and-a-claim-is-what-authorises.md)),\n * which is what makes paying it permissionless rather than an arrangement with\n * its operator.\n *\n * ## Adopting beats opening\n *\n * The interesting method is {@link TokenNetworkClient.openOrAdopt}, and its\n * default answer is *do nothing on chain*. Since ADR 0059 a channel's id is\n * `keccak256(p1, p2, channelEpoch[p1][p2])` over the sorted pair, so this client\n * can compute the id of the channel it would have with a given connector and ask\n * whether it is already open — with no event log and no local record. Where one\n * is open it is adopted, which is not merely an optimisation: `openChannel`\n * reverts `ChannelAlreadyExists` against a live channel, and a client that opened\n * blindly would either fail or (before ADR 0059's global counter was removed)\n * lock a second lot of collateral in a channel it then had to remember forever.\n *\n * The epoch read is allowed to fail. The deployed Base Sepolia `TokenNetwork` at\n * the time of writing still carries the pre-ADR-0059 global `channelCounter` and\n * REVERTS on `channelEpoch` (ADR 0059's own status note records the redeploy as\n * pending), so a client that treated the revert as fatal could not open a channel\n * on the live devnet at all. A revert is read as \"this deployment cannot tell me\",\n * and the opener falls back to the `ChannelOpened` log — the pre-0059 behaviour,\n * unchanged.\n *\n * ## The registry is the authority on the token network\n *\n * A node publishes both a `tokenNetworkRegistry` and a `tokenNetwork`, and this\n * client checks the second against the first. The registry *mints* a token\n * network (`createTokenNetwork`), so its `getTokenNetwork(token)` is the\n * definition rather than a second opinion. A disagreement is a\n * {@link ../../client/errors.js!ConfigError} raised before any collateral moves:\n * the token network is the EIP-712 `verifyingContract` every claim on the channel\n * is signed under, so signing against the wrong one produces claims that verify\n * against nothing, whose only symptom is a refused claim.\n */\nimport { rpcTransport } from '../../transport/rpc.js';\nimport {\n createPublicClient,\n createWalletClient,\n maxUint256,\n decodeEventLog,\n defineChain,\n type Hex,\n type TransactionReceipt,\n} from 'viem';\nimport type { EvmSigner } from '../../signing/evm-signer.js';\nimport {\n ChannelFundingError,\n ChannelNotOpenError,\n ConfigError,\n StaleRpcReadError,\n isInsufficientGasError,\n} from '../../client/errors.js';\nimport type {\n ChannelStatus,\n ChannelTerms,\n OnChainChannelStatus,\n OpenChannelResult,\n} from '../types.js';\nimport { ERC20_ABI, TOKEN_NETWORK_ABI, TOKEN_NETWORK_REGISTRY_ABI } from './abi.js';\nimport { deriveEvmChannelId } from './channel-id.js';\n\n/** Read-after-write polling knobs for the open path (#489). */\nexport interface EvmReadConsistencyConfig {\n /** Reads of the freshly opened channel before giving up. Default 12. */\n attempts?: number;\n /** Delay between those reads, ms. Default 1000. */\n delayMs?: number;\n /** `setTotalDeposit` retries on `InvalidChannelState()`. Default 3. */\n depositRetries?: number;\n}\n\nconst DEFAULT_READ_CONSISTENCY: Required<EvmReadConsistencyConfig> = {\n attempts: 12,\n delayMs: 1000,\n depositRetries: 3,\n};\n\n/**\n * The one-hour floor `TokenNetwork.openChannel` enforces\n * (`MIN_SETTLEMENT_TIMEOUT`). A shorter request reverts\n * `InvalidSettlementTimeout`, so it is raised to the floor here rather than\n * spending gas to be told.\n */\nexport const MIN_SETTLEMENT_TIMEOUT_SECONDS = 3600;\n\nconst ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';\n\n/** The `TokenNetwork` channel state enum, as this client names it. */\nconst STATE_MAP: Record<number, ChannelStatus> = {\n 0: 'missing',\n 1: 'open',\n 2: 'closed',\n 3: 'settled',\n};\n\nexport interface TokenNetworkClientConfig {\n /** The chain key exactly as the node publishes it: `evm:84532`. */\n chain: string;\n rpcUrl: string;\n signer: EvmSigner;\n readConsistency?: EvmReadConsistencyConfig;\n /**\n * An undici dispatcher to send RPC through — present when the client is\n * talking to a hidden service, so chain traffic rides the same overlay as the\n * packets rather than announcing this address on clearnet (ADR 0002).\n */\n rpcDispatcher?: unknown;\n}\n\n/** What one channel's `channels(id)` view says. */\nexport interface EvmChannelRecord {\n settlementTimeout: bigint;\n state: number;\n status: ChannelStatus;\n closedAt: bigint;\n openedAt: bigint;\n participant1: string;\n participant2: string;\n}\n\nexport interface OpenOrAdoptParams {\n terms: ChannelTerms;\n /** Collateral to lock, base units. `0n` opens an uncollateralised channel. */\n initialDeposit?: bigint;\n /** Challenge period in seconds. Raised to {@link MIN_SETTLEMENT_TIMEOUT_SECONDS}. */\n settlementTimeout?: number;\n}\n\nexport class TokenNetworkClient {\n readonly chain: string;\n private readonly rpcUrl: string;\n private readonly signer: EvmSigner;\n private readonly readConsistency: Required<EvmReadConsistencyConfig>;\n private readonly publicClient: ReturnType<typeof createPublicClient>;\n private readonly walletClient: ReturnType<typeof createWalletClient>;\n\n constructor(config: TokenNetworkClientConfig) {\n this.chain = config.chain;\n this.rpcUrl = config.rpcUrl;\n this.signer = config.signer;\n this.readConsistency = { ...DEFAULT_READ_CONSISTENCY, ...config.readConsistency };\n\n const viemChain = defineChain({\n id: parseEvmChainId(config.chain),\n name: config.chain,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [config.rpcUrl] } },\n });\n this.publicClient = createPublicClient({\n transport: rpcTransport(config.rpcUrl, config.rpcDispatcher),\n chain: viemChain,\n });\n this.walletClient = createWalletClient({\n account: config.signer.account,\n transport: rpcTransport(config.rpcUrl, config.rpcDispatcher),\n chain: viemChain,\n });\n }\n\n /** This client's participant address — the one a channel is opened in the name of. */\n get address(): string {\n return this.signer.address;\n }\n\n // ─── Reads ────────────────────────────────────────────────────────────────\n\n /**\n * The `TokenNetwork` the registry says serves `token`, or `undefined` when it\n * says none does (the zero address).\n */\n async resolveTokenNetwork(registry: string, token: string): Promise<string | undefined> {\n const resolved = (await this.publicClient.readContract({\n address: registry as Hex,\n abi: TOKEN_NETWORK_REGISTRY_ABI,\n functionName: 'getTokenNetwork',\n args: [token as Hex],\n })) as string;\n return resolved.toLowerCase() === ZERO_ADDRESS ? undefined : resolved;\n }\n\n /**\n * Check the node's published `tokenNetwork` against the registry it also\n * published, and refuse the pair if they disagree.\n *\n * Skipped when the node published no registry: there is then only one\n * declaration of the fact and nothing to check it against, which is a thinner\n * guarantee but not a contradiction. A registry the RPC cannot reach is also\n * not a contradiction — an unreachable endpoint would otherwise make every\n * channel unopenable — so a failed READ is re-thrown as itself, while a\n * successful read that disagrees is a {@link ConfigError}.\n *\n * @throws {ConfigError} the registry names a different token network, or names\n * none at all for a token the node claims to settle in.\n */\n async assertTokenNetworkMatchesRegistry(terms: ChannelTerms): Promise<void> {\n const registry = terms.tokenNetworkRegistry;\n const published = terms.tokenNetwork;\n if (!registry || !published) return;\n\n const resolved = await this.resolveTokenNetwork(registry, terms.token);\n if (resolved === undefined) {\n throw new ConfigError(\n `The TokenNetworkRegistry at ${registry} on ${terms.chain} has no token ` +\n `network for token ${terms.token}, but this connector publishes ` +\n `${published} as one. A claim signed under a token network the registry ` +\n 'does not recognise verifies against nothing. Check the connector\\'s ' +\n 'settlement configuration, or that both are on the chain you think.'\n );\n }\n if (resolved.toLowerCase() !== published.toLowerCase()) {\n throw new ConfigError(\n `This connector publishes tokenNetwork ${published} for token ` +\n `${terms.token} on ${terms.chain}, but its own registry ${registry} ` +\n `resolves that token to ${resolved}. The registry mints token networks, ` +\n 'so it is the authority; the published address is wrong. Refusing before ' +\n 'locking collateral, because every claim on such a channel would be ' +\n 'signed under the wrong EIP-712 verifyingContract and be refused.'\n );\n }\n }\n\n /**\n * This pair's `channelEpoch`, or `undefined` when this deployment cannot answer\n * — a pre-ADR-0059 `TokenNetwork` has no such function and the call reverts.\n *\n * `undefined` is a fact about the CONTRACT, never about the pair: epoch `0n` is\n * a real, common answer (a pair that has never settled a channel), so the two\n * must not be conflated.\n */\n async channelEpoch(\n tokenNetwork: string,\n a: string,\n b: string\n ): Promise<bigint | undefined> {\n const [p1, p2] = a.toLowerCase() < b.toLowerCase() ? [a, b] : [b, a];\n try {\n return (await this.publicClient.readContract({\n address: tokenNetwork as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'channelEpoch',\n args: [p1 as Hex, p2 as Hex],\n })) as bigint;\n } catch {\n return undefined;\n }\n }\n\n /**\n * The id of the channel this client would have with `counterparty` right now,\n * derived off chain, or `undefined` when the deployment cannot report an epoch.\n */\n async deriveChannelId(\n tokenNetwork: string,\n counterparty: string\n ): Promise<string | undefined> {\n const epoch = await this.channelEpoch(tokenNetwork, this.address, counterparty);\n if (epoch === undefined) return undefined;\n return deriveEvmChannelId(this.address, counterparty, epoch);\n }\n\n /** The `channels(id)` view, destructured. */\n async readChannel(tokenNetwork: string, channelId: string): Promise<EvmChannelRecord> {\n const res = (await this.publicClient.readContract({\n address: tokenNetwork as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'channels',\n args: [channelId as Hex],\n })) as readonly [bigint, number, bigint, bigint, string, string];\n const state = Number(res[1]);\n return {\n settlementTimeout: res[0],\n state,\n status: STATE_MAP[state] ?? 'missing',\n closedAt: res[2],\n openedAt: res[3],\n participant1: res[4],\n participant2: res[5],\n };\n }\n\n /**\n * A participant's own `deposit` / `nonce` / `transferredAmount`, straight from\n * the `participants` mapping. `participant` defaults to this client.\n */\n async readParticipant(\n tokenNetwork: string,\n channelId: string,\n participant: string = this.address\n ): Promise<{ deposit: bigint; nonce: bigint; transferredAmount: bigint }> {\n const res = (await this.publicClient.readContract({\n address: tokenNetwork as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'participants',\n args: [channelId as Hex, participant as Hex],\n })) as readonly [bigint, bigint, bigint];\n return { deposit: res[0], nonce: res[1], transferredAmount: res[2] };\n }\n\n /** The lifecycle position of one channel, as the chain reports it. */\n async getChannelState(\n tokenNetwork: string,\n channelId: string\n ): Promise<OnChainChannelStatus> {\n const record = await this.readChannel(tokenNetwork, channelId);\n const participant = await this.readParticipant(tokenNetwork, channelId).catch(\n () => undefined\n );\n return {\n channelId,\n status: record.status,\n chain: this.chain,\n ...(participant ? { deposit: participant.deposit } : {}),\n ...(record.closedAt > 0n\n ? {\n closedAt: record.closedAt,\n settleableAt: record.closedAt + record.settlementTimeout,\n }\n : {}),\n };\n }\n\n // ─── Lifecycle ────────────────────────────────────────────────────────────\n\n /**\n * Return the channel this client already holds with the connector, opening one\n * only if there is none.\n *\n * @throws {ConfigError} the published token network disagrees with its registry.\n * @throws {ChannelNotOpenError} the pair's current channel is CLOSED. Nothing\n * can be done with it and nothing can replace it: the epoch advances on\n * `settleChannel`, so this pair's next channel does not exist until the\n * current one is settled, and `openChannel` would revert\n * `ChannelAlreadyExists`.\n * @throws {ChannelFundingError} the wallet has no native gas for the open.\n */\n async openOrAdopt(params: OpenOrAdoptParams): Promise<OpenChannelResult> {\n const { terms } = params;\n const tokenNetwork = terms.tokenNetwork;\n if (!tokenNetwork) {\n throw new ConfigError(\n `This connector's ${terms.chain} settlement entry publishes no ` +\n 'tokenNetwork, so there is no contract to open a channel at.'\n );\n }\n await this.assertTokenNetworkMatchesRegistry(terms);\n\n const derived = await this.deriveChannelId(tokenNetwork, terms.counterparty);\n if (derived !== undefined) {\n const adopted = await this.adoptDerived(tokenNetwork, derived, terms);\n if (adopted) return adopted;\n }\n\n try {\n return await this.openChannel(params, tokenNetwork, derived);\n } catch (err) {\n if (!isInsufficientGasError(err)) throw err;\n throw new ChannelFundingError(\n `Settlement wallet ${this.address} has no gas on ${terms.chain} to open a ` +\n 'payment channel. Fund the wallet (`toon faucet`, or send it native ' +\n 'currency) and retry — this is the one-time on-chain open; paying for a ' +\n 'request never spends gas.',\n err instanceof Error ? err : undefined\n );\n }\n }\n\n /**\n * Read the derived id and decide whether it is already ours to use.\n * `undefined` means \"nothing there — open one\".\n */\n private async adoptDerived(\n tokenNetwork: string,\n channelId: string,\n terms: ChannelTerms\n ): Promise<OpenChannelResult | undefined> {\n const record = await this.readChannel(tokenNetwork, channelId);\n if (record.status === 'missing' || record.status === 'settled') return undefined;\n\n if (record.status === 'closed') {\n throw new ChannelNotOpenError(\n `The channel this client holds with ${terms.counterparty} on ` +\n `${terms.chain} (${channelId}) is CLOSED: its challenge period is ` +\n 'running and it can no longer carry claims. Settle it once the period ' +\n 'elapses — settling advances this pair\\'s channelEpoch, which is what ' +\n 'makes a new channel between the same two addresses possible.'\n );\n }\n\n const { deposit } = await this.readParticipant(tokenNetwork, channelId);\n return { channelId, status: 'open', depositTotal: deposit };\n }\n\n /**\n * Open a channel and collateralise it: `openChannel`, then (when there is a\n * deposit) `approve` + `setTotalDeposit`.\n *\n * `expectedId`, when the chain could report an epoch, is asserted against the\n * id the `ChannelOpened` log carries. The two are computed by different parties\n * from the same rule, so a disagreement means this client's idea of the pair —\n * or of the contract — is wrong, and it must not go on to sign claims naming an\n * id the chain does not hold.\n */\n private async openChannel(\n params: OpenOrAdoptParams,\n tokenNetwork: string,\n expectedId: string | undefined\n ): Promise<OpenChannelResult> {\n const { terms } = params;\n const deposit = params.initialDeposit ?? 0n;\n const timeout = BigInt(\n Math.max(params.settlementTimeout ?? 86400, MIN_SETTLEMENT_TIMEOUT_SECONDS)\n );\n\n if (deposit > 0n && terms.token) {\n await this.ensureAllowance(terms.token, tokenNetwork, deposit);\n }\n\n const openHash = await this.walletClient.writeContract({\n address: tokenNetwork as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'openChannel',\n args: [terms.counterparty as Hex, timeout],\n chain: this.walletClient.chain,\n account: this.signer.account,\n });\n const receipt: TransactionReceipt = await this.publicClient.waitForTransactionReceipt({\n hash: openHash,\n });\n\n const channelId = readOpenedChannelId(receipt);\n if (channelId === undefined) {\n throw new ConfigError(\n `openChannel at ${tokenNetwork} on ${terms.chain} confirmed in ${openHash} ` +\n 'but emitted no ChannelOpened event this client could decode. The address ' +\n 'may not be a TokenNetwork.'\n );\n }\n if (expectedId !== undefined && expectedId.toLowerCase() !== channelId.toLowerCase()) {\n throw new ConfigError(\n `The channel just opened at ${tokenNetwork} is ${channelId}, but this ` +\n `client derived ${expectedId} for the same pair and epoch. A claim is ` +\n 'routed by its channel id, so signing against a derived id the chain ' +\n 'disagrees with would be refused on every write. Refusing rather than ' +\n 'guessing which of the two is right.'\n );\n }\n\n if (deposit > 0n) {\n // READ-AFTER-WRITE (#489): the open receipt is confirmed, but a\n // load-balanced RPC (`sepolia.base.org`) can route this next call to a\n // replica that has not seen the open, which reverts `InvalidChannelState()`\n // and strands the just-opened channel with no collateral.\n await this.waitForChannelVisible(tokenNetwork, channelId);\n await this.setTotalDepositWithRetry(tokenNetwork, channelId, deposit);\n }\n\n return { channelId, status: 'opening', txHash: openHash, depositTotal: deposit };\n }\n\n /**\n * Add collateral. `setTotalDeposit` takes the new CUMULATIVE total rather than\n * a delta — a contract shape that makes a lost or duplicated call harmless — so\n * the caller's current total is added to.\n */\n async deposit(\n tokenNetwork: string,\n channelId: string,\n amount: bigint,\n opts: { currentDeposit: bigint; token?: string }\n ): Promise<{ txHash: string; depositTotal: bigint }> {\n if (amount <= 0n) throw new RangeError('Deposit amount must be positive.');\n const newTotal = opts.currentDeposit + amount;\n if (opts.token) await this.ensureAllowance(opts.token, tokenNetwork, amount);\n\n const hash = await this.walletClient.writeContract({\n address: tokenNetwork as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'setTotalDeposit',\n args: [channelId as Hex, this.address as Hex, newTotal],\n chain: this.walletClient.chain,\n account: this.signer.account,\n });\n await this.publicClient.waitForTransactionReceipt({ hash });\n return { txHash: hash, depositTotal: newTotal };\n }\n\n /**\n * Start the challenge period. Unilateral (channel id only); afterwards the\n * `channels()` view is re-read for the AUTHORITATIVE `closedAt` +\n * `settlementTimeout` in block-timestamp seconds, because the deadline that\n * matters is the chain's and not this process's clock.\n */\n async close(\n tokenNetwork: string,\n channelId: string\n ): Promise<{\n txHash: string;\n closedAt: bigint;\n settlementTimeout: bigint;\n settleableAt: bigint;\n }> {\n const hash = await this.walletClient.writeContract({\n address: tokenNetwork as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'closeChannel',\n args: [channelId as Hex],\n chain: this.walletClient.chain,\n account: this.signer.account,\n });\n await this.publicClient.waitForTransactionReceipt({ hash });\n const record = await this.readChannel(tokenNetwork, channelId);\n return {\n txHash: hash,\n closedAt: record.closedAt,\n settlementTimeout: record.settlementTimeout,\n settleableAt: record.closedAt + record.settlementTimeout,\n };\n }\n\n /**\n * Pay out and finish. The contract itself reverts before\n * `closedAt + settlementTimeout`, so the caller enforces the time guard first\n * rather than spending gas to be told.\n */\n async settle(tokenNetwork: string, channelId: string): Promise<{ txHash: string }> {\n const hash = await this.walletClient.writeContract({\n address: tokenNetwork as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'settleChannel',\n args: [channelId as Hex],\n chain: this.walletClient.chain,\n account: this.signer.account,\n });\n await this.publicClient.waitForTransactionReceipt({ hash });\n return { txHash: hash };\n }\n\n // ─── Private ──────────────────────────────────────────────────────────────\n\n /** Approve `spender` for at least `amount`, if the standing allowance is short. */\n private async ensureAllowance(\n token: string,\n spender: string,\n amount: bigint\n ): Promise<void> {\n const allowance = (await this.publicClient.readContract({\n address: token as Hex,\n abi: ERC20_ABI,\n functionName: 'allowance',\n args: [this.address as Hex, spender as Hex],\n })) as bigint;\n if (allowance >= amount) return;\n const hash = await this.walletClient.writeContract({\n address: token as Hex,\n abi: ERC20_ABI,\n functionName: 'approve',\n args: [spender as Hex, maxUint256],\n chain: this.walletClient.chain,\n account: this.signer.account,\n });\n await this.publicClient.waitForTransactionReceipt({ hash });\n }\n\n /**\n * Poll until the RPC reports the just-opened channel (non-zero `participant1`).\n * Tolerates a read that throws or returns nothing — a stale replica does both.\n */\n private async waitForChannelVisible(\n tokenNetwork: string,\n channelId: string\n ): Promise<void> {\n const { attempts, delayMs } = this.readConsistency;\n let lastError: Error | undefined;\n for (let i = 0; i < attempts; i++) {\n if (i > 0) await sleep(delayMs);\n try {\n const record = await this.readChannel(tokenNetwork, channelId);\n if (record.participant1.toLowerCase() !== ZERO_ADDRESS) return;\n } catch (err) {\n lastError = err instanceof Error ? err : new Error(String(err));\n }\n }\n throw new StaleRpcReadError(\n `Channel ${channelId} was opened on ${this.chain} but ${this.rpcUrl} still ` +\n `does not report it after ${attempts} reads. This is the stale-read ` +\n 'failure of a load-balanced endpoint (e.g. `https://sepolia.base.org`) — ' +\n 'point `rpcUrl` at a read-after-write consistent RPC such as ' +\n '`https://base-sepolia-rpc.publicnode.com` and retry. The channel IS open ' +\n 'on chain; it just has no collateral yet.',\n lastError\n );\n }\n\n /**\n * `setTotalDeposit`, retried on `InvalidChannelState()` — the revert a stale\n * replica produces for a channel it has not observed. Every other revert\n * propagates immediately (an under-funded wallet must not be retried).\n */\n private async setTotalDepositWithRetry(\n tokenNetwork: string,\n channelId: string,\n total: bigint\n ): Promise<void> {\n const { depositRetries, delayMs } = this.readConsistency;\n for (let attempt = 0; ; attempt++) {\n try {\n const hash = await this.walletClient.writeContract({\n address: tokenNetwork as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'setTotalDeposit',\n args: [channelId as Hex, this.address as Hex, total],\n chain: this.walletClient.chain,\n account: this.signer.account,\n });\n await this.publicClient.waitForTransactionReceipt({ hash });\n return;\n } catch (err) {\n if (attempt >= depositRetries || !isInvalidChannelStateRevert(err)) throw err;\n await sleep(delayMs);\n await this.waitForChannelVisible(tokenNetwork, channelId);\n }\n }\n }\n}\n\n/**\n * The numeric chain id inside a chain key.\n *\n * Accepts both the canonical `evm:{chainId}` a self-description carries and the\n * three-part `evm:{network}:{chainId}` some deployments still spell.\n */\nexport function parseEvmChainId(chain: string): number {\n const parts = chain.split(':');\n const raw = parts.length >= 3 ? parts[2] : parts[1];\n const chainId = raw === undefined ? Number.NaN : Number.parseInt(raw, 10);\n if (!Number.isFinite(chainId)) {\n throw new ConfigError(\n `\"${chain}\" is not an EVM chain key. Expected \"evm:{chainId}\" (e.g. \"evm:84532\").`\n );\n }\n return chainId;\n}\n\n/** The `channelId` a receipt's `ChannelOpened` log carries, if it has one. */\nfunction readOpenedChannelId(receipt: TransactionReceipt): string | undefined {\n for (const log of receipt.logs) {\n try {\n const decoded = decodeEventLog({\n abi: TOKEN_NETWORK_ABI,\n data: log.data,\n topics: log.topics,\n });\n if (decoded.eventName === 'ChannelOpened') {\n return (decoded.args as Record<string, unknown>)['channelId'] as string;\n }\n } catch {\n // Not our event.\n }\n }\n return undefined;\n}\n\n/**\n * `InvalidChannelState()` — the `TokenNetwork` revert a stale replica produces\n * when `setTotalDeposit` runs against a channel it has not observed yet. viem\n * surfaces the raw selector and/or the decoded name depending on whether the ABI\n * carried the error, so both markers are matched.\n */\nfunction isInvalidChannelStateRevert(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 text.includes('0xf806e9d9') || text.includes('invalidchannelstate');\n}\n\nfunction sleep(ms: number): Promise<void> {\n return ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();\n}\n","/**\n * The three EVM contracts this client touches, cut down to the members it\n * actually calls.\n *\n * A partial ABI is deliberate rather than lazy: every entry here is a call this\n * client makes, so the list doubles as the exhaustive statement of what a channel\n * costs its owner on chain. The contracts are\n * `connector/packages/contracts/src/{TokenNetwork,TokenNetworkRegistry}.sol`.\n */\n\n/**\n * `TokenNetwork` — one deployment per settlement token, and the EIP-712\n * `verifyingContract` every claim on a channel of its is signed under.\n *\n * Two members are worth pointing at, because everything the client can do\n * *without* an event log follows from them:\n *\n * - **`channelEpoch(p1, p2)`** is the pair's public, monotonic counter. It\n * advances only when a channel of theirs settles\n * (`TokenNetwork.sol`'s `settleChannel`), so a pair has at most one live\n * channel and its id is a pure function of the pair and this number\n * ([ADR 0059](https://github.com/toon-protocol/connector/blob/main/docs/adr/0059-a-channel-is-derived-from-its-participants.md)).\n * That is what lets a client derive its own channel id off chain and *adopt*\n * an already-open channel instead of opening a second one — see\n * {@link ./channel-id.js!deriveEvmChannelId}.\n * - **`channels(id)`** answers whether that derived id is at anything.\n *\n * `channelEpoch` is read through a call that is allowed to REVERT. The deployed\n * Base Sepolia `TokenNetwork` at the time of writing still carries ADR 0059's\n * predecessor — a global `channelCounter` — and answers `channelEpoch` with a\n * revert, so a client that treated the revert as fatal could not open a channel\n * on the live devnet at all. {@link ./TokenNetworkClient.js!TokenNetworkClient}\n * falls back to the `ChannelOpened` log in that case.\n */\nexport const TOKEN_NETWORK_ABI = [\n {\n name: 'openChannel',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'participant2', type: 'address' },\n { name: 'settlementTimeout', type: 'uint256' },\n ],\n outputs: [{ type: 'bytes32' }],\n },\n {\n name: 'setTotalDeposit',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'participant', type: 'address' },\n { name: 'totalDeposit', type: 'uint256' },\n ],\n outputs: [],\n },\n {\n name: 'closeChannel',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ name: 'channelId', type: 'bytes32' }],\n outputs: [],\n },\n {\n name: 'settleChannel',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ name: 'channelId', type: 'bytes32' }],\n outputs: [],\n },\n {\n name: 'channels',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'bytes32' }],\n outputs: [\n { name: 'settlementTimeout', type: 'uint256' },\n { name: 'state', type: 'uint8' },\n { name: 'closedAt', type: 'uint256' },\n { name: 'openedAt', type: 'uint256' },\n { name: 'participant1', type: 'address' },\n { name: 'participant2', type: 'address' },\n ],\n },\n {\n name: 'participants',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'bytes32' }, { type: 'address' }],\n outputs: [\n { name: 'deposit', type: 'uint256' },\n { name: 'nonce', type: 'uint256' },\n { name: 'transferredAmount', type: 'uint256' },\n ],\n },\n {\n // Public mapping getter: `mapping(address => mapping(address => uint256))\n // public channelEpoch`, keyed by the SORTED pair.\n name: 'channelEpoch',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'address' }, { type: 'address' }],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'ChannelOpened',\n type: 'event',\n inputs: [\n { name: 'channelId', type: 'bytes32', indexed: true },\n { name: 'participant1', type: 'address', indexed: true },\n { name: 'participant2', type: 'address', indexed: true },\n { name: 'settlementTimeout', type: 'uint256', indexed: false },\n ],\n },\n] as const;\n\n/**\n * `TokenNetworkRegistry` — the stable address, and the only authority on which\n * `TokenNetwork` serves a given token.\n *\n * A node publishes both in its self-description, and this client cross-checks\n * them: `getTokenNetwork(tokenAddress)` must equal the published `tokenNetwork`,\n * or a claim would be signed under an EIP-712 `verifyingContract` that no channel\n * of ours lives at. The registry is read rather than trusted because it is the\n * one of the two that cannot be misconfigured — a `TokenNetwork` is *minted* by\n * it (`createTokenNetwork`), so its answer is the definition.\n */\nexport const TOKEN_NETWORK_REGISTRY_ABI = [\n {\n name: 'getTokenNetwork',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'token', type: 'address' }],\n outputs: [{ type: 'address' }],\n },\n] as const;\n\n/** ERC-20, cut to the two members collateralising a channel needs. */\nexport const ERC20_ABI = [\n {\n name: 'approve',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'spender', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ type: 'bool' }],\n },\n {\n name: 'allowance',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n ],\n outputs: [{ type: 'uint256' }],\n },\n] as const;\n","/**\n * Computing a `TokenNetwork` channel id from the pair it belongs to.\n *\n * This exists because of what it makes possible, which is bigger than saving a\n * call. Since\n * [ADR 0059](https://github.com/toon-protocol/connector/blob/main/docs/adr/0059-a-channel-is-derived-from-its-participants.md)\n * a channel's id is `keccak256(abi.encodePacked(p1, p2, epoch))` over the sorted\n * participant pair, so **anyone holding two addresses can compute the id and ask\n * the chain whether that channel exists** — with no event log, no reverse index\n * and no records of their own. A client that has forgotten which channel it holds\n * with a connector, or that never knew, can therefore *adopt* the open one rather\n * than opening and collateralising a second: at most one live channel exists per\n * pair, because the epoch advances only on settlement.\n *\n * That is also why the epoch is a parameter and never a guess. It is read from\n * `TokenNetwork.channelEpoch(p1, p2)`; a caller that invents one derives an id\n * nothing is at.\n *\n * Mirrors `connector/crates/connector-settlement-evm/src/channel_id.rs`, which is\n * itself a mirror of `TokenNetwork.sol`'s `openChannel`. The three must agree\n * byte for byte, so the preimage layout is asserted in this module's tests\n * against viem's own `encodePacked` rather than only implied by a round trip.\n */\nimport { keccak256 } from 'viem';\n\n/** A 20-byte EVM address, `0x`-prefixed. */\nconst ADDRESS_SHAPE = /^0x[0-9a-fA-F]{40}$/;\n\n/**\n * Put a pair into the order `TokenNetwork.openChannel` normalises them to —\n * ascending by address, `p1 < p2` — so both sides of a channel derive the same\n * id from opposite arguments.\n *\n * The comparison is over the address BYTES, which is what Solidity's `<` on an\n * `address` compares. Comparing the hex strings gives the same answer only once\n * they are lower-cased: `'0xA…' < '0xb…'` is true in ASCII while `'0xa…' <\n * '0xB…'` is false, so an EIP-55 checksummed pair sorted as text can land in the\n * wrong order and derive an id nothing is at.\n */\nexport function sortParticipants(a: string, b: string): [string, string] {\n const [na, nb] = [normalizeAddress(a), normalizeAddress(b)];\n return na < nb ? [na, nb] : [nb, na];\n}\n\n/**\n * `keccak256(abi.encodePacked(p1, p2, epoch))` over the sorted pair — byte for\n * byte what `TokenNetwork.openChannel` computes.\n *\n * `abi.encodePacked` of `(address, address, uint256)` is 20 + 20 + 32 bytes with\n * no padding and no length prefixes; the concatenation below is exactly that.\n * Hashing the same three fields any other way — 32-byte-padded addresses, a\n * little-endian epoch — produces a well-formed, useless id.\n *\n * @param a one participant, in either order.\n * @param b the other.\n * @param epoch the pair's own `channelEpoch(p1, p2)`, READ FROM CHAIN.\n * @returns the id as `0x` + 64 lower-case hex, the one spelling\n * `client-edge-spec.md` §1.3 canonicalises a claim's `channelId` to.\n */\nexport function deriveEvmChannelId(a: string, b: string, epoch: bigint): string {\n if (epoch < 0n) {\n throw new RangeError(`channelEpoch cannot be negative; got ${epoch.toString()}`);\n }\n const [p1, p2] = sortParticipants(a, b);\n const preimage = new Uint8Array(20 + 20 + 32);\n preimage.set(addressBytes(p1), 0);\n preimage.set(addressBytes(p2), 20);\n preimage.set(uint256BigEndian(epoch), 40);\n return keccak256(preimage);\n}\n\n/** Lower-cased, `0x`-prefixed, and rejected outright if it is not an address. */\nfunction normalizeAddress(address: string): string {\n if (!ADDRESS_SHAPE.test(address)) {\n throw new TypeError(\n `\"${address}\" is not an EVM address (expected 0x + 40 hex characters)`\n );\n }\n return address.toLowerCase();\n}\n\n/** The 20 raw bytes of a normalised address. */\nfunction addressBytes(address: string): Uint8Array {\n const hex = address.slice(2);\n const out = new Uint8Array(20);\n for (let i = 0; i < 20; i++) {\n out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\n/**\n * A `uint256` as 32 big-endian bytes — Solidity's own layout, and the layout the\n * Rust mirror writes with `U256::to_big_endian`.\n */\nfunction uint256BigEndian(value: bigint): Uint8Array {\n const out = new Uint8Array(32);\n let v = value;\n for (let i = 31; i >= 0 && v > 0n; i--) {\n out[i] = Number(v & 0xffn);\n v >>= 8n;\n }\n if (v > 0n) {\n throw new RangeError(`channelEpoch ${value.toString()} does not fit in a uint256`);\n }\n return out;\n}\n","/**\n * Solana payment-channel primitives — parity with the deployed program.\n *\n * Pure, dependency-light helpers that reproduce the EXACT on-chain contract of\n * the connector's `payment-channel` program\n * (`toon-protocol/connector` `packages/solana-program/src/{instruction,state,processor}.rs`),\n * mirrored the same way the connector's own client half is\n * (`crates/connector-settlement-solana/src/wire.rs`). A mismatch anywhere below\n * makes the connector refuse the claim, or makes the chain refuse the\n * transaction — so every discriminator, account order and byte offset here is\n * cited to the Rust it was read from, and must move in lock-step with it.\n *\n * 1. PDA derivation — `[b\"channel\", min_pubkey, max_pubkey, token_mint]`,\n * participants sorted lexicographically by raw 32-byte pubkey, derived\n * against the program id (`processor.rs::derive_channel_pda`). This base58\n * PDA is the claim's `channelAccount` and the channel-state account both\n * the connector and the program read.\n * 2. The **96-byte** balance-proof message a claim's Ed25519 signature covers\n * — see {@link buildBalanceProofMessage} for the layout and for why it\n * grew from 48 bytes (connector ADR 0053).\n * 3. The six instructions the program implements: `01` initialize, `02`\n * deposit, `03` close, `04` settle, `05` force-close-expired and `06`\n * claim-from-channel — built and submitted over raw Solana JSON-RPC (no\n * `@solana/web3.js` / `@solana/kit` runtime dependency: only\n * `@noble/curves` + `@noble/hashes`, already client deps).\n * 4. The 178-byte `ChannelState` account (`state.rs`), decoded in full.\n */\n\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { base58Encode, base58Decode } from '../../utils/base58.js';\nimport { ChannelFundingError } from '../../client/errors.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';\nconst SYSTEM_PROGRAM_ID = '11111111111111111111111111111111';\nconst RENT_SYSVAR_ID = 'SysvarRent111111111111111111111111111111111';\nconst CLOCK_SYSVAR_ID = 'SysvarC1ock11111111111111111111111111111111';\nconst INSTRUCTIONS_SYSVAR_ID = 'Sysvar1nstructions1111111111111111111111111';\n/** The Ed25519 signature-verification precompile (`ed25519_program::id()`). */\nconst ED25519_PROGRAM_ID = 'Ed25519SigVerify111111111111111111111111111';\n\n/**\n * Instruction discriminators — the first byte of an 8-byte LE tag\n * (`instruction.rs:7-12`). The program dispatches on all eight bytes, so the\n * seven zero bytes are as load-bearing as the first.\n */\nconst IX_INITIALIZE_CHANNEL = new Uint8Array([0x01, 0, 0, 0, 0, 0, 0, 0]);\nconst IX_DEPOSIT = new Uint8Array([0x02, 0, 0, 0, 0, 0, 0, 0]);\nconst IX_CLOSE_CHANNEL = new Uint8Array([0x03, 0, 0, 0, 0, 0, 0, 0]);\nconst IX_SETTLE_CHANNEL = new Uint8Array([0x04, 0, 0, 0, 0, 0, 0, 0]);\nconst IX_FORCE_CLOSE_EXPIRED = new Uint8Array([0x05, 0, 0, 0, 0, 0, 0, 0]);\nconst IX_CLAIM_FROM_CHANNEL = new Uint8Array([0x06, 0, 0, 0, 0, 0, 0, 0]);\n\n/** On-chain channel-account discriminator: ASCII \"pchannel\". */\nconst CHANNEL_DISCRIMINATOR = new Uint8Array([\n 0x70, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c,\n]);\n\n/** Channel-state account size in bytes. */\nconst CHANNEL_ACCOUNT_SIZE = 178;\n\n// ---------------------------------------------------------------------------\n// Byte helpers\n// ---------------------------------------------------------------------------\n\nconst MAX_U64 = (1n << 64n) - 1n;\n\nfunction writeU64LE(buf: Uint8Array, offset: number, value: bigint): void {\n if (value < 0n || value > MAX_U64) {\n throw new RangeError(`Value ${value} outside u64 range [0, 2^64-1]`);\n }\n for (let i = 0; i < 8; i++) {\n buf[offset + i] = Number((value >> BigInt(i * 8)) & 0xffn);\n }\n}\n\n/** Left-pad / trim a byte array to exactly 32 bytes. */\nfunction 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). */\nfunction sortPubkeys(a: Uint8Array, b: Uint8Array): [Uint8Array, Uint8Array] {\n for (let i = 0; i < 32; i++) {\n const ai = a[i] ?? 0;\n const bi = b[i] ?? 0;\n if (ai < bi) return [a, b];\n if (ai > bi) return [b, a];\n }\n return [a, b];\n}\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\nfunction 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 channel PDA — connector-parity.\n * Seeds: `[b\"channel\", min_pubkey, max_pubkey, token_mint]` (participants sorted).\n *\n * @returns base58 PDA + bump.\n */\nexport function deriveChannelPDA(\n participantA: string,\n participantB: string,\n tokenMint: string,\n programId: string\n): { pda: string; bump: number } {\n const a = padTo32(base58Decode(participantA));\n const b = padTo32(base58Decode(participantB));\n const mint = padTo32(base58Decode(tokenMint));\n const program = padTo32(base58Decode(programId));\n const [min, max] = sortPubkeys(a, b);\n const seeds = [new TextEncoder().encode('channel'), min, max, mint];\n const { pda, bump } = findProgramAddress(seeds, program);\n return { pda: base58Encode(pda), bump };\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 * Derive the vault PDA for a channel — connector-parity.\n * Seeds: `[b\"vault\", channel_pda]`.\n */\nexport function deriveVaultPDA(\n channelPDA: string,\n programId: string\n): { pda: string; bump: number } {\n const channel = padTo32(base58Decode(channelPDA));\n const program = padTo32(base58Decode(programId));\n const seeds = [new TextEncoder().encode('vault'), channel];\n const { pda, bump } = findProgramAddress(seeds, program);\n return { pda: base58Encode(pda), bump };\n}\n\n// ---------------------------------------------------------------------------\n// Balance-proof message + signing (connector-parity)\n// ---------------------------------------------------------------------------\n\n/**\n * The 16-byte domain tag every balance-proof message begins with (connector\n * ADR 0053, issue #1082). Byte-identical to `connector_signer::\n * SOLANA_BALANCE_PROOF_DOMAIN_TAG`, to `connector-settlement-solana`'s\n * `wire.rs::BALANCE_PROOF_DOMAIN_TAG`, and to the on-chain program's own\n * `processor.rs::BALANCE_PROOF_DOMAIN_TAG` — four copies of one constant, kept\n * in step by the committed `peer_carriage.claim_solana` wire vector, which all\n * four are checked against (see `src/wire/wire-vectors.test.ts`).\n */\nconst BALANCE_PROOF_DOMAIN_TAG = new TextEncoder().encode('TOON-BALPROOF-V2');\n\n/** The v2 balance-proof message length. Fixed — every field is fixed-size. */\nconst BALANCE_PROOF_MESSAGE_SIZE = 96;\n\n/**\n * Build the 96-byte balance-proof message a Solana claim's Ed25519 signature\n * covers:\n *\n * | bytes | field |\n * | -------- | -------------------------------------------------- |\n * | `0..16` | `\"TOON-BALPROOF-V2\"` |\n * | `16..48` | `programId` — the settlement program, raw 32 bytes |\n * | `48..80` | `channelAccount` (the channel PDA), raw 32 bytes |\n * | `80..88` | `nonce`, u64 little-endian |\n * | `88..96` | `transferredAmount`, u64 little-endian |\n *\n * ## Why it grew from 48 bytes to 96\n *\n * Before ADR 0053 this message was `channel_pda || nonce || amount` — 48 bytes\n * that bound **nothing about which deployment the channel lives on**. An EVM\n * claim has bound its chain id and its `TokenNetwork` since ADR 0024, through\n * the EIP-712 domain separator; the Solana side had no equivalent. So a\n * signature was valid for its channel account on **any** cluster where an\n * account of that address existed, and the only separation between deployments\n * came from their program ids happening to differ — a deployment accident\n * standing in for a cryptographic guarantee. Putting the program id in the\n * signed bytes closes that replay: a proof signed for one deployment cannot be\n * redeemed at another, because the other program rebuilds the message with its\n * own id and the signature no longer verifies.\n *\n * The cluster is deliberately NOT in here. A Solana program knows its own id\n * and nothing about which cluster it runs on, so it could never rebuild a\n * message containing one — a cluster string would be unverifiable on chain. A\n * claim's declared `cluster` therefore stays what it always was, a routing hint\n * the connector cross-checks off chain against its own `[settlement.solana]\n * rpc_url`, never a security boundary.\n *\n * ## Why a domain tag rather than an appended field\n *\n * An appended field is silently truncatable by a verifier that expects the old\n * length. Prefixing a tag means the first 48 bytes of a v2 message are not a\n * valid message under either scheme, so a verifier written against the old\n * layout rejects it outright instead of reading a prefix of it as complete —\n * and the deployed program refuses a 96-byte message's 48-byte ancestor on\n * length before it ever compares bytes (`processor.rs::verify_ed25519_precompile`).\n *\n * @param programId - base58 settlement program id. The claim's `programId`\n * field must name this same program: a claim naming another names a program\n * no channel of the payer's lives under.\n * @param channelPDA - base58 channel PDA — the claim's `channelAccount`.\n */\nexport function buildBalanceProofMessage(\n programId: string,\n channelPDA: string,\n nonce: bigint,\n transferredAmount: bigint\n): Uint8Array {\n const message = new Uint8Array(BALANCE_PROOF_MESSAGE_SIZE);\n message.set(BALANCE_PROOF_DOMAIN_TAG, 0);\n message.set(padTo32(base58Decode(programId)), 16);\n message.set(padTo32(base58Decode(channelPDA)), 48);\n writeU64LE(message, 80, nonce);\n writeU64LE(message, 88, transferredAmount);\n return message;\n}\n\n/**\n * Sign the 96-byte balance-proof message with a 32-byte Ed25519 seed — the raw\n * 64-byte signature a claim carries (base64) and the on-chain Ed25519\n * precompile verifies.\n */\nexport function signBalanceProofMessage(\n programId: string,\n channelPDA: string,\n nonce: bigint,\n transferredAmount: bigint,\n seed: Uint8Array\n): Uint8Array {\n const message = buildBalanceProofMessage(\n programId,\n channelPDA,\n nonce,\n transferredAmount\n );\n return ed25519.sign(message, seed);\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\nexport async function solanaRpc(\n rpcUrl: SolanaRpcTarget,\n method: string,\n params: unknown[] = []\n): Promise<unknown> {\n const { url, fetchImpl } = resolveRpcTarget(rpcUrl);\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(30000),\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/** Latest blockhash, base58 — what `patchSolanaRecentBlockhash` accepts as-is. */\nexport async function getLatestBlockhash(rpcUrl: SolanaRpcTarget): Promise<string> {\n const result = (await solanaRpc(rpcUrl, 'getLatestBlockhash', [\n { commitment: 'confirmed' },\n ])) as { value: { blockhash: string } };\n return result.value.blockhash;\n}\n\ninterface AccountInfo {\n data: [string, string];\n owner: string;\n lamports: number;\n}\n\nasync function getAccountInfo(\n rpcUrl: SolanaRpcTarget,\n pubkey: string\n): Promise<AccountInfo | null> {\n const result = (await solanaRpc(rpcUrl, 'getAccountInfo', [\n pubkey,\n { encoding: 'base64', commitment: 'confirmed' },\n ])) as { value: AccountInfo | null };\n return result.value;\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/** Base fee per signature (lamports). Each of our txs carries exactly one. */\nconst LAMPORTS_PER_SIGNATURE = 5_000n;\n\n/**\n * Native SOL (lamports) a FRESH channel open must be able to SPEND, computed\n * rather than guessed:\n *\n * rent-exempt(178-byte channel account) = (128 + 178) × 6960 = 2_129_760\n * rent-exempt(165-byte SPL vault) = (128 + 165) × 6960 = 2_039_280\n * 2 signatures (initialize_channel, deposit) × 5_000 = 10_000\n * ──────────\n * 4_179_040\n *\n * (6960 lamports/byte-year × 2 years is Solana's rent-exemption rate, and 128\n * bytes is the fixed per-account overhead.) The devnet open behind\n * connector#646 spent ≈0.0042 SOL end to end, which matches.\n *\n * This bounds the SPEND, which is not quite the chain's whole requirement:\n * Solana additionally rejects a transaction that leaves the fee payer\n * rent-paying rather than rent-exempt (`RentState::transition_allowed`), so a\n * payer must really end at either 0 or ≥ the 890_880-lamport minimum. A payer\n * holding somewhere in [4_179_040, 5_069_920) therefore passes this preflight\n * and is still rejected on-chain with `InsufficientFundsForRent`.\n *\n * That window is left deliberately un-padded. Adding 890_880 here would reject\n * the payer who spends down to exactly 0 — which the chain permits — and this\n * preflight exists to REPLACE opaque failures with actionable ones, not to\n * invent refusals of its own. A payer inside the window still gets the chain's\n * error, exactly as it did before this preflight existed; everyone below the\n * floor gets a message naming the wallet and the shortfall.\n */\nexport const MIN_LAMPORTS_FOR_CHANNEL_OPEN = 4_179_040n;\n\n/**\n * Native SOL (lamports) a standalone top-up of an EXISTING channel must be able\n * to spend: one signature, no rent — both accounts already exist and are\n * already rent-exempt. The same rent-state caveat as\n * {@link MIN_LAMPORTS_FOR_CHANNEL_OPEN} applies, over [5_000, 895_880).\n */\nexport const MIN_LAMPORTS_FOR_DEPOSIT = LAMPORTS_PER_SIGNATURE;\n\n/**\n * Fail an on-chain open BEFORE spending anything when the payer cannot fund it.\n *\n * Two distinct assets are required and neither implies the other: native SOL\n * pays the rent for the channel + vault accounts and the signature fees, while\n * the SPL settlement token is what the `deposit` instruction moves into the\n * vault. A wallet holding USDC but no SOL fails partway through the open; a\n * wallet holding SOL but no USDC aborts the deposit AFTER `initialize_channel`\n * has already created a (rent-paying, 0-collateral) channel — exactly the state\n * connector#646 observed. Reading both up front turns either case into an\n * actionable {@link ChannelFundingError}.\n */\nasync function assertOpenFunding(opts: {\n rpcUrl: SolanaRpcTarget;\n payerPubkey: string;\n tokenMint: string;\n /** Lamport floor for the transactions about to be sent. */\n minLamports: bigint;\n deposit?: { amount: bigint; payerTokenAccount: string };\n}): Promise<void> {\n const { rpcUrl, payerPubkey, tokenMint, minLamports, deposit } = opts;\n\n const lamports = await getLamports(rpcUrl, payerPubkey);\n if (lamports < minLamports) {\n throw new ChannelFundingError(\n `Solana settlement wallet ${payerPubkey} holds ${lamports} lamports, below the ` +\n `${minLamports} needed here (rent for the channel + vault accounts, plus ` +\n `signature fees). Native SOL is separate from the settlement token: holding ` +\n `the SPL token is not enough. Airdrop/fund SOL to that address and retry.`\n );\n }\n\n if (!deposit || deposit.amount <= 0n) return;\n\n const held = await getTokenAccountBalance(rpcUrl, deposit.payerTokenAccount);\n if (held === null) {\n throw new ChannelFundingError(\n `Solana token account ${deposit.payerTokenAccount} does not exist, so the ` +\n `${deposit.amount} base-unit channel deposit of mint ${tokenMint} cannot ` +\n `be funded. Fund the settlement wallet with that token (which creates the ` +\n `associated token account) and retry.`\n );\n }\n if (held < deposit.amount) {\n throw new ChannelFundingError(\n `Solana token account ${deposit.payerTokenAccount} holds ${held} base units ` +\n `of mint ${tokenMint}, short of the ${deposit.amount} base-unit channel ` +\n `deposit. Fund the settlement wallet, or lower the deposit ` +\n `(\\`solanaChannel.deposit.amount\\` / \\`initialDeposit\\`), and retry.`\n );\n }\n}\n\n/**\n * Poll until the transaction is `confirmed`/`finalized`, THROWING if it landed\n * with an execution error. A settled-but-failed transaction is not a success.\n */\nexport async function waitForConfirmation(\n rpcUrl: SolanaRpcTarget,\n signature: string,\n timeoutMs = 30000\n): Promise<void> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n const result = (await solanaRpc(rpcUrl, 'getSignatureStatuses', [\n [signature],\n ])) as {\n value: ({ confirmationStatus: string; err?: unknown } | null)[];\n };\n const status = result.value[0];\n if (\n status?.confirmationStatus === 'confirmed' ||\n status?.confirmationStatus === 'finalized'\n ) {\n if (status.err) {\n throw new Error(\n `Transaction ${signature} failed: ${JSON.stringify(status.err)}`\n );\n }\n return;\n }\n await new Promise((r) => setTimeout(r, 500));\n }\n throw new Error(\n `Transaction ${signature} not confirmed within ${timeoutMs}ms`\n );\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 * 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): Promise<string> {\n const blockhash = await getLatestBlockhash(rpcUrl);\n const feePayerPubkey = base58Encode(feePayer.publicKey);\n\n const accountMap = new Map<string, AccountEntry>();\n accountMap.set(feePayerPubkey, {\n pubkey: feePayerPubkey,\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 === feePayerPubkey) return -1;\n if (b.pubkey === feePayerPubkey) 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(blockhash);\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 const finalMessage = message.slice(0, offset);\n\n const allSigners = [feePayer, ...additionalSigners];\n const signerPubkeys = accounts.filter((a) => a.isSigner).map((a) => a.pubkey);\n const signatures: Uint8Array[] = [];\n for (const signerPubkey of signerPubkeys) {\n const signer = allSigners.find(\n (s) => base58Encode(s.publicKey) === signerPubkey\n );\n if (!signer) throw new Error(`Missing signer for ${signerPubkey}`);\n signatures.push(ed25519.sign(finalMessage, signer.privateKey));\n }\n\n const txSize =\n compactU16Size(signatures.length) +\n signatures.length * 64 +\n finalMessage.length;\n const tx = new Uint8Array(txSize);\n let txOffset = 0;\n txOffset = writeCompactU16(tx, txOffset, signatures.length);\n for (const sig of signatures) {\n tx.set(sig, txOffset);\n txOffset += 64;\n }\n tx.set(finalMessage, txOffset);\n\n const txBase64 = Buffer.from(tx).toString('base64');\n const txSig = (await solanaRpc(rpcUrl, 'sendTransaction', [\n txBase64,\n {\n encoding: 'base64',\n skipPreflight: false,\n preflightCommitment: 'confirmed',\n },\n ])) as string;\n await waitForConfirmation(rpcUrl, txSig);\n return txSig;\n}\n\n/**\n * The 178-byte `ChannelState` account, decoded in full.\n *\n * Field offsets are `packages/solana-program/src/state.rs`'s own constants:\n * `[0..8]` discriminator, `[8..40]` participant_a, `[40..72]` participant_b,\n * `[72..104]` token_mint, `[104..112]` deposit_a, `[112..120]` deposit_b,\n * `[120..128]` transferred_amount_a, `[128..136]` transferred_amount_b,\n * `[136..144]` nonce_a, `[144..152]` nonce_b, `[152..160]` challenge_duration,\n * `[160]` state, `[161..169]` close_timestamp (**i64**, signed), `[169]` bump,\n * `[170..178]` reserved padding.\n *\n * Participants are stored SORTED — the program writes `min(a, b)` into\n * `participant_a` regardless of the order `initialize_channel` was handed them\n * (`processor.rs::sort_participants`) — so which of the two is \"us\" is a\n * lexicographic fact about the keys, never about who opened the channel.\n */\nexport interface SolanaChannelAccountState {\n exists: boolean;\n /** 'opened' | 'closed' | 'settled' when the account exists with valid data. */\n state?: 'opened' | 'closed' | 'settled';\n participantA?: string;\n participantB?: string;\n /** The SPL mint this channel settles in — what the vault holds. */\n tokenMint?: string;\n /**\n * PER-PARTICIPANT collateral (base units), as the program tracks it.\n *\n * These are what bound redeemability, NOT the vault's token balance: the\n * vault holds `deposit_a + deposit_b`, but `Claim` rejects a claim whose\n * `transferred_amount` exceeds the CLAIMER'S OWN deposit\n * (`TransferredAmountExceedsDeposit`). A peer-funded vault can therefore look\n * amply funded while this client's own collateral is still 0.\n */\n depositA?: bigint;\n depositB?: bigint;\n /**\n * The highest cumulative amount each participant's redeemed claims have\n * moved. Settlement pays `deposit_x - transferred_x + transferred_y`, so\n * these are the figures a close/settle actually divides on.\n */\n transferredAmountA?: bigint;\n transferredAmountB?: bigint;\n /**\n * The on-chain nonce watermark per participant. `ClaimFromChannel` demands\n * `nonce > stored`, so a claim at or below either of these is already spent —\n * this is the authoritative answer to \"what nonce must I sign next\", and the\n * reason a replayed nonce cannot be redeemed twice.\n */\n nonceA?: bigint;\n nonceB?: bigint;\n /** Seconds after `closeTimestamp` before `settle` is permitted. */\n challengeDuration?: bigint;\n /**\n * Unix seconds the channel was closed, `0` while it is open. **Signed** on\n * chain (`i64`), so it is decoded as such rather than as a u64 that would\n * read a negative clock as ~1.8e19.\n */\n closeTimestamp?: bigint;\n /** The PDA bump seed the program stored when it derived this account. */\n bump?: number;\n}\n\nconst STATE_MAP = ['opened', 'closed', 'settled'] as const;\n\n/** Read a little-endian u64 at `offset`. */\nfunction readU64LE(data: Uint8Array, offset: number): bigint {\n let value = 0n;\n for (let i = 7; i >= 0; i--) {\n value = (value << 8n) | BigInt(data[offset + i] ?? 0);\n }\n return value;\n}\n\n/**\n * Read a little-endian **i64** at `offset` — two's complement, so a negative\n * on-chain `close_timestamp` decodes as negative rather than as an enormous\n * positive. `settleableAt` arithmetic is only sound if this sign survives.\n */\nfunction readI64LE(data: Uint8Array, offset: number): bigint {\n const unsigned = readU64LE(data, offset);\n return unsigned >= 1n << 63n ? unsigned - (1n << 64n) : unsigned;\n}\n\n/** Decode a 178-byte `ChannelState` account's raw bytes. */\nexport function decodeChannelAccount(\n data: Uint8Array\n): SolanaChannelAccountState {\n if (data.length < CHANNEL_ACCOUNT_SIZE) return { exists: false };\n for (let i = 0; i < 8; i++) {\n if (data[i] !== CHANNEL_DISCRIMINATOR[i]) return { exists: false };\n }\n return {\n exists: true,\n state: STATE_MAP[data[160] ?? 0] ?? 'opened',\n participantA: base58Encode(data.slice(8, 40)),\n participantB: base58Encode(data.slice(40, 72)),\n tokenMint: base58Encode(data.slice(72, 104)),\n depositA: readU64LE(data, 104),\n depositB: readU64LE(data, 112),\n transferredAmountA: readU64LE(data, 120),\n transferredAmountB: readU64LE(data, 128),\n nonceA: readU64LE(data, 136),\n nonceB: readU64LE(data, 144),\n challengeDuration: readU64LE(data, 152),\n closeTimestamp: readI64LE(data, 161),\n bump: data[169] ?? 0,\n };\n}\n\n/**\n * Fetch + decode the on-chain channel account at a PDA.\n *\n * A SETTLED channel is indistinguishable from one that never existed: the\n * program zeroes the account's data and lamports on settle\n * (`processor.rs::process_settlement`), so this reports `{ exists: false }` for\n * it. Callers that must tell the two apart keep their own record of what they\n * settled.\n */\nexport async function getChannelAccountState(\n rpcUrl: SolanaRpcTarget,\n channelPDA: string\n): Promise<SolanaChannelAccountState> {\n const info = await getAccountInfo(rpcUrl, channelPDA);\n if (!info) return { exists: false };\n return decodeChannelAccount(new Uint8Array(Buffer.from(info.data[0], 'base64')));\n}\n\n/**\n * The earliest unix second `settle` will succeed on a CLOSED channel:\n * `close_timestamp + challenge_duration`, the deadline\n * `processor.rs::process_settlement` compares `Clock::unix_timestamp` against.\n *\n * `undefined` for a channel that is not closed — an open channel has no\n * settlement deadline, and reporting one derived from a zero\n * `close_timestamp` would claim it is settleable now, which it is not.\n */\nexport function settleableAt(\n account: SolanaChannelAccountState\n): bigint | undefined {\n if (account.state !== 'closed') return undefined;\n return (account.closeTimestamp ?? 0n) + (account.challengeDuration ?? 0n);\n}\n\n/**\n * This payer's OWN recorded collateral on an existing channel — the quantity\n * that bounds what its claims can redeem.\n *\n * @throws when the payer is neither participant. Unreachable via the normal\n * path (the channel PDA is derived from `[b\"channel\", min(payer,peer),\n * max(payer,peer), mint]`, so membership is structural), which is exactly why\n * a mismatch must be surfaced rather than silently skipped: it means the\n * account we parsed is not the channel we think it is.\n */\nfunction ownDeposit(\n account: SolanaChannelAccountState,\n payerPubkey: string\n): bigint {\n if (account.participantA === payerPubkey) return account.depositA ?? 0n;\n if (account.participantB === payerPubkey) return account.depositB ?? 0n;\n throw new Error(\n `Solana channel participants (${account.participantA}, ${account.participantB}) ` +\n `do not include the payer ${payerPubkey} — refusing to reason about its collateral.`\n );\n}\n\nexport interface OpenSolanaChannelParams {\n rpcUrl: SolanaRpcTarget;\n programId: string;\n tokenMint: string;\n /** Client's 32-byte Ed25519 seed (participant A + fee payer). */\n payerSeed: Uint8Array;\n /** Client's base58 pubkey (participant A). */\n payerPubkey: string;\n /** Apex's base58 settlement pubkey (participant B). */\n peerPubkey: string;\n /** Challenge-period duration in seconds. */\n challengeDuration: bigint;\n /** Optional deposit amount + funded SPL token account (ATA) of the payer. */\n deposit?: { amount: bigint; payerTokenAccount: string };\n}\n\nexport interface OpenSolanaChannelResult {\n channelPDA: string;\n /** True if a fresh on-chain initialize_channel tx was submitted. */\n opened: boolean;\n initTxSignature?: string;\n depositTxSignature?: string;\n /**\n * Collateral in the channel vault (base units) after this call. Present\n * whenever it was established here — read from chain on the existing-channel\n * path, known by construction on the fresh-open path. REPORTING only: nothing\n * gates spending on it (the Solana balance-proof signer never reads it), it\n * exists so callers can show and log real collateral instead of 0.\n */\n depositTotal?: bigint;\n}\n\n/**\n * Bring an ALREADY-OPEN channel up to the target collateral, depositing only\n * the shortfall. A no-op when no deposit is requested or when the payer's own\n * collateral already meets the target.\n *\n * Measures the PAYER'S OWN `deposit_a`/`deposit_b`, never the vault's token\n * balance. The vault holds BOTH participants' collateral, but `Claim` bounds a\n * claim by the claimer's own deposit alone — so a vault funded by the peer can\n * read at or above target while this client's collateral is still 0, and\n * comparing against it would no-op in exactly the case a top-up is needed. The\n * figure is read from the channel account already fetched for the idempotency\n * check, so this costs no extra RPC.\n *\n * This is what makes the fix reach channels that already exist: the connector#646\n * devnet channel is open with 0 collateral, and a client that merely skipped it\n * would go on signing claims that cannot be redeemed.\n */\nasync function topUpExistingChannel(opts: {\n rpcUrl: SolanaRpcTarget;\n programId: string;\n tokenMint: string;\n channelPDA: string;\n payerSeed: Uint8Array;\n payerPubkey: string;\n /** The channel account already read for the idempotency check. */\n existing: SolanaChannelAccountState;\n deposit?: { amount: bigint; payerTokenAccount: string };\n}): Promise<{ depositTxSignature?: string; depositTotal?: bigint }> {\n const {\n rpcUrl,\n programId,\n tokenMint,\n channelPDA,\n payerPubkey,\n existing,\n deposit,\n } = opts;\n if (!deposit || deposit.amount <= 0n) return {};\n\n const own = ownDeposit(existing, payerPubkey);\n if (own >= deposit.amount) return { depositTotal: own };\n\n const shortfall = deposit.amount - own;\n // No rent here — both accounts already exist — so only the signature fee.\n await assertOpenFunding({\n rpcUrl,\n payerPubkey,\n tokenMint,\n minLamports: MIN_LAMPORTS_FOR_DEPOSIT,\n deposit: {\n amount: shortfall,\n payerTokenAccount: deposit.payerTokenAccount,\n },\n });\n\n const { depositTxSignature } = await depositSolanaChannel({\n rpcUrl,\n programId,\n channelPDA,\n payerSeed: opts.payerSeed,\n payerPubkey,\n payerTokenAccount: deposit.payerTokenAccount,\n amount: shortfall,\n });\n return { depositTxSignature, depositTotal: own + shortfall };\n}\n\n/**\n * Open (initialize) and collateralize a real on-chain Solana payment channel at\n * the connector-parity PDA. Idempotent in the only sense that matters: an\n * existing channel is never re-initialized, but its vault IS topped up to the\n * requested collateral, so the outcome — \"an open channel holding `deposit`\" —\n * is the same whether or not the channel existed beforehand.\n *\n * The Ed25519 keypair derives both the participant-A identity and the fee\n * payer; the apex pubkey is participant B. The returned `channelPDA` (base58) is\n * the value carried in the claim's `channelAccount`.\n */\nexport async function openSolanaChannel(\n params: OpenSolanaChannelParams\n): Promise<OpenSolanaChannelResult> {\n const {\n rpcUrl,\n programId,\n tokenMint,\n payerSeed,\n payerPubkey,\n peerPubkey,\n challengeDuration,\n } = params;\n\n const { pda: channelPDA } = deriveChannelPDA(\n payerPubkey,\n peerPubkey,\n tokenMint,\n programId\n );\n\n // Idempotent: skip initialize if the channel account already exists — but do\n // NOT skip the collateral. A channel opened before connector#646 was fixed\n // exists on-chain with a 0-balance vault, and returning here would let the\n // client keep signing uncollateralized claims against it forever, which is\n // the very defect this path is meant to close. Top it up to the target\n // instead; already-collateralized channels are a no-op.\n const existing = await getChannelAccountState(rpcUrl, channelPDA);\n if (existing.exists) {\n // …but ONLY an `Opened` channel can take a deposit: the program rejects\n // `Deposit` on a closed/settled channel (`ChannelNotOpened`). Resuming a\n // channel this client has CLOSED is a supported, persisted state (the\n // withdraw flow), so returning it unchanged is the correct answer — firing\n // a doomed deposit would turn that flow into an opaque `custom program\n // error`. Collateral is a question for a channel that can still spend.\n if (existing.state !== 'opened') {\n return { channelPDA, opened: false };\n }\n const topUp = await topUpExistingChannel({\n rpcUrl,\n programId,\n tokenMint,\n channelPDA,\n payerSeed,\n payerPubkey,\n existing,\n deposit: params.deposit,\n });\n return { channelPDA, opened: false, ...topUp };\n }\n\n // Only a FRESH open pays rent, so the full rent+fee floor is required here.\n await assertOpenFunding({\n rpcUrl,\n payerPubkey,\n tokenMint,\n minLamports: MIN_LAMPORTS_FOR_CHANNEL_OPEN,\n deposit: params.deposit,\n });\n\n const payerPublicKey = padTo32(base58Decode(payerPubkey));\n const payer: Signer = { publicKey: payerPublicKey, privateKey: payerSeed };\n\n const { pda: vaultPDA } = deriveVaultPDA(channelPDA, programId);\n\n // initialize_channel: discriminator(8) + challenge_duration(8 LE)\n const initData = new Uint8Array(16);\n initData.set(IX_INITIALIZE_CHANNEL, 0);\n writeU64LE(initData, 8, challengeDuration);\n\n const initTxSignature = await buildAndSendTransaction(rpcUrl, payer, [\n {\n programId,\n keys: [\n { pubkey: payerPubkey, isSigner: true, isWritable: true },\n { pubkey: payerPubkey, isSigner: false, isWritable: false }, // participant A\n { pubkey: peerPubkey, isSigner: false, isWritable: false }, // participant B\n { pubkey: tokenMint, isSigner: false, isWritable: false },\n { pubkey: channelPDA, isSigner: false, isWritable: true },\n { pubkey: vaultPDA, isSigner: false, isWritable: true },\n { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: RENT_SYSVAR_ID, isSigner: false, isWritable: false },\n ],\n data: initData,\n },\n ]);\n\n let depositTxSignature: string | undefined;\n if (params.deposit && params.deposit.amount > 0n) {\n ({ depositTxSignature } = await depositSolanaChannel({\n rpcUrl,\n programId,\n channelPDA,\n payerSeed,\n payerPubkey,\n payerTokenAccount: params.deposit.payerTokenAccount,\n amount: params.deposit.amount,\n }));\n }\n\n return {\n channelPDA,\n opened: true,\n initTxSignature,\n depositTxSignature,\n ...(depositTxSignature ? { depositTotal: params.deposit?.amount } : {}),\n };\n}\n\nexport interface DepositSolanaChannelParams {\n rpcUrl: SolanaRpcTarget;\n programId: string;\n /** The channel PDA (base58) — the Solana channel id. */\n channelPDA: string;\n /** Ed25519 signing seed (32 bytes) of the payer. */\n payerSeed: Uint8Array;\n /** Payer public key (base58). */\n payerPubkey: string;\n /** Funded SPL token account (ATA, base58) the collateral is pulled from. */\n payerTokenAccount: string;\n /** Delta to deposit (base units). The on-chain `deposit` ix adds this amount. */\n amount: bigint;\n}\n\n/**\n * Deposit additional collateral into an existing on-chain Solana channel — the\n * standalone `deposit` instruction (discriminator + amount LE), the same one the\n * open flow fires post-init. Incremental: the program adds `amount` to the\n * channel vault. Returns the deposit tx signature.\n */\nexport async function depositSolanaChannel(\n params: DepositSolanaChannelParams\n): Promise<{ depositTxSignature: string }> {\n const {\n rpcUrl,\n programId,\n channelPDA,\n payerSeed,\n payerPubkey,\n payerTokenAccount,\n amount,\n } = params;\n if (amount <= 0n) throw new Error('Solana deposit amount must be positive.');\n\n const payer: Signer = {\n publicKey: padTo32(base58Decode(payerPubkey)),\n privateKey: payerSeed,\n };\n const { pda: vaultPDA } = deriveVaultPDA(channelPDA, programId);\n\n // deposit: discriminator(8) + amount(8 LE)\n const depositData = new Uint8Array(16);\n depositData.set(IX_DEPOSIT, 0);\n writeU64LE(depositData, 8, amount);\n\n const depositTxSignature = await buildAndSendTransaction(rpcUrl, payer, [\n {\n programId,\n keys: [\n { pubkey: payerPubkey, isSigner: true, isWritable: false },\n { pubkey: payerTokenAccount, isSigner: false, isWritable: true },\n { pubkey: vaultPDA, isSigner: false, isWritable: true },\n { pubkey: channelPDA, isSigner: false, isWritable: true },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n ],\n data: depositData,\n },\n ]);\n return { depositTxSignature };\n}\n\n// ---------------------------------------------------------------------------\n// close (03) / settle (04) / force-close-expired (05)\n// ---------------------------------------------------------------------------\n\nexport interface CloseSolanaChannelParams {\n rpcUrl: SolanaRpcTarget;\n programId: string;\n /** The channel PDA (base58) — the Solana channel id. */\n channelPDA: string;\n /** Ed25519 signing seed (32 bytes) of the closer. */\n closerSeed: Uint8Array;\n /** Closer's base58 pubkey. MUST be one of the channel's two participants. */\n closerPubkey: string;\n}\n\n/**\n * Close a channel — instruction `03`, which stamps `close_timestamp` from the\n * Clock sysvar and moves the state to `Closed`, starting the challenge period.\n *\n * Accounts, in the order `processor.rs::process_close_channel` reads them with\n * `next_account_info`:\n *\n * 0. `[signer]` closer — must be `participant_a` or `participant_b`\n * 1. `[writable]` channel PDA\n * 2. `[]` Clock sysvar\n *\n * The clock sysvar is passed but not read by key: the program takes the time\n * from `Clock::get()`. It is still required, because the account list is\n * positional — omitting it makes `next_account_info` fail rather than default.\n *\n * A closed channel can still be claimed against (`ClaimFromChannel` accepts\n * `Opened` and `Closed`), which is the point of the challenge period: a\n * counterparty holding a newer balance proof has `challenge_duration` seconds\n * to redeem it before {@link settleSolanaChannel} pays out on the state as it\n * then stands.\n */\nexport async function closeSolanaChannel(\n params: CloseSolanaChannelParams\n): Promise<{ closeTxSignature: string }> {\n const { rpcUrl, programId, channelPDA, closerSeed, closerPubkey } = params;\n const closer: Signer = {\n publicKey: padTo32(base58Decode(closerPubkey)),\n privateKey: closerSeed,\n };\n\n const closeTxSignature = await buildAndSendTransaction(rpcUrl, closer, [\n {\n programId,\n keys: [\n { pubkey: closerPubkey, isSigner: true, isWritable: false },\n { pubkey: channelPDA, isSigner: false, isWritable: true },\n { pubkey: CLOCK_SYSVAR_ID, isSigner: false, isWritable: false },\n ],\n data: IX_CLOSE_CHANNEL.slice(),\n },\n ]);\n return { closeTxSignature };\n}\n\nexport interface SettleSolanaChannelParams {\n rpcUrl: SolanaRpcTarget;\n programId: string;\n channelPDA: string;\n /** Ed25519 signing seed (32 bytes) of whoever pays for the settle tx. */\n callerSeed: Uint8Array;\n /** Caller's base58 pubkey. Need NOT be a participant — see below. */\n callerPubkey: string;\n /** SPL token account owned by `participant_a`, holding the channel's mint. */\n participantATokenAccount: string;\n /** SPL token account owned by `participant_b`, holding the channel's mint. */\n participantBTokenAccount: string;\n /**\n * Where the vault's and channel account's reclaimed rent lamports land.\n * Defaults to the caller — the party that is about to pay the tx fee.\n */\n rentRecipient?: string;\n /**\n * Send instruction `05` force-close-expired instead of `04` settle. The\n * program routes BOTH to the same `process_settlement`, so this changes only\n * the discriminator; it is offered because the two names mean different\n * things to an operator reading a transaction log, not because the chain\n * behaves differently.\n */\n force?: boolean;\n}\n\n/**\n * Settle a CLOSED channel whose challenge period has elapsed — instruction\n * `04` (or `05`, see `force`).\n *\n * Accounts, in `processor.rs::process_settlement`'s `next_account_info` order:\n *\n * 0. `[signer]` caller\n * 1. `[writable]` channel PDA\n * 2. `[writable]` vault token account\n * 3. `[writable]` participant_a's token account\n * 4. `[writable]` participant_b's token account\n * 5. `[writable]` rent recipient\n * 6. `[]` SPL Token program\n * 7. `[]` Clock sysvar\n *\n * The caller is deliberately unconstrained — **any** signer may settle once the\n * challenge period is over. That is a safety property, not an oversight: it\n * stops a counterparty stranding the vault by simply refusing to act, and it is\n * safe because the payout destinations are pinned. The program checks each\n * destination it actually pays into is an initialized SPL Token account holding\n * the channel's mint and owned by that leg's participant, so a caller cannot\n * redirect either payout.\n *\n * Payouts are `deposit_x - transferred_x + transferred_y` per side; a\n * participant owed nothing need not have a token account in existence at all,\n * but the account list is positional, so an address must still be supplied for\n * both slots.\n */\nexport async function settleSolanaChannel(\n params: SettleSolanaChannelParams\n): Promise<{ settleTxSignature: string }> {\n const {\n rpcUrl,\n programId,\n channelPDA,\n callerSeed,\n callerPubkey,\n participantATokenAccount,\n participantBTokenAccount,\n } = params;\n const rentRecipient = params.rentRecipient ?? callerPubkey;\n const caller: Signer = {\n publicKey: padTo32(base58Decode(callerPubkey)),\n privateKey: callerSeed,\n };\n const { pda: vaultPDA } = deriveVaultPDA(channelPDA, programId);\n\n const settleTxSignature = await buildAndSendTransaction(rpcUrl, caller, [\n {\n programId,\n keys: [\n { pubkey: callerPubkey, isSigner: true, isWritable: false },\n { pubkey: channelPDA, isSigner: false, isWritable: true },\n { pubkey: vaultPDA, isSigner: false, isWritable: true },\n {\n pubkey: participantATokenAccount,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: participantBTokenAccount,\n isSigner: false,\n isWritable: true,\n },\n { pubkey: rentRecipient, isSigner: false, isWritable: true },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: CLOCK_SYSVAR_ID, isSigner: false, isWritable: false },\n ],\n data: (params.force\n ? IX_FORCE_CLOSE_EXPIRED\n : IX_SETTLE_CHANNEL\n ).slice(),\n },\n ]);\n return { settleTxSignature };\n}\n\n// ---------------------------------------------------------------------------\n// claim-from-channel (06) + the Ed25519 precompile instruction it requires\n// ---------------------------------------------------------------------------\n\n/** `solana_sdk::ed25519_instruction`'s fixed-layout constants. */\nconst ED25519_PUBKEY_SIZE = 32;\nconst ED25519_SIGNATURE_SIZE = 64;\nconst ED25519_OFFSETS_SIZE = 14;\nconst ED25519_OFFSETS_START = 2;\nconst ED25519_DATA_START = ED25519_OFFSETS_SIZE + ED25519_OFFSETS_START;\n/** `u16::MAX` — \"this offset points inside THIS instruction's own data\". */\nconst ED25519_THIS_INSTRUCTION = 0xffff;\n\n/**\n * Build the Ed25519-precompile instruction the program requires at index **0**\n * of a `ClaimFromChannel` transaction.\n *\n * This mirrors `solana_sdk::ed25519_instruction::new_ed25519_instruction`'s\n * data layout byte-for-byte — as the connector's own\n * `wire.rs::ed25519_verify_instruction` does, and for the same reason: that\n * helper takes a keypair and signs the message itself, but a redeemer holds\n * only the counterparty's ALREADY-PRODUCED signature, never its signing key.\n *\n * ```text\n * 0 num_signatures = 1\n * 1 padding, unread\n * 2..4 signature_offset u16 LE = 48\n * 4..6 signature_instruction_index u16 LE = 0xFFFF\n * 6..8 public_key_offset u16 LE = 16\n * 8..10 public_key_instruction_index = 0xFFFF\n * 10..12 message_data_offset u16 LE = 112\n * 12..14 message_data_size u16 LE = message.length\n * 14..16 message_instruction_index = 0xFFFF\n * 16..48 public key\n * 48..112 signature\n * 112.. message\n * ```\n *\n * All three `*_instruction_index` fields are `0xFFFF` on purpose. The program\n * REFUSES any other value (`processor.rs::verify_ed25519_precompile`): letting\n * an offset point into a different instruction of the same transaction would\n * let a redeemer have the precompile verify one blob while the program reads\n * another as the message.\n *\n * @throws {RangeError} `signature` is not 64 bytes — a short signature would\n * silently shift the message offset and verify a different span of bytes.\n */\nexport function buildEd25519VerifyInstruction(\n signerPubkey: string,\n signature: Uint8Array,\n message: Uint8Array\n): RawInstruction {\n if (signature.length !== ED25519_SIGNATURE_SIZE) {\n throw new RangeError(\n `Ed25519 signature must be exactly ${ED25519_SIGNATURE_SIZE} bytes, got ${signature.length}`\n );\n }\n const publicKeyOffset = ED25519_DATA_START;\n const signatureOffset = publicKeyOffset + ED25519_PUBKEY_SIZE;\n const messageOffset = signatureOffset + ED25519_SIGNATURE_SIZE;\n\n const data = new Uint8Array(messageOffset + message.length);\n const view = new DataView(data.buffer);\n data[0] = 1; // num_signatures\n data[1] = 0; // padding\n view.setUint16(2, signatureOffset, true);\n view.setUint16(4, ED25519_THIS_INSTRUCTION, true);\n view.setUint16(6, publicKeyOffset, true);\n view.setUint16(8, ED25519_THIS_INSTRUCTION, true);\n view.setUint16(10, messageOffset, true);\n view.setUint16(12, message.length, true);\n view.setUint16(14, ED25519_THIS_INSTRUCTION, true);\n data.set(padTo32(base58Decode(signerPubkey)), publicKeyOffset);\n data.set(signature, signatureOffset);\n data.set(message, messageOffset);\n\n return { programId: ED25519_PROGRAM_ID, keys: [], data };\n}\n\nexport interface ClaimFromSolanaChannelParams {\n programId: string;\n channelPDA: string;\n /**\n * The participant being credited — whose Ed25519 key signed the balance\n * proof. NOT a transaction signer: its authorization IS the signature the\n * precompile checks.\n */\n claimerPubkey: string;\n /** Whoever signs and pays for the transaction. May be anyone. */\n feePayerPubkey: string;\n nonce: bigint;\n transferredAmount: bigint;\n /** The claimer's 64-byte signature over the 96-byte v2 message. */\n signature: Uint8Array;\n}\n\n/**\n * The two instructions that redeem a balance proof on chain, **in the order\n * they must appear in the transaction**: the Ed25519 precompile first (the\n * program loads instruction index 0 and refuses anything else there), then\n * `ClaimFromChannel` itself.\n *\n * `ClaimFromChannel` accounts, in `processor.rs::process_claim_from_channel`'s\n * `next_account_info` order:\n *\n * 0. `[signer]` fee payer — the submitter\n * 1. `[]` claimer — credited participant, NOT a tx signer\n * 2. `[writable]` channel PDA\n * 3. `[]` Instructions sysvar\n *\n * Data: `06 00 00 00 00 00 00 00 || nonce u64 LE || transferredAmount u64 LE`.\n *\n * Separating the fee payer from the claimer is what lets a connector redeem an\n * inbound peer's proof unilaterally: the peer authorized this exact\n * `(nonce, transferredAmount)` by signing the balance proof, so it never has to\n * co-sign the redemption. The program independently rebuilds the 96-byte\n * message from ITS OWN program id, the channel PDA it was handed and the\n * `(nonce, amount)` in this instruction's data, and requires the precompile's\n * message to equal it byte-for-byte — so the numbers in the data cannot differ\n * from the numbers that were signed.\n */\nexport function buildClaimFromChannelInstructions(\n params: ClaimFromSolanaChannelParams\n): RawInstruction[] {\n const {\n programId,\n channelPDA,\n claimerPubkey,\n feePayerPubkey,\n nonce,\n transferredAmount,\n signature,\n } = params;\n\n const message = buildBalanceProofMessage(\n programId,\n channelPDA,\n nonce,\n transferredAmount\n );\n\n // 06 discriminator(8) + nonce(8 LE) + transferred_amount(8 LE)\n const data = new Uint8Array(24);\n data.set(IX_CLAIM_FROM_CHANNEL, 0);\n writeU64LE(data, 8, nonce);\n writeU64LE(data, 16, transferredAmount);\n\n return [\n buildEd25519VerifyInstruction(claimerPubkey, signature, message),\n {\n programId,\n keys: [\n { pubkey: feePayerPubkey, isSigner: true, isWritable: false },\n { pubkey: claimerPubkey, isSigner: false, isWritable: false },\n { pubkey: channelPDA, isSigner: false, isWritable: true },\n { pubkey: INSTRUCTIONS_SYSVAR_ID, isSigner: false, isWritable: false },\n ],\n data,\n },\n ];\n}\n\n/**\n * Submit a balance proof for redemption — {@link buildClaimFromChannelInstructions}\n * sent as one transaction, paid for by `feePayerSeed`.\n *\n * On success the channel's `nonce_x` and `transferred_amount_x` for the CLAIMER\n * have advanced to the redeemed values; a nonce at or below the stored\n * watermark is refused by the program (`NonceNotMonotonic`), which is what\n * makes a captured claim unreplayable on chain.\n */\nexport async function claimFromSolanaChannel(\n params: ClaimFromSolanaChannelParams & {\n rpcUrl: SolanaRpcTarget;\n /** Ed25519 seed of `feePayerPubkey`. */\n feePayerSeed: Uint8Array;\n }\n): Promise<{ claimTxSignature: string }> {\n const feePayer: Signer = {\n publicKey: padTo32(base58Decode(params.feePayerPubkey)),\n privateKey: params.feePayerSeed,\n };\n const claimTxSignature = await buildAndSendTransaction(\n params.rpcUrl,\n feePayer,\n buildClaimFromChannelInstructions(params)\n );\n return { claimTxSignature };\n}\n\n// Internal helpers exported for unit tests (parity assertions).\nexport const __testing = {\n padTo32,\n sortPubkeys,\n isOnCurve,\n readI64LE,\n CLOCK_SYSVAR_ID,\n INSTRUCTIONS_SYSVAR_ID,\n ED25519_PROGRAM_ID,\n TOKEN_PROGRAM_ID,\n};\n","/**\n * The Solana half of the channel lifecycle, as one object.\n *\n * `payment-channel.ts` below is deliberately a bag of pure functions: it is what\n * the wire vectors and the on-chain lifecycle suite are checked against, and\n * free functions are what those can call without standing up a client. This\n * class is the other half of that split — the per-channel state a caller would\n * otherwise thread through every call by hand (which RPC, which program, which\n * mint, whose key), bound once so a chain-agnostic caller can say `open`,\n * `deposit`, `close`, `settle` without knowing any of it.\n *\n * Nothing here re-implements the wire. Every method delegates to the builders in\n * `./payment-channel.js`, which are the single definition of what the program\n * accepts.\n */\n\nimport {\n claimFromSolanaChannel,\n closeSolanaChannel,\n depositSolanaChannel,\n deriveAssociatedTokenAccount,\n deriveChannelPDA,\n deriveVaultPDA,\n getChannelAccountState,\n openSolanaChannel,\n settleSolanaChannel,\n settleableAt,\n type SolanaChannelAccountState,\n type SolanaRpcTarget,\n} from './payment-channel.js';\nimport type { ChainMetadata } from '../../signing/types.js';\n\nexport interface SolanaChannelClientConfig {\n rpcUrl: string;\n /**\n * `fetch` for this chain's JSON-RPC. On a hidden-service client this is the\n * proxied one, so chain reads and sends ride the overlay (ADR 0002).\n */\n rpcFetch?: typeof fetch;\n /** The settlement program. Bound into every balance proof (ADR 0053). */\n programId: string;\n /** The SPL mint this client settles in — part of the channel PDA's seeds. */\n tokenMint: string;\n /** This client's 32-byte Ed25519 seed. Signs opens, deposits and proofs. */\n payerSeed: Uint8Array;\n /** This client's base58 pubkey. */\n payerPubkey: string;\n /**\n * Challenge-period seconds a channel this client OPENS is created with.\n * Defaults to an hour, matching the EVM side's floor: the window is the\n * counterparty's chance to redeem a newer proof before settlement divides the\n * vault, so a zero here would hand the closer a free race.\n */\n challengeDuration?: bigint;\n /**\n * The cluster this client's claims declare. A routing hint the connector\n * cross-checks against its own RPC, never a security boundary — a Solana\n * program cannot learn which cluster it runs on, so no signature can bind it.\n */\n cluster?: string;\n}\n\n/** An on-chain channel plus the two figures a caller actually acts on. */\nexport interface SolanaChannelState extends SolanaChannelAccountState {\n /** This client's own collateral — what bounds its claims, not the vault. */\n ownDeposit: bigint;\n /** This client's own on-chain nonce watermark. The next claim must exceed it. */\n ownNonce: bigint;\n /** Unix seconds `settle` becomes legal; `undefined` unless closed. */\n settleableAt?: bigint;\n}\n\nconst DEFAULT_CHALLENGE_DURATION = 3600n;\n\nexport class SolanaChannelClient {\n /**\n * Where this client's JSON-RPC goes, and through which `fetch`. Built once:\n * every call below passes it straight to `payment-channel.js`, which is the\n * only place that looks inside it.\n */\n private readonly rpc: SolanaRpcTarget;\n\n constructor(private readonly config: SolanaChannelClientConfig) {\n this.rpc =\n config.rpcFetch === undefined\n ? config.rpcUrl\n : { url: config.rpcUrl, fetchImpl: config.rpcFetch };\n }\n\n /**\n * The channel PDA for a counterparty — the claim's `channelAccount`, and the\n * account the connector reads. Deterministic from the pair and the mint, and\n * order-independent: the program sorts participants, so both sides derive the\n * same address without agreeing on who opened it.\n */\n channelId(counterparty: string): string {\n return deriveChannelPDA(\n this.config.payerPubkey,\n counterparty,\n this.config.tokenMint,\n this.config.programId\n ).pda;\n }\n\n /** The vault the deposits sit in, for a given channel. */\n vaultId(channelPDA: string): string {\n return deriveVaultPDA(channelPDA, this.config.programId).pda;\n }\n\n /**\n * The domain a claim on this deployment is signed under. Handed to\n * `SolanaSigner.signBalanceProof` so the program id in the signed bytes comes\n * from configuration rather than from anything a claim declares.\n */\n claimMetadata(): ChainMetadata {\n return {\n chainType: 'solana',\n programId: this.config.programId,\n tokenMint: this.config.tokenMint,\n ...(this.config.cluster ? { cluster: this.config.cluster } : {}),\n };\n }\n\n /**\n * Open the channel to `counterparty` and bring its collateral to `deposit`.\n *\n * Idempotent in the only sense that matters: an existing channel is never\n * re-initialized, but it IS topped up — so the outcome, \"an open channel\n * holding `deposit`\", is the same either way. A channel this client has\n * already CLOSED is returned untouched, since the program refuses a deposit\n * on one.\n */\n async open(params: {\n counterparty: string;\n deposit?: bigint;\n /** The funded token account collateral is pulled from; defaults to the ATA. */\n payerTokenAccount?: string;\n }): Promise<{\n channelId: string;\n opened: boolean;\n depositTotal?: bigint;\n }> {\n const deposit =\n params.deposit && params.deposit > 0n\n ? {\n amount: params.deposit,\n payerTokenAccount:\n params.payerTokenAccount ?? this.ownTokenAccount(),\n }\n : undefined;\n\n const result = await openSolanaChannel({\n rpcUrl: this.rpc,\n programId: this.config.programId,\n tokenMint: this.config.tokenMint,\n payerSeed: this.config.payerSeed,\n payerPubkey: this.config.payerPubkey,\n peerPubkey: params.counterparty,\n challengeDuration:\n this.config.challengeDuration ?? DEFAULT_CHALLENGE_DURATION,\n ...(deposit ? { deposit } : {}),\n });\n\n return {\n channelId: result.channelPDA,\n opened: result.opened,\n ...(result.depositTotal !== undefined\n ? { depositTotal: result.depositTotal }\n : {}),\n };\n }\n\n /** Add collateral to an existing channel. Incremental, not a target. */\n async deposit(\n channelId: string,\n amount: bigint,\n payerTokenAccount?: string\n ): Promise<{ txSignature: string }> {\n const { depositTxSignature } = await depositSolanaChannel({\n rpcUrl: this.rpc,\n programId: this.config.programId,\n channelPDA: channelId,\n payerSeed: this.config.payerSeed,\n payerPubkey: this.config.payerPubkey,\n payerTokenAccount: payerTokenAccount ?? this.ownTokenAccount(),\n amount,\n });\n return { txSignature: depositTxSignature };\n }\n\n /**\n * Close the channel, starting the challenge period. The channel is still\n * claimable while it runs — that is what the period is for.\n */\n async close(\n channelId: string\n ): Promise<{ txSignature: string; settleableAt?: bigint }> {\n const { closeTxSignature } = await closeSolanaChannel({\n rpcUrl: this.rpc,\n programId: this.config.programId,\n channelPDA: channelId,\n closerSeed: this.config.payerSeed,\n closerPubkey: this.config.payerPubkey,\n });\n const after = await this.read(channelId);\n return {\n txSignature: closeTxSignature,\n ...(after.settleableAt !== undefined\n ? { settleableAt: after.settleableAt }\n : {}),\n };\n }\n\n /**\n * Settle a closed channel whose challenge period has elapsed, paying each\n * side `deposit − sent + received` and reclaiming the accounts' rent.\n *\n * Payout destinations default to each participant's ATA for the channel's\n * mint. The program checks that each destination it pays into is owned by\n * that participant and holds this mint, so supplying the wrong one is refused\n * on chain rather than misdelivered.\n */\n async settle(\n channelId: string,\n options: {\n force?: boolean;\n participantATokenAccount?: string;\n participantBTokenAccount?: string;\n } = {}\n ): Promise<{ txSignature: string }> {\n const account = await this.read(channelId);\n if (!account.exists) {\n throw new Error(\n `Solana channel ${channelId} does not exist on chain — a settled channel's ` +\n `account is zeroed by the program, so it cannot be settled twice.`\n );\n }\n const mint = account.tokenMint ?? this.config.tokenMint;\n const { settleTxSignature } = await settleSolanaChannel({\n rpcUrl: this.rpc,\n programId: this.config.programId,\n channelPDA: channelId,\n callerSeed: this.config.payerSeed,\n callerPubkey: this.config.payerPubkey,\n participantATokenAccount:\n options.participantATokenAccount ??\n deriveAssociatedTokenAccount(account.participantA ?? '', mint),\n participantBTokenAccount:\n options.participantBTokenAccount ??\n deriveAssociatedTokenAccount(account.participantB ?? '', mint),\n ...(options.force ? { force: true } : {}),\n });\n return { txSignature: settleTxSignature };\n }\n\n /**\n * Redeem a counterparty's signed balance proof — the receive side. The\n * counterparty never co-signs; its authorization is the proof itself.\n */\n async redeem(params: {\n channelId: string;\n claimer: string;\n nonce: bigint;\n transferredAmount: bigint;\n signature: Uint8Array;\n }): Promise<{ txSignature: string }> {\n const { claimTxSignature } = await claimFromSolanaChannel({\n rpcUrl: this.rpc,\n programId: this.config.programId,\n channelPDA: params.channelId,\n claimerPubkey: params.claimer,\n feePayerPubkey: this.config.payerPubkey,\n feePayerSeed: this.config.payerSeed,\n nonce: params.nonce,\n transferredAmount: params.transferredAmount,\n signature: params.signature,\n });\n return { txSignature: claimTxSignature };\n }\n\n /**\n * Read the channel, with THIS client's side of it resolved.\n *\n * Participants are stored sorted on chain, so which slot is \"ours\" is a\n * lexicographic fact about the two keys. Resolving it here is the difference\n * between reading our own collateral and reading the counterparty's — and the\n * program bounds a claim by the CLAIMER's own deposit, so getting it wrong\n * reads an amply-funded vault as our own headroom.\n */\n async read(channelId: string): Promise<SolanaChannelState> {\n const account = await getChannelAccountState(this.rpc, channelId);\n const weAreA = account.participantA === this.config.payerPubkey;\n const deadline = settleableAt(account);\n return {\n ...account,\n ownDeposit: (weAreA ? account.depositA : account.depositB) ?? 0n,\n ownNonce: (weAreA ? account.nonceA : account.nonceB) ?? 0n,\n ...(deadline !== undefined ? { settleableAt: deadline } : {}),\n };\n }\n\n /** This client's associated token account for the configured mint. */\n private ownTokenAccount(): string {\n return deriveAssociatedTokenAccount(\n this.config.payerPubkey,\n this.config.tokenMint\n );\n }\n}\n","import { ed25519 } from '@noble/curves/ed25519.js';\nimport { base58Encode, base58Decode } from '../utils/base58.js';\nimport type { SignedBalanceProof } from '../client/types.js';\nimport type {\n ChainSigner,\n ChainMetadata,\n ClaimMessage,\n SolanaClaimMessage,\n} from './types.js';\nimport { toHex as bytesToHex } from '../utils/binary.js';\nimport { buildBalanceProofMessage } from '../channel/solana/payment-channel.js';\n\n/**\n * Solana signer for the connector payment-channel claim path.\n *\n * Signs the **96-byte** `TOON-BALPROOF-V2` balance-proof message of connector\n * ADR 0053 — `tag(16) || programId(32) || channelAccount(32) || nonce(8 LE) ||\n * transferredAmount(8 LE)` (see {@link buildBalanceProofMessage} for the layout\n * and for why the program id is in it). The same 96 bytes are what the\n * connector's `verify_solana_balance_proof` reconstructs off chain and what the\n * deployed program's Ed25519-precompile check byte-compares on chain, so one\n * signature satisfies both.\n *\n * The program id is taken from {@link ChainMetadata}, never from the caller's\n * claim fields: the connector rebuilds the domain from its OWN record of the\n * channel, so signing under anything but the program the channel actually lives\n * under fails to verify rather than quietly succeeding.\n *\n * The predecessor of this message was 48 bytes and bound no deployment at all.\n * It is gone, not deprecated: the deployed program refuses a 48-byte message on\n * length, so nothing would be gained by keeping a path that can only produce\n * unredeemable claims.\n *\n * `channelId` MUST be the base58 channel PDA.\n */\n/** {@link SolanaSigner.signClaimStateChallenge}'s tag (client-edge-spec.md §1.10). */\nconst CLAIM_STATE_CHALLENGE_TAG = new TextEncoder().encode(\n 'toon-claim-state-challenge-v1'\n);\n\nexport class SolanaSigner implements ChainSigner {\n readonly chainType = 'solana' as const;\n /** 32-byte Ed25519 seed. */\n private readonly privateKey: Uint8Array;\n private pubkeyBase58Cache?: string;\n\n /**\n * @param privateKey - 32-byte Ed25519 seed (e.g. `identity.solana.secretKey.slice(0, 32)`).\n * @param publicKeyBase58 - Optional base58 public key (e.g. `identity.solana.publicKey`).\n * When omitted it is derived lazily from `privateKey`.\n */\n constructor(privateKey: Uint8Array, publicKeyBase58?: string) {\n if (privateKey.length !== 32) {\n throw new Error(\n `SolanaSigner requires a 32-byte Ed25519 seed, got ${privateKey.length} bytes`\n );\n }\n this.privateKey = privateKey;\n this.pubkeyBase58Cache = publicKeyBase58;\n }\n\n private ensurePublicKey(): string {\n if (this.pubkeyBase58Cache) return this.pubkeyBase58Cache;\n const pk = ed25519.getPublicKey(this.privateKey);\n this.pubkeyBase58Cache = base58Encode(new Uint8Array(pk));\n return this.pubkeyBase58Cache;\n }\n\n get signerIdentifier(): string {\n return this.pubkeyBase58Cache ?? 'uninitialized';\n }\n\n async signBalanceProof(params: {\n channelId: string;\n nonce: number;\n transferredAmount: bigint;\n lockedAmount: bigint;\n locksRoot: string;\n recipient: string;\n metadata: ChainMetadata;\n }): Promise<SignedBalanceProof> {\n if (params.metadata.chainType !== 'solana') {\n throw new Error(\n `SolanaSigner cannot sign for chain type: ${params.metadata.chainType}`\n );\n }\n\n const base58 = this.ensurePublicKey();\n\n // The ADR 0053 balance-proof message:\n // \"TOON-BALPROOF-V2\" || programId(32) || channelAccount(32)\n // || nonce(8 LE) || transferredAmount(8 LE)\n // `channelId` is the base58 channel PDA; `cumulativeAmount` IS\n // `transferredAmount`. There is no recipient term — which side gets paid is\n // fixed by the channel's own participants, so folding it in would bind\n // nothing the chain does not already know.\n const message = buildBalanceProofMessage(\n params.metadata.programId,\n params.channelId,\n BigInt(params.nonce),\n params.transferredAmount\n );\n\n const signature = ed25519.sign(message, this.privateKey);\n const signatureHex = '0x' + bytesToHex(new Uint8Array(signature));\n\n return {\n channelId: params.channelId,\n nonce: params.nonce,\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot,\n signature: signatureHex,\n signerAddress: base58,\n chainId: 0,\n tokenNetworkAddress: params.metadata.programId,\n recipient: params.recipient,\n };\n }\n\n /**\n * Signs a `POST /ilp/claim-state` claim-state challenge (client-edge-spec.md\n * §1.10): `\"toon-claim-state-challenge-v1\" || channelAccount(32) ||\n * expires(u64 LE)` — 69 bytes, and a different tag, so it is distinct in both\n * content and length from the 96-byte balance-proof message: a captured\n * challenge can never be replayed as a payment or vice versa. Returns base64 (the\n * connector's documented wire encoding for this endpoint, unlike the\n * hex-encoded balance-proof signature elsewhere in this class).\n *\n * @param params.expires - Unix seconds the signature stops verifying.\n */\n async signClaimStateChallenge(params: {\n channelAccount: string;\n expires: number;\n }): Promise<string> {\n const accountBytes = base58Decode(params.channelAccount);\n if (accountBytes.length !== 32) {\n throw new Error(\n `channelAccount must decode to 32 bytes, got ${accountBytes.length}`\n );\n }\n const tag = CLAIM_STATE_CHALLENGE_TAG;\n const message = new Uint8Array(tag.length + 32 + 8);\n message.set(tag, 0);\n message.set(accountBytes, tag.length);\n new DataView(message.buffer).setBigUint64(\n tag.length + 32,\n BigInt(params.expires),\n true // little-endian\n );\n\n const signature = ed25519.sign(message, this.privateKey);\n return Buffer.from(signature).toString('base64');\n }\n\n /**\n * @param options.cluster - The cluster this claim declares (`solana:devnet`,\n * …). Optional, and the one field naming a chain that no signature can\n * bind — a Solana program cannot learn which cluster it runs on, so it can\n * never rebuild a message containing one. The connector compares it against\n * the cluster it settles on and refuses a mismatch, which closes the\n * honest-misconfiguration case; the forgery case is closed by the\n * `programId` inside the signed bytes. Omitted from the JSON entirely when\n * not supplied, rather than sent empty: an absent hint and a hint saying\n * `\"\"` are not the same claim.\n */\n buildClaimMessage(\n proof: SignedBalanceProof,\n senderId: string,\n options?: { cluster?: string }\n ): ClaimMessage {\n // The connector verifies a base64 Ed25519 signature; the signed proof carries\n // a 0x-prefixed 64-byte hex signature, so convert hex -> bytes -> base64.\n const sigHex = proof.signature.startsWith('0x')\n ? proof.signature.slice(2)\n : proof.signature;\n const sigBytes = Uint8Array.from(\n sigHex.match(/.{1,2}/g)?.map((b) => parseInt(b, 16)) ?? []\n );\n const signatureBase64 = Buffer.from(sigBytes).toString('base64');\n\n const claim: SolanaClaimMessage = {\n version: '1.0',\n blockchain: 'solana',\n messageId: crypto.randomUUID(),\n timestamp: new Date().toISOString().replace(/\\.\\d{3}Z$/, '.000Z'),\n senderId,\n // channelId IS the base58 channel PDA -> connector's channelAccount.\n channelAccount: proof.channelId,\n nonce: proof.nonce,\n transferredAmount: proof.transferredAmount.toString(),\n signature: signatureBase64,\n signerPublicKey: this.pubkeyBase58Cache ?? proof.signerAddress,\n programId: proof.tokenNetworkAddress,\n ...(options?.cluster ? { cluster: options.cluster } : {}),\n };\n return claim;\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/** Collateral for the first channel, base units — 0.1 USDC at 6 decimals. */\nexport const DEFAULT_DEPOSIT = 100_000n;\n/** Challenge period in seconds when the caller sets none. */\nexport const DEFAULT_SETTLEMENT_TIMEOUT = 86_400;\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 * The undici dispatcher built from {@link socksProxy}, for chain RPC.\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 one, so {@link resolveConfig} only reserves\n * the slot and leaves it `undefined`.\n */\n rpcDispatcher: unknown;\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 settlementTimeout: number;\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 settlementTimeout = config.settlementTimeout ?? DEFAULT_SETTLEMENT_TIMEOUT;\n if (!Number.isInteger(settlementTimeout) || settlementTimeout <= 0) {\n throw new ConfigError(\n `settlementTimeout must be a positive whole number of seconds; got ${String(\n settlementTimeout\n )}.`\n );\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 connectorIsHiddenService,\n socksProxy,\n proxyRpc: config.proxyRpc ?? true,\n rpcDispatcher: undefined,\n settlementTimeout,\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.store.url}'. 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, and a proxy without one is a misunderstanding.\n *\n * Both directions fail here rather than later. Without a proxy, a `.anyone`\n * address resolves nowhere — but only after the hostname has gone out in a\n * plaintext DNS query, which is the one thing the address exists to avoid. With\n * a proxy but a clearnet connector, the caller believes they are anonymous and\n * are not.\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` CLI, which ' +\n 'can start one for you.'\n );\n }\n if (!connectorIsHiddenService) {\n throw new ConfigError(\n `socksProxy is set, but connector ${JSON.stringify(connector)} is a clearnet ` +\n 'address, so nothing would ride the proxy. Point `connector` at the node\\'s ' +\n '.anyone address, or drop `socksProxy`.'\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 {@link ChannelManager.adoptConnectorWatermark}).\n */\n signedCeiling?: 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` 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/**\n * Chain context needed to re-track a RESUMED channel — the same shape\n * {@link ChannelManager.trackChannel} takes.\n */\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 * 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\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 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}\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 ChannelManager'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.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.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 };\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 };\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 * The channel, as a caller sees it: open, deposit, close, settle, inspect.\n *\n * Every method here spends the caller's own gas on the caller's own transaction.\n * A connector has no endpoint that opens a channel (`self-description-spec.md`\n * ND-03) — it reads the chain\n * ([ADR 0052](https://github.com/toon-protocol/connector/blob/main/docs/adr/0052-permissionless-payment-is-guaranteed-and-a-claim-is-what-authorises.md))\n * — so there is nobody to ask and nothing to be granted. That is what makes\n * paying permissionless, and it is also why this facade is where a client first\n * touches a chain at all: {@link ToonClient.create} does not.\n *\n * ## Which chain\n *\n * {@link ChannelFacade.ensure} picks the settlement from the node's OWN\n * `settlements[]`, never from a preset: the node proved each entry against a live\n * chain when it booted (ND-07), and two declarations of one fact is how a mainnet\n * node comes to be described as devnet. The pick is `config.chain` when the caller\n * named one, else the first chain in the node's published order that this client\n * holds a key for, else a {@link ChainUnavailableError} naming what the node does\n * offer.\n *\n * ## Opening is never a side effect\n *\n * With `autoOpenChannel: false`, {@link ChannelFacade.ensure} resolves an\n * existing channel and otherwise raises {@link ChannelNotOpenError} — it does not\n * read the chain and it certainly does not transact. A consumer that must not\n * lock collateral behind the user's back (the CLI's `send`) relies on that being\n * the *whole* behaviour of the flag, not merely a preference the opener consults.\n */\nimport type {\n ChainKind,\n ChannelFacade,\n ChannelState,\n OpenChannelOptions,\n TxRef,\n} from './types.js';\nimport type { ChannelTerms, OnChainChannelStatus } from '../channel/types.js';\nimport type { NodeSelfDescription } from '../connector/self-description.js';\nimport type { ConnectorChainSettlementTerms } from '../connector/ConnectorEdgeClient.js';\nimport type { ChannelManager } from '../channel/ChannelManager.js';\nimport type { OnChainChannelClient } from '../channel/OnChainChannelClient.js';\nimport { parseEvmChainId } from '../channel/evm/TokenNetworkClient.js';\nimport {\n ChainUnavailableError,\n ChannelNotOpenError,\n chainUnavailableMessage,\n} from './errors.js';\nimport type { ResolvedConfig } from './config.js';\n\n/** What the facade needs from the client around it. */\nexport interface ChannelFacadeDeps {\n config: ResolvedConfig;\n channels: ChannelManager;\n /** The node's `GET /ilp`, cached. */\n describe: () => Promise<NodeSelfDescription>;\n /** Built lazily on the first chain operation, so `create()` touches no chain. */\n onChainClient: () => OnChainChannelClient;\n /** Told which chain was picked, so the client can report it and label claims. */\n onChainSelected?: (chain: ChainKind, terms: ChannelTerms) => void;\n}\n\nexport class ClientChannelFacade implements ChannelFacade {\n private readonly deps: ChannelFacadeDeps;\n /** The channel in use, and the terms it lives under. Set by {@link ensure}. */\n private current: { channelId: string; terms: ChannelTerms } | undefined;\n\n constructor(deps: ChannelFacadeDeps) {\n this.deps = deps;\n }\n\n get id(): string | undefined {\n return this.current?.channelId;\n }\n\n /**\n * The settlement terms in use, once a chain has been picked. Exposed so the\n * client can report the chain it settles on without re-picking.\n */\n get terms(): ChannelTerms | undefined {\n return this.current?.terms;\n }\n\n /**\n * Ensure a usable channel exists, and return its id.\n *\n * @throws {ChainUnavailableError} the node settles on no chain this client can\n * pay on.\n * @throws {ChannelNotOpenError} `autoOpenChannel` is off and no channel is held.\n */\n /**\n * Teach the chain client the context of a channel this process did not open.\n *\n * A channel outlives the process that opened it — that is the point of the\n * store — but the chain client's knowledge of it does not: which chain it is\n * on, and which contract or program holds it, live in memory and start empty.\n * Paying needs none of that (a claim is signed from the channel's recorded\n * terms), which is why the gap only shows up the first time a resumed channel\n * is deposited into, closed or settled — and shows up there as a channel this\n * client \"neither opened nor adopted\".\n *\n * Adoption is bookkeeping and nothing else: no transaction, no chain read.\n */\n private adoptOnChain(channelId: string, terms: ChannelTerms): void {\n this.deps.onChainClient().adoptChannel(channelId, {\n chain: terms.chain,\n tokenNetworkAddress:\n terms.kind === 'evm' ? (terms.tokenNetwork ?? '') : (terms.programId ?? ''),\n ...(terms.token !== '' ? { tokenAddress: terms.token } : {}),\n });\n }\n\n async ensure(description?: NodeSelfDescription): Promise<string> {\n const desc = description ?? (await this.deps.describe());\n const terms = this.pickSettlement(desc);\n const { config, channels } = this.deps;\n\n const existing = channels.resolveChannel(config.connector, terms);\n if (existing !== undefined) {\n this.current = { channelId: existing, terms };\n // A channel resolved from the store was resumed, not opened, and the\n // manager could not hand the chain client its context on the way — the\n // chain client does not exist yet on this path (it is built lazily by\n // `onChainClient()`, which nothing above has called). `requireChannel`\n // adopts for exactly this reason, but it returns `current` untouched\n // when it is already set, and `ensure()` is what sets it. Without this\n // line a resumed channel could be paid on but never deposited into,\n // closed or settled: \"neither opened nor adopted\".\n this.adoptOnChain(existing, terms);\n return existing;\n }\n\n if (!config.autoOpenChannel) {\n throw new ChannelNotOpenError(\n `No payment channel is open with ${config.connector} on ${terms.chain}, ` +\n 'and `autoOpenChannel` is off, so nothing will be opened on your behalf. ' +\n 'Open one explicitly first — it locks collateral on chain and spends gas, ' +\n 'which is exactly why it is not done as a side effect of sending.'\n );\n }\n\n // Opening reaches the chain, and the manager only holds a chain client once\n // this has been called — it is lazy so that `create()` and every free read\n // stay chain-free. Calling it before `ensureChannel` is what makes the\n // manager able to open at all.\n this.deps.onChainClient();\n\n const channelId = await channels.ensureChannel(config.connector, terms, {\n initialDeposit: config.deposit,\n settlementTimeout: config.settlementTimeout,\n });\n this.current = { channelId, terms };\n return channelId;\n }\n\n /**\n * Open a channel, or adopt the one already open with this connector.\n *\n * Adoption is the normal outcome and costs nothing: a channel's id is derived\n * from its participants on both chains (EVM since ADR 0059, Solana always), so\n * the chain itself answers \"do I already have one with this counterparty?\".\n */\n async open(options: OpenChannelOptions = {}): Promise<ChannelState> {\n const desc = await this.deps.describe();\n const terms = this.pickSettlement(desc);\n const { config, channels } = this.deps;\n\n // As in `ensure`: the manager has no chain client until this lazy getter\n // has run, and opening is precisely the operation that needs one.\n this.deps.onChainClient();\n\n const channelId = await channels.ensureChannel(config.connector, terms, {\n initialDeposit: options.deposit !== undefined ? BigInt(options.deposit) : config.deposit,\n settlementTimeout: options.settlementTimeout ?? config.settlementTimeout,\n });\n this.current = { channelId, terms };\n // Covers the resumed case: `ensureChannel` returns a channel it found in the\n // store without opening one, and the chain client has never heard of it.\n this.adoptOnChain(channelId, terms);\n return this.state();\n }\n\n /**\n * Add collateral. Monotonic on both chains — a deposit can never decrease\n * (`setTotalDeposit` reverts on a decrease; the Solana handler only adds) — so\n * a connector that read a deposit earlier holds a permanent lower bound and can\n * never under-credit a claim because of a stale read.\n */\n async deposit(amount: bigint | string): Promise<ChannelState> {\n const { channelId } = await this.requireChannel('deposit into');\n const delta = BigInt(amount);\n if (delta <= 0n) throw new RangeError('Deposit amount must be positive.');\n\n const { channels } = this.deps;\n const result = await this.deps\n .onChainClient()\n .depositToChannel(channelId, delta, {\n currentDeposit: channels.getDepositTotal(channelId),\n });\n channels.setDepositTotal(channelId, result.depositTotal);\n return this.state();\n }\n\n /**\n * Start the challenge period.\n *\n * The deadline is read back from the chain rather than computed here: the\n * contract stamps `closedAt` with the block timestamp, and a local clock that\n * disagreed by a few seconds would have a caller settle early and pay gas for a\n * revert.\n */\n async close(): Promise<TxRef & { closedAt?: bigint; settleableAt?: bigint }> {\n const { channelId } = await this.requireChannel('close');\n const result = await this.deps.onChainClient().closeChannel(channelId);\n this.deps.channels.setChannelClosed(channelId, result.closedAt, result.settleableAt);\n return {\n ...(result.txHash !== undefined ? { txHash: result.txHash } : {}),\n closedAt: result.closedAt,\n settleableAt: result.settleableAt,\n };\n }\n\n /**\n * Pay out and finish.\n *\n * The time guard is enforced HERE, before any gas is spent: the contract\n * reverts before `closedAt + settlementTimeout` anyway, and a caller learning\n * that from a failed transaction has paid to be told something this client\n * already knew.\n */\n async settle(): Promise<TxRef> {\n const { channelId } = await this.requireChannel('settle');\n const settleableAt = this.deps.channels.getSettleableAt(channelId);\n if (settleableAt === undefined) {\n throw new ChannelNotOpenError(\n `Channel ${channelId} has not been closed, so there is nothing to settle. ` +\n 'Call close() first; it starts the challenge period.'\n );\n }\n const nowSec = BigInt(Math.floor(Date.now() / 1000));\n if (nowSec < settleableAt) {\n throw new ChannelNotOpenError(\n `Channel ${channelId} is not settleable yet — ${(settleableAt - nowSec).toString()}s ` +\n `of its challenge period remain (settleable at ${settleableAt.toString()}). ` +\n 'The contract would revert; refusing before spending gas.'\n );\n }\n const result = await this.deps.onChainClient().settleChannel(channelId);\n this.deps.channels.setChannelSettled(channelId, nowSec);\n return { ...(result.txHash !== undefined ? { txHash: result.txHash } : {}) };\n }\n\n /**\n * The channel as this client and (optionally) the chain jointly see it.\n *\n * `spent`/`nonce` are always the LOCAL watermark — what this client has signed.\n * The connector keeps its own and is the one that decides; the two agree unless\n * a claim was signed and never accepted. `client.claimState()` asks the\n * connector for its side, and `{ onChain: true }` asks the chain for its.\n */\n async state(options: { onChain?: boolean } = {}): Promise<ChannelState> {\n const { channelId, terms } = await this.requireChannel('read');\n const { channels } = this.deps;\n\n const spent = channels.getCumulativeAmount(channelId);\n const depositTotal = channels.getDepositTotal(channelId);\n const nonce = channels.getNonce(channelId);\n\n let onChain: OnChainChannelStatus | undefined;\n if (options.onChain === true) {\n onChain = await this.deps.onChainClient().getChannelState(channelId);\n }\n\n const status = onChain?.status ?? localStatus(channels.getChannelCloseState(channelId));\n const deposit = onChain?.deposit ?? depositTotal;\n\n return {\n chain: terms.kind,\n channelId,\n counterparty: terms.counterparty,\n status,\n depositTotal: deposit,\n spent,\n nonce,\n available: deposit > spent ? deposit - spent : 0n,\n ...(onChain !== undefined\n ? {\n onChain: {\n ...(onChain.deposit !== undefined ? { deposit: onChain.deposit } : {}),\n ...(onChain.closedAt !== undefined ? { closedAt: onChain.closedAt } : {}),\n ...(onChain.settleableAt !== undefined\n ? { settleableAt: onChain.settleableAt }\n : {}),\n },\n }\n : {}),\n domain: terms,\n };\n }\n\n // ─── Private ──────────────────────────────────────────────────────────────\n\n /**\n * The channel every lifecycle method needs, resolved without opening one.\n *\n * `deposit`/`close`/`settle`/`state` operate on a channel that must already\n * exist, so this never opens: a `deposit` that quietly opened a channel first\n * would lock the configured collateral *plus* the requested amount.\n */\n private async requireChannel(\n verb: string\n ): Promise<{ channelId: string; terms: ChannelTerms }> {\n if (this.current) return this.current;\n\n const desc = await this.deps.describe();\n const terms = this.pickSettlement(desc);\n const existing = this.deps.channels.resolveChannel(this.deps.config.connector, terms);\n if (existing === undefined) {\n throw new ChannelNotOpenError(\n `No payment channel is open with ${this.deps.config.connector} on ` +\n `${terms.chain}, so there is nothing to ${verb}. Call channel.open() first.`\n );\n }\n this.current = { channelId: existing, terms };\n // Resolved from the store, so this process has never opened it and the\n // chain client has no context for it. Every caller of this method is about\n // to reach the chain, which is exactly when that matters.\n this.adoptOnChain(existing, terms);\n return this.current;\n }\n\n /**\n * Choose the chain to settle on, from the node's own published settlements.\n *\n * @throws {ChainUnavailableError} naming the chains the node DOES offer, since\n * the remedy is always to pick one of them or to hold a key for one.\n */\n private pickSettlement(description: NodeSelfDescription): ChannelTerms {\n const offered = description.settlements.map((s) => s.chain);\n const { config } = this.deps;\n\n if (description.settlements.length === 0) {\n throw new ChainUnavailableError(\n chainUnavailableMessage(config.chain, offered, 'none'),\n offered\n );\n }\n\n if (config.chain !== undefined) {\n const match = description.settlements.find((s) => s.kind === config.chain);\n if (!match) {\n throw new ChainUnavailableError(\n chainUnavailableMessage(config.chain, offered, 'not-offered'),\n offered\n );\n }\n return this.adopt(match);\n }\n\n // The node's own order is the preference order: it published these, and the\n // first one it lists is the one it expects to be paid on.\n const match = description.settlements.find(\n (s) => config.identity[s.kind] !== undefined\n );\n if (!match) {\n throw new ChainUnavailableError(\n chainUnavailableMessage(undefined, offered, 'no-key'),\n offered\n );\n }\n return this.adopt(match);\n }\n\n /** Read one published settlement entry as the terms a channel opens under. */\n private adopt(entry: ConnectorChainSettlementTerms): ChannelTerms {\n const terms = settlementToTerms(entry);\n this.deps.onChainSelected?.(terms.kind, terms);\n return terms;\n }\n}\n\n/**\n * A node's published settlement entry, as {@link ChannelTerms}.\n *\n * The EVM `chainId` is parsed out of the chain key (`evm:84532`) rather than\n * published separately, and it matters: it is the EIP-712 domain's `chainId`, so\n * a claim signed under the wrong one verifies against nothing.\n */\nexport function settlementToTerms(entry: ConnectorChainSettlementTerms): ChannelTerms {\n if (entry.kind === 'solana') {\n return {\n kind: 'solana',\n chain: entry.chain,\n counterparty: entry.settlementAddress,\n token: entry.tokenAddress,\n decimals: entry.decimals,\n programId: entry.programId,\n };\n }\n return {\n kind: 'evm',\n chain: entry.chain,\n chainId: parseEvmChainId(entry.chain),\n counterparty: entry.settlementAddress,\n token: entry.tokenAddress,\n decimals: entry.decimals,\n tokenNetwork: entry.tokenNetwork,\n tokenNetworkRegistry: entry.tokenNetworkRegistry,\n };\n}\n\n/**\n * The channel's status from the local withdraw timers alone.\n *\n * `closing` and `settleable` are both `closed` on chain — the difference between\n * them is only whether the challenge period has elapsed, which is a timer rather\n * than a state the contract holds.\n */\nfunction localStatus(\n state: 'open' | 'closing' | 'settleable' | 'settled'\n): ChannelState['status'] {\n if (state === 'settled') return 'settled';\n if (state === 'open') return 'open';\n return 'closed';\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 { 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\nfunction rpcTimeoutMs(): number {\n const raw =\n typeof process !== 'undefined' ? process.env?.[RPC_TIMEOUT_ENV] : undefined;\n const n = raw === undefined || raw === '' ? NaN : Number(raw);\n return Number.isFinite(n) && n >= 0 ? n : DEFAULT_RPC_TIMEOUT_MS;\n}\n\n/** AbortSignal firing after {@link rpcTimeoutMs}; undefined when disabled (`0`). */\nfunction rpcAbortSignal(): AbortSignal | undefined {\n const ms = rpcTimeoutMs();\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() ? { timeout: rpcTimeoutMs() } : {}),\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() ? { timeout: rpcTimeoutMs() } : {}),\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}): 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(),\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}): 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(),\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}\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 } = 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 }),\n tokenMint\n ? readSolanaTokenBalance({ rpcUrl, mint: tokenMint, owner, fetchImpl })\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 { 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 publicClient.waitForTransactionReceipt({\n hash: txHash,\n });\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 publicClient.waitForTransactionReceipt({\n hash: txHash,\n });\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 the ungated mock USDC on 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","/**\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 type { ConnectorChainSettlementTerms } from '../connector/ConnectorEdgeClient.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 * On a clearnet client that is `config.fetch` — the caller's own if they\n * injected one, and otherwise the global. On a hidden-service client\n * `config.fetch` is the proxy-bound one, and `rpcDispatcher` is the single\n * signal for \"chain RPC rides the proxy\" (ADR 0002): `proxyRpc: false` clears\n * it, and the Solana reads have to leave the proxy with the EVM ones. A payer\n * who opted out because their node is on loopback would otherwise still be\n * 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.rpcDispatcher !== undefined ? config.fetch : globalThis.fetch;\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 };\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 ...(config.rpcDispatcher !== undefined ? { rpcDispatcher: config.rpcDispatcher } : {}),\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 ...(config.rpcDispatcher !== undefined\n ? { rpcDispatcher: config.rpcDispatcher }\n : {}),\n ...(entry?.tokenAddress ? { tokenAddress: entry.tokenAddress } : {}),\n },\n }\n : {}),\n ...(config.identity.solana\n ? {\n solana: {\n rpcUrl: config.rpcUrls.solana,\n ...(config.rpcDispatcher !== undefined\n ? { rpcFetch: solanaRpcFetch(config) }\n : {}),\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 /** The node's settlements, keyed by chain family. */\n private async settlements(): Promise<Map<ChainKind, ConnectorChainSettlementTerms>> {\n const description = await this.deps.describe();\n const byKind = new Map<ChainKind, ConnectorChainSettlementTerms>();\n for (const entry of description.settlements) {\n if (!byKind.has(entry.kind)) byKind.set(entry.kind, entry);\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 * Recognising the connector's own answer to a stale peer→channel binding\n * (toon-client#581).\n *\n * #578/#580 added a counterparty check: a cached binding whose recorded\n * counterparty disagrees with what the destination announces TODAY is\n * superseded before it is resumed. That check is a PREDICTION — it catches a\n * record that visibly disagrees with the announce. It cannot catch a record\n * whose recorded counterparty happens to look current: a node that keeps its\n * settlement address but loses its channel state (a wiped connector, a\n * restored-from-backup box, a redeployed contract) still answers every paid\n * write with\n *\n * F01 - claim rejected: names a channel this connector has no record of\n *\n * and the only recovery, until this module existed, was hand-editing JSON.\n *\n * That reject is GROUND TRUTH rather than inference, so it is the better\n * trigger — but only for the \"no record of this channel\" flavour. `F01` is\n * also how the connector reports a claim whose NONCE did not advance (two\n * writes racing on one channel; see `BtpPaidWriteTransport`'s module docs).\n * Evicting a binding on a nonce race would be actively destructive: the\n * channel is fine, and re-resolving would open and fund a SECOND one while the\n * first still holds collateral. So the discrimination below is deliberately\n * conservative — a marker must positively say \"unknown channel\", and any\n * mention of a nonce vetoes the match. An unrecognised `F01` is left alone.\n */\n\n/** The ILP reject code the connector uses for a refused claim. */\nexport const CLAIM_REJECT_CODE = 'F01';\n\n/**\n * Phrases that mean \"the claim named a channel I hold no record of\". The live\n * devnet connector emits the first; the others cover the same condition as\n * phrased by the other connector generations (the TS edge, the Rust edge) so a\n * fleet upgrade does not silently turn this guard off.\n */\nconst UNKNOWN_CHANNEL_MARKERS = [\n 'no record of',\n 'unknown channel',\n 'channel not found',\n 'no such channel',\n 'not a known channel',\n];\n\n/**\n * Phrases that mean the channel is FINE and the claim was not — a nonce that\n * did not advance, an amount below the watermark. Evicting here would strand\n * collateral in a healthy channel, so any of these vetoes the match even when\n * an unknown-channel marker is also present.\n */\nconst HEALTHY_CHANNEL_MARKERS = ['nonce', 'not advancing', 'watermark'];\n\n/**\n * True when `result` is the connector reporting that the claim just sent named\n * a channel it holds no record of — the signal to evict that binding and\n * re-resolve.\n *\n * Fail-closed in the safe direction: anything that is not unambiguously an\n * unknown-channel reject returns `false` and the write fails as it does today.\n * A false negative costs one failed write; a false positive costs an on-chain\n * channel.\n */\nexport function isUnknownChannelReject(result: {\n accepted: boolean;\n code?: string;\n message?: string;\n}): boolean {\n if (result.accepted) return false;\n if (result.code !== CLAIM_REJECT_CODE) return false;\n const message = (result.message ?? '').toLowerCase();\n if (HEALTHY_CHANNEL_MARKERS.some((m) => message.includes(m))) return false;\n return UNKNOWN_CHANNEL_MARKERS.some((m) => message.includes(m));\n}\n\n/**\n * True when the reject can be attributed to `channelId` — either because the\n * message names it, or because it names no channel at all (the live message\n * does not, and this client attaches exactly ONE claim per packet, so the\n * channel that produced that claim is the only candidate).\n *\n * The point of the check is the negative case: a message that names a\n * DIFFERENT channel is somebody else's problem and must not evict this\n * binding.\n */\nexport function rejectNamesChannel(\n message: string | undefined,\n channelId: string\n): boolean {\n if (!message || channelId === '') return true;\n if (message.toLowerCase().includes(channelId.toLowerCase())) return true;\n return !mentionsAnyChannelId(message);\n}\n\n/**\n * Channel-id shapes across the three settlement chains: an EVM `bytes32`\n * (`0x` + 64 hex), or a base58 Solana account / Mina public key long enough\n * not to be an ordinary word.\n */\nconst CHANNEL_ID_SHAPES = [\n /0x[0-9a-fA-F]{64}/,\n /\\b[1-9a-km-zA-HJ-NP-Z]{32,44}\\b/,\n];\n\nfunction mentionsAnyChannelId(message: string): boolean {\n return CHANNEL_ID_SHAPES.some((shape) => shape.test(message));\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. **Ensure a channel**, then **sign a claim** on it for that amount.\n * 6. **Choose a carriage and send.**\n * 7. **Read the answer** with the secret from step 4.\n *\n * ## Two things this deliberately gets right\n *\n * **The watermark is repaid on every refusal.**\n * {@link ChannelManager.signBalanceProof} advances and persists the nonce and the\n * cumulative amount before the packet leaves, because a signed claim must never\n * be re-signable at the same nonce. When the connector then refuses the claim —\n * `F03` underpayment, `F03` over-deposit, `F01` unknown channel, or a\n * `claimAck.result === 'rejected'` riding beside any verdict — it banked nothing\n * (`client-edge-spec.md` §1.3: \"a validation failure ... is rejected before it\n * reaches the terminating app or advances any watermark\"), and our cumulative is\n * left inflated by value it never admitted. Every path that ends in a refusal\n * calls {@link ChannelManager.rollbackAmount}, including a thrown transport\n * error. The error case is a deliberate asymmetry: a lost response *may* have\n * been banked, so rolling back can leave us one claim short — being short spends\n * nothing, whereas running ahead silently spends the channel's deposit on\n * nothing and eventually breaches the deposit ceiling.\n *\n * **And a doubtful watermark is settled before the next claim, not after.**\n * Being one claim short is not actually self-correcting: every later claim\n * under-advances by the same gap and is refused `F03`, then `F01`, forever\n * (toon-client#671). On a clearnet loopback the window barely exists; over a\n * hidden-service circuit, timeout-but-delivered is ordinary. So a transport\n * error, and a refused claim, both leave the channel marked\n * {@link ChannelManager.markWatermarkUncertain}, and the next attempt on it asks\n * the connector for its own figure (`POST /ilp/claim-state`) and adopts it\n * BEFORE signing — the same read the client would otherwise reach for after two\n * refusals, moved to before the first one.\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 { ChannelManager } from '../channel/ChannelManager.js';\nimport { isUnknownChannelReject, rejectNamesChannel } from '../channel/stale-channel.js';\nimport { toBase64, fromBase64, encodeUtf8, decodeUtf8 } from '../utils/binary.js';\nimport {\n BeforePayRefusedError,\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 /** Open or adopt a channel with this node, returning its id. */\n ensureChannel(description: NodeSelfDescription): Promise<string>;\n /**\n * Retire the binding `channelId` was resolved through, so the next\n * {@link SendContext.ensureChannel} re-resolves. `false` when there was\n * nothing to retire — which is the signal NOT to retry.\n */\n evictChannel(channelId: string): boolean;\n /** The watermark and the signers. */\n channels: ChannelManager;\n /**\n * Re-read the connector's own watermark for `channelId`\n * (`POST /ilp/claim-state`) and adopt it, settling a doubt\n * {@link ChannelManager.markWatermarkUncertain} recorded.\n *\n * Optional: a context with no client edge to ask simply keeps the older\n * behaviour of discovering the disagreement through a refusal. It may throw —\n * it is a network call, and the connector may be exactly what is unreachable —\n * and {@link send} treats that as \"still in doubt\" rather than as a failed\n * request.\n */\n reconcileWatermark?(channelId: string): Promise<void>;\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 /** The label every claim carries. Never an authority (connector ADR 0052). */\n senderId: string;\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` ensures a channel and signs a\n // balance proof, and a signed claim cannot be unsigned (its rollback restores\n // the cumulative amount but deliberately not the nonce). Placed outside\n // `attempt` on purpose: the stale-channel path runs `attempt` twice, and the\n // hook is a decision about the REQUEST, not about an attempt at it.\n refuseIfCallerSaysSo(options.beforePay, destination, amount, request);\n const carriage = await context.transport(description, destination);\n\n const first = await attempt(context, {\n destination,\n amount,\n exchange,\n carriage,\n description,\n timeoutMs: options.timeoutMs ?? context.timeoutMs,\n });\n\n // The bounded stale-channel recovery. `F01 — names a channel this connector\n // has no record of` is GROUND TRUTH that our binding is dead (a wiped\n // connector, a restored-from-backup box, a redeployed contract), where the\n // counterparty check that runs before a packet exists can only ever be a\n // prediction. Retire that binding, re-resolve, and retry the SAME packet once.\n //\n // Bounded deliberately: ONE retry, never a loop — a second `F01` is returned\n // as the failure it is, because a repeated eviction could open a channel per\n // request. And only when re-resolution actually MOVES: a retry onto the same\n // channel id would just repeat the reject.\n const retry = await maybeRetryStaleChannel(context, first, {\n destination,\n amount,\n exchange,\n carriage,\n description,\n timeoutMs: options.timeoutMs ?? context.timeoutMs,\n });\n return retry ?? first.result;\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\n/** One signed claim, one packet, one outcome — plus the channel it was drawn on. */\ninterface Attempt {\n result: SendResult;\n /** Absent for a free route, which opens no channel and signs nothing. */\n channelId: string | undefined;\n}\n\nasync function attempt(context: SendContext, params: AttemptParams): Promise<Attempt> {\n // A route priced at zero is deliberately free, and free means no claim.\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.\n //\n // So opening a payment channel to use one would be a real cost (gas, locked\n // collateral, an on-chain round trip) demanded for nothing. That is why this\n // path exists before `ensureChannel`: 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(context, params);\n\n const channelId = await context.ensureChannel(params.description);\n await settleWatermarkDoubt(context, channelId);\n const proof = await context.channels.signBalanceProof(channelId, params.amount);\n const signer = context.channels.getSignerForChannel(channelId);\n const claim = signer.buildClaimMessage(proof, context.senderId);\n const summary: ClaimSummary = {\n channelId,\n chain: context.chain,\n nonce: proof.nonce,\n cumulative: proof.transferredAmount,\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 claim as unknown as Record<string, unknown>\n );\n } catch (error) {\n // Nothing is known to have arrived, so the claim is repaid. See this\n // module's docs for why being one claim short is the safer failure.\n context.channels.rollbackAmount(channelId, params.amount);\n const greeting = asGreeting(error, params.carriage.kind, summary);\n // A greeting is the connector ANSWERING — it refused before routing, so\n // nothing travelled and nothing is in doubt.\n if (greeting) return { result: greeting, channelId };\n // Everything else is a transport failure or a timeout, where \"nothing\n // arrived\" is the safer guess rather than a fact. Say so, so the next claim\n // asks instead of guessing again.\n context.channels.markWatermarkUncertain(channelId);\n throw error;\n }\n\n if (claimWasRefused(result)) {\n context.channels.rollbackAmount(channelId, params.amount);\n // A refused claim means the two watermarks already disagreed about\n // something. The rollback is right when the disagreement was this packet's\n // own price; it changes nothing when the gap predates this request — which\n // is exactly the state a timeout leaves behind in a process that has since\n // restarted. Reconciling before the next claim covers both.\n context.channels.markWatermarkUncertain(channelId);\n } else {\n // The mirror image: the claim was BANKED, at the figure we signed it at, so\n // the two watermarks provably agree and any earlier doubt is settled — for\n // free, without the claim-state read it would otherwise have cost.\n context.channels.markWatermarkCertain(channelId);\n }\n\n return {\n result: toSendResult(result, params, summary),\n channelId,\n };\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(\n context: SendContext,\n params: AttemptParams\n): Promise<Attempt> {\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 { result: toSendResult(result, params, undefined), channelId: undefined };\n}\n\n/**\n * Settle a doubtful watermark before a claim is signed against it.\n *\n * Best effort by design: the read can fail — a connector that just timed out is\n * a connector that may still be unreachable — and a failure here must not turn\n * a request into a throw of its own. The doubt is simply left standing — only\n * an adoption, or a later claim the connector banks, clears it — so the next\n * attempt asks again, and this one proceeds on the local figure exactly as it\n * did before #671.\n */\nasync function settleWatermarkDoubt(\n context: SendContext,\n channelId: string\n): Promise<void> {\n if (context.reconcileWatermark === undefined) return;\n if (!context.channels.isWatermarkUncertain(channelId)) return;\n try {\n await context.reconcileWatermark(channelId);\n } catch (error) {\n (context.warn ?? console.warn)(\n `[toon] could not re-read the connector's watermark for channel ${channelId} ` +\n `(${error instanceof Error ? error.message : String(error)}). The last claim ` +\n 'on it was signed and never confirmed, so this one may under-advance and be ' +\n 'refused; the next attempt will ask again.'\n );\n }\n}\n\n/**\n * Retry once against a re-resolved channel, when — and only when — the refusal\n * was the connector saying it holds no record of the channel we drew on.\n */\nasync function maybeRetryStaleChannel(\n context: SendContext,\n first: Attempt,\n params: AttemptParams\n): Promise<SendResult | undefined> {\n const result = first.result;\n if (result.fulfilled) return undefined;\n if (!isUnknownChannelReject({ accepted: false, code: result.code, message: result.message })) {\n return undefined;\n }\n // A free route opens no channel, so there is no binding to retire.\n if (first.channelId === undefined) return undefined;\n const staleChannelId = first.channelId;\n if (!rejectNamesChannel(result.message, staleChannelId)) return undefined;\n if (!context.evictChannel(staleChannelId)) return undefined;\n\n (context.warn ?? console.warn)(\n `[toon] the connector refused a claim drawn on channel ${staleChannelId} ` +\n `(${result.code} — ${result.message}). It holds no record of that channel, ` +\n 'so its binding is retired (superseded, so any on-chain deposit stays ' +\n 'reclaimable) and the request is retried once against a re-resolved channel.'\n );\n\n const retry = await attempt(context, params);\n // Re-resolution landed on the same channel: the retry would repeat the reject,\n // so report the original refusal rather than spending a second claim on it.\n if (retry.channelId === first.channelId) return undefined;\n return retry.result;\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","/**\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 channel 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 settle on, since the node's own `settlements[]` 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: locking collateral is a transaction the user\n * pays gas for, and a constructor is not where that belongs. The first chain\n * access happens when something explicitly asks for it — `channel.open()`, or a\n * `send()` on a client left with the default `autoOpenChannel: true`.\n */\nimport { ConnectorEdgeClient, decodeConnectorPublicKey } from '../connector/ConnectorEdgeClient.js';\nimport type {\n ClaimStateOk,\n ClaimStateRequestEntry,\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 { ChannelManager } from '../channel/ChannelManager.js';\nimport { OnChainChannelClient } from '../channel/OnChainChannelClient.js';\nimport { EvmSigner } from '../signing/evm-signer.js';\nimport { SolanaSigner } from '../signing/solana-signer.js';\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 { send, type PaidWriteTransport, type SendContext } from './send.js';\nimport { ChainUnavailableError, ConfigError, chainUnavailableMessage } 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/** How long a claim-state challenge signature stays valid, in seconds. */\nconst CLAIM_STATE_CHALLENGE_TTL = 300;\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 channels: ChannelManager;\n private readonly channelFacade: ClientChannelFacade;\n private description: NodeSelfDescription;\n private onChain: OnChainChannelClient | undefined;\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 channels: ChannelManager;\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.channels = init.channels;\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.channelFacade = new ClientChannelFacade({\n config: init.config,\n channels: init.channels,\n describe: () => this.describe(),\n onChainClient: () => this.onChainClient(),\n });\n this.channel = this.channelFacade;\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 'claims with. Supply a `mnemonic`, the raw key for that chain, or an ' +\n 'explicit `senderId`.'\n );\n }\n\n const channels = new ChannelManager(\n resolved.identity.evm ? new EvmSigner(resolved.identity.evm.privateKey) : undefined,\n resolved.channelStore,\n {\n initialDeposit: resolved.deposit.toString(),\n settlementTimeout: resolved.settlementTimeout,\n }\n );\n if (resolved.identity.solana) {\n channels.registerChainSigner(\n 'solana',\n new SolanaSigner(\n resolved.identity.solana.secretKey.slice(0, 32),\n resolved.identity.solana.publicKey\n )\n );\n }\n\n return new ToonClient({\n config: resolved,\n edge,\n channels,\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 carry a claim on a\n * channel this connector recognises, because free traversal offered to anyone\n * is an amplifier. The claim **identifies rather than pays** — it is validated\n * in full against a price of zero, so possession of the channel is proven and a\n * replay is still refused, but no value need advance.\n *\n * @throws {ChannelNotOpenError} there is no channel to identify with.\n */\n async probe(\n destination: string\n ): Promise<{ accumulatedCost: bigint; code: string; message: string }> {\n const channelId = await this.channelFacade.ensure(this.description);\n // Zero value, fresh nonce: the gate's freshness check still applies, so the\n // nonce must advance even though the cumulative does not.\n const proof = await this.channels.signBalanceProof(channelId, 0n);\n const signer = this.channels.getSignerForChannel(channelId);\n const claim = signer.buildClaimMessage(proof, this.identity.senderId);\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 claim as unknown 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.state()`, which reports what this client has\n * signed. The two agree unless a claim was signed and never accepted, and this\n * is how a caller finds that out — the connector's figure is the one that\n * decides, so it is asked rather than derived.\n *\n * Ownership is proved with a signature over a challenge that is deliberately\n * DISTINCT from a balance proof, so it moves no value and can never be replayed\n * as a payment. A channel with no signer or no recorded context is skipped\n * rather than failing the batch.\n */\n async claimState(channelIds?: string[]): Promise<ClaimStateResult[]> {\n const ids = channelIds ?? this.channels.getTrackedChannels();\n if (ids.length === 0) return [];\n const expires = Math.floor(Date.now() / 1000) + CLAIM_STATE_CHALLENGE_TTL;\n\n const entries = await Promise.all(\n ids.map((channelId) => this.signClaimStateChallenge(channelId, expires))\n );\n const requests = entries.filter((e): e is ClaimStateRequestEntry => e !== undefined);\n if (requests.length === 0) return [];\n return this.edge.getClaimState(this.connector, requests);\n }\n\n /**\n * Release the BTP session and stop using this client.\n *\n * Does **not** touch the channel: closing a channel is an on-chain transaction\n * that starts a challenge period measured in hours, and conflating it with\n * releasing a socket would settle a user's collateral because their script\n * ended. `channel.close()` is that operation, and it is deliberately spelled\n * differently.\n *\n * The channel store is written through on every claim, so there is no flush to\n * 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 ensureChannel: (description) => this.channelFacade.ensure(description),\n evictChannel: (channelId) => this.evictChannel(channelId),\n channels: this.channels,\n reconcileWatermark: (channelId) => this.reconcileWatermark(channelId),\n transport: (description, destination) => this.transportFor(description, destination),\n senderId: this.identity.senderId,\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 * Re-read the connector's own watermark for one channel and adopt it\n * (toon-client#671).\n *\n * Called by {@link send} before signing a claim on a channel whose last claim\n * was signed and never confirmed — a transport error, a timeout, or a refusal.\n * A packet that timed out on a long path may have been delivered and banked\n * anyway, and the local figure would then be one claim behind for good: every\n * later claim under-advances and is refused. The connector's figure is the one\n * that decides, so it is asked, and {@link ChannelManager.adoptConnectorWatermark}\n * takes it (clamped to what this client has actually signed).\n *\n * A channel the connector cannot verify (`ok: false`) leaves the doubt in\n * place rather than resolving it wrongly — `\"unverified\"` covers \"no such\n * channel\" and \"bad signature\" identically, and neither is a watermark.\n */\n private async reconcileWatermark(channelId: string): Promise<void> {\n const entry = (await this.claimState([channelId])).find(\n (e): e is ClaimStateOk =>\n e.ok && (e.channelId ?? e.channelAccount ?? channelId) === channelId\n );\n if (entry === undefined) return;\n\n const adoption = this.channels.adoptConnectorWatermark(channelId, {\n nonce: entry.nonce,\n cumulativeClaimed: BigInt(entry.cumulativeClaimed),\n });\n // Silent when the two already agreed, which is the common case: the read\n // exists to be boring.\n if (!adoption.adopted || adoption.moved === 0n) return;\n console.warn(\n `[toon] the connector's watermark for channel ${channelId} was ` +\n `${adoption.moved > 0n ? 'ahead of' : 'behind'} this client's by ` +\n `${(adoption.moved < 0n ? -adoption.moved : adoption.moved).toString()} ` +\n `(a claim was signed and never confirmed). Adopted its figure — ` +\n `cumulative ${adoption.cumulative.toString()}, nonce ${adoption.nonce} — ` +\n 'so this request pays the right amount rather than being refused.' +\n (adoption.clampedTo !== undefined\n ? ` It reported more than this client has ever signed, so the figure was ` +\n `clamped to ${adoption.clampedTo.toString()}.`\n : '')\n );\n }\n\n /**\n * Retire the binding a refused claim was drawn on. `false` when there is\n * nothing to retire, which is {@link send}'s signal not to retry.\n */\n private evictChannel(channelId: string): boolean {\n const terms = this.channelFacade.terms;\n if (terms === undefined) return false;\n return this.channels.evictBinding(this.connector, terms, channelId);\n }\n\n /**\n * The on-chain client, built on first use.\n *\n * Lazy so `create()` opens no RPC connection. The RPC URL is keyed by the chain\n * the node actually publishes (`evm:84532`), not by a family name, because that\n * key is what the settlement entry names and what a channel is recorded under.\n */\n private onChainClient(): OnChainChannelClient {\n if (this.onChain) return this.onChain;\n const chainKeys = this.description.settlements.map((s) => s.chain);\n const chainRpcUrls: Record<string, string> = {};\n for (const entry of this.description.settlements) {\n chainRpcUrls[entry.chain] = this.config.rpcUrls[entry.kind];\n }\n if (chainKeys.length === 0) {\n throw new ChainUnavailableError(\n chainUnavailableMessage(this.config.chain, [], 'none'),\n []\n );\n }\n const client = new OnChainChannelClient({\n evmSigner: new EvmSigner(this.requireEvmKey()),\n chainRpcUrls,\n ...(this.config.rpcDispatcher !== undefined\n ? { rpcDispatcher: this.config.rpcDispatcher }\n : {}),\n ...(this.config.identity.solana\n ? {\n solanaConfig: {\n rpcUrl: this.config.rpcUrls.solana,\n // Same condition as the EVM dispatcher: proxied only when there is\n // a proxy and the caller has not opted RPC out of it.\n ...(this.config.rpcDispatcher !== undefined\n ? { rpcFetch: this.config.fetch }\n : {}),\n keypair: this.config.identity.solana.secretKey,\n // The DEFAULT only. Each channel opens under the program its own\n // terms name, because ADR 0053 binds that program into the signed\n // balance proof: opening under one and signing under another\n // produces claims no channel of ours lives under.\n programId: solanaProgramId(this.description) ?? '',\n },\n }\n : {}),\n });\n this.channels.setChannelClient(client);\n this.onChain = client;\n return client;\n }\n\n /**\n * The EVM key the on-chain client needs.\n *\n * `OnChainChannelClient` requires one even for a Solana-only deployment, since\n * it is the EVM transaction signer as well as the EVM claim signer. A\n * Solana-only client is a real configuration, so this reports the gap plainly\n * rather than constructing a signer over empty bytes.\n */\n private requireEvmKey(): Uint8Array {\n const key = this.config.identity.evm?.privateKey;\n if (key === undefined) {\n throw new ConfigError(\n 'On-chain channel operations need an EVM key even on a Solana-only node ' +\n '(the same object drives both chains). Supply a `mnemonic`, which derives ' +\n 'both, rather than a bare `solanaSecretKey`.'\n );\n }\n return key;\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 on the BTP auth greeting, so a connector crediting\n * earned increments learns the association without this client ever paying\n * for the introduction. `undefined` — no channel yet, or a chain with no\n * signer — leaves the greeting exactly as it would have been.\n */\n private async channelDeclaration(): Promise<BtpChannelDeclaration | undefined> {\n const channelId = this.channelFacade.id;\n if (channelId === undefined) return undefined;\n const expires = Math.floor(Date.now() / 1000) + CLAIM_STATE_CHALLENGE_TTL;\n return this.signClaimStateChallenge(channelId, expires);\n }\n\n /**\n * Sign the channel-ownership challenge for one channel. `undefined` for a\n * channel this client has no signer or no recorded context for — skipping is\n * right because the batch is a best-effort read, not a payment.\n */\n private async signClaimStateChallenge(\n channelId: string,\n expires: number\n ): Promise<ClaimStateRequestEntry | undefined> {\n const context = this.channels.getChannelContext(channelId);\n if (!context) return undefined;\n\n if (context.chainType === 'evm' && this.config.identity.evm) {\n const signature = await new EvmSigner(\n this.config.identity.evm.privateKey\n ).signClaimStateChallenge({\n chainId: context.chainId,\n tokenNetworkAddress: context.tokenNetworkAddress,\n channelId,\n expires,\n });\n return { blockchain: 'evm', channelId, expires, signature };\n }\n\n if (context.chainType === 'solana' && this.config.identity.solana) {\n const signature = await new SolanaSigner(\n this.config.identity.solana.secretKey.slice(0, 32),\n this.config.identity.solana.publicKey\n ).signClaimStateChallenge({ channelAccount: channelId, expires });\n return { blockchain: 'solana', channelAccount: channelId, expires, signature };\n }\n\n return undefined;\n }\n}\n\n/**\n * Which chain this client will settle on: the caller's choice when they made\n * one, else the first chain the node publishes that this client 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 offered = description.settlements.map((s) => s.chain);\n if (description.settlements.length === 0) {\n throw new ChainUnavailableError(\n chainUnavailableMessage(config.chain, offered, 'none'),\n offered\n );\n }\n if (config.chain !== undefined) {\n if (!description.settlements.some((s) => s.kind === 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 = description.settlements.find((s) => config.identity[s.kind] !== undefined);\n if (!match) {\n throw new ChainUnavailableError(\n chainUnavailableMessage(undefined, offered, 'no-key'),\n offered\n );\n }\n return match.kind;\n}\n\n/** The settlement program the node publishes for Solana, if it publishes one. */\nfunction solanaProgramId(description: NodeSelfDescription): string | undefined {\n for (const entry of description.settlements) {\n if (entry.kind === 'solana') return entry.programId;\n }\n return undefined;\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 the proxy-bound transport for a hidden-service connector, or returns\n * `undefined` for a clearnet one.\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 * A browser that somehow reached here would have failed at `resolveConfig`\n * already — a `.anyone` connector demands a `socksProxy`, and a browser cannot\n * supply a working one.\n *\n * An explicitly injected `fetch` or `createWebSocket` wins over the proxy's. A\n * caller who supplied their own transport has said something specific about how\n * bytes leave this process, and silently replacing it would be a worse surprise\n * than an unproxied request they chose.\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 { createHiddenServiceTransport, probeSocks5Proxy } = 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 transport = createHiddenServiceTransport(socksProxy);\n\n return {\n transport,\n config: {\n ...resolved,\n fetch: config.fetch ?? transport.fetch,\n createWebSocket: config.createWebSocket ?? transport.createWebSocket,\n rpcDispatcher: resolved.proxyRpc ? transport.dispatcher : undefined,\n },\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,cA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BAAgB,aAAsD;AAC7E,aAAW,SAAS,YAAY,aAAa;AAC3C,QAAI,MAAM,SAAS,SAAU,QAAO,MAAM;AAAA,EAC5C;AACA,SAAO;AACT;AAUA,SAAS,eAAe,aAAkC,WAA2B;AACnF,QAAM,YAAY,YAAY;AAC9B,MAAI,cAAc,OAAW,QAAO,GAAG,SAAS;AAChD,SAAO,4BAA4B,KAAK,SAAS,IAC7C,YACA,IAAI,IAAI,WAAW,SAAS,EAAE,SAAS;AAC7C;AAiBA,eAAe,kBACb,UACA,QACwF;AACxF,QAAM,aAAa,SAAS;AAC5B,MAAI,eAAe,OAAW,QAAO;AAErC,QAAM,EAAE,8BAA8B,iBAAiB,IAAI,MAAM,OAAO,qBAAuB;AAG/F,QAAM,iBAAiB,UAAU;AACjC,QAAM,YAAY,6BAA6B,UAAU;AAEzD,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,MACN,GAAG;AAAA,MACH,OAAO,OAAO,SAAS,UAAU;AAAA,MACjC,iBAAiB,OAAO,mBAAmB,UAAU;AAAA,MACrD,eAAe,SAAS,WAAW,UAAU,aAAa;AAAA,IAC5D;AAAA,EACF;AACF;","names":["data","protocolData","textEncoder","attempt","readString","readResponseMeta","require","readResponseMeta","http","resolveEndpoint","isConnectionError","attempt","toHex","settleableAt","ed25519","sleep","attempt","TOKEN_PROGRAM_ID","STATE_MAP","ed25519","ed25519","ed25519","OerErrorKind","encodeVarOctetString","decodeVarOctetString","EnvelopeErrorKind","decodeVarOctetString","concat","encodeVarOctetString","sha256","GiftWrapErrorKind","concat","ed25519","DEFAULT_TIMEOUT_MS","ed25519","settleableAt","match","createPublicClient","defineChain","parseEvmChainId","createPublicClient","defineChain","createPublicClient","createWalletClient","defineChain","ed25519","parseEvmChainId","defineChain","createPublicClient","createWalletClient","senderBalance","readDest","before","txHash","receipt","after","writeU64LE","ed25519","lamports","http","carriage"]}
|