@toon-protocol/client 0.25.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,250 +1,916 @@
1
1
  import * as _toon_protocol_core from '@toon-protocol/core';
2
2
  import { IlpPeerInfo, IlpSendResult, IlpClient, SwapPair, NetworkFamilyStatus, ConnectorAdminClient, ConnectorChannelClient, OpenChannelParams, OpenChannelResult, ChannelState } from '@toon-protocol/core';
3
3
  export { UI_RENDERER_KIND, UI_TAG, UiCoordinate, buildUiCoordinate, getUiCoordinate, parseUiCoordinate, selectLatestAddressable } from '@toon-protocol/core';
4
- import { NostrEvent, EventTemplate } from 'nostr-tools/pure';
4
+ import { UnsignedEvent, NostrEvent, EventTemplate } from 'nostr-tools/pure';
5
+ import { PrivateKeyAccount } from 'viem/accounts';
5
6
  import { MinaSignerClientLike, SettlementBundle } from '@toon-protocol/sdk';
6
7
  import { AccumulatedClaim } from '@toon-protocol/sdk/swap';
7
- import { PrivateKeyAccount, Hex, Address } from 'viem';
8
- import { PrivateKeyAccount as PrivateKeyAccount$1 } from 'viem/accounts';
8
+ import { PrivateKeyAccount as PrivateKeyAccount$1, Hex, Address } from 'viem';
9
9
  export { A2uiDecision, ConsentDecision, ConsentRequest, DispatchGuardInfo, DispatchInput, GenerateContext, GeneratedRenderer, GenerativeDecision, GenerativeFallbackOptions, GenerativeFallbackRenderer, GenerativeFallbackResult, GuardedDispatchInput, IntentClassification, KindRegistry, MIME_A2UI, MIME_MCP_APP, McpUiDecision, NativeDecision, PublishBackOptions, RenderBranch, RenderDecision, RenderTrust, RendererGenerator, RendererPin, RendererPinStore, RendererPublisher, RendererSigner, ResolvedCoordinate, SwapApproval, SwapDecision, SwapRejection, SwapRejectionReason, UiResource, VerifyRendererInput, WidgetIntent, buildConsentRequest, buildRendererEventTemplate, classifyIntent, deterministicGenerator, extractUiResource, guardedRenderDispatch, isTrustDowngrade, publishBackCoordinate, renderDeterministicHtml, renderDispatch, resolveRendererMime, resolveUiCoordinate, resolveUiRenderer, verifyRendererTrust } from './render/index.js';
10
10
 
11
- /** One on-chain wallet token balance. `amount` is base-unit integer, decimal. */
12
- interface WalletBalance {
13
- chain: 'evm' | 'solana' | 'mina';
14
- address: string;
15
- amount: string;
16
- /** Token symbol, when resolved (e.g. `'USDC'`, `'MINA'`). */
17
- asset?: string;
18
- /** Token decimals, when resolved. */
19
- assetScale?: number;
11
+ /**
12
+ * Base error class for all TOON client errors.
13
+ */
14
+ declare class ToonClientError extends Error {
15
+ readonly code: string;
16
+ constructor(message: string, code: string, cause?: Error);
20
17
  }
21
18
  /**
22
- * One asset amount within a chain's wallet view — the native coin or one token.
23
- * `amount` is a base-unit integer, decimal string.
19
+ * Network error for connection failures (ECONNREFUSED, ETIMEDOUT).
20
+ * These errors trigger retry logic with exponential backoff.
24
21
  */
25
- interface WalletTokenAmount {
26
- /** Asset symbol (e.g. `'ETH'`, `'SOL'`, `'MINA'`, `'USDC'`), when known. */
27
- symbol?: string;
28
- /** Base-unit integer, decimal string. */
29
- amount: string;
30
- /** Decimals for formatting (ETH 18, SOL 9, MINA 9, USDC 6). */
31
- decimals?: number;
32
- /** Token contract / SPL mint address. Absent for the native coin. */
33
- address?: string;
22
+ declare class NetworkError extends ToonClientError {
23
+ constructor(message: string, cause?: Error);
34
24
  }
35
25
  /**
36
- * The full wallet view for ONE chain the identity is configured for: the native
37
- * coin plus every configured token, keyed by the chain's full key (e.g.
38
- * `'evm:31337'`). `unreadable` marks a chain whose RPC could not be reached at
39
- * all — the caller renders a per-chain notice rather than crashing.
26
+ * Connector error for 5xx server errors.
27
+ * These errors indicate the connector is unavailable or malfunctioning.
40
28
  */
41
- interface WalletChainBalances {
42
- chain: 'evm' | 'solana' | 'mina';
43
- /** Full chain key, e.g. `'evm:31337'`, `'solana'`, `'mina'`. */
44
- chainKey: string;
45
- address: string;
46
- /** Native-coin balance, when readable. */
47
- native?: WalletTokenAmount;
48
- /** Configured token balances (e.g. USDC), each best-effort. */
49
- tokens: WalletTokenAmount[];
50
- /** True when nothing on this chain could be read (RPC unreachable). */
51
- unreadable?: boolean;
52
- /** First read error, when any read failed (for diagnostics). */
53
- error?: string;
29
+ declare class ConnectorError extends ToonClientError {
30
+ constructor(message: string, cause?: Error);
54
31
  }
55
- /** Read an ERC-20 token balance (balance + decimals + symbol) for `owner`. */
56
- declare function readEvmTokenBalance(opts: {
57
- rpcUrl: string;
58
- chainKey: string;
59
- tokenAddress: string;
60
- owner: string;
61
- }): Promise<WalletBalance>;
62
- /** Read the native ETH balance (wei) for `owner` via `eth_getBalance`. */
63
- declare function readEvmNativeBalance(opts: {
64
- rpcUrl: string;
65
- chainKey: string;
66
- owner: string;
67
- }): Promise<WalletTokenAmount>;
68
- /** Read the native SOL balance (lamports) for `owner` via the `getBalance` RPC. */
69
- declare function readSolanaNativeBalance(opts: {
70
- rpcUrl: string;
71
- owner: string;
72
- fetchImpl?: typeof fetch;
73
- }): Promise<WalletTokenAmount>;
74
- /** Read the SPL-token balance for `owner`'s token account(s) of `mint`. */
75
- declare function readSolanaTokenBalance(opts: {
76
- rpcUrl: string;
77
- mint: string;
78
- owner: string;
79
- fetchImpl?: typeof fetch;
80
- }): Promise<WalletBalance>;
81
- /** Read the native MINA balance (nanomina) for `owner` via the Mina GraphQL API. */
82
- declare function readMinaBalance(opts: {
83
- graphqlUrl: string;
84
- owner: string;
85
- fetchImpl?: typeof fetch;
86
- }): Promise<WalletBalance>;
87
32
  /**
88
- * Per-chain inputs for {@link readWalletBalances}: the resolved RPC URL, the
89
- * identity's address on that chain, and the configured token (USDC) — sourced by
90
- * the caller from the network topology / presets, never hardcoded here. A chain
91
- * key absent from the object is simply not read.
33
+ * Validation error for invalid input parameters.
34
+ * These errors are thrown before making any HTTP requests.
92
35
  */
93
- interface WalletBalanceSources {
94
- evm?: {
95
- chainKey: string;
96
- rpcUrl: string;
97
- owner: string;
98
- tokenAddress?: string;
99
- };
100
- solana?: {
101
- chainKey?: string;
102
- rpcUrl: string;
103
- owner: string;
104
- tokenMint?: string;
105
- };
106
- mina?: {
107
- chainKey?: string;
108
- graphqlUrl: string;
109
- owner: string;
110
- /** Settlement-token Field id (decimal). Reads the token balance when set. */
111
- tokenId?: string;
112
- };
113
- /** Injectable fetch (Solana/Mina JSON-RPC & GraphQL) for tests. */
114
- fetchImpl?: typeof fetch;
36
+ declare class ValidationError extends ToonClientError {
37
+ constructor(message: string, cause?: Error);
115
38
  }
116
39
  /**
117
- * Read the full wallet view — native coin + configured tokens — for every chain
118
- * in `sources`, keyed per chain. FREE: read-only RPC, no signing. Each chain is
119
- * read independently and in parallel; a chain whose RPC is unreachable degrades
120
- * to `{ unreadable: true, error }` instead of failing the others. Within a chain
121
- * the native and token reads are independent, so a native read can succeed even
122
- * if the token read fails (and vice versa).
40
+ * Thrown when the one-time on-chain payment-channel OPEN reverts because the
41
+ * local settlement wallet has no native gas to pay for its own
42
+ * approve/openChannel/setTotalDeposit transactions. This is the channel OPEN
43
+ * only — per-write settlement rides ILP-over-HTTP and never spends gas. We
44
+ * remap ONLY this case so callers get an actionable message (fund the wallet)
45
+ * instead of the raw viem "...exceeds the balance of the account" string
46
+ * (toon-meta#65). Retryable once the wallet is funded; the underlying viem/RPC
47
+ * error is preserved as `cause`.
123
48
  */
124
- declare function readWalletBalances(sources: WalletBalanceSources): Promise<WalletChainBalances[]>;
125
-
49
+ declare class ChannelFundingError extends ToonClientError {
50
+ readonly retryable = true;
51
+ constructor(message: string, cause?: Error);
52
+ }
126
53
  /**
127
- * The structured envelope (ADR 0018): what a packet carries between a
128
- * connector and the app behind it, encoded with the same OER primitives an ILP
129
- * packet already uses rather than as HTTP text.
130
- *
131
- * A faithful port of `connector_domain::envelope`
132
- * (`crates/connector-domain/src/envelope.rs`) — a method, target, ordered
133
- * headers and body going in; a two-byte big-endian status, headers and body
134
- * coming back. `vectors/wire-vectors.json` is the contract this is checked
135
- * against, and `wire-vectors.test.ts` is where that check happens; the prose
136
- * here describes the same thing but the bytes decide.
137
- *
138
- * ─── Why not HTTP text ─────────────────────────────────────────────────────
139
- * `utils/store-envelope.ts` builds latin1 HTTP/1.1 request text and
140
- * `utils/fulfill-http.ts` hand-parses a status line and scans for `\r\n\r\n`,
141
- * which is how they acquired leniencies nobody chose: a missing header/body
142
- * separator yielding an empty body, blank header lines skipped, spaces
143
- * tolerated inside the target. A structured encoding has exactly one
144
- * representation per message and nothing to smuggle. This module lands BESIDE
145
- * those two rather than replacing them — the swap is a later child — so it can
146
- * be reviewed against the vectors in isolation.
147
- *
148
- * ─── Headers are a list, not a map ─────────────────────────────────────────
149
- * A count prefix then `(name, value)` pairs in order. Both header ORDER and
150
- * DUPLICATE NAMES are meaningful on this wire and both survive a round trip; a
151
- * `Record<string, string>` would silently destroy each.
54
+ * Thrown when a persisted peer→channel binding names a channel whose CLAIM
55
+ * WATERMARK (nonce + cumulative amount) is missing from the channel store.
152
56
  *
153
- * Pure: no keys, no I/O, no clock. `@noble/*` is not involved.
57
+ * Resuming it anyway would re-track the live channel at nonce 0, and the
58
+ * connector rejects every claim below the nonce it has already seen — the F01
59
+ * failure from the live measurement runs. Opening a fresh channel instead would
60
+ * silently strand the collateral in the existing one. Neither is safe to do
61
+ * quietly, so this is a hard error: the operator decides (settle the old
62
+ * channel, or restore the watermark file). Never delete a channel store for a
63
+ * live channel.
154
64
  */
65
+ declare class ChannelResumeError extends ToonClientError {
66
+ constructor(message: string, cause?: Error);
67
+ }
155
68
  /**
156
- * Every distinguishable way an envelope can fail to decode. These strings are
157
- * the vector file's `expected_error` values verbatim — the same names
158
- * `EnvelopeError` uses in `connector-domain` — so a replay compares reasons,
159
- * not just "it threw".
160
- *
161
- * There is deliberately no catch-all: a decoder with an `Invalid` bucket is a
162
- * decoder that can be lenient without anyone noticing.
69
+ * Thrown by {@link ../transfer.js!sendTransfer} when the sender cannot cover
70
+ * the requested amount (plus, where applicable, the chain's own transaction
71
+ * fee) on the source chain. A PREFLIGHT failure — thrown before any
72
+ * transaction is built or submitted, so it never costs gas/fees.
163
73
  */
164
- declare enum EnvelopeErrorKind {
165
- /** The buffer ends before the envelope does. */
166
- BufferUnderflow = "buffer_underflow",
167
- /** A length determinant that is not the minimal encoding of its value. */
168
- NonCanonicalLength = "non_canonical_length",
169
- /** A length determinant wider than eight bytes. */
170
- LengthDeterminantOverflow = "length_determinant_overflow",
171
- /** The type byte is not the one the requested direction requires. */
172
- InvalidType = "invalid_type",
173
- /** A field that must be UTF-8 is not. */
174
- InvalidUtf8 = "invalid_utf8",
175
- /** Bytes remain after a fully decoded envelope. */
176
- TrailingBytes = "trailing_bytes"
74
+ declare class InsufficientBalanceError extends ToonClientError {
75
+ constructor(message: string, cause?: Error);
177
76
  }
178
77
  /**
179
- * A refusal to decode. `kind` is the machine-readable reason; `field` names
180
- * the offending field for {@link EnvelopeErrorKind.InvalidUtf8}, matching
181
- * `EnvelopeError::InvalidUtf8(&'static str)` on the Rust side.
78
+ * Thrown when an EVM RPC never converges on a just-confirmed channel open —
79
+ * the read-after-write hole behind `sepolia.base.org`'s load balancer, whose
80
+ * replicas can serve a state that predates the `openChannel` receipt, making
81
+ * the follow-up `setTotalDeposit` revert `InvalidChannelState()` (#489).
182
82
  */
183
- declare class EnvelopeError extends Error {
184
- readonly kind: EnvelopeErrorKind;
185
- readonly field?: string | undefined;
186
- constructor(kind: EnvelopeErrorKind, field?: string | undefined);
83
+ declare class StaleRpcReadError extends ToonClientError {
84
+ readonly retryable = true;
85
+ constructor(message: string, cause?: Error);
187
86
  }
188
- /** One `(name, value)` header, in wire order. Duplicates are legal. */
189
- type EnvelopeHeader = readonly [name: string, value: string];
190
- /** The request a connector is to make of the app behind a terminated route. */
191
- interface EnvelopeRequest {
192
- method: string;
193
- target: string;
194
- headers: readonly EnvelopeHeader[];
195
- body: Uint8Array;
87
+ /**
88
+ * Thrown by {@link ../transfer.js!sendTransfer} when `chain` is not one this
89
+ * client can send on — either an unrecognized chain identifier, or a
90
+ * recognized chain the client instance has no configuration for (no
91
+ * `chainRpcUrls` entry, no `solanaChannel`, no `minaChannel`). Distinct from
92
+ * {@link InvalidAddressError} (the chain is fine, the destination isn't) and
93
+ * from a plain unsupported chain/asset combination (see the transfer module
94
+ * for chain-specific gaps, e.g. the Mina settlement token).
95
+ */
96
+ declare class UnknownChainError extends ToonClientError {
97
+ constructor(message: string, cause?: Error);
196
98
  }
197
- /** The app's response back to the connector. */
198
- interface EnvelopeResponse {
199
- /** HTTP status, two bytes big-endian on the wire (`0..=65535`). */
200
- status: number;
201
- headers: readonly EnvelopeHeader[];
202
- body: Uint8Array;
99
+ /**
100
+ * Thrown by {@link ../transfer.js!sendTransfer} when the destination address
101
+ * is malformed for the target chain (wrong format, wrong length, invalid
102
+ * charset) — checked BEFORE any transaction is built, so a typo never costs
103
+ * gas/fees or risks sending funds into a black hole.
104
+ */
105
+ declare class InvalidAddressError extends ToonClientError {
106
+ constructor(message: string, cause?: Error);
203
107
  }
204
- /** Either direction, tagged — the shape the vector file's `decoded` carries. */
205
- type Envelope = ({
206
- direction: 'request';
207
- } & EnvelopeRequest) | ({
208
- direction: 'response';
209
- } & EnvelopeResponse);
210
- /** Encode a request envelope. The inverse of {@link decodeEnvelopeRequest}. */
211
- declare function encodeEnvelopeRequest(request: EnvelopeRequest): Uint8Array;
212
108
  /**
213
- * Decode a request envelope, consuming the WHOLE buffer.
214
- *
215
- * @throws {EnvelopeError} and nothing else, for any input whatsoever.
109
+ * Thrown by {@link ../transfer.js!sendTransfer} when a send was ACCEPTED by
110
+ * the chain (a landed, non-reverted transaction / a node-accepted payment)
111
+ * but the destination's observed balance never rose by the sent amount
112
+ * within the bounded wait. This is the failure {@link sendTransfer} exists to
113
+ * catch: the devnet faucet's Solana leg has been observed returning success
114
+ * with a real transaction signature while delivering 0 lamports
115
+ * (toon-protocol/connector#691) — trusting the send call's return value alone
116
+ * would report a funded destination that in fact holds nothing.
216
117
  */
217
- declare function decodeEnvelopeRequest(buf: Uint8Array): EnvelopeRequest;
218
- /** Encode a response envelope. The inverse of {@link decodeEnvelopeResponse}. */
219
- declare function encodeEnvelopeResponse(response: EnvelopeResponse): Uint8Array;
118
+ declare class TransferNotDeliveredError extends ToonClientError {
119
+ constructor(message: string, cause?: Error);
120
+ }
220
121
  /**
221
- * Decode a response envelope, consuming the WHOLE buffer.
222
- *
223
- * @throws {EnvelopeError} and nothing else, for any input whatsoever.
122
+ * Thrown by {@link ../transfer.js!sendTransfer} for a chain/asset combination
123
+ * that is not implemented yet — e.g. the Mina settlement token (a custom
124
+ * token transfer needs an o1js zkApp-approval path this client doesn't build
125
+ * yet; native MINA is unaffected). Mirrors the documented Mina
126
+ * deposit/close/settle gaps in {@link ../channel/OnChainChannelClient.js!OnChainChannelClient}.
224
127
  */
225
- declare function decodeEnvelopeResponse(buf: Uint8Array): EnvelopeResponse;
226
- /** Encode either direction from its tagged form. */
227
- declare function encodeEnvelope(envelope: Envelope): Uint8Array;
128
+ declare class TransferUnsupportedError extends ToonClientError {
129
+ constructor(message: string, cause?: Error);
130
+ }
228
131
  /**
229
- * Decode as the named direction. The direction is an INPUT, never guessed from
230
- * the type byte: a caller that asked for a request and got a response has been
231
- * handed the wrong bytes, and `invalid_type` is the honest answer.
132
+ * True when `err` (or any error in its nested `cause` chain) is an
133
+ * insufficient-native-gas revert. viem wraps the node error one or more levels
134
+ * deep, so the whole chain is flattened and scanned.
232
135
  */
233
- declare function decodeEnvelope(buf: Uint8Array, direction: 'request' | 'response'): Envelope;
136
+ declare function isInsufficientGasError(err: unknown): boolean;
234
137
 
235
138
  /**
236
- * Solana payment-channel parameters supplied via `ToonClientConfig.solanaChannel`.
139
+ * Ask a terminating connector who it is and what it charges — the step that
140
+ * has to happen BEFORE a packet can be formed at all.
237
141
  *
238
- * Mirrors the `SolanaChannelConfig` consumed by `OnChainChannelClient`, minus
239
- * the Ed25519 keypair (derived from the client's `mnemonic`, see
240
- * `ToonClientConfig.solanaChannel`).
241
- */
242
- interface SolanaChannelClientOptions {
243
- /** Solana JSON-RPC URL used to open the channel + read PDA state. */
244
- rpcUrl: string;
245
- /** Deployed payment-channel program id (base58). */
246
- programId: string;
247
- /**
142
+ * ADR 0018 makes holding the terminating connector's public key a
143
+ * precondition of forming a packet: `Prepare.data` is sealed to that key, and
144
+ * sealing to the wrong one is a confidentiality failure, not a delivery
145
+ * failure. ADR 0022 says the connector *answers* — it never announces — so
146
+ * both facts are fetched from the connector's own client edge, on the same
147
+ * origin this client already POSTs `/ilp` to
148
+ * (`docs/protocol/client-edge-spec.md` §1.7):
149
+ *
150
+ * - `GET /ilp/identity` → `{ "keyId": "...", "publicKey": "0x04..." }` — the
151
+ * uncompressed secp256k1 key, 65 bytes, `0x`-prefixed hex.
152
+ * - `GET /ilp/routes/price?destination=<ILP address>` →
153
+ * `{ "destination": "...", "price": 100 }`, or `404` when no
154
+ * locally-terminated route matches.
155
+ *
156
+ * Both are unauthenticated and neither changes state.
157
+ *
158
+ * ─── What this module refuses to do ────────────────────────────────────────
159
+ * Unlike the 402-challenge parser next door (which degrades gracefully so an
160
+ * unrecognised connector shape falls back to the vanilla 402), an identity is
161
+ * parsed STRICTLY. A key that is the wrong length, not `0x04`-prefixed, or not
162
+ * valid hex is refused with a distinguishable error rather than carried
163
+ * forward: a half-understood key would be sealed to, and the failure would be
164
+ * silent. There is no "best effort" reading of a public key.
165
+ *
166
+ * Pure transport + parsing: no keys are held, nothing is signed, and the only
167
+ * state is the identity cache.
168
+ */
169
+
170
+ /** The terminating connector's own identity, as reported by `GET /ilp/identity`. */
171
+ interface ConnectorIdentity {
172
+ /** The key id identifying the key (opaque to this client). */
173
+ keyId: string;
174
+ /** The uncompressed secp256k1 public key — exactly 65 raw bytes, leading `0x04`. */
175
+ publicKey: Uint8Array;
176
+ /** The key exactly as reported, `0x`-prefixed lowercase hex (65 bytes → 132 chars). */
177
+ publicKeyHex: string;
178
+ /** The normalized client-edge base URL this identity was read from. */
179
+ endpoint: string;
180
+ }
181
+ /**
182
+ * The channel-opening facts a settling connector carries in its x402
183
+ * greeting (connector #617): everything a buyer needs to OPEN a channel
184
+ * with the node, learned by ASKING (ADR 0022) rather than from a
185
+ * kind:10032 announce the Rust fleet never makes.
186
+ */
187
+ interface ConnectorSettlementTerms {
188
+ /** `evm:<chainId>` — the chain the node's settlement backend runs on. */
189
+ chain: string;
190
+ /** The on-chain counterparty a buyer opens a channel WITH. */
191
+ settlementAddress: string;
192
+ /** The stable TokenNetworkRegistry factory address. */
193
+ tokenNetworkRegistry: string;
194
+ /** The resolved TokenNetwork — the EIP-712 verifyingContract. */
195
+ tokenNetwork: string;
196
+ tokenAddress: string;
197
+ /** Informational; claims are already in base units. */
198
+ decimals: number;
199
+ }
200
+ /**
201
+ * The Solana twin of {@link ConnectorSettlementTerms} (connector #632): what
202
+ * an unaffiliated buyer needs to open a channel against a Solana settlement
203
+ * backend's deployed `payment-channel` program instance.
204
+ */
205
+ interface ConnectorSolanaSettlementTerms {
206
+ /** Always `'solana'` — unlike EVM there is no chain id to append. */
207
+ chain: string;
208
+ /** The on-chain counterparty a buyer opens a channel WITH, base58. */
209
+ settlementAddress: string;
210
+ /** The deployed `payment-channel` program instance, base58. */
211
+ programId: string;
212
+ /** The SPL mint every channel this backend opens settles in, base58. */
213
+ tokenAddress: string;
214
+ /** Informational; claims are already in base units. */
215
+ decimals: number;
216
+ }
217
+ /**
218
+ * One chain's entry in the x402 greeting's per-chain `settlements` list
219
+ * (connector #632). `kind` is added by this parser, not present on the wire
220
+ * — the wire is untagged, disambiguated structurally (`tokenNetworkRegistry`
221
+ * names EVM, `programId` names Solana).
222
+ */
223
+ type ConnectorChainSettlementTerms = ({
224
+ kind: 'evm';
225
+ } & ConnectorSettlementTerms) | ({
226
+ kind: 'solana';
227
+ } & ConnectorSolanaSettlementTerms);
228
+ /**
229
+ * A route's terms as the x402 greeting states them: the price, plus (from a
230
+ * settling node) the channel-opening facts. `settlement` is absent exactly
231
+ * when the node has no settlement backend — the wire's own shape. `settlements`
232
+ * is the additive per-chain list (connector #632): one entry per chain the
233
+ * node settles on, including the same EVM entry `settlement` already carries.
234
+ * Absent — not an empty array — on a node with no settlement backend, or one
235
+ * still answering the pre-#632 greeting shape.
236
+ */
237
+ interface ConnectorRouteTerms {
238
+ destination: string;
239
+ price: string;
240
+ settlement?: ConnectorSettlementTerms;
241
+ settlements?: ConnectorChainSettlementTerms[];
242
+ }
243
+ /** What a locally-terminated route costs, as reported by `GET /ilp/routes/price`. */
244
+ interface ConnectorRoutePrice {
245
+ /** The ILP destination that was asked about (echoed by the connector). */
246
+ destination: string;
247
+ /** The price in ILP base units of the route `destination` matched. */
248
+ price: bigint;
249
+ }
250
+ /**
251
+ * One `POST /ilp/claim-state` request entry: proof of ownership of a channel
252
+ * this client controls, via a signature over a challenge distinct from a
253
+ * real claim's balance-proof (never reusable as one). `signature` is
254
+ * `EvmSigner.signClaimStateChallenge`'s `0x`-prefixed 65-byte hex for `evm`,
255
+ * `SolanaSigner.signClaimStateChallenge`'s base64 64-byte Ed25519 for
256
+ * `solana`.
257
+ */
258
+ type ClaimStateRequestEntry = {
259
+ blockchain: 'evm';
260
+ channelId: string;
261
+ expires: number;
262
+ signature: string;
263
+ } | {
264
+ blockchain: 'solana';
265
+ channelAccount: string;
266
+ expires: number;
267
+ signature: string;
268
+ };
269
+ /**
270
+ * The credited/spendable position of one channel this client asked about —
271
+ * the runway source of truth (toon-meta#261/#262 decision 9). Money fields
272
+ * are decimal strings (never a bare JS number, which cannot represent a
273
+ * value past 2^53 exactly).
274
+ */
275
+ interface ClaimStateOk {
276
+ blockchain: 'evm' | 'solana';
277
+ channelId?: string;
278
+ channelAccount?: string;
279
+ ok: true;
280
+ /** On-chain deposit, or `null` for a channel this connector only DECLARED. */
281
+ depositTotal: string | null;
282
+ /** The channel's watermark; `"0"` if this connector has never accepted a claim. */
283
+ cumulativeClaimed: string;
284
+ /** `depositTotal - cumulativeClaimed`; `null` exactly when `depositTotal` is. */
285
+ available: string | null;
286
+ nonce: number;
287
+ /**
288
+ * Best-effort and non-durable (unlike every other field here): `null`
289
+ * means "unknown", NEVER "never claimed" — see client-edge-spec.md §1.10.
290
+ */
291
+ lastClaimTime: number | null;
292
+ }
293
+ /**
294
+ * A failed claim-state entry. `error` is deliberately collapsed to two
295
+ * causes (unlike a claim's own refusal taxonomy) so a caller learns nothing
296
+ * about a channel it does not control: `"unverified"` covers "no such
297
+ * channel" and "bad signature" identically.
298
+ */
299
+ interface ClaimStateFailed {
300
+ blockchain: 'evm' | 'solana';
301
+ channelId?: string;
302
+ channelAccount?: string;
303
+ ok: false;
304
+ error: 'expired' | 'unverified';
305
+ }
306
+ type ClaimStateResult = ClaimStateOk | ClaimStateFailed;
307
+ /**
308
+ * Every distinguishable way asking a connector for its identity or terms can
309
+ * fail. Each code names exactly one cause; there is no catch-all, because the
310
+ * caller's next move differs per cause (retry a transport failure; never
311
+ * retry a malformed key).
312
+ */
313
+ type ConnectorEdgeErrorCode =
314
+ /** Non-2xx from `GET /ilp/identity`. */
315
+ 'IDENTITY_HTTP_STATUS'
316
+ /** `GET /ilp/identity` answered 2xx with a body that is not the documented object. */
317
+ | 'IDENTITY_MALFORMED'
318
+ /** `publicKey` is present but is not `0x`-prefixed even-length hex. */
319
+ | 'IDENTITY_KEY_NOT_HEX'
320
+ /** `publicKey` decodes, but not to exactly 65 bytes. */
321
+ | 'IDENTITY_KEY_LENGTH'
322
+ /** `publicKey` is 65 bytes but does not start with the SEC1 uncompressed tag `0x04`. */
323
+ | 'IDENTITY_KEY_NOT_UNCOMPRESSED'
324
+ /** Non-2xx, non-404 from `GET /ilp/routes/price` (404 is not an error — see below). */
325
+ | 'ROUTE_PRICE_HTTP_STATUS'
326
+ /** `GET /ilp/routes/price` answered 2xx with a body that is not the documented object. */
327
+ | 'ROUTE_PRICE_MALFORMED'
328
+ /** A destination that cannot be put in a query string was asked about. */
329
+ | 'INVALID_DESTINATION'
330
+ /** A 402 greeting whose body is not the documented x402 shape (or whose
331
+ * optional `settlement` facts are present but malformed — refused rather
332
+ * than silently dropped, since they would be opened AGAINST). */
333
+ | 'TERMS_MALFORMED'
334
+ /** Non-2xx from `POST /ilp/claim-state`. */
335
+ | 'CLAIM_STATE_HTTP_STATUS'
336
+ /** `POST /ilp/claim-state` answered 2xx with a body that is not the documented shape. */
337
+ | 'CLAIM_STATE_MALFORMED';
338
+ /**
339
+ * A refusal to carry a connector's answer forward. Distinct from
340
+ * {@link NetworkError} (which this module throws for a transport failure), so
341
+ * "the connector is unreachable" and "the connector answered something I will
342
+ * not seal to" are never confused.
343
+ */
344
+ declare class ConnectorEdgeError extends ToonClientError {
345
+ /** Narrowed from `ToonClientError`'s `string`; type-only, no runtime field. */
346
+ readonly code: ConnectorEdgeErrorCode;
347
+ constructor(message: string, code: ConnectorEdgeErrorCode, cause?: Error);
348
+ }
349
+ /**
350
+ * Normalize any client-edge URL a caller already holds into the base the
351
+ * `/ilp/*` routes hang off.
352
+ *
353
+ * Callers reach this module holding whatever the x402 offer or their config
354
+ * gave them — `https://apex.example`, `https://apex.example/`, or the
355
+ * `POST /ilp` endpoint `https://apex.example/ilp` itself. All three name the
356
+ * same client edge, so all three normalize to `https://apex.example`.
357
+ */
358
+ declare function connectorEdgeBaseUrl(endpoint: string): string;
359
+ /**
360
+ * Decode a `0x`-prefixed hex public key into its 65 raw bytes, refusing
361
+ * anything that is not exactly one uncompressed secp256k1 key.
362
+ */
363
+ declare function decodeConnectorPublicKey(publicKeyHex: string): Uint8Array;
364
+ /**
365
+ * Parse an already-decoded `GET /ilp/identity` body. Exported so the shape the
366
+ * connector actually emits can be pinned without standing up a server.
367
+ */
368
+ declare function parseConnectorIdentity(body: unknown, endpoint: string): ConnectorIdentity;
369
+ /** Parse an already-decoded `GET /ilp/routes/price` 200 body. */
370
+ declare function parseConnectorRoutePrice(body: unknown): ConnectorRoutePrice;
371
+ /**
372
+ * Parse an already-decoded `POST /ilp/claim-state` body. Exported so the wire
373
+ * shape is testable without a server. Refuses a body that is not the
374
+ * documented `{ channels: [...] }` object, or any entry within it that is
375
+ * not the documented ok/failed shape — a half-understood credited balance
376
+ * would misreport an agent's runway, which is the one thing this endpoint
377
+ * exists to get right (toon-meta#262 decision 9).
378
+ */
379
+ declare function parseClaimStateResponse(body: unknown): ClaimStateResult[];
380
+ interface ConnectorEdgeClientConfig {
381
+ /** HTTP fetch implementation. Default: global `fetch`. Injectable for tests. */
382
+ fetch?: typeof fetch;
383
+ /** Per-request timeout in milliseconds. Default 10_000. */
384
+ timeout?: number;
385
+ }
386
+ /**
387
+ * Asks connectors for their identity and their terms, caching each identity
388
+ * per client-edge endpoint and each route price per (endpoint, destination).
389
+ *
390
+ * The cache is per endpoint rather than per client instance because a sender
391
+ * routinely speaks to several connectors, and re-fetching a key per packet
392
+ * would put a network round trip in front of every send. Nothing here expires
393
+ * on a timer: an operator key rotation, or a route being repriced, is a
394
+ * deliberate event, so {@link invalidateIdentity} / {@link invalidateRoutePrice}
395
+ * are how a stale answer is dropped.
396
+ *
397
+ * A price is cached the same way and for the same reason (toon-client#452):
398
+ * under ADR 0020 a route's price is FLAT — one handler, one price — so it does
399
+ * not vary with what is being sent, and asking again per packet would buy
400
+ * nothing but latency.
401
+ */
402
+ declare class ConnectorEdgeClient {
403
+ private readonly fetchImpl;
404
+ private readonly timeout;
405
+ private readonly identities;
406
+ private readonly prices;
407
+ constructor(config?: ConnectorEdgeClientConfig);
408
+ /**
409
+ * The terminating connector's public key, fetched once per endpoint.
410
+ *
411
+ * @param endpoint any client-edge URL (`https://apex`, `https://apex/ilp`).
412
+ * @param options `forceRefresh` bypasses (and replaces) the cache entry.
413
+ */
414
+ getIdentity(endpoint: string, options?: {
415
+ forceRefresh?: boolean;
416
+ }): Promise<ConnectorIdentity>;
417
+ /**
418
+ * Drop a cached identity — one endpoint's, or every endpoint's when
419
+ * `endpoint` is omitted. The way to react to a key rotation.
420
+ */
421
+ invalidateIdentity(endpoint?: string): void;
422
+ /** Whether an identity for `endpoint` is already held (no request is made). */
423
+ hasCachedIdentity(endpoint: string): boolean;
424
+ /**
425
+ * What `destination` costs at this connector, or `null` when the connector
426
+ * answers `404` — no locally-terminated route matches it.
427
+ *
428
+ * `null` is the answer to "you do not terminate this", which is information;
429
+ * a transport failure throws {@link NetworkError} instead, so a caller can
430
+ * always tell "not mine" from "could not ask".
431
+ *
432
+ * Fetched once per (endpoint, destination) and reused. ADR 0020 makes a
433
+ * price flat per handler, so it does not vary with the packet — a route
434
+ * being repriced is an operator event, and {@link invalidateRoutePrice} is
435
+ * how a caller reacts to one.
436
+ *
437
+ * @param options `forceRefresh` bypasses (and replaces) the cache entry.
438
+ */
439
+ getRoutePrice(endpoint: string, destination: string, options?: {
440
+ forceRefresh?: boolean;
441
+ }): Promise<ConnectorRoutePrice | null>;
442
+ /**
443
+ * Ask a route for its full x402 terms — the greeting a claimless PREPARE
444
+ * is answered with (client-edge-spec.md §1.4) — including, from a settling
445
+ * node, the channel-opening facts (connector #617).
446
+ *
447
+ * This is a real `POST /ilp` carrying a minimal PREPARE with no claim
448
+ * header. It is free by the wire's own contract: an unpaid request to a
449
+ * priced route is answered with terms instead of performed, and nothing
450
+ * is charged for asking. `null` when the connector does not price the
451
+ * destination (the request would be routed or refused, not greeted) —
452
+ * mapped from anything other than a 402 answer.
453
+ */
454
+ getRouteTerms(endpoint: string, destination: string): Promise<ConnectorRouteTerms | null>;
455
+ /**
456
+ * The credited/spendable position of one or more channels this client
457
+ * controls (`POST /ilp/claim-state`, client-edge-spec.md §1.10) — the
458
+ * runway source of truth (toon-meta#261/#262 decision 9): earnings net
459
+ * off-chain on the same channel a client spends from, so this is also
460
+ * where a credited balance is read. Never cached: unlike identity/price,
461
+ * a claim watermark changes on every accepted claim, on EITHER side.
462
+ *
463
+ * Each entry is independently authenticated (own signature, own
464
+ * blockchain) — a request MAY mix EVM and Solana channels. Returns `[]`
465
+ * without a request when `channels` is empty.
466
+ *
467
+ * @throws {NetworkError} the connector could not be reached.
468
+ * @throws {ConnectorEdgeError} a non-2xx status, or a body that is not the
469
+ * documented shape.
470
+ */
471
+ getClaimState(endpoint: string, channels: ClaimStateRequestEntry[]): Promise<ClaimStateResult[]>;
472
+ /**
473
+ * Drop a cached route price — one (endpoint, destination)'s, every
474
+ * destination's at one endpoint when `destination` is omitted, or all of
475
+ * them when both are. The way to react to a route being repriced.
476
+ */
477
+ invalidateRoutePrice(endpoint?: string, destination?: string): void;
478
+ /**
479
+ * Whether a price for `(endpoint, destination)` is already held (no request
480
+ * is made).
481
+ */
482
+ hasCachedRoutePrice(endpoint: string, destination: string): boolean;
483
+ private fetchRoutePrice;
484
+ private fetchIdentity;
485
+ private readJson;
486
+ /** GET with a timeout, mapping any transport failure onto {@link NetworkError}. */
487
+ private get;
488
+ }
489
+
490
+ /**
491
+ * NIP-59 gift-wrap UNWRAP, receiver side only. Backs the daemon's
492
+ * `POST /nip59-unwrap` control-API endpoint (toon-meta#256): an external
493
+ * agent process (buzz#19's agent-members) hands the daemon a kind:1059 event
494
+ * addressed to the daemon's own Nostr identity, and gets back the decrypted
495
+ * inner event — without the daemon's secret key ever leaving this process,
496
+ * let alone the caller's.
497
+ *
498
+ * There is deliberately no `wrap` (sender) side here yet — nothing in this
499
+ * client originates gift wraps today (the swap rumor path builds its own via
500
+ * the sdk). Add one only when a sender use case actually needs it.
501
+ *
502
+ * Uses `nostr-tools/nip44` for both decrypt layers and `nostr-tools/pure`'s
503
+ * `verifyEvent` for the seal signature check — no hand-rolled crypto.
504
+ *
505
+ * ─── Why a bespoke unwrap instead of `nostr-tools/nip59`'s `unwrapEvent` ────
506
+ * `unwrapEvent` throws away the seal once it has decrypted through it, so it
507
+ * can never tell a caller who actually signed the rumor — only the wrap's
508
+ * ephemeral, throwaway `pubkey` is visible from outside. NIP-59 is explicit
509
+ * that authorship must be read off the SEAL, never the wrap, so this module
510
+ * decrypts the two layers by hand (still via `nip44.getConversationKey` /
511
+ * `nip44.decrypt`, the same primitives `unwrapEvent` uses internally) in
512
+ * order to surface `seal.pubkey` — verified against the seal's own
513
+ * signature, not merely trusted as a decrypted field.
514
+ */
515
+
516
+ /** `kind:1059` — the outer gift wrap. */
517
+ declare const GIFT_WRAP_KIND = 1059;
518
+ /** `kind:13` — the inner seal, signed by the real author. */
519
+ declare const SEAL_KIND = 13;
520
+ /**
521
+ * The wrap was structurally invalid, not a gift wrap, or not addressed to
522
+ * the identity attempting to unwrap it. None of these required decrypting
523
+ * anything — they're rejectable from the event's plaintext envelope alone.
524
+ * Maps to HTTP 400 at the control-API boundary.
525
+ */
526
+ declare class GiftWrapAddressError extends Error {
527
+ constructor(message: string);
528
+ }
529
+ /**
530
+ * The wrap looked addressable but a cryptographic step failed: a NIP-44
531
+ * layer didn't decrypt, the decrypted payload wasn't the expected event
532
+ * shape, or the seal's signature didn't verify against its own `pubkey`.
533
+ * Maps to HTTP 422 at the control-API boundary.
534
+ */
535
+ declare class GiftWrapDecryptError extends Error {
536
+ constructor(message: string);
537
+ }
538
+ /** Result of a successful unwrap. */
539
+ interface UnwrappedGiftWrap {
540
+ /** The decrypted inner event (NIP-59 calls it the "rumor") — unsigned. */
541
+ rumor: UnsignedEvent & {
542
+ id?: string;
543
+ };
544
+ /**
545
+ * The hex pubkey that signed the kind:13 seal, VERIFIED against the seal's
546
+ * own signature. This — never `wrap.pubkey`, which NIP-59 mints fresh and
547
+ * throws away per wrap — is the real author.
548
+ */
549
+ sealPubkey: string;
550
+ }
551
+ /**
552
+ * Unwrap a NIP-59 gift wrap addressed to `recipientPubkey`, decrypting both
553
+ * layers with `recipientSecretKey`. Pure function (no I/O, no client state)
554
+ * so it can be unit-tested directly against real `nostr-tools/nip59` fixtures
555
+ * — see `nip59.test.ts`. {@link ToonClient.unwrapGiftWrap} is a thin
556
+ * passthrough that supplies the client's own identity key.
557
+ *
558
+ * @throws {GiftWrapAddressError} malformed input, wrong kind, or not
559
+ * addressed to `recipientPubkey`.
560
+ * @throws {GiftWrapDecryptError} a NIP-44 layer failed to decrypt, decrypted
561
+ * to the wrong shape, or the seal's signature didn't verify.
562
+ */
563
+ declare function unwrapGiftWrapWithKey(recipientSecretKey: Uint8Array, recipientPubkey: string, wrap: NostrEvent): UnwrappedGiftWrap;
564
+
565
+ /** One on-chain wallet token balance. `amount` is base-unit integer, decimal. */
566
+ interface WalletBalance {
567
+ chain: 'evm' | 'solana' | 'mina';
568
+ address: string;
569
+ amount: string;
570
+ /** Token symbol, when resolved (e.g. `'USDC'`, `'MINA'`). */
571
+ asset?: string;
572
+ /** Token decimals, when resolved. */
573
+ assetScale?: number;
574
+ }
575
+ /**
576
+ * One asset amount within a chain's wallet view — the native coin or one token.
577
+ * `amount` is a base-unit integer, decimal string.
578
+ */
579
+ interface WalletTokenAmount {
580
+ /** Asset symbol (e.g. `'ETH'`, `'SOL'`, `'MINA'`, `'USDC'`), when known. */
581
+ symbol?: string;
582
+ /** Base-unit integer, decimal string. */
583
+ amount: string;
584
+ /** Decimals for formatting (ETH 18, SOL 9, MINA 9, USDC 6). */
585
+ decimals?: number;
586
+ /** Token contract / SPL mint address. Absent for the native coin. */
587
+ address?: string;
588
+ }
589
+ /**
590
+ * The full wallet view for ONE chain the identity is configured for: the native
591
+ * coin plus every configured token, keyed by the chain's full key (e.g.
592
+ * `'evm:31337'`). `unreadable` marks a chain whose RPC could not be reached at
593
+ * all — the caller renders a per-chain notice rather than crashing.
594
+ */
595
+ interface WalletChainBalances {
596
+ chain: 'evm' | 'solana' | 'mina';
597
+ /** Full chain key, e.g. `'evm:31337'`, `'solana'`, `'mina'`. */
598
+ chainKey: string;
599
+ address: string;
600
+ /** Native-coin balance, when readable. */
601
+ native?: WalletTokenAmount;
602
+ /** Configured token balances (e.g. USDC), each best-effort. */
603
+ tokens: WalletTokenAmount[];
604
+ /** True when nothing on this chain could be read (RPC unreachable). */
605
+ unreadable?: boolean;
606
+ /** First read error, when any read failed (for diagnostics). */
607
+ error?: string;
608
+ }
609
+ /** Read an ERC-20 token balance (balance + decimals + symbol) for `owner`. */
610
+ declare function readEvmTokenBalance(opts: {
611
+ rpcUrl: string;
612
+ chainKey: string;
613
+ tokenAddress: string;
614
+ owner: string;
615
+ }): Promise<WalletBalance>;
616
+ /** Read the native ETH balance (wei) for `owner` via `eth_getBalance`. */
617
+ declare function readEvmNativeBalance(opts: {
618
+ rpcUrl: string;
619
+ chainKey: string;
620
+ owner: string;
621
+ }): Promise<WalletTokenAmount>;
622
+ /** Read the native SOL balance (lamports) for `owner` via the `getBalance` RPC. */
623
+ declare function readSolanaNativeBalance(opts: {
624
+ rpcUrl: string;
625
+ owner: string;
626
+ fetchImpl?: typeof fetch;
627
+ }): Promise<WalletTokenAmount>;
628
+ /** Read the SPL-token balance for `owner`'s token account(s) of `mint`. */
629
+ declare function readSolanaTokenBalance(opts: {
630
+ rpcUrl: string;
631
+ mint: string;
632
+ owner: string;
633
+ fetchImpl?: typeof fetch;
634
+ }): Promise<WalletBalance>;
635
+ /** Read the native MINA balance (nanomina) for `owner` via the Mina GraphQL API. */
636
+ declare function readMinaBalance(opts: {
637
+ graphqlUrl: string;
638
+ owner: string;
639
+ fetchImpl?: typeof fetch;
640
+ }): Promise<WalletBalance>;
641
+ /**
642
+ * Per-chain inputs for {@link readWalletBalances}: the resolved RPC URL, the
643
+ * identity's address on that chain, and the configured token (USDC) — sourced by
644
+ * the caller from the network topology / presets, never hardcoded here. A chain
645
+ * key absent from the object is simply not read.
646
+ */
647
+ interface WalletBalanceSources {
648
+ evm?: {
649
+ chainKey: string;
650
+ rpcUrl: string;
651
+ owner: string;
652
+ tokenAddress?: string;
653
+ };
654
+ solana?: {
655
+ chainKey?: string;
656
+ rpcUrl: string;
657
+ owner: string;
658
+ tokenMint?: string;
659
+ };
660
+ mina?: {
661
+ chainKey?: string;
662
+ graphqlUrl: string;
663
+ owner: string;
664
+ /** Settlement-token Field id (decimal). Reads the token balance when set. */
665
+ tokenId?: string;
666
+ };
667
+ /** Injectable fetch (Solana/Mina JSON-RPC & GraphQL) for tests. */
668
+ fetchImpl?: typeof fetch;
669
+ }
670
+ /**
671
+ * Read the full wallet view — native coin + configured tokens — for every chain
672
+ * in `sources`, keyed per chain. FREE: read-only RPC, no signing. Each chain is
673
+ * read independently and in parallel; a chain whose RPC is unreachable degrades
674
+ * to `{ unreadable: true, error }` instead of failing the others. Within a chain
675
+ * the native and token reads are independent, so a native read can succeed even
676
+ * if the token read fails (and vice versa).
677
+ */
678
+ declare function readWalletBalances(sources: WalletBalanceSources): Promise<WalletChainBalances[]>;
679
+
680
+ /**
681
+ * The structured envelope (ADR 0018): what a packet carries between a
682
+ * connector and the app behind it, encoded with the same OER primitives an ILP
683
+ * packet already uses rather than as HTTP text.
684
+ *
685
+ * A faithful port of `connector_domain::envelope`
686
+ * (`crates/connector-domain/src/envelope.rs`) — a method, target, ordered
687
+ * headers and body going in; a two-byte big-endian status, headers and body
688
+ * coming back. `vectors/wire-vectors.json` is the contract this is checked
689
+ * against, and `wire-vectors.test.ts` is where that check happens; the prose
690
+ * here describes the same thing but the bytes decide.
691
+ *
692
+ * ─── Why not HTTP text ─────────────────────────────────────────────────────
693
+ * `utils/store-envelope.ts` builds latin1 HTTP/1.1 request text and
694
+ * `utils/fulfill-http.ts` hand-parses a status line and scans for `\r\n\r\n`,
695
+ * which is how they acquired leniencies nobody chose: a missing header/body
696
+ * separator yielding an empty body, blank header lines skipped, spaces
697
+ * tolerated inside the target. A structured encoding has exactly one
698
+ * representation per message and nothing to smuggle. This module lands BESIDE
699
+ * those two rather than replacing them — the swap is a later child — so it can
700
+ * be reviewed against the vectors in isolation.
701
+ *
702
+ * ─── Headers are a list, not a map ─────────────────────────────────────────
703
+ * A count prefix then `(name, value)` pairs in order. Both header ORDER and
704
+ * DUPLICATE NAMES are meaningful on this wire and both survive a round trip; a
705
+ * `Record<string, string>` would silently destroy each.
706
+ *
707
+ * Pure: no keys, no I/O, no clock. `@noble/*` is not involved.
708
+ */
709
+ /**
710
+ * Every distinguishable way an envelope can fail to decode. These strings are
711
+ * the vector file's `expected_error` values verbatim — the same names
712
+ * `EnvelopeError` uses in `connector-domain` — so a replay compares reasons,
713
+ * not just "it threw".
714
+ *
715
+ * There is deliberately no catch-all: a decoder with an `Invalid` bucket is a
716
+ * decoder that can be lenient without anyone noticing.
717
+ */
718
+ declare enum EnvelopeErrorKind {
719
+ /** The buffer ends before the envelope does. */
720
+ BufferUnderflow = "buffer_underflow",
721
+ /** A length determinant that is not the minimal encoding of its value. */
722
+ NonCanonicalLength = "non_canonical_length",
723
+ /** A length determinant wider than eight bytes. */
724
+ LengthDeterminantOverflow = "length_determinant_overflow",
725
+ /** The type byte is not the one the requested direction requires. */
726
+ InvalidType = "invalid_type",
727
+ /** A field that must be UTF-8 is not. */
728
+ InvalidUtf8 = "invalid_utf8",
729
+ /** Bytes remain after a fully decoded envelope. */
730
+ TrailingBytes = "trailing_bytes"
731
+ }
732
+ /**
733
+ * A refusal to decode. `kind` is the machine-readable reason; `field` names
734
+ * the offending field for {@link EnvelopeErrorKind.InvalidUtf8}, matching
735
+ * `EnvelopeError::InvalidUtf8(&'static str)` on the Rust side.
736
+ */
737
+ declare class EnvelopeError extends Error {
738
+ readonly kind: EnvelopeErrorKind;
739
+ readonly field?: string | undefined;
740
+ constructor(kind: EnvelopeErrorKind, field?: string | undefined);
741
+ }
742
+ /** One `(name, value)` header, in wire order. Duplicates are legal. */
743
+ type EnvelopeHeader = readonly [name: string, value: string];
744
+ /** The request a connector is to make of the app behind a terminated route. */
745
+ interface EnvelopeRequest {
746
+ method: string;
747
+ target: string;
748
+ headers: readonly EnvelopeHeader[];
749
+ body: Uint8Array;
750
+ }
751
+ /** The app's response back to the connector. */
752
+ interface EnvelopeResponse {
753
+ /** HTTP status, two bytes big-endian on the wire (`0..=65535`). */
754
+ status: number;
755
+ headers: readonly EnvelopeHeader[];
756
+ body: Uint8Array;
757
+ }
758
+ /** Either direction, tagged — the shape the vector file's `decoded` carries. */
759
+ type Envelope = ({
760
+ direction: 'request';
761
+ } & EnvelopeRequest) | ({
762
+ direction: 'response';
763
+ } & EnvelopeResponse);
764
+ /** Encode a request envelope. The inverse of {@link decodeEnvelopeRequest}. */
765
+ declare function encodeEnvelopeRequest(request: EnvelopeRequest): Uint8Array;
766
+ /**
767
+ * Decode a request envelope, consuming the WHOLE buffer.
768
+ *
769
+ * @throws {EnvelopeError} and nothing else, for any input whatsoever.
770
+ */
771
+ declare function decodeEnvelopeRequest(buf: Uint8Array): EnvelopeRequest;
772
+ /** Encode a response envelope. The inverse of {@link decodeEnvelopeResponse}. */
773
+ declare function encodeEnvelopeResponse(response: EnvelopeResponse): Uint8Array;
774
+ /**
775
+ * Decode a response envelope, consuming the WHOLE buffer.
776
+ *
777
+ * @throws {EnvelopeError} and nothing else, for any input whatsoever.
778
+ */
779
+ declare function decodeEnvelopeResponse(buf: Uint8Array): EnvelopeResponse;
780
+ /** Encode either direction from its tagged form. */
781
+ declare function encodeEnvelope(envelope: Envelope): Uint8Array;
782
+ /**
783
+ * Decode as the named direction. The direction is an INPUT, never guessed from
784
+ * the type byte: a caller that asked for a request and got a response has been
785
+ * handed the wrong bytes, and `invalid_type` is the honest answer.
786
+ */
787
+ declare function decodeEnvelope(buf: Uint8Array, direction: 'request' | 'response'): Envelope;
788
+
789
+ interface BTPProtocolData {
790
+ protocolName: string;
791
+ contentType: number;
792
+ data: Uint8Array;
793
+ }
794
+
795
+ /**
796
+ * Isomorphic BTP client — works in both browser and Node.js.
797
+ * Uses native WebSocket (browser) or globalThis.WebSocket (Node 21+).
798
+ * No dependency on `ws`, `events`, or `Buffer`.
799
+ *
800
+ * Replaces the @toon-protocol/connector BTPClient for the client SDK.
801
+ */
802
+
803
+ /** A server-originated MESSAGE (RFC-0023 symmetric grammar, toon-client#493). */
804
+ interface InboundBtpMessage {
805
+ requestId: number;
806
+ protocolData: BTPProtocolData[];
807
+ ilpPacket?: Uint8Array;
808
+ }
809
+ /** A server-originated TRANSFER — settlement value, never an ILP packet. */
810
+ interface InboundBtpTransfer {
811
+ requestId: number;
812
+ amount: bigint;
813
+ protocolData: BTPProtocolData[];
814
+ }
815
+ /** What an inbound handler answers with — becomes the RESPONSE frame's body. */
816
+ interface BtpHandlerResponse {
817
+ protocolData?: BTPProtocolData[];
818
+ ilpPacket?: Uint8Array;
819
+ }
820
+ type BtpMessageHandler = (message: InboundBtpMessage) => Promise<BtpHandlerResponse> | BtpHandlerResponse;
821
+ type BtpTransferHandler = (transfer: InboundBtpTransfer) => Promise<BtpHandlerResponse> | BtpHandlerResponse;
822
+
823
+ /**
824
+ * Serve-side job handling (toon-client#494, toon-meta#262 "agents earning").
825
+ *
826
+ * The connector originates a server-originated BTP MESSAGE carrying a PREPARE
827
+ * for this client's registered ILP address (RFC-0023 symmetric grammar,
828
+ * toon-client#493) — the earning half of the wire that `sendSwapPacket` /
829
+ * `publishEvent` already use to PAY. {@link createJobMessageHandler} plugs a
830
+ * caller-supplied {@link JobHandler} into `BtpRuntimeClientConfig.onMessage`
831
+ * so a provider writes a handler, never a payments integration
832
+ * (`connector-runtime/src/app_client.rs`'s payment-oblivious app contract,
833
+ * carried over to the BTP-served case this ticket adds).
834
+ *
835
+ * Delivery is hashlock (toon-meta#262 decision 5, `hashlock-delivery.ts`
836
+ * toon-client#495): the handler returns the fulfillment preimage it already
837
+ * minted at quote time via {@link encryptArtifact}/{@link fulfillIncrement} —
838
+ * this module never derives a condition/preimage relationship itself, only
839
+ * verifies the handler's answer against the PREPARE's own condition before
840
+ * it goes on the wire.
841
+ *
842
+ * Error policy (ADR 0020 "you pay for an answer, not the answer you
843
+ * wanted", RFC-0027 F99 "Application Error — the terminating app declined
844
+ * the delivery, or supplied no fulfilment matching the execution
845
+ * condition"): a handler that throws, or whose returned fulfillment does not
846
+ * satisfy the PREPARE's condition, answers F99 — the two cases RFC-0027's
847
+ * own F99 gloss already names together. An already-expired PREPARE is
848
+ * refused R00 without ever invoking the handler, so a provider is never
849
+ * asked to do paid work for a packet that can no longer be honored. An
850
+ * undecodable PREPARE is refused F00. None of these paths ever throw back
851
+ * into the BTP transport — every outcome is an answer (a RESPONSE frame
852
+ * carrying FULFILL or REJECT), matching the symmetric grammar's "every
853
+ * request gets an answer" contract.
854
+ */
855
+
856
+ /** One connector-originated job PREPARE, decoded and ready for a handler. */
857
+ interface JobRequest {
858
+ /** The packet's paid amount (base units) — informational only; see ADR 0020. */
859
+ amount: bigint;
860
+ /** The ILP address the PREPARE addressed (this client's own, per §1.9). */
861
+ destination: string;
862
+ /** The hashlock condition the handler's fulfillment must satisfy. */
863
+ executionCondition: Uint8Array;
864
+ /** When this PREPARE can no longer be honored. */
865
+ expiresAt: Date;
866
+ /** Opaque application payload — passed through unexamined (ADR 0018). */
867
+ data: Uint8Array;
868
+ }
869
+ /** What a {@link JobHandler} answers a job with. */
870
+ interface JobAnswer {
871
+ /**
872
+ * The fulfillment preimage — reveals the hashlock key (toon-meta#262
873
+ * decision 5). MUST satisfy `sha256(fulfillment) === executionCondition`;
874
+ * see {@link fulfillIncrement} in `hashlock-delivery.ts` for the one call
875
+ * site that should ever produce this value.
876
+ */
877
+ fulfillment: Uint8Array;
878
+ /** Answer payload returned in the FULFILL's `data` field. Defaults to empty. */
879
+ data?: Uint8Array;
880
+ }
881
+ /**
882
+ * A provider's job handler: receives a job and returns an answer. Amount,
883
+ * payer and chain never arrive as parameters here (ADR 0020's payment-
884
+ * oblivious app contract) — the handler is never something that must verify
885
+ * a payment, only produce a fulfillment for one already validated by the
886
+ * claim gate before this MESSAGE was ever originated.
887
+ */
888
+ type JobHandler = (job: JobRequest) => Promise<JobAnswer> | JobAnswer;
889
+ /**
890
+ * Wraps a {@link JobHandler} as a `BtpRuntimeClientConfig`/`IsomorphicBtpClientConfig`
891
+ * `onMessage` handler: decodes an inbound job PREPARE, invokes `handler`, and
892
+ * answers with a RESPONSE carrying FULFILL or REJECT — see this module's own
893
+ * doc for the exact error-code policy.
894
+ *
895
+ * A server-originated MESSAGE that carries no PREPARE at all (§1.9 step 1's
896
+ * auth MESSAGE, or a claim-only standalone MESSAGE) is not a job; it is
897
+ * answered with an empty RESPONSE, unchanged from the pre-#494 default.
898
+ */
899
+ declare function createJobMessageHandler(handler: JobHandler): BtpMessageHandler;
900
+
901
+ /**
902
+ * Solana payment-channel parameters supplied via `ToonClientConfig.solanaChannel`.
903
+ *
904
+ * Mirrors the `SolanaChannelConfig` consumed by `OnChainChannelClient`, minus
905
+ * the Ed25519 keypair (derived from the client's `mnemonic`, see
906
+ * `ToonClientConfig.solanaChannel`).
907
+ */
908
+ interface SolanaChannelClientOptions {
909
+ /** Solana JSON-RPC URL used to open the channel + read PDA state. */
910
+ rpcUrl: string;
911
+ /** Deployed payment-channel program id (base58). */
912
+ programId: string;
913
+ /**
248
914
  * Default SPL token mint (base58) for PDA derivation. The per-channel
249
915
  * negotiated token (the peer's preferred token) takes precedence when present.
250
916
  */
@@ -460,6 +1126,17 @@ interface ToonClientConfig {
460
1126
  network?: 'mainnet' | 'testnet' | 'devnet' | 'custom';
461
1127
  /** Supported settlement chain identifiers (e.g., ["evm:anvil:31337"]) */
462
1128
  supportedChains?: string[];
1129
+ /**
1130
+ * Explicitly-configured settlement chain FAMILY (e.g. from the daemon's
1131
+ * `TOON_CLIENT_CHAIN` env var / `chain` config field, #485). When set,
1132
+ * default-chain resolution (`getDefaultChainContext`, the lightweight
1133
+ * bootstrap-fallback chain match) MUST pick the `supportedChains` entry
1134
+ * whose family (the part before the first `:`) matches this value —
1135
+ * throwing a clear error instead of silently substituting a different
1136
+ * chain when none matches. Leave unset to keep the pre-#485 behavior of
1137
+ * defaulting to `supportedChains[0]`.
1138
+ */
1139
+ preferredChain?: 'evm' | 'solana' | 'mina';
463
1140
  /** Maps chain identifier to EVM settlement address */
464
1141
  settlementAddresses?: Record<string, string>;
465
1142
  /** Maps chain identifier to preferred token contract address */
@@ -517,6 +1194,39 @@ interface ToonClientConfig {
517
1194
  * false (no upgrade) when omitted.
518
1195
  */
519
1196
  connectorSupportsUpgrade?: boolean;
1197
+ /**
1198
+ * Prefer the persistent, strictly-ordered {@link BtpPaidWriteTransport} for
1199
+ * paid writes (`publishEvent`/`sendSwapPacket`/`sendPayment`) over the
1200
+ * default stateless HTTP one-shot transport, when a `btpUrl` is configured.
1201
+ *
1202
+ * The BTP client-facing websocket ingress processes claims on one session
1203
+ * strictly in arrival order (client-edge-spec.md §1.9), which is what a
1204
+ * burst of concurrent paid writes on one channel needs to avoid racing
1205
+ * itself into `F01 NonceNotAdvancing` — a failure mode possible on the
1206
+ * default stateless HTTP transport, where each write is an independent
1207
+ * request. Set this when the consumer sends many paid writes on one
1208
+ * channel in quick succession (e.g. relay-native huddle audio frames);
1209
+ * leave it unset for ordinary publish-and-forget usage.
1210
+ *
1211
+ * Default: `false` — paid writes keep going through the existing HTTP
1212
+ * transport unchanged (toon-client#482 productizes BTP as an opt-in
1213
+ * upgrade, not a default-behavior change). When `true` and no `btpUrl`
1214
+ * (directly or derived) resolves, this has no effect — the existing
1215
+ * transport selection is unchanged.
1216
+ */
1217
+ preferBtpForPaidWrites?: boolean;
1218
+ /**
1219
+ * Serve-side registration (toon-client#494, toon-meta#262 "agents
1220
+ * earning"): a handler for connector-originated jobs addressed to this
1221
+ * client's own ILP address. When set, a server-originated BTP MESSAGE
1222
+ * carrying a PREPARE (RFC-0023 symmetric grammar, toon-client#493) is
1223
+ * decoded, handed to this function, and answered with the FULFILL/REJECT
1224
+ * it produces — see `serve-job.ts` for the exact error-code policy. Only
1225
+ * takes effect when a `btpUrl` is configured (job serving rides the same
1226
+ * persistent BTP session paid writes use); unset means this client never
1227
+ * answers a connector-originated job, unchanged from the pre-#494 default.
1228
+ */
1229
+ jobHandler?: JobHandler;
520
1230
  /**
521
1231
  * ILP destination address for event publishing.
522
1232
  * Defaults to the connector's local address (derived from connectorUrl host).
@@ -586,7 +1296,16 @@ interface ToonClientConfig {
586
1296
  r: string;
587
1297
  s: string;
588
1298
  }>;
589
- /** File path for persisting payment channel nonce/amount state across restarts */
1299
+ /**
1300
+ * File path for persisting payment channel nonce/amount state across restarts.
1301
+ *
1302
+ * Also enables CHANNEL RESUME (#489): a sibling file (`channels.json` →
1303
+ * `channels.peers.json`) records which on-chain channel this identity holds
1304
+ * with each peer, so a restarted client re-attaches to it — with its claim
1305
+ * watermark — instead of opening a second channel and locking a second lot of
1306
+ * collateral. Never delete these files for a live channel: the collateral
1307
+ * stays locked on-chain and the watermark is unrecoverable.
1308
+ */
590
1309
  channelStorePath?: string;
591
1310
  /** Nostr relay URL for peer discovery. Default: 'wss://relay-ws.devnet.toonprotocol.dev' */
592
1311
  relayUrl?: string;
@@ -832,598 +1551,603 @@ declare function requestBlobStorage(client: ToonClient, secretKey: Uint8Array, p
832
1551
  declare function extractArweaveTxId(response: EnvelopeResponse): string;
833
1552
 
834
1553
  /**
835
- * Shared sender-side plumbing for sender-chosen execution conditions
836
- * (toon-client#350; contract: connector `docs/local-delivery-fulfillment-contract.md`,
837
- * connector#309; spec: toon-meta `docs/rolling-swap.md` §3).
838
- *
839
- * Both ILP transports (HTTP `POST /ilp` and BTP) take the SAME extended send
840
- * params and map FULFILL/REJECT responses through the SAME verifier so the
841
- * two paths cannot drift:
842
- *
843
- * - absent/all-zero `executionCondition` → legacy class: today's behavior,
844
- * byte-for-byte (zero condition on the wire, no FULFILL verification);
845
- * - non-zero `executionCondition` → sender-chosen: the condition goes on
846
- * the PREPARE verbatim and the FULFILL's 32-byte fulfillment MUST hash
847
- * back to it — a missing/malformed/mismatching preimage is surfaced as a
848
- * FAILED result (never a silent accept, never retried).
1554
+ * Chain-specific metadata (discriminated union).
849
1555
  */
850
-
1556
+ type ChainMetadata = {
1557
+ chainType: 'evm';
1558
+ chainId: number;
1559
+ tokenNetworkAddress: string;
1560
+ tokenAddress?: string;
1561
+ } | {
1562
+ chainType: 'solana';
1563
+ programId: string;
1564
+ tokenMint?: string;
1565
+ } | {
1566
+ chainType: 'mina';
1567
+ zkAppAddress: string;
1568
+ tokenId?: string;
1569
+ };
851
1570
  /**
852
- * Send parameters accepted by both ILP transports. Extends the
853
- * `@toon-protocol/core` `IlpClient` param shape with the sender-chosen
854
- * condition and an explicit expiry — plain `IlpClient` callers keep working
855
- * unchanged (both extras are optional; omitting them is the legacy path).
1571
+ * Chain-agnostic signing interface for balance proofs.
856
1572
  */
857
- interface IlpSendParams {
858
- destination: string;
859
- amount: string;
860
- /** Base64 ILP `data` payload. */
861
- data: string;
862
- /** Transport timeout in ms; also the default expiry window. */
863
- timeout?: number;
864
- /**
865
- * Sender-chosen 32-byte execution condition `C = sha256(P)` (spec R2).
866
- * Absent or all-zero = legacy unverified packet (default — ordinary
867
- * publish/upload writes MUST keep this default).
868
- */
869
- executionCondition?: Uint8Array;
870
- /**
871
- * Explicit PREPARE `expiresAt` (spec R7). Defaults to `now + timeout`,
872
- * preserving pre-#350 behavior. Accepts a `Date` or an ISO 8601 string —
873
- * `@toon-protocol/core` ≥2.1.0's `IlpClient` passes the string form.
874
- */
875
- expiresAt?: Date | string;
1573
+ interface ChainSigner {
1574
+ readonly chainType: 'evm' | 'solana' | 'mina';
1575
+ readonly signerIdentifier: string;
1576
+ signBalanceProof(params: {
1577
+ channelId: string;
1578
+ nonce: number;
1579
+ transferredAmount: bigint;
1580
+ lockedAmount: bigint;
1581
+ locksRoot: string;
1582
+ /**
1583
+ * Counterparty settlement address the proof is bound to. Required for
1584
+ * Solana/Mina (folded into the canonical balance-proof message); the EVM
1585
+ * adapter ignores it (EIP-712 has no recipient term).
1586
+ */
1587
+ recipient: string;
1588
+ metadata: ChainMetadata;
1589
+ /**
1590
+ * On-chain channel `depositTotal` (base units). When supplied (>0), a Mina
1591
+ * signer binds the conserved `balanceB = depositTotal − balanceA` commitment
1592
+ * required to settle on a funded zkApp (connector#133); EVM/Solana signers
1593
+ * ignore it. When omitted, a Mina signer self-resolves it from chain if it
1594
+ * was configured with a GraphQL URL (#223), else falls back to the legacy
1595
+ * `balanceB = 0` form.
1596
+ */
1597
+ depositTotal?: bigint;
1598
+ }): Promise<SignedBalanceProof>;
1599
+ buildClaimMessage(proof: SignedBalanceProof, senderId: string): ClaimMessage;
876
1600
  }
1601
+ type ClaimMessage = EVMClaimMessage | SolanaClaimMessage | MinaClaimMessage;
877
1602
  /**
878
- * `IlpSendResult` plus the FULFILL preimage when a sender-chosen condition
879
- * was verified. Only populated on the sender-chosen path so legacy result
880
- * objects stay byte-identical.
1603
+ * Solana payment-channel claim — wire-compatible with the connector's
1604
+ * `SolanaClaimMessage` (`@toon-protocol/connector` `btp/btp-claim-types.ts`).
1605
+ * Field names match the connector's `validateSolanaClaim` exactly:
1606
+ * `channelAccount` (base58 PDA), `signerPublicKey` (base58), base64 `signature`.
881
1607
  */
882
- interface IlpSendResultWithFulfillment extends IlpSendResult {
883
- /** Base64 32-byte fulfillment preimage (verified: sha256 == condition). */
884
- fulfillment?: string;
885
- }
886
- /** ILP code used for a client-side fulfillment-verification failure. */
887
- declare const FULFILLMENT_MISMATCH_CODE = "F99";
888
- /** Message for a client-side fulfillment-verification failure. */
889
- declare const FULFILLMENT_MISMATCH_MESSAGE: string;
890
-
891
- interface BtpRuntimeClientConfig {
892
- btpUrl: string;
893
- peerId: string;
894
- authToken: string;
895
- /** Max reconnection attempts on send failure (default: 3) */
896
- maxRetries?: number;
897
- /** Delay between reconnection attempts in ms (default: 1000) */
898
- retryDelay?: number;
899
- /** Custom WebSocket constructor (for testing / custom transports). */
900
- createWebSocket?: (url: string) => WebSocket;
1608
+ interface SolanaClaimMessage {
1609
+ version: '1.0';
1610
+ blockchain: 'solana';
1611
+ messageId: string;
1612
+ timestamp: string;
1613
+ senderId: string;
1614
+ /** On-chain PDA account address for the payment channel (base58). */
1615
+ channelAccount: string;
1616
+ nonce: number;
1617
+ /** Cumulative transferred amount (string for bigint precision). */
1618
+ transferredAmount: string;
1619
+ /** Ed25519 signature over the 48-byte balance-proof message (base64). */
1620
+ signature: string;
1621
+ /** Base58-encoded Ed25519 public key of the signer. */
1622
+ signerPublicKey: string;
1623
+ /** Solana program id for the payment-channel program (base58). */
1624
+ programId: string;
901
1625
  }
902
1626
  /**
903
- * BTP transport implementing IlpClient.
904
- * Uses IsomorphicBtpClient (browser-native, no Node.js dependencies).
905
- */
906
- declare class BtpRuntimeClient implements IlpClient {
907
- private btpClient;
908
- private readonly config;
909
- private _isConnected;
910
- constructor(config: BtpRuntimeClientConfig);
911
- /**
912
- * Connects to the BTP peer via WebSocket.
913
- */
914
- connect(): Promise<void>;
915
- /**
916
- * Attempts to reconnect by creating a fresh client and connecting.
917
- */
918
- reconnect(): Promise<void>;
919
- /**
920
- * Disconnects from the BTP peer.
921
- */
922
- disconnect(): Promise<void>;
923
- get isConnected(): boolean;
924
- /**
925
- * Sends an ILP packet via BTP with auto-reconnect on connection errors.
926
- * Satisfies IlpClient interface.
927
- *
928
- * `params` may carry a sender-chosen `executionCondition` and an explicit
929
- * `expiresAt` (toon-client#350); omitting both is the legacy zero-condition
930
- * path, unchanged. With a non-zero condition the FULFILL preimage is
931
- * verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced
932
- * as a failed result — see `mapIlpResponse`.
933
- */
934
- sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;
1627
+ * Mina payment-channel claim — wire-compatible with the connector's
1628
+ * `MinaClaimMessage` (`@toon-protocol/connector` `btp/btp-claim-types.ts`).
1629
+ * Field names + types match `validateMinaClaim` exactly: `zkAppAddress`
1630
+ * (B62-prefixed 55-char base58, the channel id), `tokenId`, `balanceCommitment`
1631
+ * (`Poseidon([balA,balB,salt])` decimal string), integer `nonce`, base64 `proof`,
1632
+ * and `salt`. `transferredAmount`/`balanceB`/`signatureB`/`network` are OPTIONAL
1633
+ * at validation; the apex-as-recipient single-direction claim sends party-A only.
1634
+ */
1635
+ interface MinaClaimMessage {
1636
+ version: '1.0';
1637
+ blockchain: 'mina';
1638
+ messageId: string;
1639
+ timestamp: string;
1640
+ senderId: string;
1641
+ /** Deployed payment-channel zkApp address (B62 base58) — the channel id. */
1642
+ zkAppAddress: string;
1643
+ /** Mina token id (default `'MINA'`). */
1644
+ tokenId: string;
1645
+ /** `Poseidon([balanceA, balanceB, salt]).toString()`. */
1646
+ balanceCommitment: string;
1647
+ nonce: number;
1648
+ /** base64-encoded JSON `{ commitment, signature: { r, s }, nonce, signerPublicKey }`. */
1649
+ proof: string;
1650
+ /** Commitment salt (decimal string). */
1651
+ salt: string;
1652
+ /** Cumulative transferred amount (optional; string for bigint precision). */
1653
+ transferredAmount?: string;
935
1654
  /**
936
- * Sends a balance proof claim via BTP protocol data, then sends an ILP packet.
937
- * Auto-reconnects on connection errors.
1655
+ * Signer's Mina public key (B62 base58) — the claiming participant.
938
1656
  *
939
- * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are
940
- * identical to {@link sendIlpPacket}.
941
- */
942
- sendIlpPacketWithClaim(params: IlpSendParams, claim: Record<string, unknown>): Promise<IlpSendResult>;
943
- /**
944
- * Send a standalone `payment-channel-claim` BTP MESSAGE (no ILP packet
945
- * attached). The connector's ClaimReceiver consumes this fire-and-forget
946
- * to register cumulative claim state independently of the per-packet
947
- * forwarding path. Auto-reconnects on connection errors.
948
- */
949
- sendClaimMessage(claim: Record<string, unknown>): Promise<void>;
950
- private _sendClaimMessageOnce;
951
- /**
952
- * Build the ILP PREPARE for a send, applying the sender-chosen condition /
953
- * explicit expiry when provided (toon-client#350) and validating that a
954
- * non-zero condition is exactly 32 bytes (the OER serializer would
955
- * otherwise silently zero-fill it, downgrading the packet to the legacy
956
- * unverified class).
957
- */
958
- private buildPrepare;
959
- /**
960
- * Single-attempt ILP packet send. Reconnects if not connected.
961
- */
962
- private _sendIlpPacketOnce;
963
- /**
964
- * Single-attempt claim + ILP packet send. Reconnects if not connected.
1657
+ * Surfaced top-level (in addition to being embedded in `proof`) so the
1658
+ * connector's `SettlementExecutor` can resolve participant keys for the
1659
+ * on-chain `claimFromChannel` on an externally-opened (inbound) channel. The
1660
+ * connector reads `latestClaim.signerPublicKey` directly (not the proof blob);
1661
+ * without it the Mina SDK's `claimFromChannel` throws `ACCOUNT_NOT_FOUND`
1662
+ * ("Participant keys not found in cache and none were supplied"). The
1663
+ * connector accepts this as an optional `MinaClaimMessage` field.
965
1664
  */
966
- private _sendIlpPacketWithClaimOnce;
1665
+ signerPublicKey?: string;
1666
+ /** Mina network id — defaults to `devnet` connector-side when omitted. */
1667
+ network?: 'mainnet' | 'devnet' | 'berkeley' | 'lightnet';
967
1668
  }
968
1669
 
969
1670
  /**
970
- * ILP-over-HTTP (RFC-0035) transport for the TOON client.
971
- *
972
- * The connector now serves ILP-over-HTTP on the SAME port as BTP (connector
973
- * PR #181). This adapter lets a client do stateless one-shot writes over HTTP
974
- * (`POST /ilp`) and upgrade to a duplex BTP session when it needs to receive
975
- * server-initiated packets or act as a peer.
976
- *
977
- * Wire contract (targets connector PR #181's `/ilp`):
978
- * - One-shot write: `POST /ilp`
979
- * body: OER-encoded ILP PREPARE (`application/octet-stream`)
980
- * header: `ILP-Payment-Channel-Claim: base64(JSON of the claim)` — the
981
- * SAME claim JSON the BTP path attaches as the
982
- * `payment-channel-claim` protocolData entry.
983
- * optional: `ILP-Peer-Id` + `Authorization: Bearer <secret>` identity.
984
- * response: `200 OK` with an OER FULFILL or REJECT body. HTTP non-2xx is
985
- * reserved for TRANSPORT errors (400/401/413/5xx); ILP-level
986
- * rejects come back as a 200 + REJECT body.
987
- * - Upgrade to BTP: standard HTTP `Upgrade` with `Sec-WebSocket-Protocol: btp`
988
- * plus the same `ILP-Peer-Id` + `Authorization` headers. The connector
989
- * pre-authenticates the BTP session from those headers (continuity), so
990
- * after `101` we send BTP frames WITHOUT a separate in-band auth frame.
991
- * Omitting the auth headers falls back to the normal BTP auth-frame flow.
1671
+ * EVM claim message for BTP protocol data.
1672
+ * Matches @toon-protocol/connector's EVMClaimMessage interface.
992
1673
  *
993
- * Reuses `serializeIlpPrepare`/`deserializeIlpPacket` from `btp/protocol.ts` —
994
- * the SAME OER codec the BTP path uses. Claim signing/construction is owned by
995
- * the caller (BootstrapService); this transport never builds or signs claims.
1674
+ * The connector's validateClaimMessage() requires envelope fields
1675
+ * (version, messageId, timestamp) plus EVM claim fields, and optionally
1676
+ * chainId + tokenNetworkAddress for self-describing signature verification.
996
1677
  */
997
-
998
- /** Header carrying the base64(JSON) payment-channel claim. */
999
- declare const ILP_CLAIM_HEADER = "ILP-Payment-Channel-Claim";
1000
- /** Header carrying the peer identity. */
1001
- declare const ILP_PEER_ID_HEADER = "ILP-Peer-Id";
1002
- interface HttpIlpClientConfig {
1003
- /** The peer's `POST /ilp` URL (the `httpEndpoint` from discovery). */
1004
- httpEndpoint: string;
1005
- /**
1006
- * Optional peer identity. With no `peerId`/`authToken` the connector treats
1007
- * the request as an anonymous no-auth peer (permissionless default) and
1008
- * derives an ephemeral id from the claim signer.
1009
- */
1010
- peerId?: string;
1011
- /** Bearer secret for `Authorization`. Omit for the no-auth peer path. */
1012
- authToken?: string;
1013
- /** Request timeout in milliseconds (default: 30000). */
1014
- timeout?: number;
1015
- /** Max retry attempts for transport-level network failures (default: 3). */
1016
- maxRetries?: number;
1017
- /** Initial retry delay in milliseconds (default: 1000). */
1018
- retryDelay?: number;
1019
- /** Custom fetch implementation (for testing / custom transports). */
1020
- httpClient?: typeof fetch;
1021
- /**
1022
- * Custom WebSocket constructor for the BTP upgrade path (for testing /
1023
- * custom transports). Forwarded to the underlying BtpRuntimeClient.
1024
- */
1025
- createWebSocket?: (url: string) => WebSocket;
1678
+ interface EVMClaimMessage {
1679
+ version: '1.0';
1680
+ blockchain: 'evm';
1681
+ messageId: string;
1682
+ timestamp: string;
1683
+ senderId: string;
1684
+ channelId: string;
1685
+ nonce: number;
1686
+ transferredAmount: string;
1687
+ lockedAmount: string;
1688
+ locksRoot: string;
1689
+ signature: string;
1690
+ signerAddress: string;
1691
+ /** Chain ID for self-describing EIP-712 verification */
1692
+ chainId: number;
1693
+ /** TokenNetwork address for self-describing EIP-712 verification */
1694
+ tokenNetworkAddress: string;
1695
+ /** ERC-20 token address for self-describing claim verification */
1696
+ tokenAddress?: string;
1026
1697
  }
1027
1698
  /**
1028
- * Stateless ILP-over-HTTP transport implementing `IlpClient`.
1699
+ * EVM signer for EIP-712 balance proofs and on-chain transactions.
1029
1700
  *
1030
- * Use this for pure one-shot consumers (publish-and-forget writes). When the
1031
- * client needs a duplex session — to receive server-initiated packets or to act
1032
- * as a peer — call {@link upgradeToBtp} to obtain a connected BtpRuntimeClient
1033
- * that reuses the existing BTP code path.
1701
+ * Encapsulates the private key — no getPrivateKey() method is exposed.
1034
1702
  */
1035
- declare class HttpIlpClient implements IlpClient {
1036
- private readonly httpEndpoint;
1037
- private readonly peerId;
1038
- private readonly authToken;
1039
- private readonly timeout;
1040
- private readonly retryConfig;
1041
- private readonly httpClient;
1042
- private readonly createWebSocket;
1043
- constructor(config: HttpIlpClientConfig);
1044
- /**
1045
- * The client edge this transport pays — the origin `GET /ilp/identity` and
1046
- * `GET /ilp/routes/price` hang off (`ConnectorEdgeClient` normalizes the
1047
- * trailing `/ilp` away). Exposed because a sealed write must ask the
1048
- * connector it is ACTUALLY paying for its key, not a configured guess.
1049
- */
1050
- get clientEdgeEndpoint(): string;
1703
+ declare class EvmSigner {
1704
+ readonly chainType: "evm";
1705
+ private readonly _account;
1051
1706
  /**
1052
- * Send an ILP PREPARE via `POST /ilp` WITHOUT a claim. The connector accepts
1053
- * this only on free/zero-amount routes; paid writes must use
1054
- * {@link sendIlpPacketWithClaim}. Satisfies the IlpClient interface.
1055
- *
1056
- * `params` may carry a sender-chosen `executionCondition` and an explicit
1057
- * `expiresAt` (toon-client#350); omitting both is the legacy zero-condition
1058
- * path, unchanged. With a non-zero condition the FULFILL preimage is
1059
- * verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced
1060
- * as a failed result — see {@link mapIlpResponse}.
1707
+ * @param privateKey - EVM private key as hex string (with or without 0x prefix) or Uint8Array
1061
1708
  */
1062
- sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;
1709
+ constructor(privateKey: string | Uint8Array);
1710
+ /** Derived 0x EVM address */
1711
+ get address(): string;
1712
+ /** ChainSigner identifier — EVM address */
1713
+ get signerIdentifier(): string;
1714
+ /** Viem PrivateKeyAccount — usable with walletClient for on-chain transactions */
1715
+ get account(): PrivateKeyAccount;
1063
1716
  /**
1064
- * Send an ILP PREPARE via `POST /ilp` with the payment-channel claim attached
1065
- * as the `ILP-Payment-Channel-Claim` header. `claim` is the SAME JSON object
1066
- * the BTP path attaches as the `payment-channel-claim` protocolData entry —
1067
- * we base64(JSON.stringify(claim)) it, byte-for-byte identical to BTP.
1717
+ * Signs a balance proof using EIP-712 typed data.
1068
1718
  *
1069
- * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are
1070
- * identical to {@link sendIlpPacket}.
1719
+ * @param params - Balance proof parameters plus chain context
1720
+ * @returns Signed balance proof with signature
1071
1721
  */
1072
- sendIlpPacketWithClaim(params: IlpSendParams, claim: unknown): Promise<IlpSendResult>;
1722
+ signBalanceProof(params: BalanceProofParams & {
1723
+ chainId: number;
1724
+ tokenNetworkAddress: string;
1725
+ tokenAddress?: string;
1726
+ }): Promise<SignedBalanceProof>;
1073
1727
  /**
1074
- * Upgrade to a duplex BTP session over the SAME endpoint.
1728
+ * Signs a `POST /ilp/claim-state` claim-state challenge (client-edge-spec.md
1729
+ * §1.10): proves ownership of `channelId` without moving any value or
1730
+ * advancing the channel's nonce — this is a READ, not a claim. Read the
1731
+ * connector's answer for the actual credited/available balance (toon-meta#262
1732
+ * decision 9); this signature only unlocks the read.
1075
1733
  *
1076
- * Derives the `ws(s)://` URL from `httpEndpoint`, opens a WebSocket with
1077
- * `Sec-WebSocket-Protocol: btp` and the same `ILP-Peer-Id` + `Authorization`
1078
- * headers, and returns a connected {@link BtpRuntimeClient}. When auth headers
1079
- * are present the connector pre-authenticates the session (no in-band auth
1080
- * frame); without them the BtpRuntimeClient falls back to the normal BTP
1081
- * auth-frame flow.
1082
- *
1083
- * NOTE: passing per-connection headers + a subprotocol to a WebSocket is
1084
- * Node-only (the `ws` package). Browsers cannot set arbitrary request headers
1085
- * on a WebSocket handshake, so a browser consumer must use the gateway
1086
- * transport or BTP-with-auth-frame instead.
1087
- */
1088
- upgradeToBtp(): Promise<BtpRuntimeClient>;
1089
- private authHeaders;
1090
- /**
1091
- * Single attempt: serialize the PREPARE, POST it, and map the response.
1092
- * @throws {NetworkError} On connection/timeout failures (retried).
1093
- * @throws {ConnectorError} On non-retryable transport errors (5xx / unexpected).
1734
+ * @param params.expires - Unix seconds the signature stops verifying.
1735
+ * Reissue with a fresh value whenever an outstanding one should stop
1736
+ * being trusted — the endpoint has no other replay bound.
1094
1737
  */
1095
- private postPrepare;
1738
+ signClaimStateChallenge(params: {
1739
+ chainId: number;
1740
+ tokenNetworkAddress: string;
1741
+ channelId: string;
1742
+ expires: number;
1743
+ }): Promise<string>;
1096
1744
  /**
1097
- * Map a `200 OK` body (OER FULFILL/REJECT) to an IlpSendResult; map a non-2xx
1098
- * to a transport error. Per the wire contract, ILP-level rejects arrive as a
1099
- * 200 + REJECT body — only HTTP non-2xx means a transport-layer failure.
1745
+ * Builds an EVMClaimMessage from a signed balance proof.
1746
+ * Static so it can be called without an EvmSigner instance.
1100
1747
  *
1101
- * When `sentCondition` is non-zero the FULFILL preimage is verified against
1102
- * it; a mismatch yields `accepted: false` (shared `mapIlpResponse` logic,
1103
- * identical to the BTP path).
1748
+ * @param proof - Signed balance proof (includes chainId and tokenNetworkAddress)
1749
+ * @param senderId - Nostr pubkey or identifier of the sender
1750
+ * @returns EVMClaimMessage compatible with BTP_CLAIM_PROTOCOL
1104
1751
  */
1105
- private mapResponse;
1106
- private mapTransportError;
1107
- }
1108
- /**
1109
- * Derive the BTP WebSocket URL from a `POST /ilp` HTTP endpoint. The connector
1110
- * serves BTP on the SAME path, so we only swap the scheme (http→ws, https→wss).
1111
- */
1112
- declare function httpEndpointToBtpUrl(httpEndpoint: string): string;
1113
-
1114
- /**
1115
- * Base error class for all TOON client errors.
1116
- */
1117
- declare class ToonClientError extends Error {
1118
- readonly code: string;
1119
- constructor(message: string, code: string, cause?: Error);
1120
- }
1121
- /**
1122
- * Network error for connection failures (ECONNREFUSED, ETIMEDOUT).
1123
- * These errors trigger retry logic with exponential backoff.
1124
- */
1125
- declare class NetworkError extends ToonClientError {
1126
- constructor(message: string, cause?: Error);
1752
+ static buildClaimMessage(proof: SignedBalanceProof, senderId: string): EVMClaimMessage;
1127
1753
  }
1754
+
1128
1755
  /**
1129
- * Connector error for 5xx server errors.
1130
- * These errors indicate the connector is unavailable or malfunctioning.
1756
+ * Plain token transfer — send the settlement token or native gas from the
1757
+ * caller's own configured key to an ARBITRARY address, on any chain this
1758
+ * client already supports (evm/solana/mina). This is the missing primitive
1759
+ * underneath provisioning a buzz agent (toon-protocol/buzz#74): before a
1760
+ * derived agent address can open a payment channel, the owner's treasury has
1761
+ * to send it USDC and native gas.
1762
+ *
1763
+ * `@toon-protocol/client` was built around payment CHANNELS, not transfers —
1764
+ * `faucet.ts` is the only prior funding path, and it only reaches the devnet
1765
+ * faucet. This module is a direct, non-custodial send: the caller's own key
1766
+ * signs its own transaction/payment, straight to `to`.
1767
+ *
1768
+ * Every send is confirmed by an OBSERVED balance delta at the destination,
1769
+ * never by the send call/transaction merely landing. The devnet faucet's
1770
+ * Solana leg has been seen returning success with a REAL transaction
1771
+ * signature while delivering 0 lamports (toon-protocol/connector#691) — a
1772
+ * send that trusted its own receipt would report a funded agent that in fact
1773
+ * holds nothing. {@link TransferNotDeliveredError} is exactly that failure
1774
+ * mode, made loud instead of silent.
1131
1775
  */
1132
- declare class ConnectorError extends ToonClientError {
1133
- constructor(message: string, cause?: Error);
1776
+
1777
+ /** Chains this client can send a plain transfer on. */
1778
+ type TransferChain = 'evm' | 'solana' | 'mina';
1779
+ /** `'native'` — the chain's own gas token. `'token'` — the settlement token. */
1780
+ type TransferAssetKind = 'native' | 'token';
1781
+ interface SendTransferParams {
1782
+ chain: TransferChain;
1783
+ asset: TransferAssetKind;
1784
+ /** Destination address, in the target chain's native format. */
1785
+ to: string;
1786
+ /** Amount to send, in the asset's base units (wei / lamports+SPL / nanomina). */
1787
+ amount: string | bigint;
1788
+ /**
1789
+ * How long to wait for the destination's observed balance to reflect the
1790
+ * transfer before giving up with {@link TransferNotDeliveredError}. Defaults
1791
+ * are chain-specific (EVM/Solana 30s, Mina 5 min — Mina block inclusion is
1792
+ * materially slower).
1793
+ */
1794
+ confirmTimeoutMs?: number;
1795
+ /** Poll interval (ms) while waiting for the balance delta. Default 2000. */
1796
+ confirmPollIntervalMs?: number;
1797
+ }
1798
+ interface SendTransferResult {
1799
+ chain: TransferChain;
1800
+ asset: TransferAssetKind;
1801
+ to: string;
1802
+ /** Base units actually requested (echoed back as a decimal string). */
1803
+ amount: string;
1804
+ /** Transaction hash / signature of the send. */
1805
+ txHash: string;
1806
+ /** Destination's observed balance immediately before the send. */
1807
+ balanceBefore: string;
1808
+ /** Destination's observed balance once the delta was confirmed. */
1809
+ balanceAfter: string;
1810
+ }
1811
+ /** Per-chain config a caller supplies to {@link sendTransfer}. */
1812
+ interface EvmTransferConfig {
1813
+ /** Chain key, e.g. `'evm:base-sepolia:84532'` (used for chainId + RPC). */
1814
+ chainKey: string;
1815
+ rpcUrl: string;
1816
+ signer: EvmSigner;
1817
+ /** ERC-20 settlement-token address. Required only for `asset: 'token'`. */
1818
+ tokenAddress?: string;
1134
1819
  }
1135
- /**
1136
- * Validation error for invalid input parameters.
1137
- * These errors are thrown before making any HTTP requests.
1138
- */
1139
- declare class ValidationError extends ToonClientError {
1140
- constructor(message: string, cause?: Error);
1820
+ interface SolanaTransferConfig {
1821
+ rpcUrl: string;
1822
+ /** Ed25519 signing seed (32 bytes) or a 64-byte seed||pubkey keypair. */
1823
+ keypair: Uint8Array;
1824
+ /** SPL settlement-token mint. Required only for `asset: 'token'`. */
1825
+ tokenMint?: string;
1141
1826
  }
1142
- /**
1143
- * Thrown when the one-time on-chain payment-channel OPEN reverts because the
1144
- * local settlement wallet has no native gas to pay for its own
1145
- * approve/openChannel/setTotalDeposit transactions. This is the channel OPEN
1146
- * only — per-write settlement rides ILP-over-HTTP and never spends gas. We
1147
- * remap ONLY this case so callers get an actionable message (fund the wallet)
1148
- * instead of the raw viem "...exceeds the balance of the account" string
1149
- * (toon-meta#65). Retryable once the wallet is funded; the underlying viem/RPC
1150
- * error is preserved as `cause`.
1151
- */
1152
- declare class ChannelFundingError extends ToonClientError {
1153
- readonly retryable = true;
1154
- constructor(message: string, cause?: Error);
1827
+ interface MinaTransferConfig {
1828
+ graphqlUrl: string;
1829
+ /** Big-endian hex scalar (as `deriveFullIdentity` emits) or `EK…` base58. */
1830
+ privateKey: string;
1831
+ /** Mina network id for the signature domain separator. Default `'devnet'`. */
1832
+ networkId?: 'devnet' | 'mainnet';
1833
+ /** Transaction fee, nanomina. Default 1_000_000 (0.001 MINA). */
1834
+ fee?: string;
1835
+ /** Injectable fetch (tests). */
1836
+ fetchImpl?: typeof fetch;
1155
1837
  }
1156
- /**
1157
- * True when `err` (or any error in its nested `cause` chain) is an
1158
- * insufficient-native-gas revert. viem wraps the node error one or more levels
1159
- * deep, so the whole chain is flattened and scanned.
1160
- */
1161
- declare function isInsufficientGasError(err: unknown): boolean;
1838
+ interface TransferConfig {
1839
+ evm?: EvmTransferConfig;
1840
+ solana?: SolanaTransferConfig;
1841
+ mina?: MinaTransferConfig;
1842
+ }
1843
+ /**
1844
+ * Send `params.amount` base units of `params.asset` to `params.to` on
1845
+ * `params.chain`, using whichever chain config in `config` matches. Confirms
1846
+ * delivery by re-reading the destination's balance (see module docs) rather
1847
+ * than trusting the send call's own success signal.
1848
+ *
1849
+ * @throws {UnknownChainError} `params.chain` is unrecognized, or this client
1850
+ * has no configuration for it.
1851
+ * @throws {InvalidAddressError} `params.to` is malformed for the chain.
1852
+ * @throws {InsufficientBalanceError} the sender cannot cover the amount
1853
+ * (plus fees, where applicable) — checked before anything is submitted.
1854
+ * @throws {TransferNotDeliveredError} the send was accepted (a landed,
1855
+ * non-reverted transaction / a node-accepted payment) but the destination
1856
+ * balance never reflected it within the wait window.
1857
+ * @throws {TransferUnsupportedError} this chain/asset combination isn't
1858
+ * implemented yet (currently: the Mina settlement token).
1859
+ */
1860
+ declare function sendTransfer(config: TransferConfig, params: SendTransferParams): Promise<SendTransferResult>;
1162
1861
 
1163
1862
  /**
1164
- * Ask a terminating connector who it is and what it charges — the step that
1165
- * has to happen BEFORE a packet can be formed at all.
1166
- *
1167
- * ADR 0018 makes holding the terminating connector's public key a
1168
- * precondition of forming a packet: `Prepare.data` is sealed to that key, and
1169
- * sealing to the wrong one is a confidentiality failure, not a delivery
1170
- * failure. ADR 0022 says the connector *answers* — it never announces — so
1171
- * both facts are fetched from the connector's own client edge, on the same
1172
- * origin this client already POSTs `/ilp` to
1173
- * (`docs/protocol/client-edge-spec.md` §1.7):
1174
- *
1175
- * - `GET /ilp/identity` → `{ "keyId": "...", "publicKey": "0x04..." }` — the
1176
- * uncompressed secp256k1 key, 65 bytes, `0x`-prefixed hex.
1177
- * - `GET /ilp/routes/price?destination=<ILP address>` →
1178
- * `{ "destination": "...", "price": 100 }`, or `404` when no
1179
- * locally-terminated route matches.
1180
- *
1181
- * Both are unauthenticated and neither changes state.
1863
+ * Shared sender-side plumbing for sender-chosen execution conditions
1864
+ * (toon-client#350; contract: connector `docs/local-delivery-fulfillment-contract.md`,
1865
+ * connector#309; spec: toon-meta `docs/rolling-swap.md` §3).
1182
1866
  *
1183
- * ─── What this module refuses to do ────────────────────────────────────────
1184
- * Unlike the 402-challenge parser next door (which degrades gracefully so an
1185
- * unrecognised connector shape falls back to the vanilla 402), an identity is
1186
- * parsed STRICTLY. A key that is the wrong length, not `0x04`-prefixed, or not
1187
- * valid hex is refused with a distinguishable error rather than carried
1188
- * forward: a half-understood key would be sealed to, and the failure would be
1189
- * silent. There is no "best effort" reading of a public key.
1867
+ * Both ILP transports (HTTP `POST /ilp` and BTP) take the SAME extended send
1868
+ * params and map FULFILL/REJECT responses through the SAME verifier so the
1869
+ * two paths cannot drift:
1190
1870
  *
1191
- * Pure transport + parsing: no keys are held, nothing is signed, and the only
1192
- * state is the identity cache.
1871
+ * - absent/all-zero `executionCondition` → legacy class: today's behavior,
1872
+ * byte-for-byte (zero condition on the wire, no FULFILL verification);
1873
+ * - non-zero `executionCondition` → sender-chosen: the condition goes on
1874
+ * the PREPARE verbatim and the FULFILL's 32-byte fulfillment MUST hash
1875
+ * back to it — a missing/malformed/mismatching preimage is surfaced as a
1876
+ * FAILED result (never a silent accept, never retried).
1193
1877
  */
1194
1878
 
1195
- /** The terminating connector's own identity, as reported by `GET /ilp/identity`. */
1196
- interface ConnectorIdentity {
1197
- /** The key id identifying the key (opaque to this client). */
1198
- keyId: string;
1199
- /** The uncompressed secp256k1 public key — exactly 65 raw bytes, leading `0x04`. */
1200
- publicKey: Uint8Array;
1201
- /** The key exactly as reported, `0x`-prefixed lowercase hex (65 bytes → 132 chars). */
1202
- publicKeyHex: string;
1203
- /** The normalized client-edge base URL this identity was read from. */
1204
- endpoint: string;
1205
- }
1206
- /**
1207
- * The channel-opening facts a settling connector carries in its x402
1208
- * greeting (connector #617): everything a buyer needs to OPEN a channel
1209
- * with the node, learned by ASKING (ADR 0022) rather than from a
1210
- * kind:10032 announce the Rust fleet never makes.
1211
- */
1212
- interface ConnectorSettlementTerms {
1213
- /** `evm:<chainId>` — the chain the node's settlement backend runs on. */
1214
- chain: string;
1215
- /** The on-chain counterparty a buyer opens a channel WITH. */
1216
- settlementAddress: string;
1217
- /** The stable TokenNetworkRegistry factory address. */
1218
- tokenNetworkRegistry: string;
1219
- /** The resolved TokenNetwork — the EIP-712 verifyingContract. */
1220
- tokenNetwork: string;
1221
- tokenAddress: string;
1222
- /** Informational; claims are already in base units. */
1223
- decimals: number;
1224
- }
1225
1879
  /**
1226
- * The Solana twin of {@link ConnectorSettlementTerms} (connector #632): what
1227
- * an unaffiliated buyer needs to open a channel against a Solana settlement
1228
- * backend's deployed `payment-channel` program instance.
1880
+ * Send parameters accepted by both ILP transports. Extends the
1881
+ * `@toon-protocol/core` `IlpClient` param shape with the sender-chosen
1882
+ * condition and an explicit expiry — plain `IlpClient` callers keep working
1883
+ * unchanged (both extras are optional; omitting them is the legacy path).
1229
1884
  */
1230
- interface ConnectorSolanaSettlementTerms {
1231
- /** Always `'solana'` — unlike EVM there is no chain id to append. */
1232
- chain: string;
1233
- /** The on-chain counterparty a buyer opens a channel WITH, base58. */
1234
- settlementAddress: string;
1235
- /** The deployed `payment-channel` program instance, base58. */
1236
- programId: string;
1237
- /** The SPL mint every channel this backend opens settles in, base58. */
1238
- tokenAddress: string;
1239
- /** Informational; claims are already in base units. */
1240
- decimals: number;
1885
+ interface IlpSendParams {
1886
+ destination: string;
1887
+ amount: string;
1888
+ /** Base64 ILP `data` payload. */
1889
+ data: string;
1890
+ /** Transport timeout in ms; also the default expiry window. */
1891
+ timeout?: number;
1892
+ /**
1893
+ * Sender-chosen 32-byte execution condition `C = sha256(P)` (spec R2).
1894
+ * Absent or all-zero = legacy unverified packet (default — ordinary
1895
+ * publish/upload writes MUST keep this default).
1896
+ */
1897
+ executionCondition?: Uint8Array;
1898
+ /**
1899
+ * Explicit PREPARE `expiresAt` (spec R7). Defaults to `now + timeout`,
1900
+ * preserving pre-#350 behavior. Accepts a `Date` or an ISO 8601 string —
1901
+ * `@toon-protocol/core` ≥2.1.0's `IlpClient` passes the string form.
1902
+ */
1903
+ expiresAt?: Date | string;
1241
1904
  }
1242
1905
  /**
1243
- * One chain's entry in the x402 greeting's per-chain `settlements` list
1244
- * (connector #632). `kind` is added by this parser, not present on the wire
1245
- * — the wire is untagged, disambiguated structurally (`tokenNetworkRegistry`
1246
- * names EVM, `programId` names Solana).
1247
- */
1248
- type ConnectorChainSettlementTerms = ({
1249
- kind: 'evm';
1250
- } & ConnectorSettlementTerms) | ({
1251
- kind: 'solana';
1252
- } & ConnectorSolanaSettlementTerms);
1253
- /**
1254
- * A route's terms as the x402 greeting states them: the price, plus (from a
1255
- * settling node) the channel-opening facts. `settlement` is absent exactly
1256
- * when the node has no settlement backend — the wire's own shape. `settlements`
1257
- * is the additive per-chain list (connector #632): one entry per chain the
1258
- * node settles on, including the same EVM entry `settlement` already carries.
1259
- * Absent — not an empty array — on a node with no settlement backend, or one
1260
- * still answering the pre-#632 greeting shape.
1906
+ * `IlpSendResult` plus the FULFILL preimage when a sender-chosen condition
1907
+ * was verified. Only populated on the sender-chosen path so legacy result
1908
+ * objects stay byte-identical.
1261
1909
  */
1262
- interface ConnectorRouteTerms {
1263
- destination: string;
1264
- price: string;
1265
- settlement?: ConnectorSettlementTerms;
1266
- settlements?: ConnectorChainSettlementTerms[];
1910
+ interface IlpSendResultWithFulfillment extends IlpSendResult {
1911
+ /** Base64 32-byte fulfillment preimage (verified: sha256 == condition). */
1912
+ fulfillment?: string;
1267
1913
  }
1268
- /** What a locally-terminated route costs, as reported by `GET /ilp/routes/price`. */
1269
- interface ConnectorRoutePrice {
1270
- /** The ILP destination that was asked about (echoed by the connector). */
1271
- destination: string;
1272
- /** The price in ILP base units of the route `destination` matched. */
1273
- price: bigint;
1914
+ /** ILP code used for a client-side fulfillment-verification failure. */
1915
+ declare const FULFILLMENT_MISMATCH_CODE = "F99";
1916
+ /** Message for a client-side fulfillment-verification failure. */
1917
+ declare const FULFILLMENT_MISMATCH_MESSAGE: string;
1918
+
1919
+ interface BtpRuntimeClientConfig {
1920
+ btpUrl: string;
1921
+ peerId: string;
1922
+ authToken: string;
1923
+ /** Max reconnection attempts on send failure (default: 3) */
1924
+ maxRetries?: number;
1925
+ /** Delay between reconnection attempts in ms (default: 1000) */
1926
+ retryDelay?: number;
1927
+ /** Custom WebSocket constructor (for testing / custom transports). */
1928
+ createWebSocket?: (url: string) => WebSocket;
1929
+ /**
1930
+ * Handles a server-originated MESSAGE (RFC-0023 symmetric grammar,
1931
+ * toon-client#493). Re-registered on every `connect()`/`reconnect()` since
1932
+ * each creates a fresh `IsomorphicBtpClient` for the new socket.
1933
+ */
1934
+ onMessage?: BtpMessageHandler;
1935
+ /** Handles a server-originated TRANSFER. Re-registered the same way as `onMessage`. */
1936
+ onTransfer?: BtpTransferHandler;
1937
+ /** Surfaces in-flight inbound work orphaned by a disconnect instead of silently vanishing. */
1938
+ onInboundError?: (error: Error, requestId: number) => void;
1274
1939
  }
1275
1940
  /**
1276
- * Every distinguishable way asking a connector for its identity or terms can
1277
- * fail. Each code names exactly one cause; there is no catch-all, because the
1278
- * caller's next move differs per cause (retry a transport failure; never
1279
- * retry a malformed key).
1280
- */
1281
- type ConnectorEdgeErrorCode =
1282
- /** Non-2xx from `GET /ilp/identity`. */
1283
- 'IDENTITY_HTTP_STATUS'
1284
- /** `GET /ilp/identity` answered 2xx with a body that is not the documented object. */
1285
- | 'IDENTITY_MALFORMED'
1286
- /** `publicKey` is present but is not `0x`-prefixed even-length hex. */
1287
- | 'IDENTITY_KEY_NOT_HEX'
1288
- /** `publicKey` decodes, but not to exactly 65 bytes. */
1289
- | 'IDENTITY_KEY_LENGTH'
1290
- /** `publicKey` is 65 bytes but does not start with the SEC1 uncompressed tag `0x04`. */
1291
- | 'IDENTITY_KEY_NOT_UNCOMPRESSED'
1292
- /** Non-2xx, non-404 from `GET /ilp/routes/price` (404 is not an error — see below). */
1293
- | 'ROUTE_PRICE_HTTP_STATUS'
1294
- /** `GET /ilp/routes/price` answered 2xx with a body that is not the documented object. */
1295
- | 'ROUTE_PRICE_MALFORMED'
1296
- /** A destination that cannot be put in a query string was asked about. */
1297
- | 'INVALID_DESTINATION'
1298
- /** A 402 greeting whose body is not the documented x402 shape (or whose
1299
- * optional `settlement` facts are present but malformed — refused rather
1300
- * than silently dropped, since they would be opened AGAINST). */
1301
- | 'TERMS_MALFORMED';
1302
- /**
1303
- * A refusal to carry a connector's answer forward. Distinct from
1304
- * {@link NetworkError} (which this module throws for a transport failure), so
1305
- * "the connector is unreachable" and "the connector answered something I will
1306
- * not seal to" are never confused.
1941
+ * BTP transport implementing IlpClient.
1942
+ * Uses IsomorphicBtpClient (browser-native, no Node.js dependencies).
1307
1943
  */
1308
- declare class ConnectorEdgeError extends ToonClientError {
1309
- /** Narrowed from `ToonClientError`'s `string`; type-only, no runtime field. */
1310
- readonly code: ConnectorEdgeErrorCode;
1311
- constructor(message: string, code: ConnectorEdgeErrorCode, cause?: Error);
1944
+ declare class BtpRuntimeClient implements IlpClient {
1945
+ private btpClient;
1946
+ private readonly config;
1947
+ private _isConnected;
1948
+ constructor(config: BtpRuntimeClientConfig);
1949
+ /**
1950
+ * Connects to the BTP peer via WebSocket.
1951
+ */
1952
+ connect(): Promise<void>;
1953
+ /**
1954
+ * Attempts to reconnect by creating a fresh client and connecting.
1955
+ */
1956
+ reconnect(): Promise<void>;
1957
+ /**
1958
+ * Disconnects from the BTP peer.
1959
+ */
1960
+ disconnect(): Promise<void>;
1961
+ get isConnected(): boolean;
1962
+ /**
1963
+ * Sends an ILP packet via BTP with auto-reconnect on connection errors.
1964
+ * Satisfies IlpClient interface.
1965
+ *
1966
+ * `params` may carry a sender-chosen `executionCondition` and an explicit
1967
+ * `expiresAt` (toon-client#350); omitting both is the legacy zero-condition
1968
+ * path, unchanged. With a non-zero condition the FULFILL preimage is
1969
+ * verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced
1970
+ * as a failed result — see `mapIlpResponse`.
1971
+ */
1972
+ sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;
1973
+ /**
1974
+ * Sends a balance proof claim via BTP protocol data, then sends an ILP packet.
1975
+ * Auto-reconnects on connection errors.
1976
+ *
1977
+ * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are
1978
+ * identical to {@link sendIlpPacket}.
1979
+ */
1980
+ sendIlpPacketWithClaim(params: IlpSendParams, claim: Record<string, unknown>): Promise<IlpSendResult>;
1981
+ /**
1982
+ * Send a standalone `payment-channel-claim` BTP MESSAGE (no ILP packet
1983
+ * attached). The connector's ClaimReceiver consumes this fire-and-forget
1984
+ * to register cumulative claim state independently of the per-packet
1985
+ * forwarding path. Auto-reconnects on connection errors.
1986
+ */
1987
+ sendClaimMessage(claim: Record<string, unknown>): Promise<void>;
1988
+ private _sendClaimMessageOnce;
1989
+ /**
1990
+ * Build the ILP PREPARE for a send, applying the sender-chosen condition /
1991
+ * explicit expiry when provided (toon-client#350) and validating that a
1992
+ * non-zero condition is exactly 32 bytes (the OER serializer would
1993
+ * otherwise silently zero-fill it, downgrading the packet to the legacy
1994
+ * unverified class).
1995
+ */
1996
+ private buildPrepare;
1997
+ /**
1998
+ * Single-attempt ILP packet send. Reconnects if not connected.
1999
+ */
2000
+ private _sendIlpPacketOnce;
2001
+ /**
2002
+ * Single-attempt claim + ILP packet send. Reconnects if not connected.
2003
+ */
2004
+ private _sendIlpPacketWithClaimOnce;
1312
2005
  }
2006
+
1313
2007
  /**
1314
- * Normalize any client-edge URL a caller already holds into the base the
1315
- * `/ilp/*` routes hang off.
2008
+ * ILP-over-HTTP (RFC-0035) transport for the TOON client.
1316
2009
  *
1317
- * Callers reach this module holding whatever the x402 offer or their config
1318
- * gave them — `https://apex.example`, `https://apex.example/`, or the
1319
- * `POST /ilp` endpoint `https://apex.example/ilp` itself. All three name the
1320
- * same client edge, so all three normalize to `https://apex.example`.
1321
- */
1322
- declare function connectorEdgeBaseUrl(endpoint: string): string;
1323
- /**
1324
- * Decode a `0x`-prefixed hex public key into its 65 raw bytes, refusing
1325
- * anything that is not exactly one uncompressed secp256k1 key.
1326
- */
1327
- declare function decodeConnectorPublicKey(publicKeyHex: string): Uint8Array;
1328
- /**
1329
- * Parse an already-decoded `GET /ilp/identity` body. Exported so the shape the
1330
- * connector actually emits can be pinned without standing up a server.
2010
+ * The connector now serves ILP-over-HTTP on the SAME port as BTP (connector
2011
+ * PR #181). This adapter lets a client do stateless one-shot writes over HTTP
2012
+ * (`POST /ilp`) and upgrade to a duplex BTP session when it needs to receive
2013
+ * server-initiated packets or act as a peer.
2014
+ *
2015
+ * Wire contract (targets connector PR #181's `/ilp`):
2016
+ * - One-shot write: `POST /ilp`
2017
+ * body: OER-encoded ILP PREPARE (`application/octet-stream`)
2018
+ * header: `ILP-Payment-Channel-Claim: base64(JSON of the claim)` — the
2019
+ * SAME claim JSON the BTP path attaches as the
2020
+ * `payment-channel-claim` protocolData entry.
2021
+ * optional: `ILP-Peer-Id` + `Authorization: Bearer <secret>` identity.
2022
+ * response: `200 OK` with an OER FULFILL or REJECT body. HTTP non-2xx is
2023
+ * reserved for TRANSPORT errors (400/401/413/5xx); ILP-level
2024
+ * rejects come back as a 200 + REJECT body.
2025
+ * - Upgrade to BTP: standard HTTP `Upgrade` with `Sec-WebSocket-Protocol: btp`
2026
+ * plus the same `ILP-Peer-Id` + `Authorization` headers. The connector
2027
+ * pre-authenticates the BTP session from those headers (continuity), so
2028
+ * after `101` we send BTP frames WITHOUT a separate in-band auth frame.
2029
+ * Omitting the auth headers falls back to the normal BTP auth-frame flow.
2030
+ *
2031
+ * Reuses `serializeIlpPrepare`/`deserializeIlpPacket` from `btp/protocol.ts` —
2032
+ * the SAME OER codec the BTP path uses. Claim signing/construction is owned by
2033
+ * the caller (BootstrapService); this transport never builds or signs claims.
1331
2034
  */
1332
- declare function parseConnectorIdentity(body: unknown, endpoint: string): ConnectorIdentity;
1333
- /** Parse an already-decoded `GET /ilp/routes/price` 200 body. */
1334
- declare function parseConnectorRoutePrice(body: unknown): ConnectorRoutePrice;
1335
- interface ConnectorEdgeClientConfig {
1336
- /** HTTP fetch implementation. Default: global `fetch`. Injectable for tests. */
1337
- fetch?: typeof fetch;
1338
- /** Per-request timeout in milliseconds. Default 10_000. */
2035
+
2036
+ /** Header carrying the base64(JSON) payment-channel claim. */
2037
+ declare const ILP_CLAIM_HEADER = "ILP-Payment-Channel-Claim";
2038
+ /** Header carrying the peer identity. */
2039
+ declare const ILP_PEER_ID_HEADER = "ILP-Peer-Id";
2040
+ interface HttpIlpClientConfig {
2041
+ /** The peer's `POST /ilp` URL (the `httpEndpoint` from discovery). */
2042
+ httpEndpoint: string;
2043
+ /**
2044
+ * Optional peer identity. With no `peerId`/`authToken` the connector treats
2045
+ * the request as an anonymous no-auth peer (permissionless default) and
2046
+ * derives an ephemeral id from the claim signer.
2047
+ */
2048
+ peerId?: string;
2049
+ /** Bearer secret for `Authorization`. Omit for the no-auth peer path. */
2050
+ authToken?: string;
2051
+ /** Request timeout in milliseconds (default: 30000). */
1339
2052
  timeout?: number;
2053
+ /** Max retry attempts for transport-level network failures (default: 3). */
2054
+ maxRetries?: number;
2055
+ /** Initial retry delay in milliseconds (default: 1000). */
2056
+ retryDelay?: number;
2057
+ /** Custom fetch implementation (for testing / custom transports). */
2058
+ httpClient?: typeof fetch;
2059
+ /**
2060
+ * Custom WebSocket constructor for the BTP upgrade path (for testing /
2061
+ * custom transports). Forwarded to the underlying BtpRuntimeClient.
2062
+ */
2063
+ createWebSocket?: (url: string) => WebSocket;
1340
2064
  }
1341
2065
  /**
1342
- * Asks connectors for their identity and their terms, caching each identity
1343
- * per client-edge endpoint and each route price per (endpoint, destination).
1344
- *
1345
- * The cache is per endpoint rather than per client instance because a sender
1346
- * routinely speaks to several connectors, and re-fetching a key per packet
1347
- * would put a network round trip in front of every send. Nothing here expires
1348
- * on a timer: an operator key rotation, or a route being repriced, is a
1349
- * deliberate event, so {@link invalidateIdentity} / {@link invalidateRoutePrice}
1350
- * are how a stale answer is dropped.
2066
+ * Stateless ILP-over-HTTP transport implementing `IlpClient`.
1351
2067
  *
1352
- * A price is cached the same way and for the same reason (toon-client#452):
1353
- * under ADR 0020 a route's price is FLAT — one handler, one price — so it does
1354
- * not vary with what is being sent, and asking again per packet would buy
1355
- * nothing but latency.
2068
+ * Use this for pure one-shot consumers (publish-and-forget writes). When the
2069
+ * client needs a duplex session — to receive server-initiated packets or to act
2070
+ * as a peer — call {@link upgradeToBtp} to obtain a connected BtpRuntimeClient
2071
+ * that reuses the existing BTP code path.
1356
2072
  */
1357
- declare class ConnectorEdgeClient {
1358
- private readonly fetchImpl;
2073
+ declare class HttpIlpClient implements IlpClient {
2074
+ private readonly httpEndpoint;
2075
+ private readonly peerId;
2076
+ private readonly authToken;
1359
2077
  private readonly timeout;
1360
- private readonly identities;
1361
- private readonly prices;
1362
- constructor(config?: ConnectorEdgeClientConfig);
2078
+ private readonly retryConfig;
2079
+ private readonly httpClient;
2080
+ private readonly createWebSocket;
2081
+ constructor(config: HttpIlpClientConfig);
1363
2082
  /**
1364
- * The terminating connector's public key, fetched once per endpoint.
1365
- *
1366
- * @param endpoint any client-edge URL (`https://apex`, `https://apex/ilp`).
1367
- * @param options `forceRefresh` bypasses (and replaces) the cache entry.
2083
+ * The client edge this transport pays — the origin `GET /ilp/identity` and
2084
+ * `GET /ilp/routes/price` hang off (`ConnectorEdgeClient` normalizes the
2085
+ * trailing `/ilp` away). Exposed because a sealed write must ask the
2086
+ * connector it is ACTUALLY paying for its key, not a configured guess.
1368
2087
  */
1369
- getIdentity(endpoint: string, options?: {
1370
- forceRefresh?: boolean;
1371
- }): Promise<ConnectorIdentity>;
2088
+ get clientEdgeEndpoint(): string;
1372
2089
  /**
1373
- * Drop a cached identity — one endpoint's, or every endpoint's when
1374
- * `endpoint` is omitted. The way to react to a key rotation.
2090
+ * Send an ILP PREPARE via `POST /ilp` WITHOUT a claim. The connector accepts
2091
+ * this only on free/zero-amount routes; paid writes must use
2092
+ * {@link sendIlpPacketWithClaim}. Satisfies the IlpClient interface.
2093
+ *
2094
+ * `params` may carry a sender-chosen `executionCondition` and an explicit
2095
+ * `expiresAt` (toon-client#350); omitting both is the legacy zero-condition
2096
+ * path, unchanged. With a non-zero condition the FULFILL preimage is
2097
+ * verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced
2098
+ * as a failed result — see {@link mapIlpResponse}.
1375
2099
  */
1376
- invalidateIdentity(endpoint?: string): void;
1377
- /** Whether an identity for `endpoint` is already held (no request is made). */
1378
- hasCachedIdentity(endpoint: string): boolean;
2100
+ sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;
1379
2101
  /**
1380
- * What `destination` costs at this connector, or `null` when the connector
1381
- * answers `404` — no locally-terminated route matches it.
1382
- *
1383
- * `null` is the answer to "you do not terminate this", which is information;
1384
- * a transport failure throws {@link NetworkError} instead, so a caller can
1385
- * always tell "not mine" from "could not ask".
1386
- *
1387
- * Fetched once per (endpoint, destination) and reused. ADR 0020 makes a
1388
- * price flat per handler, so it does not vary with the packet — a route
1389
- * being repriced is an operator event, and {@link invalidateRoutePrice} is
1390
- * how a caller reacts to one.
2102
+ * Send an ILP PREPARE via `POST /ilp` with the payment-channel claim attached
2103
+ * as the `ILP-Payment-Channel-Claim` header. `claim` is the SAME JSON object
2104
+ * the BTP path attaches as the `payment-channel-claim` protocolData entry —
2105
+ * we base64(JSON.stringify(claim)) it, byte-for-byte identical to BTP.
1391
2106
  *
1392
- * @param options `forceRefresh` bypasses (and replaces) the cache entry.
2107
+ * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are
2108
+ * identical to {@link sendIlpPacket}.
1393
2109
  */
1394
- getRoutePrice(endpoint: string, destination: string, options?: {
1395
- forceRefresh?: boolean;
1396
- }): Promise<ConnectorRoutePrice | null>;
2110
+ sendIlpPacketWithClaim(params: IlpSendParams, claim: unknown): Promise<IlpSendResult>;
1397
2111
  /**
1398
- * Ask a route for its full x402 terms — the greeting a claimless PREPARE
1399
- * is answered with (client-edge-spec.md §1.4) — including, from a settling
1400
- * node, the channel-opening facts (connector #617).
2112
+ * Upgrade to a duplex BTP session over the SAME endpoint.
1401
2113
  *
1402
- * This is a real `POST /ilp` carrying a minimal PREPARE with no claim
1403
- * header. It is free by the wire's own contract: an unpaid request to a
1404
- * priced route is answered with terms instead of performed, and nothing
1405
- * is charged for asking. `null` when the connector does not price the
1406
- * destination (the request would be routed or refused, not greeted) —
1407
- * mapped from anything other than a 402 answer.
2114
+ * Derives the `ws(s)://` URL from `httpEndpoint`, opens a WebSocket with
2115
+ * `Sec-WebSocket-Protocol: btp` and the same `ILP-Peer-Id` + `Authorization`
2116
+ * headers, and returns a connected {@link BtpRuntimeClient}. When auth headers
2117
+ * are present the connector pre-authenticates the session (no in-band auth
2118
+ * frame); without them the BtpRuntimeClient falls back to the normal BTP
2119
+ * auth-frame flow.
2120
+ *
2121
+ * NOTE: passing per-connection headers + a subprotocol to a WebSocket is
2122
+ * Node-only (the `ws` package). Browsers cannot set arbitrary request headers
2123
+ * on a WebSocket handshake, so a browser consumer must use the gateway
2124
+ * transport or BTP-with-auth-frame instead.
1408
2125
  */
1409
- getRouteTerms(endpoint: string, destination: string): Promise<ConnectorRouteTerms | null>;
2126
+ upgradeToBtp(): Promise<BtpRuntimeClient>;
2127
+ private authHeaders;
1410
2128
  /**
1411
- * Drop a cached route price — one (endpoint, destination)'s, every
1412
- * destination's at one endpoint when `destination` is omitted, or all of
1413
- * them when both are. The way to react to a route being repriced.
2129
+ * Single attempt: serialize the PREPARE, POST it, and map the response.
2130
+ * @throws {NetworkError} On connection/timeout failures (retried).
2131
+ * @throws {ConnectorError} On non-retryable transport errors (5xx / unexpected).
1414
2132
  */
1415
- invalidateRoutePrice(endpoint?: string, destination?: string): void;
2133
+ private postPrepare;
1416
2134
  /**
1417
- * Whether a price for `(endpoint, destination)` is already held (no request
1418
- * is made).
2135
+ * Map a `200 OK` body (OER FULFILL/REJECT) to an IlpSendResult; map a non-2xx
2136
+ * to a transport error. Per the wire contract, ILP-level rejects arrive as a
2137
+ * 200 + REJECT body — only HTTP non-2xx means a transport-layer failure.
2138
+ *
2139
+ * When `sentCondition` is non-zero the FULFILL preimage is verified against
2140
+ * it; a mismatch yields `accepted: false` (shared `mapIlpResponse` logic,
2141
+ * identical to the BTP path).
1419
2142
  */
1420
- hasCachedRoutePrice(endpoint: string, destination: string): boolean;
1421
- private fetchRoutePrice;
1422
- private fetchIdentity;
1423
- private readJson;
1424
- /** GET with a timeout, mapping any transport failure onto {@link NetworkError}. */
1425
- private get;
2143
+ private mapResponse;
2144
+ private mapTransportError;
1426
2145
  }
2146
+ /**
2147
+ * Derive the BTP WebSocket URL from a `POST /ilp` HTTP endpoint. The connector
2148
+ * serves BTP on the SAME path, so we only swap the scheme (http→ws, https→wss).
2149
+ */
2150
+ declare function httpEndpointToBtpUrl(httpEndpoint: string): string;
1427
2151
 
1428
2152
  /**
1429
2153
  * Payment-aware HTTP fetch over TOON (the "h402" flow).
@@ -1811,7 +2535,7 @@ interface SubmitEvmSettlementParams {
1811
2535
  /** JSON-RPC endpoint of the bundle's chain (`chainRpcUrls[bundle.chain]`). */
1812
2536
  rpcUrl: string;
1813
2537
  /** The claim recipient's EVM account (signs + pays gas for the redeem). */
1814
- account: PrivateKeyAccount;
2538
+ account: PrivateKeyAccount$1;
1815
2539
  /** Receipt wait bound, ms (default 60_000). */
1816
2540
  timeoutMs?: number;
1817
2541
  }
@@ -1938,7 +2662,25 @@ declare class ToonClient {
1938
2662
  * or agent supplies only `{ kind, content, tags, created_at }` and never holds
1939
2663
  * the private key — signing happens here, inside the key owner.
1940
2664
  */
1941
- signEvent(template: EventTemplate): NostrEvent;
2665
+ signEvent(template: EventTemplate): NostrEvent;
2666
+ /**
2667
+ * Unwrap a NIP-59 gift wrap (kind:1059) addressed to this client's own
2668
+ * Nostr identity, decrypting both NIP-44 layers with the identity's secret
2669
+ * key. The secret key never leaves this call — only the decrypted rumor
2670
+ * and the seal's (signature-verified) signer pubkey come back out.
2671
+ *
2672
+ * Backs the daemon's `POST /nip59-unwrap` control-API endpoint (buzz#19
2673
+ * agent-members receiving gift-wrapped channel keys addressed to the
2674
+ * daemon's identity). Callers MUST validate authorship from the returned
2675
+ * `sealPubkey` — never from `wrap.pubkey`, which NIP-59 mints fresh and
2676
+ * throws away per wrap.
2677
+ *
2678
+ * @throws {GiftWrapAddressError} malformed input, wrong kind, or not
2679
+ * addressed to this identity.
2680
+ * @throws {GiftWrapDecryptError} a NIP-44 layer failed to decrypt, or the
2681
+ * seal's signature didn't verify.
2682
+ */
2683
+ unwrapGiftWrap(wrap: NostrEvent): UnwrappedGiftWrap;
1942
2684
  /**
1943
2685
  * Upload bytes to Arweave via the kind:5094 blob-storage DVM (single-packet),
1944
2686
  * signing the request with this client's Nostr key and paying through its
@@ -2189,6 +2931,13 @@ declare class ToonClient {
2189
2931
  * `connectorHttpEndpoint` is configured, else the BtpRuntimeClient.
2190
2932
  * 2. `btpClient` as an explicit fallback (always present when `btpUrl` is set).
2191
2933
  *
2934
+ * `config.preferBtpForPaidWrites` (toon-client#482) SWAPS that order: when
2935
+ * set, `btpClient` — which `modes/http.ts` wraps in a
2936
+ * {@link BtpPaidWriteTransport} for this case, giving persistent,
2937
+ * strictly-ordered claim dispatch with its own fallback to `runtimeClient`
2938
+ * — is tried first, and `runtimeClient` remains as a second candidate.
2939
+ * Default `false` reproduces the exact precedence above, unchanged.
2940
+ *
2192
2941
  * The level-3 `HttpRuntimeClient` (connector-admin HTTP, no `btpUrl` AND no
2193
2942
  * proxy) does NOT implement `sendIlpPacketWithClaim`; in that case there is no
2194
2943
  * paid-write transport and we throw a clear, actionable error.
@@ -2227,6 +2976,17 @@ declare class ToonClient {
2227
2976
  * configured, or peer negotiation metadata missing.
2228
2977
  */
2229
2978
  openChannel(destination?: string): Promise<string>;
2979
+ /**
2980
+ * Adopt an ALREADY-OPEN payment channel for `destination` — the restart path
2981
+ * for a host that persisted the channel id itself (#489).
2982
+ *
2983
+ * Tracking a channel is not enough: the lazy-open path keys off the peer, so
2984
+ * a host that only re-tracked its saved channel still opened (and funded) a
2985
+ * SECOND one on the first paid write. This binds it, so every later write
2986
+ * resumes it, with its claim watermark, and the on-chain client can deposit
2987
+ * into and close it too. Idempotent.
2988
+ */
2989
+ adoptChannel(destination: string, channelId: string): Promise<void>;
2230
2990
  /**
2231
2991
  * Gets list of tracked payment channel IDs.
2232
2992
  */
@@ -2239,6 +2999,28 @@ declare class ToonClient {
2239
2999
  * Gets the cumulative transferred amount for a tracked channel.
2240
3000
  */
2241
3001
  getChannelCumulativeAmount(channelId: string): bigint;
3002
+ /**
3003
+ * The credited balance — earning's read surface (toon-client#494,
3004
+ * toon-meta#262 decision 9). Asks the connector's `POST /ilp/claim-state`
3005
+ * (client-edge-spec.md §1.10) for the netted off-chain position of one or
3006
+ * more tracked channels: deposit, cumulative claimed, available, nonce and
3007
+ * last-claim time — the SAME place `getBalances`'s on-chain reads and a
3008
+ * paid write's claim gate both already treat as this channel's runway
3009
+ * source of truth, rather than a parallel figure this client derives
3010
+ * itself (#262 decision 4 forbids self-reported money).
3011
+ *
3012
+ * `channelIds` defaults to every tracked channel. A channel this client has
3013
+ * no signer for (e.g. Mina — unsupported by this endpoint) or no recorded
3014
+ * chain context for is silently skipped, matching `getBalances`'s
3015
+ * best-effort-per-chain posture.
3016
+ *
3017
+ * @param opts.expiresInSeconds - How long the signed challenge stays valid
3018
+ * (default 300s). This is a READ signature, distinct from a real claim —
3019
+ * it moves no value and advances no nonce.
3020
+ */
3021
+ getClaimState(channelIds?: string[], opts?: {
3022
+ expiresInSeconds?: number;
3023
+ }): Promise<ClaimStateResult[]>;
2242
3024
  /**
2243
3025
  * Gets the on-chain deposit total (locked collateral) for a tracked channel.
2244
3026
  * The available (spendable) balance is this minus the cumulative spent amount.
@@ -2317,6 +3099,21 @@ declare class ToonClient {
2317
3099
  * are derived there).
2318
3100
  */
2319
3101
  getBalances(): Promise<WalletBalance[]>;
3102
+ /**
3103
+ * Lazily derive the mnemonic's full multi-chain identity, at most once per
3104
+ * call to the returned function. Solana/Mina keys are only registered as
3105
+ * signers during `start()`; this lets an UNSTARTED client (e.g. `rig
3106
+ * balance`, or `sendTransfer` before `start()`) derive them on demand
3107
+ * instead. Shared by {@link getWalletBalances} and {@link sendTransfer}.
3108
+ */
3109
+ private createIdentityDeriver;
3110
+ /**
3111
+ * The EVM chain key + RPC URL to use for a settlement-token/native-gas
3112
+ * operation: the settlement chain wins over the preset-first chain, mirroring
3113
+ * {@link getBalances}. Shared by {@link getWalletBalances} and
3114
+ * {@link sendTransfer}.
3115
+ */
3116
+ private resolveSettlementEvmChain;
2320
3117
  /**
2321
3118
  * The FULL multi-chain wallet view (#299): for every chain the identity is
2322
3119
  * configured for, the native coin (ETH / SOL / MINA) AND every configured
@@ -2343,6 +3140,34 @@ declare class ToonClient {
2343
3140
  solanaChannel?: ToonClientConfig['solanaChannel'];
2344
3141
  minaChannel?: ToonClientConfig['minaChannel'];
2345
3142
  }): Promise<WalletChainBalances[]>;
3143
+ /**
3144
+ * Send the settlement token or native gas from THIS client's own wallet to
3145
+ * an arbitrary address, on any chain this client is configured for.
3146
+ * Non-custodial plain send (issue #491) — distinct from the payment-channel
3147
+ * machinery, and the missing primitive underneath provisioning a buzz agent
3148
+ * (toon-protocol/buzz#74): the owner's treasury funds a freshly-derived
3149
+ * agent address with USDC + gas before that address can open a channel.
3150
+ *
3151
+ * Confirmed by an OBSERVED balance delta at the destination, never by the
3152
+ * send call/transaction merely landing — see `transfer.ts` module docs
3153
+ * (the devnet faucet's Solana leg has returned a real tx signature while
3154
+ * delivering 0 lamports, connector#691).
3155
+ *
3156
+ * Chain resolution mirrors {@link getWalletBalances}: EVM picks the
3157
+ * settlement chain key (falling back to the first usable EVM chain) from
3158
+ * `chainRpcUrls`/`settlementAddresses`; Solana/Mina need `solanaChannel`/
3159
+ * `minaChannel` configured, and their signing keys are either already
3160
+ * derived (client was `start()`-ed) or derived on demand from `mnemonic`.
3161
+ *
3162
+ * @throws {UnknownChainError} `params.chain` isn't configured on this client.
3163
+ * @throws {InvalidAddressError} `params.to` is malformed for the chain.
3164
+ * @throws {InsufficientBalanceError} the sender can't cover amount (+ fees).
3165
+ * @throws {TransferNotDeliveredError} accepted on-chain/by-node, but the
3166
+ * destination balance never reflected it within the wait window.
3167
+ * @throws {TransferUnsupportedError} chain/asset combination not implemented
3168
+ * yet (currently: the Mina settlement token).
3169
+ */
3170
+ sendTransfer(params: SendTransferParams): Promise<SendTransferResult>;
2346
3171
  /**
2347
3172
  * Resolves an ILP destination address to a peer ID.
2348
3173
  * Convention: destination "g.toon.peer1" → peerId "peer1" (last segment).
@@ -2445,7 +3270,27 @@ declare class ToonClient {
2445
3270
  */
2446
3271
  private getChainContext;
2447
3272
  /**
2448
- * Gets the default chain context from the first supported chain in config.
3273
+ * Picks the settlement chain both `ourChains` and `peerChains` support,
3274
+ * used by the lightweight bootstrap-fallback negotiation (peer discovered
3275
+ * but no connector admin registered a chain). Prefers
3276
+ * `this.config.preferredChain`'s family (#485) over array order; falls
3277
+ * back to the first mutually-supported chain (legacy behavior) when
3278
+ * unconfigured.
3279
+ *
3280
+ * @throws {ToonClientError} `CHAIN_NOT_SUPPORTED` if a chain is explicitly
3281
+ * configured but the peer doesn't support any chain in that family —
3282
+ * this must fail loudly rather than silently negotiate a different chain.
3283
+ */
3284
+ private matchNegotiatedChain;
3285
+ /**
3286
+ * Gets the default chain context: the explicitly-configured
3287
+ * `preferredChain` family when set (#485 — e.g. `TOON_CLIENT_CHAIN=evm`
3288
+ * must not silently pin to `supportedChains[0]` when that happens to be a
3289
+ * different chain, such as Solana), else the first supported chain.
3290
+ *
3291
+ * @throws {ToonClientError} `CHAIN_NOT_SUPPORTED` if `preferredChain` is
3292
+ * set but none of `supportedChains` belong to that family — this must
3293
+ * fail loudly rather than fall back to a chain the caller didn't choose.
2449
3294
  */
2450
3295
  private getDefaultChainContext;
2451
3296
  /**
@@ -2491,6 +3336,131 @@ declare class ToonClient {
2491
3336
  getDiscoveredPeers(): _toon_protocol_core.DiscoveredPeer[];
2492
3337
  }
2493
3338
 
3339
+ /**
3340
+ * Hashlock delivery helpers (toon-meta#262 decision 5, toon-client#495) —
3341
+ * symmetric between the provider and buyer sides of one factory-job
3342
+ * increment, per `docs/factory-job-protocol.md` §4.2 (toon-meta).
3343
+ *
3344
+ * The provider encrypts an increment's artifact under a fresh key and sets
3345
+ * `condition = sha256(key)`; the only way to claim the increment's payment
3346
+ * is to reveal `key` as the ILP fulfillment — which is the same instant the
3347
+ * buyer can decrypt. Neither party moves first, because there is no first.
3348
+ *
3349
+ * That property holds only if `condition` is derived from nothing but the
3350
+ * key that actually decrypts the artifact. {@link encryptArtifact} is the
3351
+ * ONLY place a `condition` is minted, and it takes no key or condition
3352
+ * parameter — there is no way to call it with a condition that does not
3353
+ * match the key it generates. Do not build a second path that derives a
3354
+ * condition from the artifact, a job id, or any other value.
3355
+ *
3356
+ * Artifacts are permanent on Arweave (decision 13) — there is no deletion —
3357
+ * so confidentiality rests entirely on `key`. Never log a key, and never let
3358
+ * one reach an error message.
3359
+ *
3360
+ * AEAD: ChaCha20-Poly1305 (RFC 8439), the same primitive `wire/giftwrap.ts`
3361
+ * uses for the connector's sealed envelopes — 12-byte random nonce prepended
3362
+ * to the ciphertext, no additional authenticated data. The key doubles as
3363
+ * the 32-byte ILP fulfillment ({@link fulfillIncrement}), which is why it is
3364
+ * exactly {@link CONDITION_LENGTH} bytes rather than a cipher-chosen size.
3365
+ *
3366
+ * Isomorphic: `@noble/*` only, no Buffer, no `node:crypto`.
3367
+ */
3368
+ /** What encrypting an artifact produces (provider side). */
3369
+ interface EncryptedArtifact {
3370
+ /** `nonce(12) || AEAD ciphertext` — safe to upload to Arweave as-is. */
3371
+ readonly ciphertext: Uint8Array;
3372
+ /**
3373
+ * The freshly minted 32-byte symmetric key. This is also the ILP
3374
+ * fulfillment ({@link fulfillIncrement}) — never reuse it for another
3375
+ * increment, never log it, never put it in an error message.
3376
+ */
3377
+ readonly key: Uint8Array;
3378
+ /** `sha256(key)` — publish as the kind:7000 offer's `condition` tag. */
3379
+ readonly condition: Uint8Array;
3380
+ }
3381
+ /**
3382
+ * Provider: encrypt one increment's artifact under a freshly minted key and
3383
+ * derive its hashlock condition.
3384
+ *
3385
+ * Deliberately takes only the artifact bytes. There is no `key` or
3386
+ * `condition` parameter — accepting either would let a caller mint a
3387
+ * condition that does not match the key that actually decrypts the
3388
+ * artifact, silently breaking the atomicity this module exists to
3389
+ * guarantee. Call this once per increment; a reused key means paying for
3390
+ * increment *i* unlocks increment *i+1*.
3391
+ */
3392
+ declare function encryptArtifact(artifact: Uint8Array): EncryptedArtifact;
3393
+ /**
3394
+ * Provider: fulfil an increment by revealing `key` as the ILP fulfillment.
3395
+ * The key IS the fulfillment (identity) — this exists so the "reveal the
3396
+ * key" step has one named call site rather than being inlined wherever a
3397
+ * FULFILL is built, and so a wrongly-sized key fails loudly here instead of
3398
+ * on the wire.
3399
+ *
3400
+ * @throws {Error} if `key` is not exactly {@link CONDITION_LENGTH} bytes.
3401
+ */
3402
+ declare function fulfillIncrement(key: Uint8Array): Uint8Array;
3403
+ /**
3404
+ * Thrown when `sha256(key)` does not match the condition the buyer actually
3405
+ * paid. Never carries `key` or any derived secret — only lengths and hex of
3406
+ * the (public) conditions being compared.
3407
+ */
3408
+ declare class HashlockConditionMismatchError extends Error {
3409
+ constructor(message: string);
3410
+ }
3411
+ /**
3412
+ * Thrown when a ciphertext fails to decrypt under a key that DID satisfy the
3413
+ * paid condition — a corrupted or tampered artifact fetch. Never carries the
3414
+ * key or any recovered plaintext.
3415
+ */
3416
+ declare class HashlockDecryptError extends Error {
3417
+ readonly cause?: Error | undefined;
3418
+ constructor(message: string, cause?: Error | undefined);
3419
+ }
3420
+ /**
3421
+ * Buyer: verify `key` against `paidCondition`, then decrypt.
3422
+ *
3423
+ * `paidCondition` MUST be the condition the buyer's own PREPARE carried as
3424
+ * `executionCondition` — read from local state, never re-derived from the
3425
+ * `key` just handed over by the provider at reveal time. Re-deriving it
3426
+ * would make this check tautological and defeat the reason it exists: to
3427
+ * catch a provider who advertised one condition, got paid against it, then
3428
+ * revealed a DIFFERENT key that happens to decrypt something.
3429
+ *
3430
+ * @throws {HashlockConditionMismatchError} `sha256(key) !== paidCondition`.
3431
+ * @throws {HashlockDecryptError} the AEAD open failed (tampered/corrupted
3432
+ * ciphertext, or a truncated one).
3433
+ */
3434
+ declare function decryptArtifact(ciphertext: Uint8Array, key: Uint8Array, paidCondition: Uint8Array): Uint8Array;
3435
+ /** What a buyer reads off an advertised kind:7000 increment offer (§4.1). */
3436
+ interface IncrementOfferTags {
3437
+ /** The `condition` tag's value: hex-encoded `sha256(key)`. */
3438
+ readonly conditionHex: string;
3439
+ /** The `amount` tag's value: decimal micro-USDC. */
3440
+ readonly amountUsdc: string;
3441
+ }
3442
+ /** PREPARE-ready fields derived from an advertised increment offer. */
3443
+ interface IncrementPrepare {
3444
+ /** Spread into `ToonClient.sendSwapPacket`'s `executionCondition`. */
3445
+ readonly executionCondition: Uint8Array;
3446
+ /** Spread into `ToonClient.sendSwapPacket`'s `amount`. */
3447
+ readonly amount: bigint;
3448
+ }
3449
+ /**
3450
+ * Buyer: turn an advertised kind:7000 increment offer's `condition` and
3451
+ * `amount` tags into the fields a PREPARE needs — `executionCondition` MUST
3452
+ * equal the offer's `condition` byte for byte (spec §4.2), which is exactly
3453
+ * what this returns, undecorated.
3454
+ *
3455
+ * Pure parsing: does not send anything, does not touch a channel. Feed the
3456
+ * result into `sendSwapPacket({ destination, amount, toonData, executionCondition })`.
3457
+ *
3458
+ * @throws {Error} a malformed hex condition, a condition that is not
3459
+ * {@link CONDITION_LENGTH} bytes once decoded, or a non-positive/
3460
+ * non-numeric amount.
3461
+ */
3462
+ declare function buildIncrementPrepare(offer: IncrementOfferTags): IncrementPrepare;
3463
+
2494
3464
  /**
2495
3465
  * Configuration options for HttpRuntimeClient.
2496
3466
  */
@@ -2755,316 +3725,254 @@ declare class HttpConnectorAdmin implements ConnectorAdminClient {
2755
3725
  /**
2756
3726
  * Send HTTP POST request to add a peer.
2757
3727
  * Separated for retry logic wrapping.
2758
- */
2759
- private sendAddPeerRequest;
2760
- /**
2761
- * Send HTTP DELETE request to remove a peer.
2762
- * Separated for retry logic wrapping.
2763
- */
2764
- private sendRemovePeerRequest;
2765
- /**
2766
- * Handle network errors from HTTP requests.
2767
- *
2768
- * Converts connection failures, timeouts, and unknown errors to NetworkError.
2769
- * Re-throws existing ToonClientError instances.
2770
- *
2771
- * @param error - Error thrown by HTTP client
2772
- * @param url - Request URL (for error messages)
2773
- * @param operation - Operation name (for error messages)
2774
- * @throws {NetworkError} Network connection or timeout error
2775
- */
2776
- private handleNetworkError;
2777
- /**
2778
- * Handle HTTP error responses from the admin API.
2779
- *
2780
- * Converts HTTP status codes to appropriate error types.
2781
- *
2782
- * @param response - HTTP response from admin API
2783
- * @param endpoint - Endpoint being called (for error messages)
2784
- * @param peerId - Peer ID (for error messages)
2785
- * @throws {UnauthorizedError} 401 Unauthorized
2786
- * @throws {PeerNotFoundError} 404 Not Found
2787
- * @throws {PeerAlreadyExistsError} 409 Conflict
2788
- * @throws {ConnectorError} 5xx Server Error
2789
- */
2790
- private handleErrorResponse;
2791
- }
2792
-
2793
- /**
2794
- * Transport selection policy for the client ILP layer.
2795
- *
2796
- * The connector serves ILP-over-HTTP (`POST /ilp`) and BTP on the SAME port
2797
- * (connector PR #181). A peer advertises this in discovery via the toon-core
2798
- * `IlpPeerInfo` fields added in toon PR #29:
2799
- * - `httpEndpoint?: string` — the `POST /ilp` URL.
2800
- * - `supportsUpgrade?: boolean` — whether the host accepts the BTP upgrade.
2801
- *
2802
- * Those fields may not yet exist on the installed `@toon-protocol/core`
2803
- * `IlpPeerInfo` type, so we read them defensively here (see `DiscoveredIlpPeer`).
2804
- *
2805
- * Policy:
2806
- * - Pure one-shot consumers (`needsDuplex: false`) prefer HTTP when the peer
2807
- * advertises an `httpEndpoint` — stateless, no persistent socket.
2808
- * - Clients that must receive server-initiated packets or act as a peer
2809
- * (`needsDuplex: true`) use BTP. If the peer only exposes `httpEndpoint`
2810
- * and `supportsUpgrade` is true, we go HTTP-then-upgrade; otherwise we
2811
- * connect to the BTP endpoint directly.
2812
- */
2813
- /**
2814
- * The subset of discovery fields this policy reads. Structurally compatible with
2815
- * core's `IlpPeerInfo`; `httpEndpoint`/`supportsUpgrade` are optional so a
2816
- * pre-PR-#29 `IlpPeerInfo` can be passed through a cast.
2817
- */
2818
- interface DiscoveredIlpPeer {
2819
- /** BTP WebSocket endpoint (always present on a TOON peer). */
2820
- btpEndpoint?: string;
2821
- /** `POST /ilp` URL (toon PR #29). */
2822
- httpEndpoint?: string;
2823
- /** Whether the host accepts the BTP upgrade over the HTTP endpoint (toon PR #29). */
2824
- supportsUpgrade?: boolean;
2825
- }
2826
- type IlpTransportChoice =
2827
- /** Stateless one-shot writes via `POST /ilp`. */
2828
- {
2829
- kind: 'http';
2830
- httpEndpoint: string;
2831
- canUpgrade: boolean;
2832
- }
2833
- /** Duplex BTP session via the WebSocket endpoint. */
2834
- | {
2835
- kind: 'btp';
2836
- btpEndpoint: string;
2837
- }
2838
- /**
2839
- * Open HTTP first (one-shot writes) but upgrade to BTP when duplex is needed.
2840
- * Only chosen when the peer exposes `httpEndpoint` + `supportsUpgrade` and no
2841
- * separate `btpEndpoint`.
2842
- */
2843
- | {
2844
- kind: 'http-upgradable';
2845
- httpEndpoint: string;
2846
- };
2847
- interface SelectIlpTransportOptions {
2848
- /**
2849
- * Whether the client needs a duplex session (receive server-initiated
2850
- * packets / act as a peer). Default: false (pure one-shot consumer).
2851
- */
2852
- needsDuplex?: boolean;
2853
- }
2854
- /**
2855
- * Read discovery fields defensively from a (possibly pre-PR-#29) peer info
2856
- * object. Accepts core's `IlpPeerInfo` or any structurally-compatible shape.
2857
- */
2858
- declare function readDiscoveredIlpPeer(peer: unknown): DiscoveredIlpPeer;
2859
- /**
2860
- * Choose the ILP transport for a discovered peer given the consumer's needs.
2861
- *
2862
- * @throws {Error} If the peer advertises no usable endpoint at all.
2863
- */
2864
- declare function selectIlpTransport(peer: DiscoveredIlpPeer, options?: SelectIlpTransportOptions): IlpTransportChoice;
2865
-
2866
- /**
2867
- * Chain-specific metadata (discriminated union).
2868
- */
2869
- type ChainMetadata = {
2870
- chainType: 'evm';
2871
- chainId: number;
2872
- tokenNetworkAddress: string;
2873
- tokenAddress?: string;
2874
- } | {
2875
- chainType: 'solana';
2876
- programId: string;
2877
- tokenMint?: string;
2878
- } | {
2879
- chainType: 'mina';
2880
- zkAppAddress: string;
2881
- tokenId?: string;
2882
- };
2883
- /**
2884
- * Chain-agnostic signing interface for balance proofs.
2885
- */
2886
- interface ChainSigner {
2887
- readonly chainType: 'evm' | 'solana' | 'mina';
2888
- readonly signerIdentifier: string;
2889
- signBalanceProof(params: {
2890
- channelId: string;
2891
- nonce: number;
2892
- transferredAmount: bigint;
2893
- lockedAmount: bigint;
2894
- locksRoot: string;
2895
- /**
2896
- * Counterparty settlement address the proof is bound to. Required for
2897
- * Solana/Mina (folded into the canonical balance-proof message); the EVM
2898
- * adapter ignores it (EIP-712 has no recipient term).
2899
- */
2900
- recipient: string;
2901
- metadata: ChainMetadata;
2902
- /**
2903
- * On-chain channel `depositTotal` (base units). When supplied (>0), a Mina
2904
- * signer binds the conserved `balanceB = depositTotal − balanceA` commitment
2905
- * required to settle on a funded zkApp (connector#133); EVM/Solana signers
2906
- * ignore it. When omitted, a Mina signer self-resolves it from chain if it
2907
- * was configured with a GraphQL URL (#223), else falls back to the legacy
2908
- * `balanceB = 0` form.
2909
- */
2910
- depositTotal?: bigint;
2911
- }): Promise<SignedBalanceProof>;
2912
- buildClaimMessage(proof: SignedBalanceProof, senderId: string): ClaimMessage;
2913
- }
2914
- type ClaimMessage = EVMClaimMessage | SolanaClaimMessage | MinaClaimMessage;
2915
- /**
2916
- * Solana payment-channel claim — wire-compatible with the connector's
2917
- * `SolanaClaimMessage` (`@toon-protocol/connector` `btp/btp-claim-types.ts`).
2918
- * Field names match the connector's `validateSolanaClaim` exactly:
2919
- * `channelAccount` (base58 PDA), `signerPublicKey` (base58), base64 `signature`.
2920
- */
2921
- interface SolanaClaimMessage {
2922
- version: '1.0';
2923
- blockchain: 'solana';
2924
- messageId: string;
2925
- timestamp: string;
2926
- senderId: string;
2927
- /** On-chain PDA account address for the payment channel (base58). */
2928
- channelAccount: string;
2929
- nonce: number;
2930
- /** Cumulative transferred amount (string for bigint precision). */
2931
- transferredAmount: string;
2932
- /** Ed25519 signature over the 48-byte balance-proof message (base64). */
2933
- signature: string;
2934
- /** Base58-encoded Ed25519 public key of the signer. */
2935
- signerPublicKey: string;
2936
- /** Solana program id for the payment-channel program (base58). */
2937
- programId: string;
2938
- }
2939
- /**
2940
- * Mina payment-channel claim — wire-compatible with the connector's
2941
- * `MinaClaimMessage` (`@toon-protocol/connector` `btp/btp-claim-types.ts`).
2942
- * Field names + types match `validateMinaClaim` exactly: `zkAppAddress`
2943
- * (B62-prefixed 55-char base58, the channel id), `tokenId`, `balanceCommitment`
2944
- * (`Poseidon([balA,balB,salt])` decimal string), integer `nonce`, base64 `proof`,
2945
- * and `salt`. `transferredAmount`/`balanceB`/`signatureB`/`network` are OPTIONAL
2946
- * at validation; the apex-as-recipient single-direction claim sends party-A only.
2947
- */
2948
- interface MinaClaimMessage {
2949
- version: '1.0';
2950
- blockchain: 'mina';
2951
- messageId: string;
2952
- timestamp: string;
2953
- senderId: string;
2954
- /** Deployed payment-channel zkApp address (B62 base58) — the channel id. */
2955
- zkAppAddress: string;
2956
- /** Mina token id (default `'MINA'`). */
2957
- tokenId: string;
2958
- /** `Poseidon([balanceA, balanceB, salt]).toString()`. */
2959
- balanceCommitment: string;
2960
- nonce: number;
2961
- /** base64-encoded JSON `{ commitment, signature: { r, s }, nonce, signerPublicKey }`. */
2962
- proof: string;
2963
- /** Commitment salt (decimal string). */
2964
- salt: string;
2965
- /** Cumulative transferred amount (optional; string for bigint precision). */
2966
- transferredAmount?: string;
3728
+ */
3729
+ private sendAddPeerRequest;
2967
3730
  /**
2968
- * Signer's Mina public key (B62 base58) — the claiming participant.
3731
+ * Send HTTP DELETE request to remove a peer.
3732
+ * Separated for retry logic wrapping.
3733
+ */
3734
+ private sendRemovePeerRequest;
3735
+ /**
3736
+ * Handle network errors from HTTP requests.
2969
3737
  *
2970
- * Surfaced top-level (in addition to being embedded in `proof`) so the
2971
- * connector's `SettlementExecutor` can resolve participant keys for the
2972
- * on-chain `claimFromChannel` on an externally-opened (inbound) channel. The
2973
- * connector reads `latestClaim.signerPublicKey` directly (not the proof blob);
2974
- * without it the Mina SDK's `claimFromChannel` throws `ACCOUNT_NOT_FOUND`
2975
- * ("Participant keys not found in cache and none were supplied"). The
2976
- * connector accepts this as an optional `MinaClaimMessage` field.
3738
+ * Converts connection failures, timeouts, and unknown errors to NetworkError.
3739
+ * Re-throws existing ToonClientError instances.
3740
+ *
3741
+ * @param error - Error thrown by HTTP client
3742
+ * @param url - Request URL (for error messages)
3743
+ * @param operation - Operation name (for error messages)
3744
+ * @throws {NetworkError} Network connection or timeout error
2977
3745
  */
2978
- signerPublicKey?: string;
2979
- /** Mina network id — defaults to `devnet` connector-side when omitted. */
2980
- network?: 'mainnet' | 'devnet' | 'berkeley' | 'lightnet';
3746
+ private handleNetworkError;
3747
+ /**
3748
+ * Handle HTTP error responses from the admin API.
3749
+ *
3750
+ * Converts HTTP status codes to appropriate error types.
3751
+ *
3752
+ * @param response - HTTP response from admin API
3753
+ * @param endpoint - Endpoint being called (for error messages)
3754
+ * @param peerId - Peer ID (for error messages)
3755
+ * @throws {UnauthorizedError} 401 Unauthorized
3756
+ * @throws {PeerNotFoundError} 404 Not Found
3757
+ * @throws {PeerAlreadyExistsError} 409 Conflict
3758
+ * @throws {ConnectorError} 5xx Server Error
3759
+ */
3760
+ private handleErrorResponse;
2981
3761
  }
2982
3762
 
2983
3763
  /**
2984
- * EVM claim message for BTP protocol data.
2985
- * Matches @toon-protocol/connector's EVMClaimMessage interface.
2986
- *
2987
- * The connector's validateClaimMessage() requires envelope fields
2988
- * (version, messageId, timestamp) plus EVM claim fields, and optionally
2989
- * chainId + tokenNetworkAddress for self-describing signature verification.
3764
+ * Persistent, strictly-ordered BTP transport for paid writes (issue #482).
3765
+ *
3766
+ * ─── Why this exists ─────────────────────────────────────────────────────
3767
+ * `HttpIlpClient` (the default paid-write transport, `POST /ilp`) is
3768
+ * stateless: every write is an independent HTTP request, and the connector's
3769
+ * claim gate advances a channel's nonce watermark per request in WHATEVER
3770
+ * order those requests happen to arrive — client-edge-spec.md §1.3 step 2. A
3771
+ * burst of concurrent paid writes on one channel can therefore race each
3772
+ * other into `F01 NonceNotAdvancing`: two requests both built against the
3773
+ * same last-known nonce, one arrives first and advances the watermark, the
3774
+ * other is now stale.
3775
+ *
3776
+ * The connector's client-facing BTP websocket ingress (client-edge-spec.md
3777
+ * §1.9, connector#680/#674) processes frames on ONE session strictly in
3778
+ * arrival order — the next frame is not read until the previous frame's
3779
+ * claim has been judged. A client that dispatches its OWN claims in the same
3780
+ * order it enqueued them therefore never races itself. This was measured on
3781
+ * the huddle-over-ILP prototype (`toon-meta/prototypes/huddle-over-ilp`,
3782
+ * branch `proto/huddle-over-ilp`): 0 F01 rejects across 4,156 events at a
3783
+ * paced 50fps (audio-frame-rate) sustained load, where the equivalent
3784
+ * unordered concurrent-HTTP baseline raced.
3785
+ *
3786
+ * This module productizes that pattern as a reusable transport rather than
3787
+ * a one-off harness: a caller that needs many ordered paid writes on one
3788
+ * channel (the motivating consumer is relay-native huddle audio, ~140fps of
3789
+ * measured headroom per session) constructs one `BtpPaidWriteTransport`
3790
+ * around a `BtpRuntimeClient` session and sends through it exactly like any
3791
+ * other `sendIlpPacketWithClaim`-shaped transport.
3792
+ *
3793
+ * ─── What it adds over a bare `BtpRuntimeClient` ────────────────────────
3794
+ * - **Persistent session**: the underlying session is connected once,
3795
+ * lazily, on the first write, and stays open across every subsequent
3796
+ * write. This is NOT the `Http402Client.upgradeToBtp()` pattern (open,
3797
+ * send one packet, immediately disconnect) — the whole point is to reuse
3798
+ * one ordered socket across a burst.
3799
+ * - **Strictly ordered dispatch**: every `sendIlpPacketWithClaim` call is
3800
+ * appended to a FIFO queue; the next call is not dispatched onto the wire
3801
+ * until the previous one has fully settled (fulfilled, rejected, or
3802
+ * fallen back to HTTP). Callers may still fire writes concurrently
3803
+ * (`Promise.all`) — ordering is enforced here, not pushed onto the
3804
+ * caller.
3805
+ * - **Reconnect + resume**: a write that fails on a connection-level error
3806
+ * (socket dropped mid-burst) reconnects the SAME session and retries
3807
+ * that write in place, without losing its position in the queue and
3808
+ * without reordering the writes queued behind it — they simply wait for
3809
+ * it to resolve one way or another.
3810
+ * - **Falls back to HTTP**: once the reconnect budget for one write is
3811
+ * exhausted, the write is handed to `fallback` (typically the existing
3812
+ * `HttpIlpClient`) when one is configured, so a BTP outage degrades a
3813
+ * session to the pre-existing one-shot behavior instead of failing the
3814
+ * write outright.
3815
+ *
3816
+ * Only CONNECTION-level failures (dropped socket, timeout — the errors
3817
+ * `BtpRuntimeClient`/`IsomorphicBtpClient` throw) are retried or routed to
3818
+ * the fallback. An ILP-level REJECT (F02, T01, ...) is a normal
3819
+ * `IlpSendResult`, exactly like every other transport here — it is returned
3820
+ * to the caller unchanged, never retried and never silently resent over
3821
+ * HTTP (a claim that was actually judged and refused must not be replayed).
2990
3822
  */
2991
- interface EVMClaimMessage {
2992
- version: '1.0';
2993
- blockchain: 'evm';
2994
- messageId: string;
2995
- timestamp: string;
2996
- senderId: string;
2997
- channelId: string;
2998
- nonce: number;
2999
- transferredAmount: string;
3000
- lockedAmount: string;
3001
- locksRoot: string;
3002
- signature: string;
3003
- signerAddress: string;
3004
- /** Chain ID for self-describing EIP-712 verification */
3005
- chainId: number;
3006
- /** TokenNetwork address for self-describing EIP-712 verification */
3007
- tokenNetworkAddress: string;
3008
- /** ERC-20 token address for self-describing claim verification */
3009
- tokenAddress?: string;
3823
+
3824
+ /**
3825
+ * The narrow shape a paid-write transport candidate needs — the same method
3826
+ * `ToonClient.getClaimTransport()` already requires of `HttpIlpClient` and
3827
+ * `BtpRuntimeClient`. Declared independently so this module (and its tests)
3828
+ * do not need the concrete transport classes.
3829
+ */
3830
+ interface ClaimSendingTransport {
3831
+ sendIlpPacketWithClaim(params: IlpSendParams, claim: unknown): Promise<IlpSendResult>;
3010
3832
  }
3011
3833
  /**
3012
- * EVM signer for EIP-712 balance proofs and on-chain transactions.
3013
- *
3014
- * Encapsulates the private key — no getPrivateKey() method is exposed.
3834
+ * The subset of `BtpRuntimeClient` this transport drives. `BtpRuntimeClient`
3835
+ * satisfies this structurally — no adapter needed — but tests can supply a
3836
+ * lightweight fake instead of a real WebSocket-backed instance.
3015
3837
  */
3016
- declare class EvmSigner {
3017
- readonly chainType: "evm";
3018
- private readonly _account;
3838
+ interface OrderedBtpSession {
3839
+ readonly isConnected: boolean;
3840
+ connect(): Promise<void>;
3841
+ reconnect(): Promise<void>;
3842
+ disconnect(): Promise<void>;
3843
+ sendIlpPacketWithClaim(params: IlpSendParams, claim: Record<string, unknown>): Promise<IlpSendResult>;
3844
+ }
3845
+ interface BtpPaidWriteTransportConfig {
3019
3846
  /**
3020
- * @param privateKey - EVM private key as hex string (with or without 0x prefix) or Uint8Array
3847
+ * The persistent BTP session this transport owns the connect/reconnect
3848
+ * lifecycle of. May already be connected (the common case — `modes/http.ts`
3849
+ * connects `btpClient` at startup) or not; either way it is connected
3850
+ * lazily on first use and never disconnected between writes.
3021
3851
  */
3022
- constructor(privateKey: string | Uint8Array);
3023
- /** Derived 0x EVM address */
3024
- get address(): string;
3025
- /** ChainSigner identifier — EVM address */
3026
- get signerIdentifier(): string;
3027
- /** Viem PrivateKeyAccount — usable with walletClient for on-chain transactions */
3028
- get account(): PrivateKeyAccount$1;
3852
+ session: OrderedBtpSession;
3029
3853
  /**
3030
- * Signs a balance proof using EIP-712 typed data.
3031
- *
3032
- * @param params - Balance proof parameters plus chain context
3033
- * @returns Signed balance proof with signature
3854
+ * Stateless fallback used once a write's reconnect budget is exhausted.
3855
+ * Typically an `HttpIlpClient` pointed at the same connector's `POST /ilp`.
3856
+ * Omit to have an exhausted BTP session fail the write outright.
3034
3857
  */
3035
- signBalanceProof(params: BalanceProofParams & {
3036
- chainId: number;
3037
- tokenNetworkAddress: string;
3038
- tokenAddress?: string;
3039
- }): Promise<SignedBalanceProof>;
3858
+ fallback?: ClaimSendingTransport;
3040
3859
  /**
3041
- * Builds an EVMClaimMessage from a signed balance proof.
3042
- * Static so it can be called without an EvmSigner instance.
3043
- *
3044
- * @param proof - Signed balance proof (includes chainId and tokenNetworkAddress)
3045
- * @param senderId - Nostr pubkey or identifier of the sender
3046
- * @returns EVMClaimMessage compatible with BTP_CLAIM_PROTOCOL
3860
+ * Reconnect attempts for one write before giving up on BTP (and, if
3861
+ * configured, falling back to HTTP). Default 1 — one explicit reconnect
3862
+ * beyond whatever retrying the session already does internally.
3047
3863
  */
3048
- static buildClaimMessage(proof: SignedBalanceProof, senderId: string): EVMClaimMessage;
3864
+ maxReconnectAttempts?: number;
3865
+ /** Delay before each reconnect attempt, in ms. Default 250. */
3866
+ reconnectDelay?: number;
3867
+ }
3868
+ /**
3869
+ * Wraps an {@link OrderedBtpSession} (a `BtpRuntimeClient`) as a first-class,
3870
+ * persistent, strictly-ordered paid-write transport with an optional HTTP
3871
+ * fallback. See the module docs above for the full rationale.
3872
+ */
3873
+ declare class BtpPaidWriteTransport implements ClaimSendingTransport {
3874
+ private readonly session;
3875
+ private readonly fallback;
3876
+ private readonly maxReconnectAttempts;
3877
+ private readonly reconnectDelay;
3878
+ /**
3879
+ * Tail of the ordering queue. ALWAYS settles (never rejects) so one
3880
+ * failed write can never strand every write queued behind it — only the
3881
+ * write itself carries its own outcome, via the promise `sendIlpPacketWithClaim`
3882
+ * returns to its caller.
3883
+ */
3884
+ private queueTail;
3885
+ constructor(config: BtpPaidWriteTransportConfig);
3886
+ /** Whether the underlying session currently holds an open socket. */
3887
+ get isConnected(): boolean;
3888
+ /** Explicitly closes the persistent session (e.g. `ToonClient.stop()`). */
3889
+ disconnect(): Promise<void>;
3890
+ /**
3891
+ * Enqueue a claim-bearing write. The returned promise resolves/rejects
3892
+ * with THIS write's own outcome; its position in the queue only controls
3893
+ * WHEN it is dispatched onto the wire, never what it returns.
3894
+ */
3895
+ sendIlpPacketWithClaim(params: IlpSendParams, claim: unknown): Promise<IlpSendResult>;
3896
+ /**
3897
+ * One write's worth of connect/send/reconnect/fallback policy. Runs
3898
+ * strictly after every write enqueued ahead of it has settled.
3899
+ */
3900
+ private dispatchWithRetry;
3049
3901
  }
3050
3902
 
3051
3903
  /**
3052
- * Solana signer for the connector payment-channel claim path.
3904
+ * Transport selection policy for the client ILP layer.
3905
+ *
3906
+ * The connector serves ILP-over-HTTP (`POST /ilp`) and BTP on the SAME port
3907
+ * (connector PR #181). A peer advertises this in discovery via the toon-core
3908
+ * `IlpPeerInfo` fields added in toon PR #29:
3909
+ * - `httpEndpoint?: string` — the `POST /ilp` URL.
3910
+ * - `supportsUpgrade?: boolean` — whether the host accepts the BTP upgrade.
3911
+ *
3912
+ * Those fields may not yet exist on the installed `@toon-protocol/core`
3913
+ * `IlpPeerInfo` type, so we read them defensively here (see `DiscoveredIlpPeer`).
3053
3914
  *
3054
- * Signs the connector's on-chain payment-channel balance-proof message — the
3055
- * raw 48-byte `channel_pda(32) || nonce(8 LE) || transferredAmount(8 LE)` (see
3056
- * `@toon-protocol/connector` `SolanaPaymentChannelSDK._buildBalanceProofMessage`
3057
- * + `solana-payment-channel-provider.verifyBalanceProof`). The produced 64-byte
3058
- * Ed25519 signature verifies on the connector's `verifySolanaClaim` path, which
3059
- * is what makes a client-issued Solana payment-channel claim (paying the apex
3060
- * to write) acceptable on connector 3.9.0.
3915
+ * Policy:
3916
+ * - Pure one-shot consumers (`needsDuplex: false`) prefer HTTP when the peer
3917
+ * advertises an `httpEndpoint` — stateless, no persistent socket.
3918
+ * - Clients that must receive server-initiated packets or act as a peer
3919
+ * (`needsDuplex: true`) use BTP. If the peer only exposes `httpEndpoint`
3920
+ * and `supportsUpgrade` is true, we go HTTP-then-upgrade; otherwise we
3921
+ * connect to the BTP endpoint directly.
3922
+ */
3923
+ /**
3924
+ * The subset of discovery fields this policy reads. Structurally compatible with
3925
+ * core's `IlpPeerInfo`; `httpEndpoint`/`supportsUpgrade` are optional so a
3926
+ * pre-PR-#29 `IlpPeerInfo` can be passed through a cast.
3927
+ */
3928
+ interface DiscoveredIlpPeer {
3929
+ /** BTP WebSocket endpoint (always present on a TOON peer). */
3930
+ btpEndpoint?: string;
3931
+ /** `POST /ilp` URL (toon PR #29). */
3932
+ httpEndpoint?: string;
3933
+ /** Whether the host accepts the BTP upgrade over the HTTP endpoint (toon PR #29). */
3934
+ supportsUpgrade?: boolean;
3935
+ }
3936
+ type IlpTransportChoice =
3937
+ /** Stateless one-shot writes via `POST /ilp`. */
3938
+ {
3939
+ kind: 'http';
3940
+ httpEndpoint: string;
3941
+ canUpgrade: boolean;
3942
+ }
3943
+ /** Duplex BTP session via the WebSocket endpoint. */
3944
+ | {
3945
+ kind: 'btp';
3946
+ btpEndpoint: string;
3947
+ }
3948
+ /**
3949
+ * Open HTTP first (one-shot writes) but upgrade to BTP when duplex is needed.
3950
+ * Only chosen when the peer exposes `httpEndpoint` + `supportsUpgrade` and no
3951
+ * separate `btpEndpoint`.
3952
+ */
3953
+ | {
3954
+ kind: 'http-upgradable';
3955
+ httpEndpoint: string;
3956
+ };
3957
+ interface SelectIlpTransportOptions {
3958
+ /**
3959
+ * Whether the client needs a duplex session (receive server-initiated
3960
+ * packets / act as a peer). Default: false (pure one-shot consumer).
3961
+ */
3962
+ needsDuplex?: boolean;
3963
+ }
3964
+ /**
3965
+ * Read discovery fields defensively from a (possibly pre-PR-#29) peer info
3966
+ * object. Accepts core's `IlpPeerInfo` or any structurally-compatible shape.
3967
+ */
3968
+ declare function readDiscoveredIlpPeer(peer: unknown): DiscoveredIlpPeer;
3969
+ /**
3970
+ * Choose the ILP transport for a discovered peer given the consumer's needs.
3061
3971
  *
3062
- * NOTE: this is a DIFFERENT message from the swap peer ↔ sender swap-claim wire
3063
- * contract (`balanceProofHashSolana`, SDK `verifyEd25519Signature`). The client
3064
- * here is paying a payment-channel claim to the apex, not issuing a swap claim,
3065
- * so it must sign the connector's on-chain payment-channel message. `channelId`
3066
- * MUST be the base58 channel PDA (produced by `OnChainChannelClient.openChannel`).
3972
+ * @throws {Error} If the peer advertises no usable endpoint at all.
3067
3973
  */
3974
+ declare function selectIlpTransport(peer: DiscoveredIlpPeer, options?: SelectIlpTransportOptions): IlpTransportChoice;
3975
+
3068
3976
  declare class SolanaSigner implements ChainSigner {
3069
3977
  readonly chainType: "solana";
3070
3978
  /** 32-byte Ed25519 seed. */
@@ -3087,6 +3995,21 @@ declare class SolanaSigner implements ChainSigner {
3087
3995
  recipient: string;
3088
3996
  metadata: ChainMetadata;
3089
3997
  }): Promise<SignedBalanceProof>;
3998
+ /**
3999
+ * Signs a `POST /ilp/claim-state` claim-state challenge (client-edge-spec.md
4000
+ * §1.10): `"toon-claim-state-challenge-v1" || channelAccount(32) ||
4001
+ * expires(u64 LE)` — a tagged message distinct in both content and length
4002
+ * from a real 48-byte balance-proof message, so a captured challenge can
4003
+ * never be replayed as a payment or vice versa. Returns base64 (the
4004
+ * connector's documented wire encoding for this endpoint, unlike the
4005
+ * hex-encoded balance-proof signature elsewhere in this class).
4006
+ *
4007
+ * @param params.expires - Unix seconds the signature stops verifying.
4008
+ */
4009
+ signClaimStateChallenge(params: {
4010
+ channelAccount: string;
4011
+ expires: number;
4012
+ }): Promise<string>;
3090
4013
  buildClaimMessage(proof: SignedBalanceProof, senderId: string): ClaimMessage;
3091
4014
  }
3092
4015
 
@@ -3308,6 +4231,25 @@ interface OnChainChannelClientConfig {
3308
4231
  chainRpcUrls: Record<string, string>;
3309
4232
  solanaConfig?: SolanaChannelConfig;
3310
4233
  minaConfig?: MinaChannelConfig;
4234
+ /**
4235
+ * How hard the EVM opener works to survive a STALE-READ RPC (#489).
4236
+ *
4237
+ * Public Base Sepolia (`sepolia.base.org`) is a load balancer: the
4238
+ * `setTotalDeposit` that follows a just-confirmed `openChannel` can land on a
4239
+ * replica that has not seen the open yet and reverts `InvalidChannelState()`
4240
+ * (`0xf806e9d9`). So the opener polls the channel back until the RPC agrees
4241
+ * it exists, and retries the deposit on that specific revert.
4242
+ */
4243
+ readConsistency?: EvmReadConsistencyConfig;
4244
+ }
4245
+ /** Read-after-write polling knobs for the EVM open path (#489). */
4246
+ interface EvmReadConsistencyConfig {
4247
+ /** Reads of the freshly opened channel before giving up. Default 12. */
4248
+ attempts?: number;
4249
+ /** Delay between those reads, ms. Default 1000. */
4250
+ delayMs?: number;
4251
+ /** `setTotalDeposit` retries on `InvalidChannelState()`. Default 3. */
4252
+ depositRetries?: number;
3311
4253
  }
3312
4254
  /**
3313
4255
  * Implements ConnectorChannelClient using viem for direct on-chain
@@ -3321,7 +4263,20 @@ declare class OnChainChannelClient implements ConnectorChannelClient {
3321
4263
  private solanaConfig?;
3322
4264
  private minaConfig?;
3323
4265
  private readonly channelContext;
4266
+ private readonly readConsistency;
3324
4267
  constructor(config: OnChainChannelClientConfig);
4268
+ /**
4269
+ * Adopt a channel this process did NOT open — a RESUMED one (#489), whose
4270
+ * chain/token-network/token context came back from the channel store rather
4271
+ * than from an `openChannel` call. Without it a restarted client can track
4272
+ * and pay on a resumed channel but cannot deposit into, close, or read it,
4273
+ * because those all look up the in-memory `channelContext` this seeds.
4274
+ */
4275
+ adoptChannel(channelId: string, ctx: {
4276
+ chain: string;
4277
+ tokenNetworkAddress: string;
4278
+ tokenAddress?: string;
4279
+ }): void;
3325
4280
  /**
3326
4281
  * Late-binds the Solana channel config.
3327
4282
  *
@@ -3516,6 +4471,19 @@ declare class OnChainChannelClient implements ConnectorChannelClient {
3516
4471
  * 4. Deposit initial funds if specified
3517
4472
  */
3518
4473
  private openEvmChannelUnchecked;
4474
+ /**
4475
+ * Poll the TokenNetwork until it reports the just-opened channel (non-zero
4476
+ * `participant1`). Tolerates a read that throws or returns nothing — a stale
4477
+ * replica does both — and surfaces a {@link StaleRpcReadError} naming the RPC
4478
+ * when the endpoint never converges.
4479
+ */
4480
+ private waitForEvmChannelVisible;
4481
+ /**
4482
+ * `setTotalDeposit`, retried on `InvalidChannelState()` — the revert a stale
4483
+ * replica produces for a channel it hasn't observed. Every other revert
4484
+ * propagates immediately (an under-funded wallet must not be retried).
4485
+ */
4486
+ private setTotalDepositWithRetry;
3519
4487
  /**
3520
4488
  * Gets the current state of a payment channel from on-chain data.
3521
4489
  */
@@ -3532,14 +4500,109 @@ interface ChannelStoreEntry {
3532
4500
  /** Unix SECONDS the channel was settled (collateral released). */
3533
4501
  settledAt?: bigint;
3534
4502
  }
4503
+ /**
4504
+ * Chain context needed to re-track a RESUMED channel — the same shape
4505
+ * {@link ChannelManager.trackChannel} takes.
4506
+ */
4507
+ interface ChannelBindingContext {
4508
+ chainType: string;
4509
+ chainId: number;
4510
+ tokenNetworkAddress: string;
4511
+ tokenAddress?: string;
4512
+ /** Counterparty settlement address (required for Solana/Mina proofs). */
4513
+ recipient?: string;
4514
+ }
4515
+ /**
4516
+ * One persisted peer→channel binding: WHICH on-chain channel this identity
4517
+ * already holds with a peer, on a given chain + token network (#489).
4518
+ */
4519
+ interface ChannelBinding {
4520
+ /** On-chain payment channel id (EVM bytes32 / Solana PDA / Mina zkApp). */
4521
+ channelId: string;
4522
+ /** Context for `trackChannel` on resume. */
4523
+ context: ChannelBindingContext;
4524
+ /** On-chain collateral locked at open time, when the open surfaced it. */
4525
+ depositTotal?: bigint;
4526
+ /** ISO timestamp of the open that created this binding. */
4527
+ openedAt?: string;
4528
+ }
3535
4529
  /**
3536
4530
  * Persistence interface for payment channel nonce/amount state.
4531
+ *
4532
+ * The binding methods are OPTIONAL so a third-party `ChannelStore` written
4533
+ * against the pre-#489 surface still satisfies the type; a store that omits
4534
+ * them simply can't resume a peer's channel across restarts (it will open a
4535
+ * fresh one, the old behaviour). {@link JsonFileChannelStore} implements them.
3537
4536
  */
3538
4537
  interface ChannelStore {
3539
4538
  save(channelId: string, tracking: ChannelStoreEntry): void;
3540
4539
  load(channelId: string): ChannelStoreEntry | undefined;
3541
4540
  list(): string[];
3542
4541
  delete(channelId: string): void;
4542
+ /** Persist the channel a peer key is bound to. */
4543
+ saveBinding?(key: string, binding: ChannelBinding): void;
4544
+ /** The channel a peer key is bound to, if any. */
4545
+ loadBinding?(key: string): ChannelBinding | undefined;
4546
+ /** Every persisted binding, keyed as {@link saveBinding} stored it. */
4547
+ listBindings?(): {
4548
+ key: string;
4549
+ binding: ChannelBinding;
4550
+ }[];
4551
+ /** Forget a binding (its nonce watermark is deliberately left intact). */
4552
+ deleteBinding?(key: string): void;
4553
+ }
4554
+ /**
4555
+ * JSON file-backed ChannelStore.
4556
+ * Uses synchronous I/O to match ChannelManager's sync API surface.
4557
+ *
4558
+ * Two files, on purpose: the nonce/cumulative watermark keeps its historical
4559
+ * `{ [channelId]: entry }` schema in `filePath` (rig and the MCP daemon parse
4560
+ * that file directly), while the peer→channel bindings live in a SIBLING file
4561
+ * (`channels.json` → `channels.peers.json`, override with `bindingsPath`).
4562
+ * Extending the watermark file's schema in place would have broken those
4563
+ * external readers.
4564
+ */
4565
+ declare class JsonFileChannelStore implements ChannelStore {
4566
+ private readonly filePath;
4567
+ private readonly bindingsPath;
4568
+ constructor(filePath: string, options?: {
4569
+ bindingsPath?: string;
4570
+ });
4571
+ save(channelId: string, tracking: ChannelStoreEntry): void;
4572
+ load(channelId: string): ChannelStoreEntry | undefined;
4573
+ list(): string[];
4574
+ delete(channelId: string): void;
4575
+ saveBinding(key: string, binding: ChannelBinding): void;
4576
+ loadBinding(key: string): ChannelBinding | undefined;
4577
+ listBindings(): {
4578
+ key: string;
4579
+ binding: ChannelBinding;
4580
+ }[];
4581
+ deleteBinding(key: string): void;
4582
+ private readFile;
4583
+ private writeFile;
4584
+ private readBindings;
4585
+ private writeBindings;
4586
+ }
4587
+ /**
4588
+ * In-memory {@link ChannelStore} (watermarks + bindings). Handy for tests and
4589
+ * for a process that wants resume semantics within its own lifetime without
4590
+ * touching disk.
4591
+ */
4592
+ declare class InMemoryChannelStore implements ChannelStore {
4593
+ private readonly entries;
4594
+ private readonly bindings;
4595
+ save(channelId: string, tracking: ChannelStoreEntry): void;
4596
+ load(channelId: string): ChannelStoreEntry | undefined;
4597
+ list(): string[];
4598
+ delete(channelId: string): void;
4599
+ saveBinding(key: string, binding: ChannelBinding): void;
4600
+ loadBinding(key: string): ChannelBinding | undefined;
4601
+ listBindings(): {
4602
+ key: string;
4603
+ binding: ChannelBinding;
4604
+ }[];
4605
+ deleteBinding(key: string): void;
3543
4606
  }
3544
4607
 
3545
4608
  interface ChannelManagerConfig {
@@ -3591,13 +4654,69 @@ declare class ChannelManager {
3591
4654
  * For EVM, returns an adapter wrapping the EvmSigner.
3592
4655
  */
3593
4656
  getSignerForChannel(channelId: string): ChainSigner;
4657
+ /**
4658
+ * The key a peer's channel binding is persisted under: the peer, the
4659
+ * negotiated chain, and the token network the channel lives on. All three
4660
+ * matter — the same peer on a second chain (or a redeployed token network) is
4661
+ * a DIFFERENT channel.
4662
+ */
4663
+ private static bindingKey;
3594
4664
  /**
3595
4665
  * Lazily open a channel for a peer. Idempotent — returns existing channel
3596
4666
  * if already open. Deduplicates concurrent opens for the same peer.
4667
+ *
4668
+ * RESUME (#489): before opening anything on-chain, the persisted peer→channel
4669
+ * binding is consulted, so a restarted process re-attaches to the channel it
4670
+ * already holds instead of locking a second lot of collateral. Solana got this
4671
+ * for free (its channel id is a deterministic PDA, so a re-open re-derived the
4672
+ * same channel); EVM mints a fresh `bytes32` per `openChannel` call, so every
4673
+ * restart stranded a deposit until this binding existed.
3597
4674
  */
3598
4675
  ensureChannel(peerId: string, negotiation: PeerNegotiation): Promise<string>;
3599
4676
  /**
3600
- * Get channel ID for a peer (if any).
4677
+ * Adopt an ALREADY-OPEN channel as this peer's channel: track it (rehydrating
4678
+ * its watermark from the store), bind it so later lazy opens RESUME it rather
4679
+ * than opening a second one, and hand the on-chain client its context back.
4680
+ *
4681
+ * For a host that persisted the channel id itself before the client could
4682
+ * (the MCP daemon's apex-channel store, rig's channel map): those hosts used
4683
+ * to `trackChannel` on restart, which left `ensureChannel` unaware — so the
4684
+ * first paid write opened a SECOND on-chain channel anyway (#489).
4685
+ */
4686
+ adoptChannel(peerId: string, negotiation: PeerNegotiation, channelId: string): void;
4687
+ /**
4688
+ * Re-attach to the channel this identity already holds with `peerId`, from the
4689
+ * store's peer→channel binding. Returns the resumed channel id, or undefined
4690
+ * when there is nothing to resume (no store, no binding, or a binding whose
4691
+ * channel is closing/settled — a spent channel must not be reused).
4692
+ *
4693
+ * `trackChannel` rehydrates the nonce/cumulative watermark from the store, so
4694
+ * the resumed channel keeps signing ABOVE the last claim the connector saw.
4695
+ *
4696
+ * @throws {ChannelResumeError} when the binding's watermark is missing —
4697
+ * resuming would silently reset the nonce and every later claim would be
4698
+ * rejected (F01), so the caller is told loudly instead.
4699
+ */
4700
+ private resumeChannel;
4701
+ /**
4702
+ * Persist a freshly opened channel as this peer's binding, and SEED its
4703
+ * watermark entry (`nonce 0`) so a later resume can tell "never claimed
4704
+ * against" apart from "watermark lost" (which is a hard
4705
+ * {@link ChannelResumeError}).
4706
+ */
4707
+ private bindChannel;
4708
+ /**
4709
+ * Re-seed the on-chain client's per-channel context for a RESUMED channel.
4710
+ * `OnChainChannelClient` caches `chain`/`tokenNetwork`/`token` only for
4711
+ * channels it opened in this process, so without this a resumed channel
4712
+ * cannot be deposited into or closed. Optional capability — a channel client
4713
+ * that doesn't implement `adoptChannel` is simply left alone.
4714
+ */
4715
+ private adoptOnChainContext;
4716
+ /**
4717
+ * Get channel ID for a peer (if any). Channels are held per peer AND chain
4718
+ * AND token network, so a peer settled with on two chains has two — this
4719
+ * returns the first one tracked for the peer.
3601
4720
  */
3602
4721
  getChannelForPeer(peerId: string): string | undefined;
3603
4722
  /**
@@ -3674,6 +4793,20 @@ declare class ChannelManager {
3674
4793
  * Returns true if the channel is being tracked.
3675
4794
  */
3676
4795
  isTracking(channelId: string): boolean;
4796
+ /**
4797
+ * The chain context a tracked channel was opened/resumed with — the
4798
+ * chainType/chainId/tokenNetworkAddress a caller needs to build a
4799
+ * `POST /ilp/claim-state` request (toon-client#494) without re-deriving
4800
+ * them from the peer negotiation. `undefined` when `channelId` is not
4801
+ * tracked.
4802
+ */
4803
+ getChannelContext(channelId: string): {
4804
+ chainType: string;
4805
+ chainId: number;
4806
+ tokenNetworkAddress: string;
4807
+ tokenAddress?: string;
4808
+ recipient?: string;
4809
+ } | undefined;
3677
4810
  }
3678
4811
 
3679
4812
  /**
@@ -4505,7 +5638,7 @@ declare function validateConfig(config: ToonClientConfig): void;
4505
5638
  * The resolved config type after defaults are applied.
4506
5639
  * secretKey is guaranteed to be present (auto-generated if omitted).
4507
5640
  */
4508
- type ResolvedConfig = Required<Omit<ToonClientConfig, 'connector' | 'mnemonic' | 'mnemonicAccountIndex' | 'evmPrivateKey' | 'network' | 'supportedChains' | 'settlementAddresses' | 'preferredTokens' | 'tokenNetworks' | 'btpUrl' | 'btpAuthToken' | 'btpPeerId' | 'connectorHttpEndpoint' | 'proxyUrl' | 'faucetUrl' | 'connectorSupportsUpgrade' | 'chainRpcUrls' | 'initialDeposit' | 'settlementTimeout' | 'solanaChannel' | 'minaChannel' | 'swapMinaMakerSignatures' | 'channelStorePath' | 'knownPeers' | 'destinationAddress'>> & {
5641
+ type ResolvedConfig = Required<Omit<ToonClientConfig, 'connector' | 'mnemonic' | 'mnemonicAccountIndex' | 'evmPrivateKey' | 'network' | 'supportedChains' | 'preferredChain' | 'settlementAddresses' | 'preferredTokens' | 'tokenNetworks' | 'btpUrl' | 'btpAuthToken' | 'btpPeerId' | 'connectorHttpEndpoint' | 'proxyUrl' | 'faucetUrl' | 'connectorSupportsUpgrade' | 'chainRpcUrls' | 'initialDeposit' | 'settlementTimeout' | 'solanaChannel' | 'minaChannel' | 'swapMinaMakerSignatures' | 'channelStorePath' | 'knownPeers' | 'destinationAddress' | 'jobHandler'>> & {
4509
5642
  connector?: unknown;
4510
5643
  /** Always present after applyDefaults() — derived from secretKey if not explicitly provided */
4511
5644
  evmPrivateKey: string | Uint8Array;
@@ -4524,6 +5657,7 @@ type ResolvedConfig = Required<Omit<ToonClientConfig, 'connector' | 'mnemonic' |
4524
5657
  /** Named network tier, retained for `getNetworkStatus()`. */
4525
5658
  network?: ToonClientConfig['network'];
4526
5659
  supportedChains?: string[];
5660
+ preferredChain?: ToonClientConfig['preferredChain'];
4527
5661
  settlementAddresses?: Record<string, string>;
4528
5662
  preferredTokens?: Record<string, string>;
4529
5663
  tokenNetworks?: Record<string, string>;
@@ -4547,6 +5681,7 @@ type ResolvedConfig = Required<Omit<ToonClientConfig, 'connector' | 'mnemonic' |
4547
5681
  btpEndpoint?: string;
4548
5682
  }[];
4549
5683
  destinationAddress: string;
5684
+ jobHandler?: ToonClientConfig['jobHandler'];
4550
5685
  };
4551
5686
  /**
4552
5687
  * Applies default values to optional configuration fields.
@@ -5565,4 +6700,4 @@ declare function readExchangeOutcome(result: {
5565
6700
  /** Read a response header, case-insensitively; the first match wins. */
5566
6701
  declare function envelopeHeader(response: EnvelopeResponse, name: string): string | undefined;
5567
6702
 
5568
- export { type BackupPayload, type BalanceProofParams, BtpRuntimeClient, type BtpRuntimeClientConfig, type BuildSwapSettlementsParams, CLAIM_TYPEHASH, CONDITION_LENGTH, COOP_CLOSE_TYPEHASH, type ChainMetadata, type ChainSigner, ChannelFundingError, ChannelManager, type ClaimMessage, type ClaimResolver, type ClaimSignature, ConnectorEdgeClient, type ConnectorEdgeClientConfig, ConnectorEdgeError, type ConnectorEdgeErrorCode, ConnectorError, type ConnectorIdentity, type ConnectorRoutePrice, type Decoded, type DeployMinaZkAppParams, type DiscoveredIlpPeer, type EVMClaimMessage, type EncryptedKeystore, type EnsureOwnedMinaZkAppParams, type EnsureOwnedMinaZkAppResult, type Envelope, EnvelopeError, EnvelopeErrorKind, type EnvelopeHeader, type EnvelopeRequest, type EnvelopeResponse, type EvmClaimDomainContext, type EvmClaimMessage, type EvmClaimVerifyResult, type EvmCooperativeCloseMessage, EvmSigner, type ExchangeOutcome, type ExecutionConditionPair, FULFILLMENT_MISMATCH_CODE, FULFILLMENT_MISMATCH_MESSAGE, type FaucetChain, type FundWalletOptions, type FundWalletResult, GIFTWRAP_NONCE_LENGTH, GIFTWRAP_PUBLIC_KEY_LENGTH, GIFTWRAP_SECRET_LENGTH, GIFTWRAP_TYPE_REQUEST, GIFTWRAP_TYPE_RESPONSE, type GiftWrapEcdh, GiftWrapError, GiftWrapErrorKind, type H402FetchOptions, Http402Client, type Http402ClientConfig, HttpConnectorAdmin, type HttpConnectorAdminConfig, HttpIlpClient, type HttpIlpClientConfig, type HttpIlpClientFactory, HttpRuntimeClient, type HttpRuntimeClientConfig, ILP_CLAIM_HEADER, ILP_PEER_ID_HEADER, type IlpSendParams, type IlpSendResultWithFulfillment, type IlpTransportChoice, InMemoryPreimageRetentionStore, InMemoryReceivedClaimStore, type IngestAndRevealParams, type IngestAndRevealResult, type IngestReceivedClaimsParams, type IngestReceivedClaimsResult, JsonFileReceivedClaimStore, KeyManager, type KeyManagerConfig, MINA_CHANNEL_STATE, type MinaChannelStateReader, type MinaClaimMessage, type MinaClaimSubmitArgs, type MinaClaimSubmitter, type MinaCoSignInputs, type MinaCoSignedClaim, type MinaDepositReader, type MinaOnChainChannelState, type MinaSettlementContext, MinaSettlementError, type MinaSettlementErrorCode, type MinaSettlementResult, type MinaSignaturePair, MinaSigner, type MinaSignerOptions, type MinaZkAppDeployRecord, NetworkError, OerError, OerErrorKind, OnChainChannelClient, type OnChainChannelClientConfig, type OpenedRequest, type ParsedX402Challenge, type PasskeyInfo, type PreimageRetentionStore, type PublishEventResult, ROLLING_SWAP_DOMAIN_NAME, ROLLING_SWAP_DOMAIN_VERSION, type ReceivedClaimEntry, type ReceivedClaimRejection, type ReceivedClaimRejectionCode, type ReceivedClaimStore, type RequestBlobStorageParams, type RequestBlobStorageResult, type RetainedPreimage, type RetryOptions, type RevealDecision, type RevealFn, type RevealResult, type RevealedClaim, type RolledBackClaim, type SealedExchange, type SealedRequest, SealedResponseError, type SealedResponseErrorKind, type SelectIlpTransportOptions, type SignedBalanceProof, type SolanaChannelClientOptions, type SolanaClaimMessage, SolanaSigner, type SubmitEvmSettlementParams, type SubmitEvmSettlementResult, type SwapSettlementBuild, type ToonChannelAccept, ToonClient, type ToonClientConfig, ToonClientError, type ToonIdentity, type ToonSigners, type ToonStartResult, ValidationError, type VaultData, type VerifiedReceivedClaim, type WalletBalance, type WalletBalanceSources, type WalletChainBalances, type WalletTokenAmount, applyDefaults, applyNetworkPresets, assertValidCondition, buildBackupEvent, buildBackupFilter, buildMinaCoSignedClaim, buildSettlementInfo, buildSwapSettlements, connectorEdgeBaseUrl, createO1jsMinaClaimSubmitter, decodeConnectorPublicKey, decodeEnvelope, decodeEnvelopeRequest, decodeEnvelopeResponse, decodeEvmSettlementTx, decodeVarOctetString, decodeVarUint, decryptMnemonic, defaultFaucetTimeout, deployMinaChannelZkApp, deriveCondition, deriveFromNsec, deriveFulfillment, deriveFullIdentity, deriveNostrKeyFromMnemonic, encodeEnvelope, encodeEnvelopeRequest, encodeEnvelopeResponse, encodeVarOctetString, encodeVarUint, encryptMnemonic, ensureOwnedMinaZkApp, entryToAccumulatedClaim, envelopeHeader, evmClaimDigest, evmCooperativeCloseDigest, extractArweaveTxId, fulfillmentMatchesCondition, fundWallet, generateKeystore, generateMnemonic, generateRandomIdentity, getNetworkStatus, hasSettlementMetadata, httpEndpointToBtpUrl, importKeystore, ingestAndReveal, ingestReceivedClaims, isInsufficientGasError, isPrfSupported, isZeroCondition, loadKeystore, localGiftWrapEcdh, looksLikeSealedResponse, mintExecutionCondition, openRequest, openResponse, parseBackupPayload, parseConnectorIdentity, parseConnectorRoutePrice, parseEvmChainId, parseX402Body, parseX402Challenge, proxyIlpEndpoint, readDiscoveredIlpPeer, readEvmNativeBalance, readEvmTokenBalance, readExchangeOutcome, readMinaBalance, readMinaChannelState, readMinaDepositTotal, readSolanaNativeBalance, readSolanaTokenBalance, readWalletBalances, recoverEvmClaimSigner, requestBlobStorage, sealExchange, sealRequest, sealRequestWithRandomness, sealResponse, sealResponseWithRandomness, selectIlpTransport, submitEvmSettlement, submitMinaSettlement, validateConfig, validateMnemonic, verifyEvmClaimSignature, withRetry, writeKeystoreFile };
6703
+ export { type BackupPayload, type BalanceProofParams, BtpPaidWriteTransport, type BtpPaidWriteTransportConfig, BtpRuntimeClient, type BtpRuntimeClientConfig, type BuildSwapSettlementsParams, CLAIM_TYPEHASH, CONDITION_LENGTH, COOP_CLOSE_TYPEHASH, type ChainMetadata, type ChainSigner, type ChannelBinding, type ChannelBindingContext, ChannelFundingError, ChannelManager, ChannelResumeError, type ChannelStore, type ChannelStoreEntry, type ClaimMessage, type ClaimResolver, type ClaimSendingTransport, type ClaimSignature, type ClaimStateFailed, type ClaimStateOk, type ClaimStateRequestEntry, type ClaimStateResult, ConnectorEdgeClient, type ConnectorEdgeClientConfig, ConnectorEdgeError, type ConnectorEdgeErrorCode, ConnectorError, type ConnectorIdentity, type ConnectorRoutePrice, type Decoded, type DeployMinaZkAppParams, type DiscoveredIlpPeer, type EVMClaimMessage, type EncryptedArtifact, type EncryptedKeystore, type EnsureOwnedMinaZkAppParams, type EnsureOwnedMinaZkAppResult, type Envelope, EnvelopeError, EnvelopeErrorKind, type EnvelopeHeader, type EnvelopeRequest, type EnvelopeResponse, type EvmClaimDomainContext, type EvmClaimMessage, type EvmClaimVerifyResult, type EvmCooperativeCloseMessage, type EvmReadConsistencyConfig, EvmSigner, type EvmTransferConfig, type ExchangeOutcome, type ExecutionConditionPair, FULFILLMENT_MISMATCH_CODE, FULFILLMENT_MISMATCH_MESSAGE, type FaucetChain, type FundWalletOptions, type FundWalletResult, GIFTWRAP_NONCE_LENGTH, GIFTWRAP_PUBLIC_KEY_LENGTH, GIFTWRAP_SECRET_LENGTH, GIFTWRAP_TYPE_REQUEST, GIFTWRAP_TYPE_RESPONSE, GIFT_WRAP_KIND, GiftWrapAddressError, GiftWrapDecryptError, type GiftWrapEcdh, GiftWrapError, GiftWrapErrorKind, type H402FetchOptions, HashlockConditionMismatchError, HashlockDecryptError, Http402Client, type Http402ClientConfig, HttpConnectorAdmin, type HttpConnectorAdminConfig, HttpIlpClient, type HttpIlpClientConfig, type HttpIlpClientFactory, HttpRuntimeClient, type HttpRuntimeClientConfig, ILP_CLAIM_HEADER, ILP_PEER_ID_HEADER, type IlpSendParams, type IlpSendResultWithFulfillment, type IlpTransportChoice, InMemoryChannelStore, InMemoryPreimageRetentionStore, InMemoryReceivedClaimStore, type IncrementOfferTags, type IncrementPrepare, type IngestAndRevealParams, type IngestAndRevealResult, type IngestReceivedClaimsParams, type IngestReceivedClaimsResult, InsufficientBalanceError, InvalidAddressError, type JobAnswer, type JobHandler, type JobRequest, JsonFileChannelStore, JsonFileReceivedClaimStore, KeyManager, type KeyManagerConfig, MINA_CHANNEL_STATE, type MinaChannelStateReader, type MinaClaimMessage, type MinaClaimSubmitArgs, type MinaClaimSubmitter, type MinaCoSignInputs, type MinaCoSignedClaim, type MinaDepositReader, type MinaOnChainChannelState, type MinaSettlementContext, MinaSettlementError, type MinaSettlementErrorCode, type MinaSettlementResult, type MinaSignaturePair, MinaSigner, type MinaSignerOptions, type MinaTransferConfig, type MinaZkAppDeployRecord, NetworkError, OerError, OerErrorKind, OnChainChannelClient, type OnChainChannelClientConfig, type OpenedRequest, type OrderedBtpSession, type ParsedX402Challenge, type PasskeyInfo, type PreimageRetentionStore, type PublishEventResult, ROLLING_SWAP_DOMAIN_NAME, ROLLING_SWAP_DOMAIN_VERSION, type ReceivedClaimEntry, type ReceivedClaimRejection, type ReceivedClaimRejectionCode, type ReceivedClaimStore, type RequestBlobStorageParams, type RequestBlobStorageResult, type RetainedPreimage, type RetryOptions, type RevealDecision, type RevealFn, type RevealResult, type RevealedClaim, type RolledBackClaim, SEAL_KIND, type SealedExchange, type SealedRequest, SealedResponseError, type SealedResponseErrorKind, type SelectIlpTransportOptions, type SendTransferParams, type SendTransferResult, type SignedBalanceProof, type SolanaChannelClientOptions, type SolanaClaimMessage, SolanaSigner, type SolanaTransferConfig, StaleRpcReadError, type SubmitEvmSettlementParams, type SubmitEvmSettlementResult, type SwapSettlementBuild, type ToonChannelAccept, ToonClient, type ToonClientConfig, ToonClientError, type ToonIdentity, type ToonSigners, type ToonStartResult, type TransferAssetKind, type TransferChain, type TransferConfig, TransferNotDeliveredError, TransferUnsupportedError, UnknownChainError, type UnwrappedGiftWrap, ValidationError, type VaultData, type VerifiedReceivedClaim, type WalletBalance, type WalletBalanceSources, type WalletChainBalances, type WalletTokenAmount, applyDefaults, applyNetworkPresets, assertValidCondition, buildBackupEvent, buildBackupFilter, buildIncrementPrepare, buildMinaCoSignedClaim, buildSettlementInfo, buildSwapSettlements, connectorEdgeBaseUrl, createJobMessageHandler, createO1jsMinaClaimSubmitter, decodeConnectorPublicKey, decodeEnvelope, decodeEnvelopeRequest, decodeEnvelopeResponse, decodeEvmSettlementTx, decodeVarOctetString, decodeVarUint, decryptArtifact, decryptMnemonic, defaultFaucetTimeout, deployMinaChannelZkApp, deriveCondition, deriveFromNsec, deriveFulfillment, deriveFullIdentity, deriveNostrKeyFromMnemonic, encodeEnvelope, encodeEnvelopeRequest, encodeEnvelopeResponse, encodeVarOctetString, encodeVarUint, encryptArtifact, encryptMnemonic, ensureOwnedMinaZkApp, entryToAccumulatedClaim, envelopeHeader, evmClaimDigest, evmCooperativeCloseDigest, extractArweaveTxId, fulfillIncrement, fulfillmentMatchesCondition, fundWallet, generateKeystore, generateMnemonic, generateRandomIdentity, getNetworkStatus, hasSettlementMetadata, httpEndpointToBtpUrl, importKeystore, ingestAndReveal, ingestReceivedClaims, isInsufficientGasError, isPrfSupported, isZeroCondition, loadKeystore, localGiftWrapEcdh, looksLikeSealedResponse, mintExecutionCondition, openRequest, openResponse, parseBackupPayload, parseClaimStateResponse, parseConnectorIdentity, parseConnectorRoutePrice, parseEvmChainId, parseX402Body, parseX402Challenge, proxyIlpEndpoint, readDiscoveredIlpPeer, readEvmNativeBalance, readEvmTokenBalance, readExchangeOutcome, readMinaBalance, readMinaChannelState, readMinaDepositTotal, readSolanaNativeBalance, readSolanaTokenBalance, readWalletBalances, recoverEvmClaimSigner, requestBlobStorage, sealExchange, sealRequest, sealRequestWithRandomness, sealResponse, sealResponseWithRandomness, selectIlpTransport, sendTransfer, submitEvmSettlement, submitMinaSettlement, unwrapGiftWrapWithKey, validateConfig, validateMnemonic, verifyEvmClaimSignature, withRetry, writeKeystoreFile };