@toon-protocol/client 0.27.0 → 0.28.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,5 +1,5 @@
1
1
  import * as _toon_protocol_core from '@toon-protocol/core';
2
- import { IlpPeerInfo, IlpSendResult, IlpClient, SwapPair, NetworkFamilyStatus, ConnectorAdminClient, ConnectorChannelClient, OpenChannelParams, OpenChannelResult, ChannelState } from '@toon-protocol/core';
2
+ import { IlpSendResult, IlpClient, IlpPeerInfo, 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
4
  import { UnsignedEvent, NostrEvent, EventTemplate } from 'nostr-tools/pure';
5
5
  import { PrivateKeyAccount } from 'viem/accounts';
@@ -135,2283 +135,2299 @@ declare class TransferUnsupportedError extends ToonClientError {
135
135
  */
136
136
  declare function isInsufficientGasError(err: unknown): boolean;
137
137
 
138
+ interface BTPProtocolData {
139
+ protocolName: string;
140
+ contentType: number;
141
+ data: Uint8Array;
142
+ }
143
+
138
144
  /**
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.
141
- *
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.
145
+ * Isomorphic BTP client — works in both browser and Node.js.
146
+ * Uses native WebSocket (browser) or globalThis.WebSocket (Node 21+).
147
+ * No dependency on `ws`, `events`, or `Buffer`.
165
148
  *
166
- * Pure transport + parsing: no keys are held, nothing is signed, and the only
167
- * state is the identity cache.
149
+ * Replaces the @toon-protocol/connector BTPClient for the client SDK.
168
150
  */
169
151
 
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;
152
+ /** A server-originated MESSAGE (RFC-0023 symmetric grammar, toon-client#493). */
153
+ interface InboundBtpMessage {
154
+ requestId: number;
155
+ protocolData: BTPProtocolData[];
156
+ ilpPacket?: Uint8Array;
180
157
  }
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;
158
+ /** A server-originated TRANSFER — settlement value, never an ILP packet. */
159
+ interface InboundBtpTransfer {
160
+ requestId: number;
161
+ amount: bigint;
162
+ protocolData: BTPProtocolData[];
199
163
  }
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;
164
+ /** What an inbound handler answers with — becomes the RESPONSE frame's body. */
165
+ interface BtpHandlerResponse {
166
+ protocolData?: BTPProtocolData[];
167
+ ilpPacket?: Uint8Array;
216
168
  }
169
+ type BtpMessageHandler = (message: InboundBtpMessage) => Promise<BtpHandlerResponse> | BtpHandlerResponse;
170
+ type BtpTransferHandler = (transfer: InboundBtpTransfer) => Promise<BtpHandlerResponse> | BtpHandlerResponse;
171
+
217
172
  /**
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).
173
+ * Shared sender-side plumbing for sender-chosen execution conditions
174
+ * (toon-client#350; contract: connector `docs/local-delivery-fulfillment-contract.md`,
175
+ * connector#309; spec: toon-meta `docs/rolling-swap.md` §3).
176
+ *
177
+ * Both ILP transports (HTTP `POST /ilp` and BTP) take the SAME extended send
178
+ * params and map FULFILL/REJECT responses through the SAME verifier so the
179
+ * two paths cannot drift:
180
+ *
181
+ * - absent/all-zero `executionCondition` → legacy class: today's behavior,
182
+ * byte-for-byte (zero condition on the wire, no FULFILL verification);
183
+ * - non-zero `executionCondition` → sender-chosen: the condition goes on
184
+ * the PREPARE verbatim and the FULFILL's 32-byte fulfillment MUST hash
185
+ * back to it — a missing/malformed/mismatching preimage is surfaced as a
186
+ * FAILED result (never a silent accept, never retried).
222
187
  */
223
- type ConnectorChainSettlementTerms = ({
224
- kind: 'evm';
225
- } & ConnectorSettlementTerms) | ({
226
- kind: 'solana';
227
- } & ConnectorSolanaSettlementTerms);
188
+
228
189
  /**
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.
190
+ * Send parameters accepted by both ILP transports. Extends the
191
+ * `@toon-protocol/core` `IlpClient` param shape with the sender-chosen
192
+ * condition and an explicit expiry — plain `IlpClient` callers keep working
193
+ * unchanged (both extras are optional; omitting them is the legacy path).
236
194
  */
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). */
195
+ interface IlpSendParams {
246
196
  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;
197
+ amount: string;
198
+ /** Base64 ILP `data` payload. */
199
+ data: string;
200
+ /** Transport timeout in ms; also the default expiry window. */
201
+ timeout?: number;
287
202
  /**
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.
203
+ * Sender-chosen 32-byte execution condition `C = sha256(P)` (spec R2).
204
+ * Absent or all-zero = legacy unverified packet (default — ordinary
205
+ * publish/upload writes MUST keep this default).
290
206
  */
291
- lastClaimTime: number | null;
207
+ executionCondition?: Uint8Array;
208
+ /**
209
+ * Explicit PREPARE `expiresAt` (spec R7). Defaults to `now + timeout`,
210
+ * preserving pre-#350 behavior. Accepts a `Date` or an ISO 8601 string —
211
+ * `@toon-protocol/core` ≥2.1.0's `IlpClient` passes the string form.
212
+ */
213
+ expiresAt?: Date | string;
292
214
  }
293
215
  /**
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.
216
+ * `IlpSendResult` plus the FULFILL preimage when a sender-chosen condition
217
+ * was verified. Only populated on the sender-chosen path so legacy result
218
+ * objects stay byte-identical.
298
219
  */
299
- interface ClaimStateFailed {
300
- blockchain: 'evm' | 'solana';
301
- channelId?: string;
302
- channelAccount?: string;
303
- ok: false;
304
- error: 'expired' | 'unverified';
220
+ interface IlpSendResultWithFulfillment extends IlpSendResult {
221
+ /** Base64 32-byte fulfillment preimage (verified: sha256 == condition). */
222
+ fulfillment?: string;
223
+ }
224
+ /** ILP code used for a client-side fulfillment-verification failure. */
225
+ declare const FULFILLMENT_MISMATCH_CODE = "F99";
226
+ /** Message for a client-side fulfillment-verification failure. */
227
+ declare const FULFILLMENT_MISMATCH_MESSAGE: string;
228
+
229
+ interface BtpRuntimeClientConfig {
230
+ btpUrl: string;
231
+ peerId: string;
232
+ authToken: string;
233
+ /** Max reconnection attempts on send failure (default: 3) */
234
+ maxRetries?: number;
235
+ /** Delay between reconnection attempts in ms (default: 1000) */
236
+ retryDelay?: number;
237
+ /** Custom WebSocket constructor (for testing / custom transports). */
238
+ createWebSocket?: (url: string) => WebSocket;
239
+ /**
240
+ * Handles a server-originated MESSAGE (RFC-0023 symmetric grammar,
241
+ * toon-client#493). Re-registered on every `connect()`/`reconnect()` since
242
+ * each creates a fresh `IsomorphicBtpClient` for the new socket.
243
+ */
244
+ onMessage?: BtpMessageHandler;
245
+ /** Handles a server-originated TRANSFER. Re-registered the same way as `onMessage`. */
246
+ onTransfer?: BtpTransferHandler;
247
+ /** Surfaces in-flight inbound work orphaned by a disconnect instead of silently vanishing. */
248
+ onInboundError?: (error: Error, requestId: number) => void;
305
249
  }
306
- type ClaimStateResult = ClaimStateOk | ClaimStateFailed;
307
250
  /**
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).
251
+ * BTP transport implementing IlpClient.
252
+ * Uses IsomorphicBtpClient (browser-native, no Node.js dependencies).
312
253
  */
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);
254
+ declare class BtpRuntimeClient implements IlpClient {
255
+ private btpClient;
256
+ private readonly config;
257
+ private _isConnected;
258
+ constructor(config: BtpRuntimeClientConfig);
408
259
  /**
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.
260
+ * Connects to the BTP peer via WebSocket.
413
261
  */
414
- getIdentity(endpoint: string, options?: {
415
- forceRefresh?: boolean;
416
- }): Promise<ConnectorIdentity>;
262
+ connect(): Promise<void>;
417
263
  /**
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.
264
+ * Attempts to reconnect by creating a fresh client and connecting.
420
265
  */
421
- invalidateIdentity(endpoint?: string): void;
422
- /** Whether an identity for `endpoint` is already held (no request is made). */
423
- hasCachedIdentity(endpoint: string): boolean;
266
+ reconnect(): Promise<void>;
424
267
  /**
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.
268
+ * Disconnects from the BTP peer.
438
269
  */
439
- getRoutePrice(endpoint: string, destination: string, options?: {
440
- forceRefresh?: boolean;
441
- }): Promise<ConnectorRoutePrice | null>;
270
+ disconnect(): Promise<void>;
271
+ get isConnected(): boolean;
442
272
  /**
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).
273
+ * Sends an ILP packet via BTP with auto-reconnect on connection errors.
274
+ * Satisfies IlpClient interface.
446
275
  *
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.
276
+ * `params` may carry a sender-chosen `executionCondition` and an explicit
277
+ * `expiresAt` (toon-client#350); omitting both is the legacy zero-condition
278
+ * path, unchanged. With a non-zero condition the FULFILL preimage is
279
+ * verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced
280
+ * as a failed result — see `mapIlpResponse`.
453
281
  */
454
- getRouteTerms(endpoint: string, destination: string): Promise<ConnectorRouteTerms | null>;
282
+ sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;
455
283
  /**
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.
284
+ * Sends a balance proof claim via BTP protocol data, then sends an ILP packet.
285
+ * Auto-reconnects on connection errors.
466
286
  *
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.
287
+ * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are
288
+ * identical to {@link sendIlpPacket}.
470
289
  */
471
- getClaimState(endpoint: string, channels: ClaimStateRequestEntry[]): Promise<ClaimStateResult[]>;
290
+ sendIlpPacketWithClaim(params: IlpSendParams, claim: Record<string, unknown>): Promise<IlpSendResult>;
472
291
  /**
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.
292
+ * Send a standalone `payment-channel-claim` BTP MESSAGE (no ILP packet
293
+ * attached). The connector's ClaimReceiver consumes this fire-and-forget
294
+ * to register cumulative claim state independently of the per-packet
295
+ * forwarding path. Auto-reconnects on connection errors.
476
296
  */
477
- invalidateRoutePrice(endpoint?: string, destination?: string): void;
297
+ sendClaimMessage(claim: Record<string, unknown>): Promise<void>;
298
+ private _sendClaimMessageOnce;
478
299
  /**
479
- * Whether a price for `(endpoint, destination)` is already held (no request
480
- * is made).
300
+ * Build the ILP PREPARE for a send, applying the sender-chosen condition /
301
+ * explicit expiry when provided (toon-client#350) and validating that a
302
+ * non-zero condition is exactly 32 bytes (the OER serializer would
303
+ * otherwise silently zero-fill it, downgrading the packet to the legacy
304
+ * unverified class).
481
305
  */
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;
306
+ private buildPrepare;
307
+ /**
308
+ * Single-attempt ILP packet send. Reconnects if not connected.
309
+ */
310
+ private _sendIlpPacketOnce;
311
+ /**
312
+ * Single-attempt claim + ILP packet send. Reconnects if not connected.
313
+ */
314
+ private _sendIlpPacketWithClaimOnce;
488
315
  }
489
316
 
490
317
  /**
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.
318
+ * ILP-over-HTTP (RFC-0035) transport for the TOON client.
497
319
  *
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.
320
+ * The connector now serves ILP-over-HTTP on the SAME port as BTP (connector
321
+ * PR #181). This adapter lets a client do stateless one-shot writes over HTTP
322
+ * (`POST /ilp`) and upgrade to a duplex BTP session when it needs to receive
323
+ * server-initiated packets or act as a peer.
501
324
  *
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.
325
+ * Wire contract (targets connector PR #181's `/ilp`):
326
+ * - One-shot write: `POST /ilp`
327
+ * body: OER-encoded ILP PREPARE (`application/octet-stream`)
328
+ * header: `ILP-Payment-Channel-Claim: base64(JSON of the claim)` — the
329
+ * SAME claim JSON the BTP path attaches as the
330
+ * `payment-channel-claim` protocolData entry.
331
+ * optional: `ILP-Peer-Id` + `Authorization: Bearer <secret>` identity.
332
+ * response: `200 OK` with an OER FULFILL or REJECT body. HTTP non-2xx is
333
+ * reserved for TRANSPORT errors (400/401/413/5xx); ILP-level
334
+ * rejects come back as a 200 + REJECT body.
335
+ * - Upgrade to BTP: standard HTTP `Upgrade` with `Sec-WebSocket-Protocol: btp`
336
+ * plus the same `ILP-Peer-Id` + `Authorization` headers. The connector
337
+ * pre-authenticates the BTP session from those headers (continuity), so
338
+ * after `101` we send BTP frames WITHOUT a separate in-band auth frame.
339
+ * Omitting the auth headers falls back to the normal BTP auth-frame flow.
504
340
  *
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.
341
+ * Reuses `serializeIlpPrepare`/`deserializeIlpPacket` from `btp/protocol.ts` —
342
+ * the SAME OER codec the BTP path uses. Claim signing/construction is owned by
343
+ * the caller (BootstrapService); this transport never builds or signs claims.
514
344
  */
515
345
 
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
- };
346
+ /** Header carrying the base64(JSON) payment-channel claim. */
347
+ declare const ILP_CLAIM_HEADER = "ILP-Payment-Channel-Claim";
348
+ /** Header carrying the peer identity. */
349
+ declare const ILP_PEER_ID_HEADER = "ILP-Peer-Id";
350
+ interface HttpIlpClientConfig {
351
+ /** The peer's `POST /ilp` URL (the `httpEndpoint` from discovery). */
352
+ httpEndpoint: string;
544
353
  /**
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.
354
+ * Optional peer identity. With no `peerId`/`authToken` the connector treats
355
+ * the request as an anonymous no-auth peer (permissionless default) and
356
+ * derives an ephemeral id from the claim signer.
548
357
  */
549
- sealPubkey: string;
358
+ peerId?: string;
359
+ /** Bearer secret for `Authorization`. Omit for the no-auth peer path. */
360
+ authToken?: string;
361
+ /** Request timeout in milliseconds (default: 30000). */
362
+ timeout?: number;
363
+ /** Max retry attempts for transport-level network failures (default: 3). */
364
+ maxRetries?: number;
365
+ /** Initial retry delay in milliseconds (default: 1000). */
366
+ retryDelay?: number;
367
+ /** Custom fetch implementation (for testing / custom transports). */
368
+ httpClient?: typeof fetch;
369
+ /**
370
+ * Custom WebSocket constructor for the BTP upgrade path (for testing /
371
+ * custom transports). Forwarded to the underlying BtpRuntimeClient.
372
+ */
373
+ createWebSocket?: (url: string) => WebSocket;
550
374
  }
551
375
  /**
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.
376
+ * Stateless ILP-over-HTTP transport implementing `IlpClient`.
557
377
  *
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.
378
+ * Use this for pure one-shot consumers (publish-and-forget writes). When the
379
+ * client needs a duplex session — to receive server-initiated packets or to act
380
+ * as a peer — call {@link upgradeToBtp} to obtain a connected BtpRuntimeClient
381
+ * that reuses the existing BTP code path.
646
382
  */
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;
383
+ declare class HttpIlpClient implements IlpClient {
384
+ private readonly httpEndpoint;
385
+ private readonly peerId;
386
+ private readonly authToken;
387
+ private readonly timeout;
388
+ private readonly retryConfig;
389
+ private readonly httpClient;
390
+ private readonly createWebSocket;
391
+ constructor(config: HttpIlpClientConfig);
392
+ /**
393
+ * The client edge this transport pays — the origin `GET /ilp/identity` and
394
+ * `GET /ilp/routes/price` hang off (`ConnectorEdgeClient` normalizes the
395
+ * trailing `/ilp` away). Exposed because a sealed write must ask the
396
+ * connector it is ACTUALLY paying for its key, not a configured guess.
397
+ */
398
+ get clientEdgeEndpoint(): string;
399
+ /**
400
+ * Send an ILP PREPARE via `POST /ilp` WITHOUT a claim. The connector accepts
401
+ * this only on free/zero-amount routes; paid writes must use
402
+ * {@link sendIlpPacketWithClaim}. Satisfies the IlpClient interface.
403
+ *
404
+ * `params` may carry a sender-chosen `executionCondition` and an explicit
405
+ * `expiresAt` (toon-client#350); omitting both is the legacy zero-condition
406
+ * path, unchanged. With a non-zero condition the FULFILL preimage is
407
+ * verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced
408
+ * as a failed result — see {@link mapIlpResponse}.
409
+ */
410
+ sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;
411
+ /**
412
+ * Send an ILP PREPARE via `POST /ilp` with the payment-channel claim attached
413
+ * as the `ILP-Payment-Channel-Claim` header. `claim` is the SAME JSON object
414
+ * the BTP path attaches as the `payment-channel-claim` protocolData entry —
415
+ * we base64(JSON.stringify(claim)) it, byte-for-byte identical to BTP.
416
+ *
417
+ * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are
418
+ * identical to {@link sendIlpPacket}.
419
+ */
420
+ sendIlpPacketWithClaim(params: IlpSendParams, claim: unknown): Promise<IlpSendResult>;
421
+ /**
422
+ * Upgrade to a duplex BTP session over the SAME endpoint.
423
+ *
424
+ * Derives the `ws(s)://` URL from `httpEndpoint`, opens a WebSocket with
425
+ * `Sec-WebSocket-Protocol: btp` and the same `ILP-Peer-Id` + `Authorization`
426
+ * headers, and returns a connected {@link BtpRuntimeClient}. When auth headers
427
+ * are present the connector pre-authenticates the session (no in-band auth
428
+ * frame); without them the BtpRuntimeClient falls back to the normal BTP
429
+ * auth-frame flow.
430
+ *
431
+ * NOTE: passing per-connection headers + a subprotocol to a WebSocket is
432
+ * Node-only (the `ws` package). Browsers cannot set arbitrary request headers
433
+ * on a WebSocket handshake, so a browser consumer must use the gateway
434
+ * transport or BTP-with-auth-frame instead.
435
+ */
436
+ upgradeToBtp(): Promise<BtpRuntimeClient>;
437
+ private authHeaders;
438
+ /**
439
+ * Single attempt: serialize the PREPARE, POST it, and map the response.
440
+ * @throws {NetworkError} On connection/timeout failures (retried).
441
+ * @throws {ConnectorError} On non-retryable transport errors (5xx / unexpected).
442
+ */
443
+ private postPrepare;
444
+ /**
445
+ * Map a `200 OK` body (OER FULFILL/REJECT) to an IlpSendResult; map a non-2xx
446
+ * to a transport error. Per the wire contract, ILP-level rejects arrive as a
447
+ * 200 + REJECT body — only HTTP non-2xx means a transport-layer failure.
448
+ *
449
+ * When `sentCondition` is non-zero the FULFILL preimage is verified against
450
+ * it; a mismatch yields `accepted: false` (shared `mapIlpResponse` logic,
451
+ * identical to the BTP path).
452
+ */
453
+ private mapResponse;
454
+ private mapTransportError;
669
455
  }
670
456
  /**
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).
457
+ * Derive the BTP WebSocket URL from a `POST /ilp` HTTP endpoint. The connector
458
+ * serves BTP on the SAME path, so we only swap the scheme (http→ws, https→wss).
677
459
  */
678
- declare function readWalletBalances(sources: WalletBalanceSources): Promise<WalletChainBalances[]>;
460
+ declare function httpEndpointToBtpUrl(httpEndpoint: string): string;
679
461
 
680
462
  /**
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.
463
+ * Payment-aware HTTP fetch over TOON (the "h402" flow).
684
464
  *
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.
465
+ * This adapter makes paying for an HTTP resource transparent: it issues an
466
+ * ordinary HTTP request, and when the origin answers `402 Payment Required`
467
+ * with an x402-style challenge that offers a `toon-channel` payment option, it
468
+ * opens/reuses a payment channel, signs a balance-proof claim, and re-sends the
469
+ * SAME HTTP request as a "transparent HTTP-in-ILP" packet to the connector's
470
+ * `POST /ilp` endpoint (via {@link HttpIlpClient}). The connector terminates the
471
+ * payment, forwards the request to the origin, and returns the origin's HTTP
472
+ * response inside the ILP FULFILL `data`. We reconstruct a normal Web `Response`
473
+ * from those bytes — the caller never sees ILP.
691
474
  *
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.
475
+ * ─── x402 wire contract (the 402 challenge body) ────────────────────────────
476
+ * The shipped connector answers x402 **v2** terms (`client-edge-spec.md` §1.4,
477
+ * `crates/connector-client-edge/src/lib.rs`), and that is the shape pinned by
478
+ * `Http402Client.connectorTerms.test.ts`:
701
479
  *
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.
480
+ * ```jsonc
481
+ * {
482
+ * "x402Version": 2,
483
+ * "resource": { "url": "g.example.app" },
484
+ * "accepts": [
485
+ * {
486
+ * "scheme": "toon-channel",
487
+ * "network": "g.example.app",
488
+ * "amount": "100",
489
+ * "payTo": "g.example.app",
490
+ * "maxTimeoutSeconds": 60,
491
+ * "httpEndpoint": "/ilp", // RELATIVE to the resource's origin.
492
+ * "extra": { "ilpAddress": "g.example.app", "endpoint": "/ilp", "price": "100" }
493
+ * }
494
+ * ]
495
+ * }
496
+ * ```
706
497
  *
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".
498
+ * Two things that shape forces, both easy to get wrong:
499
+ * - The ILP address, the endpoint and the price live under **`extra`**. The
500
+ * top-level `payTo` happens to equal the destination today, so reading it
501
+ * appears to work — that is a coincidence of the connector's current code,
502
+ * not a contract, so `extra` is read first.
503
+ * - `httpEndpoint` is **relative**; it is resolved against the URL that
504
+ * answered `402` (`Response.url`, or `parseX402Body`'s `baseUrl` argument).
714
505
  *
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.
506
+ * Everything is still parsed DEFENSIVELY (mirroring `readDiscoveredIlpPeer` in
507
+ * selectIlpTransport.ts): an unrecognised connector shape degrades to the
508
+ * vanilla 402 rather than throwing. Field aliases (first present wins):
509
+ * - destination: `extra.ilpAddress` | `extra.destination` | `destination` |
510
+ * `ilpAddress` | `payTo`. (We do NOT invent a value — a missing
511
+ * destination makes the entry unusable and we fall back to the vanilla 402.)
512
+ * - amount: `extra.price` | `extra.amount` | `amount` | `price` |
513
+ * `maxAmountRequired`.
514
+ * - httpEndpoint:`httpEndpoint` | `ilpEndpoint` | `extra.httpEndpoint` |
515
+ * `extra.endpoint` | `endpoint`.
516
+ * - upgrade: `supportsUpgrade` | `upgradable`.
768
517
  *
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.
518
+ * ─── What the paid request is made of ───────────────────────────────────────
519
+ * The paid re-send is an OER `EnvelopeRequest` sealed to the terminating
520
+ * connector's identity, under a condition derived from the secret that seal
521
+ * carries — the same `sealExchange` / `readExchangeOutcome` pair
522
+ * `ToonClient.publishEvent` uses (ADR 0018/0019, toon-client#450, #451). This
523
+ * adapter used to carry its own HTTP/1.1 codec; it does not any more, and
524
+ * `packages/client` now has exactly one encoder.
776
525
  *
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.
526
+ * Two consequences of the envelope replacing HTTP text, both deliberate:
527
+ *
528
+ * - **`Host` and `Content-Length` are not synthesised.** The old codec added
529
+ * both. The connector strips them either way and lets its HTTP client
530
+ * recompute them (`connector-runtime/src/app_client.rs` skips `host` and
531
+ * `content-length` by name), and the envelope already carries the body
532
+ * length as an OER length determinant, so emitting them was writing bytes
533
+ * the far side throws away. A caller that sets either explicitly still has
534
+ * it carried verbatim, and the connector still drops it.
535
+ * - **A response has no reason phrase.** An `EnvelopeResponse` status is two
536
+ * bytes; `HTTP/1.1 201 Created`'s "Created" has nowhere to live on this
537
+ * wire. `Response.statusText` is therefore empty, and the status is the
538
+ * fact to read.
539
+ *
540
+ * A malformed answer now fails the way it fails everywhere else in this
541
+ * package — `SealedResponseError` from `readExchangeOutcome` — rather than
542
+ * this file's old `ConnectorError` on a bad status line while `fulfill-http.ts`
543
+ * quietly returned `{isHttp:false}` for the very same bytes.
544
+ *
545
+ * Claim signing/construction is owned by the CALLER (ToonClient wires the live
546
+ * ChannelManager + signer). This adapter never builds or validates claims —
547
+ * payment-claim validation lives ONLY in the connector.
786
548
  */
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
549
 
795
550
  /**
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.
551
+ * The `extra` bag of an `accepts` entry — an open set of terms from the peer,
552
+ * not a fixed contract. `session_lease_ttl_ms` (connector#722,
553
+ * `session_registry::SESSION_LEASE_BACKSTOP_TTL`) is the one member this
554
+ * client currently reads by name; everything else is preserved untouched
555
+ * (issue #506) rather than stripped by a narrower type, so a future field
556
+ * survives the round trip even before this package knows its name.
801
557
  */
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;
558
+ interface X402ChannelExtra {
559
+ /**
560
+ * The connector's session lease TTL in milliseconds. Absent on a connector
561
+ * predating #722 — `undefined`, never a substituted default.
562
+ */
563
+ session_lease_ttl_ms?: number;
564
+ [key: string]: unknown;
808
565
  }
809
- /** A server-originated TRANSFER — settlement value, never an ILP packet. */
810
- interface InboundBtpTransfer {
811
- requestId: number;
566
+ /** A single parsed `accepts` entry that offers the `toon-channel` scheme. */
567
+ interface ToonChannelAccept {
568
+ /** Always `'toon-channel'` for a matched entry. */
569
+ scheme: 'toon-channel';
570
+ /** Optional chain key, e.g. `evm:base:8453` — informational. */
571
+ network?: string;
572
+ /** ILP destination address to pay (the connector route fronting the URL). */
573
+ destination: string;
574
+ /** Price in ILP base units. */
812
575
  amount: bigint;
813
- protocolData: BTPProtocolData[];
576
+ /** The connector's `POST /ilp` URL. */
577
+ httpEndpoint: string;
578
+ /** Whether the host accepts the BTP upgrade over the HTTP endpoint. */
579
+ supportsUpgrade: boolean;
580
+ /**
581
+ * The entry's raw `extra` bag, preserved as-is. `undefined` when the entry
582
+ * carried no `extra` at all — distinct from an `extra` that merely omits a
583
+ * given key (issue #506).
584
+ */
585
+ extra?: X402ChannelExtra;
814
586
  }
815
- /** What an inbound handler answers with — becomes the RESPONSE frame's body. */
816
- interface BtpHandlerResponse {
817
- protocolData?: BTPProtocolData[];
818
- ilpPacket?: Uint8Array;
587
+ /** The parsed x402 402 body, with the selected `toon-channel` entry (if any). */
588
+ interface ParsedX402Challenge {
589
+ x402Version?: number;
590
+ /** The first usable `toon-channel` accepts entry, or `undefined`. */
591
+ toonChannel?: ToonChannelAccept;
592
+ }
593
+ /** Options for {@link Http402Client.fetch} / `ToonClient.h402Fetch`. */
594
+ interface H402FetchOptions {
595
+ /** HTTP method. Default `'GET'`. */
596
+ method?: string;
597
+ /** Request headers. */
598
+ headers?: Record<string, string>;
599
+ /** Request body. */
600
+ body?: string | Uint8Array;
601
+ /** Request timeout in milliseconds. */
602
+ timeout?: number;
603
+ /** Optional explicit ILP destination override (else the x402 entry's value). */
604
+ destination?: string;
819
605
  }
820
- type BtpMessageHandler = (message: InboundBtpMessage) => Promise<BtpHandlerResponse> | BtpHandlerResponse;
821
- type BtpTransferHandler = (transfer: InboundBtpTransfer) => Promise<BtpHandlerResponse> | BtpHandlerResponse;
822
-
823
606
  /**
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.
607
+ * Caller-supplied hook that signs a balance-proof claim for `(destination,
608
+ * amount)` and returns the chain-appropriate claim message to attach to the ILP
609
+ * PREPARE. ToonClient wires this to its ChannelManager + per-chain signer (the
610
+ * exact same plumbing as `publishEvent`). The returned value is forwarded
611
+ * opaquely as the `ILP-Payment-Channel-Claim` header by {@link HttpIlpClient}.
854
612
  */
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 {
613
+ type ClaimResolver = (destination: string, amount: bigint) => Promise<unknown>;
614
+ /** Factory for an {@link HttpIlpClient} given a resolved `POST /ilp` endpoint. */
615
+ type HttpIlpClientFactory = (httpEndpoint: string) => HttpIlpClient;
616
+ /** Caller-supplied hook invoked with every parsed x402 challenge. */
617
+ type ChallengeHandler = (challenge: ParsedX402Challenge) => void;
618
+ interface Http402ClientConfig {
871
619
  /**
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.
620
+ * Underlying HTTP fetch for the INITIAL (un-paid) request that probes for a
621
+ * 402. Default: global `fetch`.
876
622
  */
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;
623
+ fetch?: typeof fetch;
913
624
  /**
914
- * Default SPL token mint (base58) for PDA derivation. The per-channel
915
- * negotiated token (the peer's preferred token) takes precedence when present.
625
+ * Resolves + signs the payment-channel claim. REQUIRED to pay; if omitted,
626
+ * a 402 with a `toon-channel` offer is surfaced unchanged (vanilla challenge).
916
627
  */
917
- tokenMint?: string;
918
- /** Challenge-period duration (seconds) for `initialize_channel`. */
919
- challengeDuration?: number;
628
+ resolveClaim?: ClaimResolver;
920
629
  /**
921
- * OVERRIDE for the on-chain deposit made when opening the channel: `amount`
922
- * in base units (string) drawn from `payerTokenAccount` (the client's funded
923
- * SPL token account / ATA, base58 — derived from owner+mint when empty).
630
+ * Builds the {@link HttpIlpClient} for a resolved endpoint. Default: construct
631
+ * a new `HttpIlpClient({ httpEndpoint })`. Injectable for tests.
632
+ */
633
+ createIlpClient?: HttpIlpClientFactory;
634
+ /**
635
+ * AC4: request a duplex transport for the paid send. When `true` and the
636
+ * toon-channel entry advertises `supportsUpgrade`, {@link selectIlpTransport}
637
+ * returns `http-upgradable` and the send path calls
638
+ * {@link HttpIlpClient.upgradeToBtp} before writing — the wiring for
639
+ * large/streaming responses. Default `false` (stateless one-shot HTTP).
924
640
  *
925
- * Normally left unset: the open locks {@link ToonClientConfig.initialDeposit},
926
- * the same negotiated amount an EVM open locks. A 0 amount opts out and leaves
927
- * the channel uncollateralized — its claims cannot be redeemed on-chain.
641
+ * NOTE (v1 limitation): even on the upgrade path the actual write is still a
642
+ * one-shot `sendIlpPacketWithClaim`; full duplex body streaming over the BTP
643
+ * session is a documented follow-up. The selection + upgrade CALL PATH is
644
+ * wired and exercised here so the streaming consumer can take over the
645
+ * returned session in a later iteration.
928
646
  */
929
- deposit?: {
930
- amount: string;
931
- payerTokenAccount: string;
932
- };
933
- }
934
- /**
935
- * Mina payment-channel parameters supplied via `ToonClientConfig.minaChannel`.
936
- *
937
- * Mirrors the `MinaChannelConfig` consumed by `OnChainChannelClient`, minus the
938
- * Mina private key (derived from the client's `mnemonic`, the same key that
939
- * produces the registered Mina signer — so the channel-open key and the
940
- * claim-signing key are guaranteed identical).
941
- *
942
- * ────────────────────────────────────────────────────────────────────────────
943
- * PHASE-2 STAGE-3: the client's Mina claim now matches connector 3.9.0's
944
- * `MinaClaimMessage` contract — `{ zkAppAddress, tokenId, balanceCommitment,
945
- * proof (base64), salt, nonce }`, with the proof a Pallas Schnorr signature over
946
- * the connector's `Poseidon([balA,balB,salt]) / Poseidon(zkApp.x)` commitment
947
- * (verified field-by-field against the connector's o1js verify). A
948
- * Mina-denominated paid publish is ACCEPTED at `validateClaimMessage` and the
949
- * apex FULFILLs to relay. On-chain SETTLE remains gated for non-EVM dynamic
950
- * hidden-service peers by connector#88 (`No chain configured for peer`).
951
- * `zkAppAddress` must be a REAL deployed payment-channel zkApp the apex's Mina
952
- * provider can resolve on-chain (the e2e harness deploys it deterministically).
953
- * ────────────────────────────────────────────────────────────────────────────
954
- */
955
- interface MinaChannelClientOptions {
956
- /** Mina GraphQL URL used to open the channel + read zkApp state. */
957
- graphqlUrl: string;
647
+ needsDuplex?: boolean;
958
648
  /**
959
- * Deployed payment-channel zkApp address (B62 base58). Optional when
960
- * `autoDeploy` is set — the open path then resolves (or deploys) a
961
- * pair-owned zkApp itself.
649
+ * Asks the connector named by the 402 offer for its identity key, so the
650
+ * paid request can be sealed to it. Default: a fresh
651
+ * {@link ConnectorEdgeClient} over this config's `fetch`. Injectable so a
652
+ * caller that already holds one shares its identity cache rather than
653
+ * re-fetching a key per paid request.
962
654
  */
963
- zkAppAddress?: string;
655
+ connectorEdge?: ConnectorEdgeClient;
964
656
  /**
965
- * Per-pair zkApp auto-deploy: the Mina `PaymentChannel` zkApp is
966
- * single-pair (its on-chain channelHash bakes the participant pair at
967
- * initialization), so a fresh identity can never reuse a shared/announced
968
- * zkApp. With `autoDeploy`, opening a Mina channel first checks whether
969
- * the recorded/configured zkApp is provably OURS for this pair and deploys
970
- * a dedicated one otherwise (compile ≈1-3 min, inclusion ≈3-6 min,
971
- * ~1.1 MINA + fees — surfaced through `onProgress`).
657
+ * Called with the parsed challenge whenever a `402` body is parsed —
658
+ * before the pay/pass-through decision, so it fires whether or not a
659
+ * `toon-channel` entry is offered or a claim resolver is configured. The
660
+ * one-shot `fetch()` return is a plain `Response`; this is how a caller
661
+ * (e.g. `ToonClient.getLastX402Terms`) reaches the negotiated terms —
662
+ * including the `extra` bag (issue #506) — without re-issuing the probe
663
+ * itself.
972
664
  */
973
- autoDeploy?: {
974
- /** A previously recorded own deployment for this identity, if any. */
975
- deployed?: {
976
- zkAppAddress: string;
977
- zkAppPrivateKey: string;
978
- };
979
- /**
980
- * Persist hook — called with the zkApp address + key BEFORE the deploy tx
981
- * is sent (and before the circuit compiles), so a crash between send and
982
- * on-chain confirmation reuses the SAME zkApp next run instead of
983
- * deploying (and paying ~1.1 MINA for) a second one.
984
- */
985
- onDeploying?: (record: {
986
- zkAppAddress: string;
987
- zkAppPrivateKey: string;
988
- feePayer: string;
989
- }) => void | Promise<void>;
990
- /** Persist hook — called BEFORE the open proceeds on a fresh deploy. */
991
- onDeployed?: (record: {
992
- zkAppAddress: string;
993
- zkAppPrivateKey: string;
994
- feePayer: string;
995
- deployTxHash?: string;
996
- vkHash?: string;
997
- }) => void | Promise<void>;
998
- /** Progress lines for the slow compile/deploy/inclusion phases. */
999
- onProgress?: (line: string) => void;
1000
- };
1001
- /** Channel settlement timeout in slots for `initializeChannel` (default 86400). */
1002
- challengeDuration?: number;
1003
- /** Mina token id field (decimal string) for `initializeChannel` (default '1'). */
1004
- tokenId?: string;
1005
- /** Optional on-chain deposit (base units, string) after the channel opens. */
1006
- deposit?: {
1007
- amount: string;
1008
- };
1009
- /** Mina network id for the account/Schnorr prefix (default 'devnet'). */
1010
- networkId?: 'devnet' | 'mainnet';
665
+ onChallenge?: ChallengeHandler;
1011
666
  }
1012
667
  /**
1013
- * Configuration for ToonClient.
1014
- *
1015
- * This story implements HTTP mode only. Embedded mode will be added in a future epic.
1016
- *
1017
- * @example HTTP Mode (implemented)
1018
- * ```typescript
1019
- * const client = new ToonClient({
1020
- * connectorUrl: 'http://localhost:8080',
1021
- * secretKey,
1022
- * ilpInfo: { ilpAddress, btpEndpoint, pubkey },
1023
- * toonEncoder: encodeEvent,
1024
- * toonDecoder: decodeEvent,
1025
- * });
1026
- * ```
1027
- *
1028
- * @example Embedded Mode (not yet implemented)
1029
- * ```typescript
1030
- * const client = new ToonClient({
1031
- * connector: embeddedConnectorInstance, // Will throw error: "Embedded mode not yet implemented"
1032
- * secretKey,
1033
- * ilpInfo,
1034
- * toonEncoder,
1035
- * toonDecoder,
1036
- * });
1037
- * ```
668
+ * Reusable h402 fetch engine. `ToonClient.h402Fetch` is a thin wrapper that
669
+ * constructs this with the live claim/channel plumbing.
1038
670
  */
1039
- interface ToonClientConfig {
671
+ declare class Http402Client {
672
+ private readonly fetchImpl;
673
+ private readonly resolveClaim?;
674
+ private readonly createIlpClient;
675
+ private readonly needsDuplex;
676
+ private readonly connectorEdge;
677
+ private readonly onChallenge?;
678
+ constructor(config?: Http402ClientConfig);
1040
679
  /**
1041
- * HTTP URL of external connector service.
1042
- * Required for HTTP mode.
1043
- * Example: 'http://localhost:8080'
680
+ * `fetch()`-like entry point. Issues the request; on `402` parses the x402
681
+ * challenge and — when a usable `toon-channel` offer is present and a claim
682
+ * resolver is configured — pays over TOON and returns the reconstructed
683
+ * `Response`. Otherwise returns the original 402 unchanged (AC5).
1044
684
  */
1045
- connectorUrl?: string;
685
+ fetch(url: string, opts?: H402FetchOptions): Promise<Response>;
1046
686
  /**
1047
- * Embedded connector instance - NOT IMPLEMENTED in this story.
1048
- * Will throw error: "Embedded mode not yet implemented in ToonClient."
1049
- * Reserved for future implementation.
1050
- */
1051
- connector?: unknown;
1052
- /**
1053
- * BIP-39 mnemonic phrase to derive a full multi-chain identity from.
1054
- *
1055
- * When provided, the client derives the Nostr (NIP-06) + EVM keys
1056
- * synchronously at construction and the Solana (Ed25519) + Mina (Pallas) keys
1057
- * lazily in `start()`, registering per-chain signers so balance-proof claims
1058
- * can be settled on any of those chains. This is the recommended way to use
1059
- * non-EVM settlement (the raw `secretKey` path is secp256k1-only).
1060
- *
1061
- * Cannot be combined with `secretKey` (ambiguous Nostr identity). May be
1062
- * combined with `evmPrivateKey` to use a separate EVM key (e.g. hardware
1063
- * wallet) while still deriving Solana/Mina from the phrase.
1064
- *
1065
- * SECURITY: JavaScript strings are immutable and cannot be zeroed from
1066
- * memory — the phrase may persist in the heap until GC. Prefer
1067
- * passing a pre-derived `secretKey`/identity in high-security contexts.
1068
- */
1069
- mnemonic?: string;
1070
- /**
1071
- * BIP-44 account index used when deriving the multi-chain identity from
1072
- * `mnemonic`. Defaults to 0 (back-compat). A non-zero index derives a
1073
- * dedicated wallet from a shared mnemonic, producing the SAME addresses as
1074
- * the SDK's `fromMnemonicFull(mnemonic, { accountIndex })`:
1075
- * - Nostr (secp256k1): m/44'/1237'/0'/0/{index}
1076
- * - EVM (secp256k1): same key as Nostr
1077
- * - Solana (Ed25519): m/44'/501'/{index}'/0' (SLIP-0010)
1078
- * - Mina (Pallas): m/44'/12586'/{index}'/0/0
1079
- *
1080
- * Ignored unless `mnemonic` is provided.
1081
- */
1082
- mnemonicAccountIndex?: number;
1083
- /**
1084
- * 32-byte Nostr private key (hex or Uint8Array).
1085
- * Optional — if omitted, a keypair is auto-generated in applyDefaults()
1086
- * (or derived from `mnemonic` when that is provided instead).
1087
- */
1088
- secretKey?: Uint8Array;
1089
- /** ILP peer information for this client */
1090
- ilpInfo: IlpPeerInfo;
1091
- /** Function to encode Nostr events to TOON binary format */
1092
- toonEncoder: (event: NostrEvent) => Uint8Array;
1093
- /** Function to decode TOON binary format to Nostr events */
1094
- toonDecoder: (bytes: Uint8Array) => NostrEvent;
1095
- /**
1096
- * EVM private key for signing balance proofs and on-chain transactions.
1097
- *
1098
- * By default, this is derived from `secretKey` — both Nostr and EVM use
1099
- * secp256k1, so a single key provides both identities (matching the SDK's
1100
- * `fromMnemonic()`/`fromSecretKey()` behavior).
1101
- *
1102
- * Only set this if you need a *different* EVM key than your Nostr key
1103
- * (e.g., hardware wallet, custodial key, or legacy key separation).
1104
- */
1105
- evmPrivateKey?: string | Uint8Array;
1106
- /**
1107
- * Named network tier. When set (and != `'custom'`), the client defaults all
1108
- * settlement-related config — RPC/GraphQL URLs, supported chain identifiers,
1109
- * preferred tokens, EVM TokenNetwork addresses, and the Solana/Mina channel
1110
- * params (programId / zkApp) — from the shared core presets
1111
- * (`resolveClientNetwork`), so the caller no longer hand-wires every address.
1112
- * This is the client-side mirror of the relay node's `network` selector;
1113
- * both resolve the SAME deployed contracts.
1114
- *
1115
- * Precedence: any explicit per-chain field (`supportedChains`,
1116
- * `chainRpcUrls`, `settlementAddresses`, `preferredTokens`, `tokenNetworks`,
1117
- * `solanaChannel`, `minaChannel`) you also pass OVERRIDES the preset for that
1118
- * field. `'custom'` keeps the fully-manual path (no preset defaults). When
1119
- * unset, behaviour is unchanged (fully backward compatible).
1120
- *
1121
- * - `mainnet` — Base mainnet + public Solana/Mina (TOON contracts not yet
1122
- * deployed → settlement unconfigured, relay-only).
1123
- * - `testnet` / `devnet` — Base Sepolia + Solana/Mina devnet with the LIVE
1124
- * deployed TOON settlement contracts.
1125
- */
1126
- network?: 'mainnet' | 'testnet' | 'devnet' | 'custom';
1127
- /** Supported settlement chain identifiers (e.g., ["evm:anvil:31337"]) */
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';
1140
- /** Maps chain identifier to EVM settlement address */
1141
- settlementAddresses?: Record<string, string>;
1142
- /** Maps chain identifier to preferred token contract address */
1143
- preferredTokens?: Record<string, string>;
1144
- /** Maps chain identifier to TokenNetwork contract address (EVM only) */
1145
- tokenNetworks?: Record<string, string>;
1146
- /** BTP WebSocket URL (e.g., "ws://localhost:3000") */
1147
- btpUrl?: string;
1148
- /** Auth token for BTP handshake */
1149
- btpAuthToken?: string;
1150
- /** Peer ID for BTP connection (used in connector env var BTP_PEER_{ID}_SECRET) */
1151
- btpPeerId?: string;
1152
- /**
1153
- * ILP-over-HTTP one-shot endpoint of the uplink connector (the `POST /ilp`
1154
- * URL, e.g. "http://localhost:3000/ilp"). When set, the client prefers the
1155
- * stateless {@link HttpIlpClient} transport for one-shot writes instead of
1156
- * opening a persistent BTP WebSocket.
687
+ * Open/reuse a channel (via the injected claim resolver), seal the request
688
+ * envelope to the terminating connector, send it to `POST /ilp` with the
689
+ * claim and the matching condition, and open the answer.
1157
690
  *
1158
- * This mirrors the `httpEndpoint` field a peer advertises in discovery
1159
- * (`IlpPeerInfo`, toon PR #29). It is surfaced here as explicit config so the
1160
- * default runtime can opt into ILP-over-HTTP before connectors advertise the
1161
- * field on-wire. Leave unset to keep the existing BTP-only behavior (the safe
1162
- * default — no connector advertises an httpEndpoint until the connector + a
1163
- * core release with these fields ship).
691
+ * The identity is fetched BEFORE a packet is formed, and there is no default
692
+ * to fall back to: sealing to the wrong key is a confidentiality failure
693
+ * that merely presents as an undeliverable packet (ADR 0018).
1164
694
  */
1165
- connectorHttpEndpoint?: string;
695
+ private payOverToon;
1166
696
  /**
1167
- * Connector-PROXY base URL for the deployed devnet/testnet edge (e.g.
1168
- * `https://proxy.devnet.toonprotocol.dev`). The connector is now a
1169
- * payment-proxy that serves ILP-over-HTTP at `POST /ilp`; setting `proxyUrl`
1170
- * is the high-level way to route paid writes through that proxy WITHOUT a
1171
- * persistent BTP socket.
1172
- *
1173
- * When set, `applyDefaults` derives `connectorHttpEndpoint` from it (appending
1174
- * `/ilp` to the base unless the URL already ends in `/ilp`), so the existing
1175
- * {@link HttpIlpClient} transport selection (`selectIlpTransport`) picks the
1176
- * stateless one-shot HTTP transport for `publishEvent`/`sendSwapPacket`/
1177
- * `sendPayment`. An explicit `connectorHttpEndpoint` always wins over this.
697
+ * Send the sealed PREPARE over the selected transport.
1178
698
  *
1179
- * The eventual home for these endpoints is a `@toon-protocol/core` devnet
1180
- * preset; until that ships, set this field explicitly.
1181
- */
1182
- proxyUrl?: string;
1183
- /**
1184
- * Faucet base URL for the deployed devnet (e.g.
1185
- * `https://faucet.devnet.toonprotocol.dev`). Consumed by the {@link fundWallet}
1186
- * helper to drip test funds to the client's chain address before publishing.
1187
- * Has no effect on the runtime transport; it is config carried for tooling/e2e.
699
+ * - `http` / `http-upgradable`: stateless one-shot `POST /ilp` with the claim.
700
+ * - `http-upgradable` additionally exercises {@link HttpIlpClient.upgradeToBtp}
701
+ * for the duplex/streaming path (AC4). v1 still drives the actual write over
702
+ * the one-shot HTTP method even after upgrading — full duplex body streaming
703
+ * is a documented follow-up — but the upgrade call path is wired here.
704
+ * - `btp`: not reachable from h402 (the x402 offer only carries an
705
+ * `httpEndpoint`); guarded for completeness.
1188
706
  */
1189
- faucetUrl?: string;
707
+ private sendOverChoice;
708
+ }
709
+ /**
710
+ * Parse a 402 `Response` body into a {@link ParsedX402Challenge}, selecting the
711
+ * first usable `toon-channel` entry. Reads every field defensively; a malformed
712
+ * body, a non-JSON body, or an entry missing its `destination`/`httpEndpoint`
713
+ * yields `{ toonChannel: undefined }` so the caller falls back to the vanilla
714
+ * 402 rather than throwing.
715
+ */
716
+ declare function parseX402Challenge(response: Response): Promise<ParsedX402Challenge>;
717
+ /**
718
+ * Pure parser over an already-decoded x402 body (testable without a Response).
719
+ *
720
+ * `baseUrl`, when given, is the absolute URL of the resource that answered
721
+ * `402`; a relative `httpEndpoint` is resolved against it. Omitting it keeps
722
+ * the old behaviour of passing the endpoint through verbatim.
723
+ */
724
+ declare function parseX402Body(body: unknown, baseUrl?: string): ParsedX402Challenge;
725
+
726
+ /**
727
+ * Ask a terminating connector who it is and what it charges — the step that
728
+ * has to happen BEFORE a packet can be formed at all.
729
+ *
730
+ * ADR 0018 makes holding the terminating connector's public key a
731
+ * precondition of forming a packet: `Prepare.data` is sealed to that key, and
732
+ * sealing to the wrong one is a confidentiality failure, not a delivery
733
+ * failure. ADR 0022 says the connector *answers* — it never announces — so
734
+ * both facts are fetched from the connector's own client edge, on the same
735
+ * origin this client already POSTs `/ilp` to
736
+ * (`docs/protocol/client-edge-spec.md` §1.7):
737
+ *
738
+ * - `GET /ilp/identity` → `{ "keyId": "...", "publicKey": "0x04..." }` — the
739
+ * uncompressed secp256k1 key, 65 bytes, `0x`-prefixed hex.
740
+ * - `GET /ilp/routes/price?destination=<ILP address>` →
741
+ * `{ "destination": "...", "price": 100 }`, or `404` when no
742
+ * locally-terminated route matches.
743
+ *
744
+ * Both are unauthenticated and neither changes state.
745
+ *
746
+ * ─── What this module refuses to do ────────────────────────────────────────
747
+ * Unlike the 402-challenge parser next door (which degrades gracefully so an
748
+ * unrecognised connector shape falls back to the vanilla 402), an identity is
749
+ * parsed STRICTLY. A key that is the wrong length, not `0x04`-prefixed, or not
750
+ * valid hex is refused with a distinguishable error rather than carried
751
+ * forward: a half-understood key would be sealed to, and the failure would be
752
+ * silent. There is no "best effort" reading of a public key.
753
+ *
754
+ * Pure transport + parsing: no keys are held, nothing is signed, and the only
755
+ * state is the identity cache.
756
+ */
757
+
758
+ /** The terminating connector's own identity, as reported by `GET /ilp/identity`. */
759
+ interface ConnectorIdentity {
760
+ /** The key id identifying the key (opaque to this client). */
761
+ keyId: string;
762
+ /** The uncompressed secp256k1 public key — exactly 65 raw bytes, leading `0x04`. */
763
+ publicKey: Uint8Array;
764
+ /** The key exactly as reported, `0x`-prefixed lowercase hex (65 bytes → 132 chars). */
765
+ publicKeyHex: string;
766
+ /** The normalized client-edge base URL this identity was read from. */
767
+ endpoint: string;
768
+ }
769
+ /**
770
+ * The channel-opening facts a settling connector carries in its x402
771
+ * greeting (connector #617): everything a buyer needs to OPEN a channel
772
+ * with the node, learned by ASKING (ADR 0022) rather than from a
773
+ * kind:10032 announce the Rust fleet never makes.
774
+ */
775
+ interface ConnectorSettlementTerms {
776
+ /** `evm:<chainId>` — the chain the node's settlement backend runs on. */
777
+ chain: string;
778
+ /** The on-chain counterparty a buyer opens a channel WITH. */
779
+ settlementAddress: string;
780
+ /** The stable TokenNetworkRegistry factory address. */
781
+ tokenNetworkRegistry: string;
782
+ /** The resolved TokenNetwork — the EIP-712 verifyingContract. */
783
+ tokenNetwork: string;
784
+ tokenAddress: string;
785
+ /** Informational; claims are already in base units. */
786
+ decimals: number;
787
+ }
788
+ /**
789
+ * The Solana twin of {@link ConnectorSettlementTerms} (connector #632): what
790
+ * an unaffiliated buyer needs to open a channel against a Solana settlement
791
+ * backend's deployed `payment-channel` program instance.
792
+ */
793
+ interface ConnectorSolanaSettlementTerms {
794
+ /** Always `'solana'` — unlike EVM there is no chain id to append. */
795
+ chain: string;
796
+ /** The on-chain counterparty a buyer opens a channel WITH, base58. */
797
+ settlementAddress: string;
798
+ /** The deployed `payment-channel` program instance, base58. */
799
+ programId: string;
800
+ /** The SPL mint every channel this backend opens settles in, base58. */
801
+ tokenAddress: string;
802
+ /** Informational; claims are already in base units. */
803
+ decimals: number;
804
+ }
805
+ /**
806
+ * One chain's entry in the x402 greeting's per-chain `settlements` list
807
+ * (connector #632). `kind` is added by this parser, not present on the wire
808
+ * — the wire is untagged, disambiguated structurally (`tokenNetworkRegistry`
809
+ * names EVM, `programId` names Solana).
810
+ */
811
+ type ConnectorChainSettlementTerms = ({
812
+ kind: 'evm';
813
+ } & ConnectorSettlementTerms) | ({
814
+ kind: 'solana';
815
+ } & ConnectorSolanaSettlementTerms);
816
+ /**
817
+ * A route's terms as the x402 greeting states them: the price, plus (from a
818
+ * settling node) the channel-opening facts. `settlement` is absent exactly
819
+ * when the node has no settlement backend — the wire's own shape. `settlements`
820
+ * is the additive per-chain list (connector #632): one entry per chain the
821
+ * node settles on, including the same EVM entry `settlement` already carries.
822
+ * Absent — not an empty array — on a node with no settlement backend, or one
823
+ * still answering the pre-#632 greeting shape.
824
+ */
825
+ interface ConnectorRouteTerms {
826
+ destination: string;
827
+ price: string;
828
+ settlement?: ConnectorSettlementTerms;
829
+ settlements?: ConnectorChainSettlementTerms[];
1190
830
  /**
1191
- * Whether the uplink connector accepts a BTP `Upgrade` over its HTTP endpoint
1192
- * (mirrors `IlpPeerInfo.supportsUpgrade`, toon PR #29). Only consulted when
1193
- * `connectorHttpEndpoint` is set and a duplex session is required. Defaults to
1194
- * false (no upgrade) when omitted.
831
+ * The `toon-channel` accepts entry's raw `extra` bag, preserved as-is
832
+ * (issue #509 — the same posture #506/#507 established for
833
+ * `Http402Client`'s parser, e.g. `extra.session_lease_ttl_ms`,
834
+ * connector#722). `undefined` when the entry carried no `extra` at all —
835
+ * distinct from an `extra` that merely omits a given key.
1195
836
  */
1196
- connectorSupportsUpgrade?: boolean;
837
+ extra?: X402ChannelExtra;
838
+ }
839
+ /** What a locally-terminated route costs, as reported by `GET /ilp/routes/price`. */
840
+ interface ConnectorRoutePrice {
841
+ /** The ILP destination that was asked about (echoed by the connector). */
842
+ destination: string;
843
+ /** The price in ILP base units of the route `destination` matched. */
844
+ price: bigint;
845
+ }
846
+ /**
847
+ * One `POST /ilp/claim-state` request entry: proof of ownership of a channel
848
+ * this client controls, via a signature over a challenge distinct from a
849
+ * real claim's balance-proof (never reusable as one). `signature` is
850
+ * `EvmSigner.signClaimStateChallenge`'s `0x`-prefixed 65-byte hex for `evm`,
851
+ * `SolanaSigner.signClaimStateChallenge`'s base64 64-byte Ed25519 for
852
+ * `solana`.
853
+ */
854
+ type ClaimStateRequestEntry = {
855
+ blockchain: 'evm';
856
+ channelId: string;
857
+ expires: number;
858
+ signature: string;
859
+ } | {
860
+ blockchain: 'solana';
861
+ channelAccount: string;
862
+ expires: number;
863
+ signature: string;
864
+ };
865
+ /**
866
+ * The credited/spendable position of one channel this client asked about —
867
+ * the runway source of truth (toon-meta#261/#262 decision 9). Money fields
868
+ * are decimal strings (never a bare JS number, which cannot represent a
869
+ * value past 2^53 exactly).
870
+ */
871
+ interface ClaimStateOk {
872
+ blockchain: 'evm' | 'solana';
873
+ channelId?: string;
874
+ channelAccount?: string;
875
+ ok: true;
876
+ /** On-chain deposit, or `null` for a channel this connector only DECLARED. */
877
+ depositTotal: string | null;
878
+ /** The channel's watermark; `"0"` if this connector has never accepted a claim. */
879
+ cumulativeClaimed: string;
880
+ /** `depositTotal - cumulativeClaimed`; `null` exactly when `depositTotal` is. */
881
+ available: string | null;
882
+ nonce: number;
1197
883
  /**
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.
884
+ * Best-effort and non-durable (unlike every other field here): `null`
885
+ * means "unknown", NEVER "never claimed" — see client-edge-spec.md §1.10.
1216
886
  */
1217
- preferBtpForPaidWrites?: boolean;
887
+ lastClaimTime: number | null;
888
+ }
889
+ /**
890
+ * A failed claim-state entry. `error` is deliberately collapsed to two
891
+ * causes (unlike a claim's own refusal taxonomy) so a caller learns nothing
892
+ * about a channel it does not control: `"unverified"` covers "no such
893
+ * channel" and "bad signature" identically.
894
+ */
895
+ interface ClaimStateFailed {
896
+ blockchain: 'evm' | 'solana';
897
+ channelId?: string;
898
+ channelAccount?: string;
899
+ ok: false;
900
+ error: 'expired' | 'unverified';
901
+ }
902
+ type ClaimStateResult = ClaimStateOk | ClaimStateFailed;
903
+ /**
904
+ * Every distinguishable way asking a connector for its identity or terms can
905
+ * fail. Each code names exactly one cause; there is no catch-all, because the
906
+ * caller's next move differs per cause (retry a transport failure; never
907
+ * retry a malformed key).
908
+ */
909
+ type ConnectorEdgeErrorCode =
910
+ /** Non-2xx from `GET /ilp/identity`. */
911
+ 'IDENTITY_HTTP_STATUS'
912
+ /** `GET /ilp/identity` answered 2xx with a body that is not the documented object. */
913
+ | 'IDENTITY_MALFORMED'
914
+ /** `publicKey` is present but is not `0x`-prefixed even-length hex. */
915
+ | 'IDENTITY_KEY_NOT_HEX'
916
+ /** `publicKey` decodes, but not to exactly 65 bytes. */
917
+ | 'IDENTITY_KEY_LENGTH'
918
+ /** `publicKey` is 65 bytes but does not start with the SEC1 uncompressed tag `0x04`. */
919
+ | 'IDENTITY_KEY_NOT_UNCOMPRESSED'
920
+ /** Non-2xx, non-404 from `GET /ilp/routes/price` (404 is not an error — see below). */
921
+ | 'ROUTE_PRICE_HTTP_STATUS'
922
+ /** `GET /ilp/routes/price` answered 2xx with a body that is not the documented object. */
923
+ | 'ROUTE_PRICE_MALFORMED'
924
+ /** A destination that cannot be put in a query string was asked about. */
925
+ | 'INVALID_DESTINATION'
926
+ /** A 402 greeting whose body is not the documented x402 shape (or whose
927
+ * optional `settlement` facts are present but malformed — refused rather
928
+ * than silently dropped, since they would be opened AGAINST). */
929
+ | 'TERMS_MALFORMED'
930
+ /** Non-2xx from `POST /ilp/claim-state`. */
931
+ | 'CLAIM_STATE_HTTP_STATUS'
932
+ /** `POST /ilp/claim-state` answered 2xx with a body that is not the documented shape. */
933
+ | 'CLAIM_STATE_MALFORMED';
934
+ /**
935
+ * A refusal to carry a connector's answer forward. Distinct from
936
+ * {@link NetworkError} (which this module throws for a transport failure), so
937
+ * "the connector is unreachable" and "the connector answered something I will
938
+ * not seal to" are never confused.
939
+ */
940
+ declare class ConnectorEdgeError extends ToonClientError {
941
+ /** Narrowed from `ToonClientError`'s `string`; type-only, no runtime field. */
942
+ readonly code: ConnectorEdgeErrorCode;
943
+ constructor(message: string, code: ConnectorEdgeErrorCode, cause?: Error);
944
+ }
945
+ /**
946
+ * Normalize any client-edge URL a caller already holds into the base the
947
+ * `/ilp/*` routes hang off.
948
+ *
949
+ * Callers reach this module holding whatever the x402 offer or their config
950
+ * gave them — `https://apex.example`, `https://apex.example/`, or the
951
+ * `POST /ilp` endpoint `https://apex.example/ilp` itself. All three name the
952
+ * same client edge, so all three normalize to `https://apex.example`.
953
+ */
954
+ declare function connectorEdgeBaseUrl(endpoint: string): string;
955
+ /**
956
+ * Decode a `0x`-prefixed hex public key into its 65 raw bytes, refusing
957
+ * anything that is not exactly one uncompressed secp256k1 key.
958
+ */
959
+ declare function decodeConnectorPublicKey(publicKeyHex: string): Uint8Array;
960
+ /**
961
+ * Parse an already-decoded `GET /ilp/identity` body. Exported so the shape the
962
+ * connector actually emits can be pinned without standing up a server.
963
+ */
964
+ declare function parseConnectorIdentity(body: unknown, endpoint: string): ConnectorIdentity;
965
+ /** Parse an already-decoded `GET /ilp/routes/price` 200 body. */
966
+ declare function parseConnectorRoutePrice(body: unknown): ConnectorRoutePrice;
967
+ /**
968
+ * Parse an already-decoded `POST /ilp/claim-state` body. Exported so the wire
969
+ * shape is testable without a server. Refuses a body that is not the
970
+ * documented `{ channels: [...] }` object, or any entry within it that is
971
+ * not the documented ok/failed shape — a half-understood credited balance
972
+ * would misreport an agent's runway, which is the one thing this endpoint
973
+ * exists to get right (toon-meta#262 decision 9).
974
+ */
975
+ declare function parseClaimStateResponse(body: unknown): ClaimStateResult[];
976
+ interface ConnectorEdgeClientConfig {
977
+ /** HTTP fetch implementation. Default: global `fetch`. Injectable for tests. */
978
+ fetch?: typeof fetch;
979
+ /** Per-request timeout in milliseconds. Default 10_000. */
980
+ timeout?: number;
981
+ }
982
+ /**
983
+ * Asks connectors for their identity and their terms, caching each identity
984
+ * per client-edge endpoint and each route price per (endpoint, destination).
985
+ *
986
+ * The cache is per endpoint rather than per client instance because a sender
987
+ * routinely speaks to several connectors, and re-fetching a key per packet
988
+ * would put a network round trip in front of every send. Nothing here expires
989
+ * on a timer: an operator key rotation, or a route being repriced, is a
990
+ * deliberate event, so {@link invalidateIdentity} / {@link invalidateRoutePrice}
991
+ * are how a stale answer is dropped.
992
+ *
993
+ * A price is cached the same way and for the same reason (toon-client#452):
994
+ * under ADR 0020 a route's price is FLAT — one handler, one price — so it does
995
+ * not vary with what is being sent, and asking again per packet would buy
996
+ * nothing but latency.
997
+ */
998
+ declare class ConnectorEdgeClient {
999
+ private readonly fetchImpl;
1000
+ private readonly timeout;
1001
+ private readonly identities;
1002
+ private readonly prices;
1003
+ constructor(config?: ConnectorEdgeClientConfig);
1218
1004
  /**
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.
1005
+ * The terminating connector's public key, fetched once per endpoint.
1006
+ *
1007
+ * @param endpoint any client-edge URL (`https://apex`, `https://apex/ilp`).
1008
+ * @param options `forceRefresh` bypasses (and replaces) the cache entry.
1228
1009
  */
1229
- jobHandler?: JobHandler;
1010
+ getIdentity(endpoint: string, options?: {
1011
+ forceRefresh?: boolean;
1012
+ }): Promise<ConnectorIdentity>;
1230
1013
  /**
1231
- * ILP destination address for event publishing.
1232
- * Defaults to the connector's local address (derived from connectorUrl host).
1233
- * For multi-hop routing, set this to the target node's ILP address.
1234
- * Examples:
1235
- * - 'g.toon.genesis' - Publish to genesis node
1236
- * - 'g.toon.peer1' - Publish to peer1 node
1014
+ * Drop a cached identity — one endpoint's, or every endpoint's when
1015
+ * `endpoint` is omitted. The way to react to a key rotation.
1237
1016
  */
1238
- destinationAddress?: string;
1239
- /** Maps chain identifier to RPC URL (e.g., {"evm:anvil:31337": "http://localhost:8545"}) */
1240
- chainRpcUrls?: Record<string, string>;
1017
+ invalidateIdentity(endpoint?: string): void;
1018
+ /** Whether an identity for `endpoint` is already held (no request is made). */
1019
+ hasCachedIdentity(endpoint: string): boolean;
1241
1020
  /**
1242
- * Collateral (base units, string) locked on-chain when a channel is opened,
1243
- * on EVERY settlement chain (EVM `setTotalDeposit`, Solana `deposit`).
1244
- * Defaults to `"100000"` — 0.1 USDC at 6 decimals. A peer's negotiated
1245
- * `initialDeposit` still wins over this. Set `"0"` only if you accept
1246
- * uncollateralized claims (they cannot be redeemed for value on-chain).
1021
+ * What `destination` costs at this connector, or `null` when the connector
1022
+ * answers `404` — no locally-terminated route matches it.
1023
+ *
1024
+ * `null` is the answer to "you do not terminate this", which is information;
1025
+ * a transport failure throws {@link NetworkError} instead, so a caller can
1026
+ * always tell "not mine" from "could not ask".
1027
+ *
1028
+ * Fetched once per (endpoint, destination) and reused. ADR 0020 makes a
1029
+ * price flat per handler, so it does not vary with the packet — a route
1030
+ * being repriced is an operator event, and {@link invalidateRoutePrice} is
1031
+ * how a caller reacts to one.
1032
+ *
1033
+ * @param options `forceRefresh` bypasses (and replaces) the cache entry.
1247
1034
  */
1248
- initialDeposit?: string;
1249
- /** Challenge period in seconds (default: 86400) */
1250
- settlementTimeout?: number;
1035
+ getRoutePrice(endpoint: string, destination: string, options?: {
1036
+ forceRefresh?: boolean;
1037
+ }): Promise<ConnectorRoutePrice | null>;
1251
1038
  /**
1252
- * Solana payment-channel parameters for opening a REAL on-chain channel and
1253
- * signing a connector-format Solana balance proof.
1254
- *
1255
- * When present (and the client has a Solana signer — i.e. it was constructed
1256
- * from a `mnemonic`), `ToonClient.start()` wires these into the on-chain
1257
- * channel client so that negotiating a `solana:*` chain opens an on-chain
1258
- * channel at the connector-parity PDA and pays a Solana-denominated claim.
1039
+ * Ask a route for its full x402 terms — the greeting a claimless PREPARE
1040
+ * is answered with (client-edge-spec.md §1.4) — including, from a settling
1041
+ * node, the channel-opening facts (connector #617).
1259
1042
  *
1260
- * The Ed25519 keypair is NOT carried here — it is derived from the same
1261
- * `mnemonic` that produces the Solana signer, so the channel-open key and the
1262
- * claim-signing key are guaranteed identical.
1043
+ * This is a real `POST /ilp` carrying a minimal PREPARE with no claim
1044
+ * header. It is free by the wire's own contract: an unpaid request to a
1045
+ * priced route is answered with terms instead of performed, and nothing
1046
+ * is charged for asking. `null` when the connector does not price the
1047
+ * destination (the request would be routed or refused, not greeted) —
1048
+ * mapped from anything other than a 402 answer.
1263
1049
  */
1264
- solanaChannel?: SolanaChannelClientOptions;
1050
+ getRouteTerms(endpoint: string, destination: string): Promise<ConnectorRouteTerms | null>;
1265
1051
  /**
1266
- * Mina payment-channel parameters (graphqlUrl + zkAppAddress). When present
1267
- * (and the client has a Mina signer — i.e. it was constructed from a
1268
- * `mnemonic` AND `mina-signer` is installed), `ToonClient.start()` wires these
1269
- * into the on-chain channel client so negotiating a `mina:*` chain routes
1270
- * through `openMinaChannel` and pays a Mina-denominated claim.
1052
+ * The credited/spendable position of one or more channels this client
1053
+ * controls (`POST /ilp/claim-state`, client-edge-spec.md §1.10) — the
1054
+ * runway source of truth (toon-meta#261/#262 decision 9): earnings net
1055
+ * off-chain on the same channel a client spends from, so this is also
1056
+ * where a credited balance is read. Never cached: unlike identity/price,
1057
+ * a claim watermark changes on every accepted claim, on EITHER side.
1271
1058
  *
1272
- * The Mina private key is NOT carried here — it is derived from the same
1273
- * `mnemonic` that produces the Mina signer.
1059
+ * Each entry is independently authenticated (own signature, own
1060
+ * blockchain) — a request MAY mix EVM and Solana channels. Returns `[]`
1061
+ * without a request when `channels` is empty.
1274
1062
  *
1275
- * NOTE (Phase-2 Stage-3 gate): see `MinaChannelClientOptions` — supplying this
1276
- * wires the negotiation path but the resulting claim does not yet satisfy
1277
- * connector 3.9.0's Mina claim contract, so a live loop is claim-validation
1278
- * gated (distinct from the connector #88 on-chain-settle gate).
1063
+ * @throws {NetworkError} the connector could not be reached.
1064
+ * @throws {ConnectorEdgeError} a non-2xx status, or a body that is not the
1065
+ * documented shape.
1279
1066
  */
1280
- minaChannel?: MinaChannelClientOptions;
1067
+ getClaimState(endpoint: string, channels: ClaimStateRequestEntry[]): Promise<ClaimStateResult[]>;
1281
1068
  /**
1282
- * Receive-side Mina swap-claim redemption (#357): maker on-chain co-signatures
1283
- * keyed by dest-channel zkApp address (B62).
1284
- *
1285
- * On-chain `claimFromChannel` is dual-party — it verifies BOTH participants
1286
- * signed `[commitment, nonce, channelHash]`. The recipient (this client)
1287
- * produces its own co-signature from the derived Mina key, but the swap-wire
1288
- * claim only carries the maker's `balanceProofFieldsMina` signature (a
1289
- * DIFFERENT message), so the maker must additionally deliver a
1290
- * payment-channel-commitment-form co-signature. Until that flows over the swap
1291
- * wire, an operator can inject the maker's `{ r, s }` here to complete a
1292
- * receive-side redemption. Absent one, settlement fails closed with
1293
- * `MINA_MAKER_COSIGN_REQUIRED` (never a silent pass).
1069
+ * Drop a cached route price — one (endpoint, destination)'s, every
1070
+ * destination's at one endpoint when `destination` is omitted, or all of
1071
+ * them when both are. The way to react to a route being repriced.
1294
1072
  */
1295
- swapMinaMakerSignatures?: Record<string, {
1296
- r: string;
1297
- s: string;
1298
- }>;
1073
+ invalidateRoutePrice(endpoint?: string, destination?: string): void;
1299
1074
  /**
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.
1075
+ * Whether a price for `(endpoint, destination)` is already held (no request
1076
+ * is made).
1308
1077
  */
1309
- channelStorePath?: string;
1310
- /** Nostr relay URL for peer discovery. Default: 'wss://relay-ws.devnet.toonprotocol.dev' */
1311
- relayUrl?: string;
1078
+ hasCachedRoutePrice(endpoint: string, destination: string): boolean;
1079
+ private fetchRoutePrice;
1080
+ private fetchIdentity;
1081
+ private readJson;
1082
+ /** GET with a timeout, mapping any transport failure onto {@link NetworkError}. */
1083
+ private get;
1084
+ }
1085
+ /**
1086
+ * Parse an x402 v2 greeting body into {@link ConnectorRouteTerms}. Pure and
1087
+ * exported so the wire shape is testable without a server. Refuses a body
1088
+ * that is not the documented greeting; a malformed OPTIONAL `settlement`
1089
+ * object (or `settlements` entry) is also a refusal rather than a silent
1090
+ * drop — half-understood channel-opening facts would be opened AGAINST.
1091
+ */
1092
+ declare function parseConnectorRouteTerms(body: unknown): ConnectorRouteTerms;
1093
+
1094
+ /**
1095
+ * NIP-59 gift-wrap UNWRAP, receiver side only. Backs the daemon's
1096
+ * `POST /nip59-unwrap` control-API endpoint (toon-meta#256): an external
1097
+ * agent process (buzz#19's agent-members) hands the daemon a kind:1059 event
1098
+ * addressed to the daemon's own Nostr identity, and gets back the decrypted
1099
+ * inner event — without the daemon's secret key ever leaving this process,
1100
+ * let alone the caller's.
1101
+ *
1102
+ * There is deliberately no `wrap` (sender) side here yet — nothing in this
1103
+ * client originates gift wraps today (the swap rumor path builds its own via
1104
+ * the sdk). Add one only when a sender use case actually needs it.
1105
+ *
1106
+ * Uses `nostr-tools/nip44` for both decrypt layers and `nostr-tools/pure`'s
1107
+ * `verifyEvent` for the seal signature check — no hand-rolled crypto.
1108
+ *
1109
+ * ─── Why a bespoke unwrap instead of `nostr-tools/nip59`'s `unwrapEvent` ────
1110
+ * `unwrapEvent` throws away the seal once it has decrypted through it, so it
1111
+ * can never tell a caller who actually signed the rumor — only the wrap's
1112
+ * ephemeral, throwaway `pubkey` is visible from outside. NIP-59 is explicit
1113
+ * that authorship must be read off the SEAL, never the wrap, so this module
1114
+ * decrypts the two layers by hand (still via `nip44.getConversationKey` /
1115
+ * `nip44.decrypt`, the same primitives `unwrapEvent` uses internally) in
1116
+ * order to surface `seal.pubkey` — verified against the seal's own
1117
+ * signature, not merely trusted as a decrypted field.
1118
+ */
1119
+
1120
+ /** `kind:1059` — the outer gift wrap. */
1121
+ declare const GIFT_WRAP_KIND = 1059;
1122
+ /** `kind:13` — the inner seal, signed by the real author. */
1123
+ declare const SEAL_KIND = 13;
1124
+ /**
1125
+ * The wrap was structurally invalid, not a gift wrap, or not addressed to
1126
+ * the identity attempting to unwrap it. None of these required decrypting
1127
+ * anything — they're rejectable from the event's plaintext envelope alone.
1128
+ * Maps to HTTP 400 at the control-API boundary.
1129
+ */
1130
+ declare class GiftWrapAddressError extends Error {
1131
+ constructor(message: string);
1132
+ }
1133
+ /**
1134
+ * The wrap looked addressable but a cryptographic step failed: a NIP-44
1135
+ * layer didn't decrypt, the decrypted payload wasn't the expected event
1136
+ * shape, or the seal's signature didn't verify against its own `pubkey`.
1137
+ * Maps to HTTP 422 at the control-API boundary.
1138
+ */
1139
+ declare class GiftWrapDecryptError extends Error {
1140
+ constructor(message: string);
1141
+ }
1142
+ /** Result of a successful unwrap. */
1143
+ interface UnwrappedGiftWrap {
1144
+ /** The decrypted inner event (NIP-59 calls it the "rumor") — unsigned. */
1145
+ rumor: UnsignedEvent & {
1146
+ id?: string;
1147
+ };
1312
1148
  /**
1313
- * Known peers to bootstrap with.
1314
- * If provided, these peers will be used for initial bootstrap.
1315
- * DiscoveryTracker will discover additional peers from kind:10032 events after bootstrap.
1149
+ * The hex pubkey that signed the kind:13 seal, VERIFIED against the seal's
1150
+ * own signature. This — never `wrap.pubkey`, which NIP-59 mints fresh and
1151
+ * throws away per wrap — is the real author.
1316
1152
  */
1317
- knownPeers?: {
1318
- pubkey: string;
1319
- relayUrl: string;
1320
- btpEndpoint?: string;
1321
- }[];
1322
- /** Query timeout in milliseconds. Default: 30000 */
1323
- queryTimeout?: number;
1324
- /** Maximum number of retries for failed operations. Default: 3 */
1325
- maxRetries?: number;
1326
- /** Delay between retries in milliseconds. Default: 1000 */
1327
- retryDelay?: number;
1153
+ sealPubkey: string;
1328
1154
  }
1329
1155
  /**
1330
- * Result returned by ToonClient.start()
1156
+ * Unwrap a NIP-59 gift wrap addressed to `recipientPubkey`, decrypting both
1157
+ * layers with `recipientSecretKey`. Pure function (no I/O, no client state)
1158
+ * so it can be unit-tested directly against real `nostr-tools/nip59` fixtures
1159
+ * — see `nip59.test.ts`. {@link ToonClient.unwrapGiftWrap} is a thin
1160
+ * passthrough that supplies the client's own identity key.
1161
+ *
1162
+ * @throws {GiftWrapAddressError} malformed input, wrong kind, or not
1163
+ * addressed to `recipientPubkey`.
1164
+ * @throws {GiftWrapDecryptError} a NIP-44 layer failed to decrypt, decrypted
1165
+ * to the wrong shape, or the seal's signature didn't verify.
1331
1166
  */
1332
- interface ToonStartResult {
1333
- /** Number of peers discovered during bootstrap */
1334
- peersDiscovered: number;
1335
- /** Mode the client is running in */
1336
- mode: 'http' | 'embedded';
1167
+ declare function unwrapGiftWrapWithKey(recipientSecretKey: Uint8Array, recipientPubkey: string, wrap: NostrEvent): UnwrappedGiftWrap;
1168
+
1169
+ /** One on-chain wallet token balance. `amount` is base-unit integer, decimal. */
1170
+ interface WalletBalance {
1171
+ chain: 'evm' | 'solana' | 'mina';
1172
+ address: string;
1173
+ amount: string;
1174
+ /** Token symbol, when resolved (e.g. `'USDC'`, `'MINA'`). */
1175
+ asset?: string;
1176
+ /** Token decimals, when resolved. */
1177
+ assetScale?: number;
1337
1178
  }
1338
1179
  /**
1339
- * Result returned by ToonClient.publishEvent()
1180
+ * One asset amount within a chain's wallet view — the native coin or one token.
1181
+ * `amount` is a base-unit integer, decimal string.
1340
1182
  */
1341
- interface PublishEventResult {
1342
- /** Whether the event was successfully published */
1343
- success: boolean;
1344
- /** ID of the published event */
1345
- eventId?: string;
1346
- /**
1347
- * The destination's answer, opened from the sealed FULFILL: status, headers
1348
- * and body, exactly as the app behind the terminated route gave them.
1349
- *
1350
- * Present whenever the packet FULFILLED — including for a non-2xx status,
1351
- * which is envelope content rather than a packet outcome (ADR 0020): the
1352
- * answer arrived and value moved. Absent only when the packet was rejected.
1353
- */
1354
- response?: EnvelopeResponse;
1355
- /** Error message if success is false */
1356
- error?: string;
1357
- /**
1358
- * Who refused, when one did. `'destination'` is provable — the reject was
1359
- * sealed with this packet's own secret, which only the terminating
1360
- * connector could hold. `'path'` is a hop short of the termination, which
1361
- * shares no secret and so cannot authenticate anything it says.
1362
- */
1363
- refusedBy?: 'destination' | 'path';
1364
- /** The ILP reject code, when the packet was rejected. */
1365
- code?: string;
1183
+ interface WalletTokenAmount {
1184
+ /** Asset symbol (e.g. `'ETH'`, `'SOL'`, `'MINA'`, `'USDC'`), when known. */
1185
+ symbol?: string;
1186
+ /** Base-unit integer, decimal string. */
1187
+ amount: string;
1188
+ /** Decimals for formatting (ETH 18, SOL 9, MINA 9, USDC 6). */
1189
+ decimals?: number;
1190
+ /** Token contract / SPL mint address. Absent for the native coin. */
1191
+ address?: string;
1366
1192
  }
1367
1193
  /**
1368
- * Parameters for signing a balance proof.
1194
+ * The full wallet view for ONE chain the identity is configured for: the native
1195
+ * coin plus every configured token, keyed by the chain's full key (e.g.
1196
+ * `'evm:31337'`). `unreadable` marks a chain whose RPC could not be reached at
1197
+ * all — the caller renders a per-chain notice rather than crashing.
1369
1198
  */
1370
- interface BalanceProofParams {
1371
- /** Payment channel identifier */
1372
- channelId: string;
1373
- /** Monotonically increasing nonce */
1374
- nonce: number;
1375
- /** Cumulative amount transferred */
1376
- transferredAmount: bigint;
1377
- /** Amount locked in pending transfers */
1378
- lockedAmount: bigint;
1379
- /** Merkle root of pending lock hashes */
1380
- locksRoot: string;
1199
+ interface WalletChainBalances {
1200
+ chain: 'evm' | 'solana' | 'mina';
1201
+ /** Full chain key, e.g. `'evm:31337'`, `'solana'`, `'mina'`. */
1202
+ chainKey: string;
1203
+ address: string;
1204
+ /** Native-coin balance, when readable. */
1205
+ native?: WalletTokenAmount;
1206
+ /** Configured token balances (e.g. USDC), each best-effort. */
1207
+ tokens: WalletTokenAmount[];
1208
+ /** True when nothing on this chain could be read (RPC unreachable). */
1209
+ unreadable?: boolean;
1210
+ /** First read error, when any read failed (for diagnostics). */
1211
+ error?: string;
1381
1212
  }
1213
+ /** Read an ERC-20 token balance (balance + decimals + symbol) for `owner`. */
1214
+ declare function readEvmTokenBalance(opts: {
1215
+ rpcUrl: string;
1216
+ chainKey: string;
1217
+ tokenAddress: string;
1218
+ owner: string;
1219
+ }): Promise<WalletBalance>;
1220
+ /** Read the native ETH balance (wei) for `owner` via `eth_getBalance`. */
1221
+ declare function readEvmNativeBalance(opts: {
1222
+ rpcUrl: string;
1223
+ chainKey: string;
1224
+ owner: string;
1225
+ }): Promise<WalletTokenAmount>;
1226
+ /** Read the native SOL balance (lamports) for `owner` via the `getBalance` RPC. */
1227
+ declare function readSolanaNativeBalance(opts: {
1228
+ rpcUrl: string;
1229
+ owner: string;
1230
+ fetchImpl?: typeof fetch;
1231
+ }): Promise<WalletTokenAmount>;
1232
+ /** Read the SPL-token balance for `owner`'s token account(s) of `mint`. */
1233
+ declare function readSolanaTokenBalance(opts: {
1234
+ rpcUrl: string;
1235
+ mint: string;
1236
+ owner: string;
1237
+ fetchImpl?: typeof fetch;
1238
+ }): Promise<WalletBalance>;
1239
+ /** Read the native MINA balance (nanomina) for `owner` via the Mina GraphQL API. */
1240
+ declare function readMinaBalance(opts: {
1241
+ graphqlUrl: string;
1242
+ owner: string;
1243
+ fetchImpl?: typeof fetch;
1244
+ }): Promise<WalletBalance>;
1382
1245
  /**
1383
- * A signed balance proof with EIP-712 signature.
1246
+ * Per-chain inputs for {@link readWalletBalances}: the resolved RPC URL, the
1247
+ * identity's address on that chain, and the configured token (USDC) — sourced by
1248
+ * the caller from the network topology / presets, never hardcoded here. A chain
1249
+ * key absent from the object is simply not read.
1384
1250
  */
1385
- interface SignedBalanceProof extends BalanceProofParams {
1386
- /** EIP-712 signature */
1387
- signature: string;
1388
- /** Address of the signer */
1389
- signerAddress: string;
1390
- /** Chain ID used in EIP-712 domain (e.g. 421614 for Arb Sepolia) */
1391
- chainId: number;
1392
- /** TokenNetwork contract address used in EIP-712 domain */
1393
- tokenNetworkAddress: string;
1394
- /** ERC-20 token address (e.g. USDC) for self-describing claim verification */
1395
- tokenAddress?: string;
1396
- /**
1397
- * Counterparty settlement address the balance proof is bound to.
1398
- *
1399
- * Required for Solana/Mina, where the canonical balance-proof message folds
1400
- * the recipient in (`balanceProofHashSolana` / `balanceProofFieldsMina`).
1401
- * Unused for the client's EVM path (EIP-712 `BalanceProof` has no recipient
1402
- * term). Carried here so it flows from signing through to `buildClaimMessage`.
1403
- */
1404
- recipient?: string;
1405
- /**
1406
- * Mina payment-channel claim fields (connector 3.9.0 `MinaClaimMessage`).
1407
- *
1408
- * Populated only by {@link MinaSigner}, which produces the connector's
1409
- * `Poseidon([balA,balB,salt])` balance commitment + a Pallas Schnorr `proof`
1410
- * over `[commitment, Field(nonce), Poseidon(zkApp.x)]` rather than reusing the
1411
- * generic `signature` field. Carried so they flow from signing through to
1412
- * `MinaSigner.buildClaimMessage`. Absent for EVM/Solana.
1413
- */
1251
+ interface WalletBalanceSources {
1252
+ evm?: {
1253
+ chainKey: string;
1254
+ rpcUrl: string;
1255
+ owner: string;
1256
+ tokenAddress?: string;
1257
+ };
1258
+ solana?: {
1259
+ chainKey?: string;
1260
+ rpcUrl: string;
1261
+ owner: string;
1262
+ tokenMint?: string;
1263
+ };
1414
1264
  mina?: {
1415
- /** `Poseidon([balanceA, balanceB, salt]).toString()`. */
1416
- balanceCommitment: string;
1417
- /** base64-encoded JSON proof `{ commitment, signature: { r, s }, nonce, signerPublicKey }`. */
1418
- proof: string;
1419
- /** Decimal salt string. */
1420
- salt: string;
1421
- /** Mina token id (default `'MINA'`). */
1422
- tokenId: string;
1265
+ chainKey?: string;
1266
+ graphqlUrl: string;
1267
+ owner: string;
1268
+ /** Settlement-token Field id (decimal). Reads the token balance when set. */
1269
+ tokenId?: string;
1423
1270
  };
1271
+ /** Injectable fetch (Solana/Mina JSON-RPC & GraphQL) for tests. */
1272
+ fetchImpl?: typeof fetch;
1424
1273
  }
1425
-
1426
1274
  /**
1427
- * Client-side helper for kind:5094 Arweave blob storage DVM requests.
1428
- *
1429
- * This composes the three steps a caller previously had to wire by hand:
1430
- * 1. Build the kind:5094 event via `buildBlobStorageRequest()` (@toon-protocol/core).
1431
- * 2. Publish it to the DVM destination over ILP via `ToonClient.publishEvent()`
1432
- * (reusing the existing claim / channel plumbing).
1433
- * 3. Decode the FULFILL `data` field into the Arweave transaction ID.
1434
- *
1435
- * ## FULFILL data contract
1436
- *
1437
- * The deployed connector is a payment-proxy (HTTP-in-ILP): a successful blob
1438
- * upload returns the DVM's verbatim **HTTP/1.1 response message** in the ILP
1439
- * FULFILL `data` field. For a single-packet (non-chunked) upload the body is a
1440
- * JSON object:
1441
- *
1442
- * HTTP/1.1 200 OK\r\n
1443
- * content-length: 189\r\n
1444
- * \r\n
1445
- * {"accept":true,"txId":"<43-char base64url>","data":"<base64 of txId>",...}
1446
- *
1447
- * We parse the HTTP envelope, fail on a non-2xx status (or `accept:false`), and
1448
- * read the Arweave tx ID from `txId` (falling back to base64-decoding `data`).
1449
- * An Arweave tx ID is a 43-character base64url string (32 raw bytes). A legacy
1450
- * fallback still accepts a bare `base64(utf8(txId))` FULFILL (no HTTP envelope)
1451
- * so non-proxy providers do not regress. See {@link extractArweaveTxId}.
1452
- *
1453
- * See `packages/sdk/src/arweave/arweave-dvm-handler.ts` for the server side and
1454
- * `packages/client/tests/e2e/docker-arweave-dvm-e2e.test.ts` for the reference
1455
- * end-to-end flow this helper mirrors.
1456
- *
1457
- * Chunked uploads (multi-packet, via `uploadId` / `chunkIndex` / `totalChunks`
1458
- * params) are intentionally out of scope for this single-packet helper — the
1459
- * provider returns `ack:<n>` for intermediate chunks and the tx ID only on the
1460
- * final chunk. Callers needing chunking should drive `publishEvent()` directly
1461
- * (see the chunked case in the reference E2E test). Tracked as a follow-up.
1275
+ * Read the full wallet view — native coin + configured tokens — for every chain
1276
+ * in `sources`, keyed per chain. FREE: read-only RPC, no signing. Each chain is
1277
+ * read independently and in parallel; a chain whose RPC is unreachable degrades
1278
+ * to `{ unreadable: true, error }` instead of failing the others. Within a chain
1279
+ * the native and token reads are independent, so a native read can succeed even
1280
+ * if the token read fails (and vice versa).
1462
1281
  */
1282
+ declare function readWalletBalances(sources: WalletBalanceSources): Promise<WalletChainBalances[]>;
1463
1283
 
1464
1284
  /**
1465
- * Parameters for {@link requestBlobStorage}.
1466
- */
1467
- interface RequestBlobStorageParams {
1468
- /** The raw blob data to store on Arweave. */
1469
- blobData: Uint8Array;
1470
- /**
1471
- * MIME type of the blob. Defaults to `'application/octet-stream'`
1472
- * (matching `buildBlobStorageRequest`).
1473
- */
1474
- contentType?: string;
1475
- /**
1476
- * Bid amount in USDC micro-units, as a string (declared in the event's
1477
- * `bid` tag). Defaults to the stringified `ilpAmount` when omitted.
1478
- *
1479
- * At least one of `bid` / `ilpAmount` should be provided so the declared
1480
- * bid and the paid ILP amount agree.
1481
- */
1482
- bid?: string;
1483
- /**
1484
- * ILP destination address of the DVM that performs the upload
1485
- * (e.g. `'g.toon.peer1'`). Falls back to the client's configured
1486
- * `destinationAddress` when omitted.
1487
- */
1488
- destination?: string;
1489
- /**
1490
- * Pre-signed balance proof claim for this packet. When omitted, the
1491
- * client's channel manager auto-opens a channel and auto-signs a claim
1492
- * (same lazy-channel behavior as `publishEvent`).
1493
- */
1494
- claim?: SignedBalanceProof;
1495
- /**
1496
- * Explicit ILP payment amount (bigint micro-units). When omitted,
1497
- * `publishEvent` computes it from the encoded event size. When `bid`
1498
- * is omitted, this value is stringified to populate the event's bid tag.
1499
- */
1500
- ilpAmount?: bigint;
1285
+ * The structured envelope (ADR 0018): what a packet carries between a
1286
+ * connector and the app behind it, encoded with the same OER primitives an ILP
1287
+ * packet already uses rather than as HTTP text.
1288
+ *
1289
+ * A faithful port of `connector_domain::envelope`
1290
+ * (`crates/connector-domain/src/envelope.rs`) — a method, target, ordered
1291
+ * headers and body going in; a two-byte big-endian status, headers and body
1292
+ * coming back. `vectors/wire-vectors.json` is the contract this is checked
1293
+ * against, and `wire-vectors.test.ts` is where that check happens; the prose
1294
+ * here describes the same thing but the bytes decide.
1295
+ *
1296
+ * ─── Why not HTTP text ─────────────────────────────────────────────────────
1297
+ * `utils/store-envelope.ts` builds latin1 HTTP/1.1 request text and
1298
+ * `utils/fulfill-http.ts` hand-parses a status line and scans for `\r\n\r\n`,
1299
+ * which is how they acquired leniencies nobody chose: a missing header/body
1300
+ * separator yielding an empty body, blank header lines skipped, spaces
1301
+ * tolerated inside the target. A structured encoding has exactly one
1302
+ * representation per message and nothing to smuggle. This module lands BESIDE
1303
+ * those two rather than replacing them — the swap is a later child — so it can
1304
+ * be reviewed against the vectors in isolation.
1305
+ *
1306
+ * ─── Headers are a list, not a map ─────────────────────────────────────────
1307
+ * A count prefix then `(name, value)` pairs in order. Both header ORDER and
1308
+ * DUPLICATE NAMES are meaningful on this wire and both survive a round trip; a
1309
+ * `Record<string, string>` would silently destroy each.
1310
+ *
1311
+ * Pure: no keys, no I/O, no clock. `@noble/*` is not involved.
1312
+ */
1313
+ /**
1314
+ * Every distinguishable way an envelope can fail to decode. These strings are
1315
+ * the vector file's `expected_error` values verbatim — the same names
1316
+ * `EnvelopeError` uses in `connector-domain` — so a replay compares reasons,
1317
+ * not just "it threw".
1318
+ *
1319
+ * There is deliberately no catch-all: a decoder with an `Invalid` bucket is a
1320
+ * decoder that can be lenient without anyone noticing.
1321
+ */
1322
+ declare enum EnvelopeErrorKind {
1323
+ /** The buffer ends before the envelope does. */
1324
+ BufferUnderflow = "buffer_underflow",
1325
+ /** A length determinant that is not the minimal encoding of its value. */
1326
+ NonCanonicalLength = "non_canonical_length",
1327
+ /** A length determinant wider than eight bytes. */
1328
+ LengthDeterminantOverflow = "length_determinant_overflow",
1329
+ /** The type byte is not the one the requested direction requires. */
1330
+ InvalidType = "invalid_type",
1331
+ /** A field that must be UTF-8 is not. */
1332
+ InvalidUtf8 = "invalid_utf8",
1333
+ /** Bytes remain after a fully decoded envelope. */
1334
+ TrailingBytes = "trailing_bytes"
1501
1335
  }
1502
1336
  /**
1503
- * Typed result of {@link requestBlobStorage}.
1337
+ * A refusal to decode. `kind` is the machine-readable reason; `field` names
1338
+ * the offending field for {@link EnvelopeErrorKind.InvalidUtf8}, matching
1339
+ * `EnvelopeError::InvalidUtf8(&'static str)` on the Rust side.
1504
1340
  */
1505
- interface RequestBlobStorageResult {
1506
- /** Whether the upload succeeded and a tx ID was decoded. */
1507
- success: boolean;
1508
- /** The Arweave transaction ID (43-char base64url) when `success` is true. */
1509
- txId?: string;
1510
- /** The id of the kind:5094 event that was published. */
1511
- eventId?: string;
1512
- /** Error message when `success` is false. */
1513
- error?: string;
1341
+ declare class EnvelopeError extends Error {
1342
+ readonly kind: EnvelopeErrorKind;
1343
+ readonly field?: string | undefined;
1344
+ constructor(kind: EnvelopeErrorKind, field?: string | undefined);
1345
+ }
1346
+ /** One `(name, value)` header, in wire order. Duplicates are legal. */
1347
+ type EnvelopeHeader = readonly [name: string, value: string];
1348
+ /** The request a connector is to make of the app behind a terminated route. */
1349
+ interface EnvelopeRequest {
1350
+ method: string;
1351
+ target: string;
1352
+ headers: readonly EnvelopeHeader[];
1353
+ body: Uint8Array;
1354
+ }
1355
+ /** The app's response back to the connector. */
1356
+ interface EnvelopeResponse {
1357
+ /** HTTP status, two bytes big-endian on the wire (`0..=65535`). */
1358
+ status: number;
1359
+ headers: readonly EnvelopeHeader[];
1360
+ body: Uint8Array;
1514
1361
  }
1362
+ /** Either direction, tagged — the shape the vector file's `decoded` carries. */
1363
+ type Envelope = ({
1364
+ direction: 'request';
1365
+ } & EnvelopeRequest) | ({
1366
+ direction: 'response';
1367
+ } & EnvelopeResponse);
1368
+ /** Encode a request envelope. The inverse of {@link decodeEnvelopeRequest}. */
1369
+ declare function encodeEnvelopeRequest(request: EnvelopeRequest): Uint8Array;
1515
1370
  /**
1516
- * Requests permanent Arweave blob storage from a DVM in a single ILP packet.
1517
- *
1518
- * Mirrors the single-packet flow in
1519
- * `packages/client/tests/e2e/docker-arweave-dvm-e2e.test.ts`: builds a signed
1520
- * kind:5094 event, publishes it through the supplied {@link ToonClient}
1521
- * (reusing its claim/channel plumbing), and decodes the FULFILL `data` field
1522
- * into an Arweave transaction ID.
1371
+ * Decode a request envelope, consuming the WHOLE buffer.
1523
1372
  *
1524
- * @param client - A started `ToonClient` (call `client.start()` first).
1525
- * @param secretKey - The Nostr secret key used to sign the kind:5094 event.
1526
- * @param params - Blob, content type, bid, destination, and payment options.
1527
- * @returns `{ success, txId?, eventId?, error? }`.
1373
+ * @throws {EnvelopeError} and nothing else, for any input whatsoever.
1528
1374
  */
1529
- declare function requestBlobStorage(client: ToonClient, secretKey: Uint8Array, params: RequestBlobStorageParams): Promise<RequestBlobStorageResult>;
1375
+ declare function decodeEnvelopeRequest(buf: Uint8Array): EnvelopeRequest;
1376
+ /** Encode a response envelope. The inverse of {@link decodeEnvelopeResponse}. */
1377
+ declare function encodeEnvelopeResponse(response: EnvelopeResponse): Uint8Array;
1530
1378
  /**
1531
- * Extract the Arweave tx ID from the FULFILL `data` of a successful blob upload.
1532
- *
1533
- * The terminating connector seals the store's answer as a response envelope
1534
- * (ADR 0018), which `publishEvent` opens and hands back as
1535
- * `PublishEventResult.response`. For a successful single-packet upload its
1536
- * body is `{"accept":true,"txId":"<43-char base64url>","data":"<base64 of
1537
- * txId>",…}`.
1538
- *
1539
- * We fail on a non-2xx status or `accept:false`, then read `txId` (preferred)
1540
- * from the JSON body — falling back to base64-decoding the `data` field when
1541
- * `txId` is absent.
1542
- *
1543
- * Exported for callers that drive `publishEvent` directly with a hand-built
1544
- * kind:5094 event (e.g. git-object uploads carrying Git-SHA/Git-Type/Repo
1545
- * tags, toon-client#227) and need the same FULFILL→txId decode this helper
1546
- * applies.
1379
+ * Decode a response envelope, consuming the WHOLE buffer.
1547
1380
  *
1548
- * @throws {Error} If the response is non-2xx, `accept:false`, the body is not
1549
- * parseable JSON, or no valid Arweave tx ID can be extracted.
1381
+ * @throws {EnvelopeError} and nothing else, for any input whatsoever.
1550
1382
  */
1551
- declare function extractArweaveTxId(response: EnvelopeResponse): string;
1552
-
1383
+ declare function decodeEnvelopeResponse(buf: Uint8Array): EnvelopeResponse;
1384
+ /** Encode either direction from its tagged form. */
1385
+ declare function encodeEnvelope(envelope: Envelope): Uint8Array;
1553
1386
  /**
1554
- * Chain-specific metadata (discriminated union).
1387
+ * Decode as the named direction. The direction is an INPUT, never guessed from
1388
+ * the type byte: a caller that asked for a request and got a response has been
1389
+ * handed the wrong bytes, and `invalid_type` is the honest answer.
1555
1390
  */
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
- };
1391
+ declare function decodeEnvelope(buf: Uint8Array, direction: 'request' | 'response'): Envelope;
1392
+
1570
1393
  /**
1571
- * Chain-agnostic signing interface for balance proofs.
1394
+ * Serve-side job handling (toon-client#494, toon-meta#262 "agents earning").
1395
+ *
1396
+ * The connector originates a server-originated BTP MESSAGE carrying a PREPARE
1397
+ * for this client's registered ILP address (RFC-0023 symmetric grammar,
1398
+ * toon-client#493) — the earning half of the wire that `sendSwapPacket` /
1399
+ * `publishEvent` already use to PAY. {@link createJobMessageHandler} plugs a
1400
+ * caller-supplied {@link JobHandler} into `BtpRuntimeClientConfig.onMessage`
1401
+ * so a provider writes a handler, never a payments integration
1402
+ * (`connector-runtime/src/app_client.rs`'s payment-oblivious app contract,
1403
+ * carried over to the BTP-served case this ticket adds).
1404
+ *
1405
+ * Delivery is hashlock (toon-meta#262 decision 5, `hashlock-delivery.ts`
1406
+ * toon-client#495): the handler returns the fulfillment preimage it already
1407
+ * minted at quote time via {@link encryptArtifact}/{@link fulfillIncrement} —
1408
+ * this module never derives a condition/preimage relationship itself, only
1409
+ * verifies the handler's answer against the PREPARE's own condition before
1410
+ * it goes on the wire.
1411
+ *
1412
+ * Error policy (ADR 0020 "you pay for an answer, not the answer you
1413
+ * wanted", RFC-0027 F99 "Application Error — the terminating app declined
1414
+ * the delivery, or supplied no fulfilment matching the execution
1415
+ * condition"): a handler that throws, or whose returned fulfillment does not
1416
+ * satisfy the PREPARE's condition, answers F99 — the two cases RFC-0027's
1417
+ * own F99 gloss already names together. An already-expired PREPARE is
1418
+ * refused R00 without ever invoking the handler, so a provider is never
1419
+ * asked to do paid work for a packet that can no longer be honored. An
1420
+ * undecodable PREPARE is refused F00. None of these paths ever throw back
1421
+ * into the BTP transport — every outcome is an answer (a RESPONSE frame
1422
+ * carrying FULFILL or REJECT), matching the symmetric grammar's "every
1423
+ * request gets an answer" contract.
1572
1424
  */
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;
1425
+
1426
+ /** One connector-originated job PREPARE, decoded and ready for a handler. */
1427
+ interface JobRequest {
1428
+ /** The packet's paid amount (base units) — informational only; see ADR 0020. */
1429
+ amount: bigint;
1430
+ /** The ILP address the PREPARE addressed (this client's own, per §1.9). */
1431
+ destination: string;
1432
+ /** The hashlock condition the handler's fulfillment must satisfy. */
1433
+ executionCondition: Uint8Array;
1434
+ /** When this PREPARE can no longer be honored. */
1435
+ expiresAt: Date;
1436
+ /** Opaque application payload — passed through unexamined (ADR 0018). */
1437
+ data: Uint8Array;
1438
+ }
1439
+ /** What a {@link JobHandler} answers a job with. */
1440
+ interface JobAnswer {
1441
+ /**
1442
+ * The fulfillment preimage — reveals the hashlock key (toon-meta#262
1443
+ * decision 5). MUST satisfy `sha256(fulfillment) === executionCondition`;
1444
+ * see {@link fulfillIncrement} in `hashlock-delivery.ts` for the one call
1445
+ * site that should ever produce this value.
1446
+ */
1447
+ fulfillment: Uint8Array;
1448
+ /** Answer payload returned in the FULFILL's `data` field. Defaults to empty. */
1449
+ data?: Uint8Array;
1600
1450
  }
1601
- type ClaimMessage = EVMClaimMessage | SolanaClaimMessage | MinaClaimMessage;
1602
1451
  /**
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`.
1452
+ * A provider's job handler: receives a job and returns an answer. Amount,
1453
+ * payer and chain never arrive as parameters here (ADR 0020's payment-
1454
+ * oblivious app contract) — the handler is never something that must verify
1455
+ * a payment, only produce a fulfillment for one already validated by the
1456
+ * claim gate before this MESSAGE was ever originated.
1607
1457
  */
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;
1625
- }
1458
+ type JobHandler = (job: JobRequest) => Promise<JobAnswer> | JobAnswer;
1459
+ /**
1460
+ * Wraps a {@link JobHandler} as a `BtpRuntimeClientConfig`/`IsomorphicBtpClientConfig`
1461
+ * `onMessage` handler: decodes an inbound job PREPARE, invokes `handler`, and
1462
+ * answers with a RESPONSE carrying FULFILL or REJECT — see this module's own
1463
+ * doc for the exact error-code policy.
1464
+ *
1465
+ * A server-originated MESSAGE that carries no PREPARE at all (§1.9 step 1's
1466
+ * auth MESSAGE, or a claim-only standalone MESSAGE) is not a job; it is
1467
+ * answered with an empty RESPONSE, unchanged from the pre-#494 default.
1468
+ */
1469
+ declare function createJobMessageHandler(handler: JobHandler): BtpMessageHandler;
1470
+
1626
1471
  /**
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.
1472
+ * Solana payment-channel parameters supplied via `ToonClientConfig.solanaChannel`.
1473
+ *
1474
+ * Mirrors the `SolanaChannelConfig` consumed by `OnChainChannelClient`, minus
1475
+ * the Ed25519 keypair (derived from the client's `mnemonic`, see
1476
+ * `ToonClientConfig.solanaChannel`).
1634
1477
  */
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;
1478
+ interface SolanaChannelClientOptions {
1479
+ /** Solana JSON-RPC URL used to open the channel + read PDA state. */
1480
+ rpcUrl: string;
1481
+ /** Deployed payment-channel program id (base58). */
1482
+ programId: string;
1654
1483
  /**
1655
- * Signer's Mina public key (B62 base58) — the claiming participant.
1484
+ * Default SPL token mint (base58) for PDA derivation. The per-channel
1485
+ * negotiated token (the peer's preferred token) takes precedence when present.
1486
+ */
1487
+ tokenMint?: string;
1488
+ /** Challenge-period duration (seconds) for `initialize_channel`. */
1489
+ challengeDuration?: number;
1490
+ /**
1491
+ * OVERRIDE for the on-chain deposit made when opening the channel: `amount`
1492
+ * in base units (string) drawn from `payerTokenAccount` (the client's funded
1493
+ * SPL token account / ATA, base58 — derived from owner+mint when empty).
1656
1494
  *
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.
1495
+ * Normally left unset: the open locks {@link ToonClientConfig.initialDeposit},
1496
+ * the same negotiated amount an EVM open locks. A 0 amount opts out and leaves
1497
+ * the channel uncollateralized — its claims cannot be redeemed on-chain.
1664
1498
  */
1665
- signerPublicKey?: string;
1666
- /** Mina network id — defaults to `devnet` connector-side when omitted. */
1667
- network?: 'mainnet' | 'devnet' | 'berkeley' | 'lightnet';
1499
+ deposit?: {
1500
+ amount: string;
1501
+ payerTokenAccount: string;
1502
+ };
1668
1503
  }
1669
-
1670
1504
  /**
1671
- * EVM claim message for BTP protocol data.
1672
- * Matches @toon-protocol/connector's EVMClaimMessage interface.
1505
+ * Mina payment-channel parameters supplied via `ToonClientConfig.minaChannel`.
1673
1506
  *
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.
1507
+ * Mirrors the `MinaChannelConfig` consumed by `OnChainChannelClient`, minus the
1508
+ * Mina private key (derived from the client's `mnemonic`, the same key that
1509
+ * produces the registered Mina signer — so the channel-open key and the
1510
+ * claim-signing key are guaranteed identical).
1511
+ *
1512
+ * ────────────────────────────────────────────────────────────────────────────
1513
+ * PHASE-2 STAGE-3: the client's Mina claim now matches connector 3.9.0's
1514
+ * `MinaClaimMessage` contract — `{ zkAppAddress, tokenId, balanceCommitment,
1515
+ * proof (base64), salt, nonce }`, with the proof a Pallas Schnorr signature over
1516
+ * the connector's `Poseidon([balA,balB,salt]) / Poseidon(zkApp.x)` commitment
1517
+ * (verified field-by-field against the connector's o1js verify). A
1518
+ * Mina-denominated paid publish is ACCEPTED at `validateClaimMessage` and the
1519
+ * apex FULFILLs to relay. On-chain SETTLE remains gated for non-EVM dynamic
1520
+ * hidden-service peers by connector#88 (`No chain configured for peer`).
1521
+ * `zkAppAddress` must be a REAL deployed payment-channel zkApp the apex's Mina
1522
+ * provider can resolve on-chain (the e2e harness deploys it deterministically).
1523
+ * ────────────────────────────────────────────────────────────────────────────
1677
1524
  */
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;
1525
+ interface MinaChannelClientOptions {
1526
+ /** Mina GraphQL URL used to open the channel + read zkApp state. */
1527
+ graphqlUrl: string;
1528
+ /**
1529
+ * Deployed payment-channel zkApp address (B62 base58). Optional when
1530
+ * `autoDeploy` is set — the open path then resolves (or deploys) a
1531
+ * pair-owned zkApp itself.
1532
+ */
1533
+ zkAppAddress?: string;
1534
+ /**
1535
+ * Per-pair zkApp auto-deploy: the Mina `PaymentChannel` zkApp is
1536
+ * single-pair (its on-chain channelHash bakes the participant pair at
1537
+ * initialization), so a fresh identity can never reuse a shared/announced
1538
+ * zkApp. With `autoDeploy`, opening a Mina channel first checks whether
1539
+ * the recorded/configured zkApp is provably OURS for this pair and deploys
1540
+ * a dedicated one otherwise (compile ≈1-3 min, inclusion ≈3-6 min,
1541
+ * ~1.1 MINA + fees — surfaced through `onProgress`).
1542
+ */
1543
+ autoDeploy?: {
1544
+ /** A previously recorded own deployment for this identity, if any. */
1545
+ deployed?: {
1546
+ zkAppAddress: string;
1547
+ zkAppPrivateKey: string;
1548
+ };
1549
+ /**
1550
+ * Persist hook — called with the zkApp address + key BEFORE the deploy tx
1551
+ * is sent (and before the circuit compiles), so a crash between send and
1552
+ * on-chain confirmation reuses the SAME zkApp next run instead of
1553
+ * deploying (and paying ~1.1 MINA for) a second one.
1554
+ */
1555
+ onDeploying?: (record: {
1556
+ zkAppAddress: string;
1557
+ zkAppPrivateKey: string;
1558
+ feePayer: string;
1559
+ }) => void | Promise<void>;
1560
+ /** Persist hook — called BEFORE the open proceeds on a fresh deploy. */
1561
+ onDeployed?: (record: {
1562
+ zkAppAddress: string;
1563
+ zkAppPrivateKey: string;
1564
+ feePayer: string;
1565
+ deployTxHash?: string;
1566
+ vkHash?: string;
1567
+ }) => void | Promise<void>;
1568
+ /** Progress lines for the slow compile/deploy/inclusion phases. */
1569
+ onProgress?: (line: string) => void;
1570
+ };
1571
+ /** Channel settlement timeout in slots for `initializeChannel` (default 86400). */
1572
+ challengeDuration?: number;
1573
+ /** Mina token id field (decimal string) for `initializeChannel` (default '1'). */
1574
+ tokenId?: string;
1575
+ /** Optional on-chain deposit (base units, string) after the channel opens. */
1576
+ deposit?: {
1577
+ amount: string;
1578
+ };
1579
+ /** Mina network id for the account/Schnorr prefix (default 'devnet'). */
1580
+ networkId?: 'devnet' | 'mainnet';
1697
1581
  }
1698
1582
  /**
1699
- * EVM signer for EIP-712 balance proofs and on-chain transactions.
1583
+ * Configuration for ToonClient.
1700
1584
  *
1701
- * Encapsulates the private key — no getPrivateKey() method is exposed.
1585
+ * This story implements HTTP mode only. Embedded mode will be added in a future epic.
1586
+ *
1587
+ * @example HTTP Mode (implemented)
1588
+ * ```typescript
1589
+ * const client = new ToonClient({
1590
+ * connectorUrl: 'http://localhost:8080',
1591
+ * secretKey,
1592
+ * ilpInfo: { ilpAddress, btpEndpoint, pubkey },
1593
+ * toonEncoder: encodeEvent,
1594
+ * toonDecoder: decodeEvent,
1595
+ * });
1596
+ * ```
1597
+ *
1598
+ * @example Embedded Mode (not yet implemented)
1599
+ * ```typescript
1600
+ * const client = new ToonClient({
1601
+ * connector: embeddedConnectorInstance, // Will throw error: "Embedded mode not yet implemented"
1602
+ * secretKey,
1603
+ * ilpInfo,
1604
+ * toonEncoder,
1605
+ * toonDecoder,
1606
+ * });
1607
+ * ```
1702
1608
  */
1703
- declare class EvmSigner {
1704
- readonly chainType: "evm";
1705
- private readonly _account;
1609
+ interface ToonClientConfig {
1706
1610
  /**
1707
- * @param privateKey - EVM private key as hex string (with or without 0x prefix) or Uint8Array
1611
+ * HTTP URL of external connector service.
1612
+ * Required for HTTP mode.
1613
+ * Example: 'http://localhost:8080'
1614
+ */
1615
+ connectorUrl?: string;
1616
+ /**
1617
+ * Embedded connector instance - NOT IMPLEMENTED in this story.
1618
+ * Will throw error: "Embedded mode not yet implemented in ToonClient."
1619
+ * Reserved for future implementation.
1620
+ */
1621
+ connector?: unknown;
1622
+ /**
1623
+ * BIP-39 mnemonic phrase to derive a full multi-chain identity from.
1624
+ *
1625
+ * When provided, the client derives the Nostr (NIP-06) + EVM keys
1626
+ * synchronously at construction and the Solana (Ed25519) + Mina (Pallas) keys
1627
+ * lazily in `start()`, registering per-chain signers so balance-proof claims
1628
+ * can be settled on any of those chains. This is the recommended way to use
1629
+ * non-EVM settlement (the raw `secretKey` path is secp256k1-only).
1630
+ *
1631
+ * Cannot be combined with `secretKey` (ambiguous Nostr identity). May be
1632
+ * combined with `evmPrivateKey` to use a separate EVM key (e.g. hardware
1633
+ * wallet) while still deriving Solana/Mina from the phrase.
1634
+ *
1635
+ * SECURITY: JavaScript strings are immutable and cannot be zeroed from
1636
+ * memory — the phrase may persist in the heap until GC. Prefer
1637
+ * passing a pre-derived `secretKey`/identity in high-security contexts.
1638
+ */
1639
+ mnemonic?: string;
1640
+ /**
1641
+ * BIP-44 account index used when deriving the multi-chain identity from
1642
+ * `mnemonic`. Defaults to 0 (back-compat). A non-zero index derives a
1643
+ * dedicated wallet from a shared mnemonic, producing the SAME addresses as
1644
+ * the SDK's `fromMnemonicFull(mnemonic, { accountIndex })`:
1645
+ * - Nostr (secp256k1): m/44'/1237'/0'/0/{index}
1646
+ * - EVM (secp256k1): same key as Nostr
1647
+ * - Solana (Ed25519): m/44'/501'/{index}'/0' (SLIP-0010)
1648
+ * - Mina (Pallas): m/44'/12586'/{index}'/0/0
1649
+ *
1650
+ * Ignored unless `mnemonic` is provided.
1651
+ */
1652
+ mnemonicAccountIndex?: number;
1653
+ /**
1654
+ * 32-byte Nostr private key (hex or Uint8Array).
1655
+ * Optional — if omitted, a keypair is auto-generated in applyDefaults()
1656
+ * (or derived from `mnemonic` when that is provided instead).
1657
+ */
1658
+ secretKey?: Uint8Array;
1659
+ /** ILP peer information for this client */
1660
+ ilpInfo: IlpPeerInfo;
1661
+ /** Function to encode Nostr events to TOON binary format */
1662
+ toonEncoder: (event: NostrEvent) => Uint8Array;
1663
+ /** Function to decode TOON binary format to Nostr events */
1664
+ toonDecoder: (bytes: Uint8Array) => NostrEvent;
1665
+ /**
1666
+ * EVM private key for signing balance proofs and on-chain transactions.
1667
+ *
1668
+ * By default, this is derived from `secretKey` — both Nostr and EVM use
1669
+ * secp256k1, so a single key provides both identities (matching the SDK's
1670
+ * `fromMnemonic()`/`fromSecretKey()` behavior).
1671
+ *
1672
+ * Only set this if you need a *different* EVM key than your Nostr key
1673
+ * (e.g., hardware wallet, custodial key, or legacy key separation).
1708
1674
  */
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;
1675
+ evmPrivateKey?: string | Uint8Array;
1716
1676
  /**
1717
- * Signs a balance proof using EIP-712 typed data.
1677
+ * Named network tier. When set (and != `'custom'`), the client defaults all
1678
+ * settlement-related config — RPC/GraphQL URLs, supported chain identifiers,
1679
+ * preferred tokens, EVM TokenNetwork addresses, and the Solana/Mina channel
1680
+ * params (programId / zkApp) — from the shared core presets
1681
+ * (`resolveClientNetwork`), so the caller no longer hand-wires every address.
1682
+ * This is the client-side mirror of the relay node's `network` selector;
1683
+ * both resolve the SAME deployed contracts.
1718
1684
  *
1719
- * @param params - Balance proof parameters plus chain context
1720
- * @returns Signed balance proof with signature
1685
+ * Precedence: any explicit per-chain field (`supportedChains`,
1686
+ * `chainRpcUrls`, `settlementAddresses`, `preferredTokens`, `tokenNetworks`,
1687
+ * `solanaChannel`, `minaChannel`) you also pass OVERRIDES the preset for that
1688
+ * field. `'custom'` keeps the fully-manual path (no preset defaults). When
1689
+ * unset, behaviour is unchanged (fully backward compatible).
1690
+ *
1691
+ * - `mainnet` — Base mainnet + public Solana/Mina (TOON contracts not yet
1692
+ * deployed → settlement unconfigured, relay-only).
1693
+ * - `testnet` / `devnet` — Base Sepolia + Solana/Mina devnet with the LIVE
1694
+ * deployed TOON settlement contracts.
1721
1695
  */
1722
- signBalanceProof(params: BalanceProofParams & {
1723
- chainId: number;
1724
- tokenNetworkAddress: string;
1725
- tokenAddress?: string;
1726
- }): Promise<SignedBalanceProof>;
1696
+ network?: 'mainnet' | 'testnet' | 'devnet' | 'custom';
1697
+ /** Supported settlement chain identifiers (e.g., ["evm:anvil:31337"]) */
1698
+ supportedChains?: string[];
1727
1699
  /**
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.
1700
+ * Explicitly-configured settlement chain FAMILY (e.g. from the daemon's
1701
+ * `TOON_CLIENT_CHAIN` env var / `chain` config field, #485). When set,
1702
+ * default-chain resolution (`getDefaultChainContext`, the lightweight
1703
+ * bootstrap-fallback chain match) MUST pick the `supportedChains` entry
1704
+ * whose family (the part before the first `:`) matches this value —
1705
+ * throwing a clear error instead of silently substituting a different
1706
+ * chain when none matches. Leave unset to keep the pre-#485 behavior of
1707
+ * defaulting to `supportedChains[0]`.
1708
+ */
1709
+ preferredChain?: 'evm' | 'solana' | 'mina';
1710
+ /** Maps chain identifier to EVM settlement address */
1711
+ settlementAddresses?: Record<string, string>;
1712
+ /** Maps chain identifier to preferred token contract address */
1713
+ preferredTokens?: Record<string, string>;
1714
+ /** Maps chain identifier to TokenNetwork contract address (EVM only) */
1715
+ tokenNetworks?: Record<string, string>;
1716
+ /** BTP WebSocket URL (e.g., "ws://localhost:3000") */
1717
+ btpUrl?: string;
1718
+ /** Auth token for BTP handshake */
1719
+ btpAuthToken?: string;
1720
+ /** Peer ID for BTP connection (used in connector env var BTP_PEER_{ID}_SECRET) */
1721
+ btpPeerId?: string;
1722
+ /**
1723
+ * ILP-over-HTTP one-shot endpoint of the uplink connector (the `POST /ilp`
1724
+ * URL, e.g. "http://localhost:3000/ilp"). When set, the client prefers the
1725
+ * stateless {@link HttpIlpClient} transport for one-shot writes instead of
1726
+ * opening a persistent BTP WebSocket.
1733
1727
  *
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.
1728
+ * This mirrors the `httpEndpoint` field a peer advertises in discovery
1729
+ * (`IlpPeerInfo`, toon PR #29). It is surfaced here as explicit config so the
1730
+ * default runtime can opt into ILP-over-HTTP before connectors advertise the
1731
+ * field on-wire. Leave unset to keep the existing BTP-only behavior (the safe
1732
+ * default — no connector advertises an httpEndpoint until the connector + a
1733
+ * core release with these fields ship).
1737
1734
  */
1738
- signClaimStateChallenge(params: {
1739
- chainId: number;
1740
- tokenNetworkAddress: string;
1741
- channelId: string;
1742
- expires: number;
1743
- }): Promise<string>;
1735
+ connectorHttpEndpoint?: string;
1744
1736
  /**
1745
- * Builds an EVMClaimMessage from a signed balance proof.
1746
- * Static so it can be called without an EvmSigner instance.
1737
+ * Connector-PROXY base URL for the deployed devnet/testnet edge (e.g.
1738
+ * `https://proxy.devnet.toonprotocol.dev`). The connector is now a
1739
+ * payment-proxy that serves ILP-over-HTTP at `POST /ilp`; setting `proxyUrl`
1740
+ * is the high-level way to route paid writes through that proxy WITHOUT a
1741
+ * persistent BTP socket.
1747
1742
  *
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
1743
+ * When set, `applyDefaults` derives `connectorHttpEndpoint` from it (appending
1744
+ * `/ilp` to the base unless the URL already ends in `/ilp`), so the existing
1745
+ * {@link HttpIlpClient} transport selection (`selectIlpTransport`) picks the
1746
+ * stateless one-shot HTTP transport for `publishEvent`/`sendSwapPacket`/
1747
+ * `sendPayment`. An explicit `connectorHttpEndpoint` always wins over this.
1748
+ *
1749
+ * The eventual home for these endpoints is a `@toon-protocol/core` devnet
1750
+ * preset; until that ships, set this field explicitly.
1751
1751
  */
1752
- static buildClaimMessage(proof: SignedBalanceProof, senderId: string): EVMClaimMessage;
1753
- }
1754
-
1755
- /**
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.
1775
- */
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;
1752
+ proxyUrl?: string;
1788
1753
  /**
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).
1754
+ * Faucet base URL for the deployed devnet (e.g.
1755
+ * `https://faucet.devnet.toonprotocol.dev`). Consumed by the {@link fundWallet}
1756
+ * helper to drip test funds to the client's chain address before publishing.
1757
+ * Has no effect on the runtime transport; it is config carried for tooling/e2e.
1793
1758
  */
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;
1819
- }
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;
1826
- }
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;
1837
- }
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>;
1861
-
1862
- /**
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).
1866
- *
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:
1870
- *
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).
1877
- */
1878
-
1879
- /**
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).
1884
- */
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;
1759
+ faucetUrl?: string;
1760
+ /**
1761
+ * Whether the uplink connector accepts a BTP `Upgrade` over its HTTP endpoint
1762
+ * (mirrors `IlpPeerInfo.supportsUpgrade`, toon PR #29). Only consulted when
1763
+ * `connectorHttpEndpoint` is set and a duplex session is required. Defaults to
1764
+ * false (no upgrade) when omitted.
1765
+ */
1766
+ connectorSupportsUpgrade?: boolean;
1892
1767
  /**
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).
1768
+ * Prefer the persistent, strictly-ordered {@link BtpPaidWriteTransport} for
1769
+ * paid writes (`publishEvent`/`sendSwapPacket`/`sendPayment`) over the
1770
+ * default stateless HTTP one-shot transport, when a `btpUrl` is configured.
1771
+ *
1772
+ * The BTP client-facing websocket ingress processes claims on one session
1773
+ * strictly in arrival order (client-edge-spec.md §1.9), which is what a
1774
+ * burst of concurrent paid writes on one channel needs to avoid racing
1775
+ * itself into `F01 NonceNotAdvancing` — a failure mode possible on the
1776
+ * default stateless HTTP transport, where each write is an independent
1777
+ * request. Set this when the consumer sends many paid writes on one
1778
+ * channel in quick succession (e.g. relay-native huddle audio frames);
1779
+ * leave it unset for ordinary publish-and-forget usage.
1780
+ *
1781
+ * Default: `false` — paid writes keep going through the existing HTTP
1782
+ * transport unchanged (toon-client#482 productizes BTP as an opt-in
1783
+ * upgrade, not a default-behavior change). When `true` and no `btpUrl`
1784
+ * (directly or derived) resolves, this has no effect — the existing
1785
+ * transport selection is unchanged.
1896
1786
  */
1897
- executionCondition?: Uint8Array;
1787
+ preferBtpForPaidWrites?: boolean;
1898
1788
  /**
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.
1789
+ * Serve-side registration (toon-client#494, toon-meta#262 "agents
1790
+ * earning"): a handler for connector-originated jobs addressed to this
1791
+ * client's own ILP address. When set, a server-originated BTP MESSAGE
1792
+ * carrying a PREPARE (RFC-0023 symmetric grammar, toon-client#493) is
1793
+ * decoded, handed to this function, and answered with the FULFILL/REJECT
1794
+ * it produces — see `serve-job.ts` for the exact error-code policy. Only
1795
+ * takes effect when a `btpUrl` is configured (job serving rides the same
1796
+ * persistent BTP session paid writes use); unset means this client never
1797
+ * answers a connector-originated job, unchanged from the pre-#494 default.
1902
1798
  */
1903
- expiresAt?: Date | string;
1904
- }
1905
- /**
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.
1909
- */
1910
- interface IlpSendResultWithFulfillment extends IlpSendResult {
1911
- /** Base64 32-byte fulfillment preimage (verified: sha256 == condition). */
1912
- fulfillment?: string;
1913
- }
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;
1799
+ jobHandler?: JobHandler;
1929
1800
  /**
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.
1801
+ * ILP destination address for event publishing.
1802
+ * Defaults to the connector's local address (derived from connectorUrl host).
1803
+ * For multi-hop routing, set this to the target node's ILP address.
1804
+ * Examples:
1805
+ * - 'g.toon.genesis' - Publish to genesis node
1806
+ * - 'g.toon.peer1' - Publish to peer1 node
1933
1807
  */
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;
1939
- }
1940
- /**
1941
- * BTP transport implementing IlpClient.
1942
- * Uses IsomorphicBtpClient (browser-native, no Node.js dependencies).
1943
- */
1944
- declare class BtpRuntimeClient implements IlpClient {
1945
- private btpClient;
1946
- private readonly config;
1947
- private _isConnected;
1948
- constructor(config: BtpRuntimeClientConfig);
1808
+ destinationAddress?: string;
1809
+ /** Maps chain identifier to RPC URL (e.g., {"evm:anvil:31337": "http://localhost:8545"}) */
1810
+ chainRpcUrls?: Record<string, string>;
1949
1811
  /**
1950
- * Connects to the BTP peer via WebSocket.
1812
+ * Collateral (base units, string) locked on-chain when a channel is opened,
1813
+ * on EVERY settlement chain (EVM `setTotalDeposit`, Solana `deposit`).
1814
+ * Defaults to `"100000"` — 0.1 USDC at 6 decimals. A peer's negotiated
1815
+ * `initialDeposit` still wins over this. Set `"0"` only if you accept
1816
+ * uncollateralized claims (they cannot be redeemed for value on-chain).
1951
1817
  */
1952
- connect(): Promise<void>;
1818
+ initialDeposit?: string;
1819
+ /** Challenge period in seconds (default: 86400) */
1820
+ settlementTimeout?: number;
1953
1821
  /**
1954
- * Attempts to reconnect by creating a fresh client and connecting.
1822
+ * Solana payment-channel parameters for opening a REAL on-chain channel and
1823
+ * signing a connector-format Solana balance proof.
1824
+ *
1825
+ * When present (and the client has a Solana signer — i.e. it was constructed
1826
+ * from a `mnemonic`), `ToonClient.start()` wires these into the on-chain
1827
+ * channel client so that negotiating a `solana:*` chain opens an on-chain
1828
+ * channel at the connector-parity PDA and pays a Solana-denominated claim.
1829
+ *
1830
+ * The Ed25519 keypair is NOT carried here — it is derived from the same
1831
+ * `mnemonic` that produces the Solana signer, so the channel-open key and the
1832
+ * claim-signing key are guaranteed identical.
1955
1833
  */
1956
- reconnect(): Promise<void>;
1834
+ solanaChannel?: SolanaChannelClientOptions;
1957
1835
  /**
1958
- * Disconnects from the BTP peer.
1836
+ * Mina payment-channel parameters (graphqlUrl + zkAppAddress). When present
1837
+ * (and the client has a Mina signer — i.e. it was constructed from a
1838
+ * `mnemonic` AND `mina-signer` is installed), `ToonClient.start()` wires these
1839
+ * into the on-chain channel client so negotiating a `mina:*` chain routes
1840
+ * through `openMinaChannel` and pays a Mina-denominated claim.
1841
+ *
1842
+ * The Mina private key is NOT carried here — it is derived from the same
1843
+ * `mnemonic` that produces the Mina signer.
1844
+ *
1845
+ * NOTE (Phase-2 Stage-3 gate): see `MinaChannelClientOptions` — supplying this
1846
+ * wires the negotiation path but the resulting claim does not yet satisfy
1847
+ * connector 3.9.0's Mina claim contract, so a live loop is claim-validation
1848
+ * gated (distinct from the connector #88 on-chain-settle gate).
1959
1849
  */
1960
- disconnect(): Promise<void>;
1961
- get isConnected(): boolean;
1850
+ minaChannel?: MinaChannelClientOptions;
1962
1851
  /**
1963
- * Sends an ILP packet via BTP with auto-reconnect on connection errors.
1964
- * Satisfies IlpClient interface.
1852
+ * Receive-side Mina swap-claim redemption (#357): maker on-chain co-signatures
1853
+ * keyed by dest-channel zkApp address (B62).
1965
1854
  *
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`.
1855
+ * On-chain `claimFromChannel` is dual-party — it verifies BOTH participants
1856
+ * signed `[commitment, nonce, channelHash]`. The recipient (this client)
1857
+ * produces its own co-signature from the derived Mina key, but the swap-wire
1858
+ * claim only carries the maker's `balanceProofFieldsMina` signature (a
1859
+ * DIFFERENT message), so the maker must additionally deliver a
1860
+ * payment-channel-commitment-form co-signature. Until that flows over the swap
1861
+ * wire, an operator can inject the maker's `{ r, s }` here to complete a
1862
+ * receive-side redemption. Absent one, settlement fails closed with
1863
+ * `MINA_MAKER_COSIGN_REQUIRED` (never a silent pass).
1971
1864
  */
1972
- sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;
1865
+ swapMinaMakerSignatures?: Record<string, {
1866
+ r: string;
1867
+ s: string;
1868
+ }>;
1973
1869
  /**
1974
- * Sends a balance proof claim via BTP protocol data, then sends an ILP packet.
1975
- * Auto-reconnects on connection errors.
1870
+ * File path for persisting payment channel nonce/amount state across restarts.
1976
1871
  *
1977
- * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are
1978
- * identical to {@link sendIlpPacket}.
1872
+ * Also enables CHANNEL RESUME (#489): a sibling file (`channels.json` →
1873
+ * `channels.peers.json`) records which on-chain channel this identity holds
1874
+ * with each peer, so a restarted client re-attaches to it — with its claim
1875
+ * watermark — instead of opening a second channel and locking a second lot of
1876
+ * collateral. Never delete these files for a live channel: the collateral
1877
+ * stays locked on-chain and the watermark is unrecoverable.
1979
1878
  */
1980
- sendIlpPacketWithClaim(params: IlpSendParams, claim: Record<string, unknown>): Promise<IlpSendResult>;
1879
+ channelStorePath?: string;
1880
+ /** Nostr relay URL for peer discovery. Default: 'wss://relay-ws.devnet.toonprotocol.dev' */
1881
+ relayUrl?: string;
1981
1882
  /**
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.
1883
+ * Known peers to bootstrap with.
1884
+ * If provided, these peers will be used for initial bootstrap.
1885
+ * DiscoveryTracker will discover additional peers from kind:10032 events after bootstrap.
1986
1886
  */
1987
- sendClaimMessage(claim: Record<string, unknown>): Promise<void>;
1988
- private _sendClaimMessageOnce;
1887
+ knownPeers?: {
1888
+ pubkey: string;
1889
+ relayUrl: string;
1890
+ btpEndpoint?: string;
1891
+ }[];
1892
+ /** Query timeout in milliseconds. Default: 30000 */
1893
+ queryTimeout?: number;
1894
+ /** Maximum number of retries for failed operations. Default: 3 */
1895
+ maxRetries?: number;
1896
+ /** Delay between retries in milliseconds. Default: 1000 */
1897
+ retryDelay?: number;
1898
+ }
1899
+ /**
1900
+ * Result returned by ToonClient.start()
1901
+ */
1902
+ interface ToonStartResult {
1903
+ /** Number of peers discovered during bootstrap */
1904
+ peersDiscovered: number;
1905
+ /** Mode the client is running in */
1906
+ mode: 'http' | 'embedded';
1907
+ }
1908
+ /**
1909
+ * Result returned by ToonClient.publishEvent()
1910
+ */
1911
+ interface PublishEventResult {
1912
+ /** Whether the event was successfully published */
1913
+ success: boolean;
1914
+ /** ID of the published event */
1915
+ eventId?: string;
1989
1916
  /**
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).
1917
+ * The destination's answer, opened from the sealed FULFILL: status, headers
1918
+ * and body, exactly as the app behind the terminated route gave them.
1919
+ *
1920
+ * Present whenever the packet FULFILLED — including for a non-2xx status,
1921
+ * which is envelope content rather than a packet outcome (ADR 0020): the
1922
+ * answer arrived and value moved. Absent only when the packet was rejected.
1995
1923
  */
1996
- private buildPrepare;
1924
+ response?: EnvelopeResponse;
1925
+ /** Error message if success is false */
1926
+ error?: string;
1927
+ /**
1928
+ * Who refused, when one did. `'destination'` is provable — the reject was
1929
+ * sealed with this packet's own secret, which only the terminating
1930
+ * connector could hold. `'path'` is a hop short of the termination, which
1931
+ * shares no secret and so cannot authenticate anything it says.
1932
+ */
1933
+ refusedBy?: 'destination' | 'path';
1934
+ /** The ILP reject code, when the packet was rejected. */
1935
+ code?: string;
1936
+ }
1937
+ /**
1938
+ * Parameters for signing a balance proof.
1939
+ */
1940
+ interface BalanceProofParams {
1941
+ /** Payment channel identifier */
1942
+ channelId: string;
1943
+ /** Monotonically increasing nonce */
1944
+ nonce: number;
1945
+ /** Cumulative amount transferred */
1946
+ transferredAmount: bigint;
1947
+ /** Amount locked in pending transfers */
1948
+ lockedAmount: bigint;
1949
+ /** Merkle root of pending lock hashes */
1950
+ locksRoot: string;
1951
+ }
1952
+ /**
1953
+ * A signed balance proof with EIP-712 signature.
1954
+ */
1955
+ interface SignedBalanceProof extends BalanceProofParams {
1956
+ /** EIP-712 signature */
1957
+ signature: string;
1958
+ /** Address of the signer */
1959
+ signerAddress: string;
1960
+ /** Chain ID used in EIP-712 domain (e.g. 421614 for Arb Sepolia) */
1961
+ chainId: number;
1962
+ /** TokenNetwork contract address used in EIP-712 domain */
1963
+ tokenNetworkAddress: string;
1964
+ /** ERC-20 token address (e.g. USDC) for self-describing claim verification */
1965
+ tokenAddress?: string;
1997
1966
  /**
1998
- * Single-attempt ILP packet send. Reconnects if not connected.
1967
+ * Counterparty settlement address the balance proof is bound to.
1968
+ *
1969
+ * Required for Solana/Mina, where the canonical balance-proof message folds
1970
+ * the recipient in (`balanceProofHashSolana` / `balanceProofFieldsMina`).
1971
+ * Unused for the client's EVM path (EIP-712 `BalanceProof` has no recipient
1972
+ * term). Carried here so it flows from signing through to `buildClaimMessage`.
1999
1973
  */
2000
- private _sendIlpPacketOnce;
1974
+ recipient?: string;
2001
1975
  /**
2002
- * Single-attempt claim + ILP packet send. Reconnects if not connected.
1976
+ * Mina payment-channel claim fields (connector 3.9.0 `MinaClaimMessage`).
1977
+ *
1978
+ * Populated only by {@link MinaSigner}, which produces the connector's
1979
+ * `Poseidon([balA,balB,salt])` balance commitment + a Pallas Schnorr `proof`
1980
+ * over `[commitment, Field(nonce), Poseidon(zkApp.x)]` rather than reusing the
1981
+ * generic `signature` field. Carried so they flow from signing through to
1982
+ * `MinaSigner.buildClaimMessage`. Absent for EVM/Solana.
2003
1983
  */
2004
- private _sendIlpPacketWithClaimOnce;
1984
+ mina?: {
1985
+ /** `Poseidon([balanceA, balanceB, salt]).toString()`. */
1986
+ balanceCommitment: string;
1987
+ /** base64-encoded JSON proof `{ commitment, signature: { r, s }, nonce, signerPublicKey }`. */
1988
+ proof: string;
1989
+ /** Decimal salt string. */
1990
+ salt: string;
1991
+ /** Mina token id (default `'MINA'`). */
1992
+ tokenId: string;
1993
+ };
2005
1994
  }
2006
1995
 
2007
1996
  /**
2008
- * ILP-over-HTTP (RFC-0035) transport for the TOON client.
1997
+ * Client-side helper for kind:5094 Arweave blob storage DVM requests.
2009
1998
  *
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.
1999
+ * This composes the three steps a caller previously had to wire by hand:
2000
+ * 1. Build the kind:5094 event via `buildBlobStorageRequest()` (@toon-protocol/core).
2001
+ * 2. Publish it to the DVM destination over ILP via `ToonClient.publishEvent()`
2002
+ * (reusing the existing claim / channel plumbing).
2003
+ * 3. Decode the FULFILL `data` field into the Arweave transaction ID.
2014
2004
  *
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.
2005
+ * ## FULFILL data contract
2030
2006
  *
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.
2007
+ * The deployed connector is a payment-proxy (HTTP-in-ILP): a successful blob
2008
+ * upload returns the DVM's verbatim **HTTP/1.1 response message** in the ILP
2009
+ * FULFILL `data` field. For a single-packet (non-chunked) upload the body is a
2010
+ * JSON object:
2011
+ *
2012
+ * HTTP/1.1 200 OK\r\n
2013
+ * content-length: 189\r\n
2014
+ * \r\n
2015
+ * {"accept":true,"txId":"<43-char base64url>","data":"<base64 of txId>",...}
2016
+ *
2017
+ * We parse the HTTP envelope, fail on a non-2xx status (or `accept:false`), and
2018
+ * read the Arweave tx ID from `txId` (falling back to base64-decoding `data`).
2019
+ * An Arweave tx ID is a 43-character base64url string (32 raw bytes). A legacy
2020
+ * fallback still accepts a bare `base64(utf8(txId))` FULFILL (no HTTP envelope)
2021
+ * so non-proxy providers do not regress. See {@link extractArweaveTxId}.
2022
+ *
2023
+ * See `packages/sdk/src/arweave/arweave-dvm-handler.ts` for the server side and
2024
+ * `packages/client/tests/e2e/docker-arweave-dvm-e2e.test.ts` for the reference
2025
+ * end-to-end flow this helper mirrors.
2026
+ *
2027
+ * Chunked uploads (multi-packet, via `uploadId` / `chunkIndex` / `totalChunks`
2028
+ * params) are intentionally out of scope for this single-packet helper — the
2029
+ * provider returns `ack:<n>` for intermediate chunks and the tx ID only on the
2030
+ * final chunk. Callers needing chunking should drive `publishEvent()` directly
2031
+ * (see the chunked case in the reference E2E test). Tracked as a follow-up.
2034
2032
  */
2035
2033
 
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). */
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;
2064
- }
2065
2034
  /**
2066
- * Stateless ILP-over-HTTP transport implementing `IlpClient`.
2067
- *
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.
2035
+ * Parameters for {@link requestBlobStorage}.
2072
2036
  */
2073
- declare class HttpIlpClient implements IlpClient {
2074
- private readonly httpEndpoint;
2075
- private readonly peerId;
2076
- private readonly authToken;
2077
- private readonly timeout;
2078
- private readonly retryConfig;
2079
- private readonly httpClient;
2080
- private readonly createWebSocket;
2081
- constructor(config: HttpIlpClientConfig);
2082
- /**
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.
2087
- */
2088
- get clientEdgeEndpoint(): string;
2037
+ interface RequestBlobStorageParams {
2038
+ /** The raw blob data to store on Arweave. */
2039
+ blobData: Uint8Array;
2089
2040
  /**
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}.
2041
+ * MIME type of the blob. Defaults to `'application/octet-stream'`
2042
+ * (matching `buildBlobStorageRequest`).
2099
2043
  */
2100
- sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult>;
2044
+ contentType?: string;
2101
2045
  /**
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.
2046
+ * Bid amount in USDC micro-units, as a string (declared in the event's
2047
+ * `bid` tag). Defaults to the stringified `ilpAmount` when omitted.
2106
2048
  *
2107
- * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are
2108
- * identical to {@link sendIlpPacket}.
2049
+ * At least one of `bid` / `ilpAmount` should be provided so the declared
2050
+ * bid and the paid ILP amount agree.
2109
2051
  */
2110
- sendIlpPacketWithClaim(params: IlpSendParams, claim: unknown): Promise<IlpSendResult>;
2052
+ bid?: string;
2111
2053
  /**
2112
- * Upgrade to a duplex BTP session over the SAME endpoint.
2113
- *
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.
2054
+ * ILP destination address of the DVM that performs the upload
2055
+ * (e.g. `'g.toon.peer1'`). Falls back to the client's configured
2056
+ * `destinationAddress` when omitted.
2125
2057
  */
2126
- upgradeToBtp(): Promise<BtpRuntimeClient>;
2127
- private authHeaders;
2058
+ destination?: string;
2128
2059
  /**
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).
2060
+ * Pre-signed balance proof claim for this packet. When omitted, the
2061
+ * client's channel manager auto-opens a channel and auto-signs a claim
2062
+ * (same lazy-channel behavior as `publishEvent`).
2132
2063
  */
2133
- private postPrepare;
2064
+ claim?: SignedBalanceProof;
2134
2065
  /**
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).
2066
+ * Explicit ILP payment amount (bigint micro-units). When omitted,
2067
+ * `publishEvent` computes it from the encoded event size. When `bid`
2068
+ * is omitted, this value is stringified to populate the event's bid tag.
2142
2069
  */
2143
- private mapResponse;
2144
- private mapTransportError;
2070
+ ilpAmount?: bigint;
2145
2071
  }
2146
2072
  /**
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;
2151
-
2152
- /**
2153
- * Payment-aware HTTP fetch over TOON (the "h402" flow).
2154
- *
2155
- * This adapter makes paying for an HTTP resource transparent: it issues an
2156
- * ordinary HTTP request, and when the origin answers `402 Payment Required`
2157
- * with an x402-style challenge that offers a `toon-channel` payment option, it
2158
- * opens/reuses a payment channel, signs a balance-proof claim, and re-sends the
2159
- * SAME HTTP request as a "transparent HTTP-in-ILP" packet to the connector's
2160
- * `POST /ilp` endpoint (via {@link HttpIlpClient}). The connector terminates the
2161
- * payment, forwards the request to the origin, and returns the origin's HTTP
2162
- * response inside the ILP FULFILL `data`. We reconstruct a normal Web `Response`
2163
- * from those bytes — the caller never sees ILP.
2164
- *
2165
- * ─── x402 wire contract (the 402 challenge body) ────────────────────────────
2166
- * The shipped connector answers x402 **v2** terms (`client-edge-spec.md` §1.4,
2167
- * `crates/connector-client-edge/src/lib.rs`), and that is the shape pinned by
2168
- * `Http402Client.connectorTerms.test.ts`:
2169
- *
2170
- * ```jsonc
2171
- * {
2172
- * "x402Version": 2,
2173
- * "resource": { "url": "g.example.app" },
2174
- * "accepts": [
2175
- * {
2176
- * "scheme": "toon-channel",
2177
- * "network": "g.example.app",
2178
- * "amount": "100",
2179
- * "payTo": "g.example.app",
2180
- * "maxTimeoutSeconds": 60,
2181
- * "httpEndpoint": "/ilp", // RELATIVE to the resource's origin.
2182
- * "extra": { "ilpAddress": "g.example.app", "endpoint": "/ilp", "price": "100" }
2183
- * }
2184
- * ]
2185
- * }
2186
- * ```
2187
- *
2188
- * Two things that shape forces, both easy to get wrong:
2189
- * - The ILP address, the endpoint and the price live under **`extra`**. The
2190
- * top-level `payTo` happens to equal the destination today, so reading it
2191
- * appears to work — that is a coincidence of the connector's current code,
2192
- * not a contract, so `extra` is read first.
2193
- * - `httpEndpoint` is **relative**; it is resolved against the URL that
2194
- * answered `402` (`Response.url`, or `parseX402Body`'s `baseUrl` argument).
2073
+ * Typed result of {@link requestBlobStorage}.
2074
+ */
2075
+ interface RequestBlobStorageResult {
2076
+ /** Whether the upload succeeded and a tx ID was decoded. */
2077
+ success: boolean;
2078
+ /** The Arweave transaction ID (43-char base64url) when `success` is true. */
2079
+ txId?: string;
2080
+ /** The id of the kind:5094 event that was published. */
2081
+ eventId?: string;
2082
+ /** Error message when `success` is false. */
2083
+ error?: string;
2084
+ }
2085
+ /**
2086
+ * Requests permanent Arweave blob storage from a DVM in a single ILP packet.
2195
2087
  *
2196
- * Everything is still parsed DEFENSIVELY (mirroring `readDiscoveredIlpPeer` in
2197
- * selectIlpTransport.ts): an unrecognised connector shape degrades to the
2198
- * vanilla 402 rather than throwing. Field aliases (first present wins):
2199
- * - destination: `extra.ilpAddress` | `extra.destination` | `destination` |
2200
- * `ilpAddress` | `payTo`. (We do NOT invent a value — a missing
2201
- * destination makes the entry unusable and we fall back to the vanilla 402.)
2202
- * - amount: `extra.price` | `extra.amount` | `amount` | `price` |
2203
- * `maxAmountRequired`.
2204
- * - httpEndpoint:`httpEndpoint` | `ilpEndpoint` | `extra.httpEndpoint` |
2205
- * `extra.endpoint` | `endpoint`.
2206
- * - upgrade: `supportsUpgrade` | `upgradable`.
2088
+ * Mirrors the single-packet flow in
2089
+ * `packages/client/tests/e2e/docker-arweave-dvm-e2e.test.ts`: builds a signed
2090
+ * kind:5094 event, publishes it through the supplied {@link ToonClient}
2091
+ * (reusing its claim/channel plumbing), and decodes the FULFILL `data` field
2092
+ * into an Arweave transaction ID.
2207
2093
  *
2208
- * ─── What the paid request is made of ───────────────────────────────────────
2209
- * The paid re-send is an OER `EnvelopeRequest` sealed to the terminating
2210
- * connector's identity, under a condition derived from the secret that seal
2211
- * carries — the same `sealExchange` / `readExchangeOutcome` pair
2212
- * `ToonClient.publishEvent` uses (ADR 0018/0019, toon-client#450, #451). This
2213
- * adapter used to carry its own HTTP/1.1 codec; it does not any more, and
2214
- * `packages/client` now has exactly one encoder.
2094
+ * @param client - A started `ToonClient` (call `client.start()` first).
2095
+ * @param secretKey - The Nostr secret key used to sign the kind:5094 event.
2096
+ * @param params - Blob, content type, bid, destination, and payment options.
2097
+ * @returns `{ success, txId?, eventId?, error? }`.
2098
+ */
2099
+ declare function requestBlobStorage(client: ToonClient, secretKey: Uint8Array, params: RequestBlobStorageParams): Promise<RequestBlobStorageResult>;
2100
+ /**
2101
+ * Extract the Arweave tx ID from the FULFILL `data` of a successful blob upload.
2215
2102
  *
2216
- * Two consequences of the envelope replacing HTTP text, both deliberate:
2103
+ * The terminating connector seals the store's answer as a response envelope
2104
+ * (ADR 0018), which `publishEvent` opens and hands back as
2105
+ * `PublishEventResult.response`. For a successful single-packet upload its
2106
+ * body is `{"accept":true,"txId":"<43-char base64url>","data":"<base64 of
2107
+ * txId>",…}`.
2217
2108
  *
2218
- * - **`Host` and `Content-Length` are not synthesised.** The old codec added
2219
- * both. The connector strips them either way and lets its HTTP client
2220
- * recompute them (`connector-runtime/src/app_client.rs` skips `host` and
2221
- * `content-length` by name), and the envelope already carries the body
2222
- * length as an OER length determinant, so emitting them was writing bytes
2223
- * the far side throws away. A caller that sets either explicitly still has
2224
- * it carried verbatim, and the connector still drops it.
2225
- * - **A response has no reason phrase.** An `EnvelopeResponse` status is two
2226
- * bytes; `HTTP/1.1 201 Created`'s "Created" has nowhere to live on this
2227
- * wire. `Response.statusText` is therefore empty, and the status is the
2228
- * fact to read.
2109
+ * We fail on a non-2xx status or `accept:false`, then read `txId` (preferred)
2110
+ * from the JSON body — falling back to base64-decoding the `data` field when
2111
+ * `txId` is absent.
2229
2112
  *
2230
- * A malformed answer now fails the way it fails everywhere else in this
2231
- * package — `SealedResponseError` from `readExchangeOutcome` — rather than
2232
- * this file's old `ConnectorError` on a bad status line while `fulfill-http.ts`
2233
- * quietly returned `{isHttp:false}` for the very same bytes.
2113
+ * Exported for callers that drive `publishEvent` directly with a hand-built
2114
+ * kind:5094 event (e.g. git-object uploads carrying Git-SHA/Git-Type/Repo
2115
+ * tags, toon-client#227) and need the same FULFILL→txId decode this helper
2116
+ * applies.
2234
2117
  *
2235
- * Claim signing/construction is owned by the CALLER (ToonClient wires the live
2236
- * ChannelManager + signer). This adapter never builds or validates claims —
2237
- * payment-claim validation lives ONLY in the connector.
2118
+ * @throws {Error} If the response is non-2xx, `accept:false`, the body is not
2119
+ * parseable JSON, or no valid Arweave tx ID can be extracted.
2238
2120
  */
2121
+ declare function extractArweaveTxId(response: EnvelopeResponse): string;
2239
2122
 
2240
2123
  /**
2241
- * The `extra` bag of an `accepts` entry — an open set of terms from the peer,
2242
- * not a fixed contract. `session_lease_ttl_ms` (connector#722,
2243
- * `session_registry::SESSION_LEASE_BACKSTOP_TTL`) is the one member this
2244
- * client currently reads by name; everything else is preserved untouched
2245
- * (issue #506) rather than stripped by a narrower type, so a future field
2246
- * survives the round trip even before this package knows its name.
2124
+ * Chain-specific metadata (discriminated union).
2247
2125
  */
2248
- interface X402ChannelExtra {
2249
- /**
2250
- * The connector's session lease TTL in milliseconds. Absent on a connector
2251
- * predating #722 — `undefined`, never a substituted default.
2252
- */
2253
- session_lease_ttl_ms?: number;
2254
- [key: string]: unknown;
2126
+ type ChainMetadata = {
2127
+ chainType: 'evm';
2128
+ chainId: number;
2129
+ tokenNetworkAddress: string;
2130
+ tokenAddress?: string;
2131
+ } | {
2132
+ chainType: 'solana';
2133
+ programId: string;
2134
+ tokenMint?: string;
2135
+ } | {
2136
+ chainType: 'mina';
2137
+ zkAppAddress: string;
2138
+ tokenId?: string;
2139
+ };
2140
+ /**
2141
+ * Chain-agnostic signing interface for balance proofs.
2142
+ */
2143
+ interface ChainSigner {
2144
+ readonly chainType: 'evm' | 'solana' | 'mina';
2145
+ readonly signerIdentifier: string;
2146
+ signBalanceProof(params: {
2147
+ channelId: string;
2148
+ nonce: number;
2149
+ transferredAmount: bigint;
2150
+ lockedAmount: bigint;
2151
+ locksRoot: string;
2152
+ /**
2153
+ * Counterparty settlement address the proof is bound to. Required for
2154
+ * Solana/Mina (folded into the canonical balance-proof message); the EVM
2155
+ * adapter ignores it (EIP-712 has no recipient term).
2156
+ */
2157
+ recipient: string;
2158
+ metadata: ChainMetadata;
2159
+ /**
2160
+ * On-chain channel `depositTotal` (base units). When supplied (>0), a Mina
2161
+ * signer binds the conserved `balanceB = depositTotal − balanceA` commitment
2162
+ * required to settle on a funded zkApp (connector#133); EVM/Solana signers
2163
+ * ignore it. When omitted, a Mina signer self-resolves it from chain if it
2164
+ * was configured with a GraphQL URL (#223), else falls back to the legacy
2165
+ * `balanceB = 0` form.
2166
+ */
2167
+ depositTotal?: bigint;
2168
+ }): Promise<SignedBalanceProof>;
2169
+ buildClaimMessage(proof: SignedBalanceProof, senderId: string): ClaimMessage;
2255
2170
  }
2256
- /** A single parsed `accepts` entry that offers the `toon-channel` scheme. */
2257
- interface ToonChannelAccept {
2258
- /** Always `'toon-channel'` for a matched entry. */
2259
- scheme: 'toon-channel';
2260
- /** Optional chain key, e.g. `evm:base:8453` — informational. */
2261
- network?: string;
2262
- /** ILP destination address to pay (the connector route fronting the URL). */
2263
- destination: string;
2264
- /** Price in ILP base units. */
2265
- amount: bigint;
2266
- /** The connector's `POST /ilp` URL. */
2267
- httpEndpoint: string;
2268
- /** Whether the host accepts the BTP upgrade over the HTTP endpoint. */
2269
- supportsUpgrade: boolean;
2171
+ type ClaimMessage = EVMClaimMessage | SolanaClaimMessage | MinaClaimMessage;
2172
+ /**
2173
+ * Solana payment-channel claim — wire-compatible with the connector's
2174
+ * `SolanaClaimMessage` (`@toon-protocol/connector` `btp/btp-claim-types.ts`).
2175
+ * Field names match the connector's `validateSolanaClaim` exactly:
2176
+ * `channelAccount` (base58 PDA), `signerPublicKey` (base58), base64 `signature`.
2177
+ */
2178
+ interface SolanaClaimMessage {
2179
+ version: '1.0';
2180
+ blockchain: 'solana';
2181
+ messageId: string;
2182
+ timestamp: string;
2183
+ senderId: string;
2184
+ /** On-chain PDA account address for the payment channel (base58). */
2185
+ channelAccount: string;
2186
+ nonce: number;
2187
+ /** Cumulative transferred amount (string for bigint precision). */
2188
+ transferredAmount: string;
2189
+ /** Ed25519 signature over the 48-byte balance-proof message (base64). */
2190
+ signature: string;
2191
+ /** Base58-encoded Ed25519 public key of the signer. */
2192
+ signerPublicKey: string;
2193
+ /** Solana program id for the payment-channel program (base58). */
2194
+ programId: string;
2195
+ }
2196
+ /**
2197
+ * Mina payment-channel claim — wire-compatible with the connector's
2198
+ * `MinaClaimMessage` (`@toon-protocol/connector` `btp/btp-claim-types.ts`).
2199
+ * Field names + types match `validateMinaClaim` exactly: `zkAppAddress`
2200
+ * (B62-prefixed 55-char base58, the channel id), `tokenId`, `balanceCommitment`
2201
+ * (`Poseidon([balA,balB,salt])` decimal string), integer `nonce`, base64 `proof`,
2202
+ * and `salt`. `transferredAmount`/`balanceB`/`signatureB`/`network` are OPTIONAL
2203
+ * at validation; the apex-as-recipient single-direction claim sends party-A only.
2204
+ */
2205
+ interface MinaClaimMessage {
2206
+ version: '1.0';
2207
+ blockchain: 'mina';
2208
+ messageId: string;
2209
+ timestamp: string;
2210
+ senderId: string;
2211
+ /** Deployed payment-channel zkApp address (B62 base58) — the channel id. */
2212
+ zkAppAddress: string;
2213
+ /** Mina token id (default `'MINA'`). */
2214
+ tokenId: string;
2215
+ /** `Poseidon([balanceA, balanceB, salt]).toString()`. */
2216
+ balanceCommitment: string;
2217
+ nonce: number;
2218
+ /** base64-encoded JSON `{ commitment, signature: { r, s }, nonce, signerPublicKey }`. */
2219
+ proof: string;
2220
+ /** Commitment salt (decimal string). */
2221
+ salt: string;
2222
+ /** Cumulative transferred amount (optional; string for bigint precision). */
2223
+ transferredAmount?: string;
2270
2224
  /**
2271
- * The entry's raw `extra` bag, preserved as-is. `undefined` when the entry
2272
- * carried no `extra` at all — distinct from an `extra` that merely omits a
2273
- * given key (issue #506).
2225
+ * Signer's Mina public key (B62 base58) — the claiming participant.
2226
+ *
2227
+ * Surfaced top-level (in addition to being embedded in `proof`) so the
2228
+ * connector's `SettlementExecutor` can resolve participant keys for the
2229
+ * on-chain `claimFromChannel` on an externally-opened (inbound) channel. The
2230
+ * connector reads `latestClaim.signerPublicKey` directly (not the proof blob);
2231
+ * without it the Mina SDK's `claimFromChannel` throws `ACCOUNT_NOT_FOUND`
2232
+ * ("Participant keys not found in cache and none were supplied"). The
2233
+ * connector accepts this as an optional `MinaClaimMessage` field.
2274
2234
  */
2275
- extra?: X402ChannelExtra;
2276
- }
2277
- /** The parsed x402 402 body, with the selected `toon-channel` entry (if any). */
2278
- interface ParsedX402Challenge {
2279
- x402Version?: number;
2280
- /** The first usable `toon-channel` accepts entry, or `undefined`. */
2281
- toonChannel?: ToonChannelAccept;
2235
+ signerPublicKey?: string;
2236
+ /** Mina network id — defaults to `devnet` connector-side when omitted. */
2237
+ network?: 'mainnet' | 'devnet' | 'berkeley' | 'lightnet';
2282
2238
  }
2283
- /** Options for {@link Http402Client.fetch} / `ToonClient.h402Fetch`. */
2284
- interface H402FetchOptions {
2285
- /** HTTP method. Default `'GET'`. */
2286
- method?: string;
2287
- /** Request headers. */
2288
- headers?: Record<string, string>;
2289
- /** Request body. */
2290
- body?: string | Uint8Array;
2291
- /** Request timeout in milliseconds. */
2292
- timeout?: number;
2293
- /** Optional explicit ILP destination override (else the x402 entry's value). */
2294
- destination?: string;
2239
+
2240
+ /**
2241
+ * EVM claim message for BTP protocol data.
2242
+ * Matches @toon-protocol/connector's EVMClaimMessage interface.
2243
+ *
2244
+ * The connector's validateClaimMessage() requires envelope fields
2245
+ * (version, messageId, timestamp) plus EVM claim fields, and optionally
2246
+ * chainId + tokenNetworkAddress for self-describing signature verification.
2247
+ */
2248
+ interface EVMClaimMessage {
2249
+ version: '1.0';
2250
+ blockchain: 'evm';
2251
+ messageId: string;
2252
+ timestamp: string;
2253
+ senderId: string;
2254
+ channelId: string;
2255
+ nonce: number;
2256
+ transferredAmount: string;
2257
+ lockedAmount: string;
2258
+ locksRoot: string;
2259
+ signature: string;
2260
+ signerAddress: string;
2261
+ /** Chain ID for self-describing EIP-712 verification */
2262
+ chainId: number;
2263
+ /** TokenNetwork address for self-describing EIP-712 verification */
2264
+ tokenNetworkAddress: string;
2265
+ /** ERC-20 token address for self-describing claim verification */
2266
+ tokenAddress?: string;
2295
2267
  }
2296
2268
  /**
2297
- * Caller-supplied hook that signs a balance-proof claim for `(destination,
2298
- * amount)` and returns the chain-appropriate claim message to attach to the ILP
2299
- * PREPARE. ToonClient wires this to its ChannelManager + per-chain signer (the
2300
- * exact same plumbing as `publishEvent`). The returned value is forwarded
2301
- * opaquely as the `ILP-Payment-Channel-Claim` header by {@link HttpIlpClient}.
2269
+ * EVM signer for EIP-712 balance proofs and on-chain transactions.
2270
+ *
2271
+ * Encapsulates the private key — no getPrivateKey() method is exposed.
2302
2272
  */
2303
- type ClaimResolver = (destination: string, amount: bigint) => Promise<unknown>;
2304
- /** Factory for an {@link HttpIlpClient} given a resolved `POST /ilp` endpoint. */
2305
- type HttpIlpClientFactory = (httpEndpoint: string) => HttpIlpClient;
2306
- /** Caller-supplied hook invoked with every parsed x402 challenge. */
2307
- type ChallengeHandler = (challenge: ParsedX402Challenge) => void;
2308
- interface Http402ClientConfig {
2309
- /**
2310
- * Underlying HTTP fetch for the INITIAL (un-paid) request that probes for a
2311
- * 402. Default: global `fetch`.
2312
- */
2313
- fetch?: typeof fetch;
2314
- /**
2315
- * Resolves + signs the payment-channel claim. REQUIRED to pay; if omitted,
2316
- * a 402 with a `toon-channel` offer is surfaced unchanged (vanilla challenge).
2317
- */
2318
- resolveClaim?: ClaimResolver;
2273
+ declare class EvmSigner {
2274
+ readonly chainType: "evm";
2275
+ private readonly _account;
2319
2276
  /**
2320
- * Builds the {@link HttpIlpClient} for a resolved endpoint. Default: construct
2321
- * a new `HttpIlpClient({ httpEndpoint })`. Injectable for tests.
2277
+ * @param privateKey - EVM private key as hex string (with or without 0x prefix) or Uint8Array
2322
2278
  */
2323
- createIlpClient?: HttpIlpClientFactory;
2279
+ constructor(privateKey: string | Uint8Array);
2280
+ /** Derived 0x EVM address */
2281
+ get address(): string;
2282
+ /** ChainSigner identifier — EVM address */
2283
+ get signerIdentifier(): string;
2284
+ /** Viem PrivateKeyAccount — usable with walletClient for on-chain transactions */
2285
+ get account(): PrivateKeyAccount;
2324
2286
  /**
2325
- * AC4: request a duplex transport for the paid send. When `true` and the
2326
- * toon-channel entry advertises `supportsUpgrade`, {@link selectIlpTransport}
2327
- * returns `http-upgradable` and the send path calls
2328
- * {@link HttpIlpClient.upgradeToBtp} before writing — the wiring for
2329
- * large/streaming responses. Default `false` (stateless one-shot HTTP).
2287
+ * Signs a balance proof using EIP-712 typed data.
2330
2288
  *
2331
- * NOTE (v1 limitation): even on the upgrade path the actual write is still a
2332
- * one-shot `sendIlpPacketWithClaim`; full duplex body streaming over the BTP
2333
- * session is a documented follow-up. The selection + upgrade CALL PATH is
2334
- * wired and exercised here so the streaming consumer can take over the
2335
- * returned session in a later iteration.
2289
+ * @param params - Balance proof parameters plus chain context
2290
+ * @returns Signed balance proof with signature
2336
2291
  */
2337
- needsDuplex?: boolean;
2292
+ signBalanceProof(params: BalanceProofParams & {
2293
+ chainId: number;
2294
+ tokenNetworkAddress: string;
2295
+ tokenAddress?: string;
2296
+ }): Promise<SignedBalanceProof>;
2338
2297
  /**
2339
- * Asks the connector named by the 402 offer for its identity key, so the
2340
- * paid request can be sealed to it. Default: a fresh
2341
- * {@link ConnectorEdgeClient} over this config's `fetch`. Injectable so a
2342
- * caller that already holds one shares its identity cache rather than
2343
- * re-fetching a key per paid request.
2298
+ * Signs a `POST /ilp/claim-state` claim-state challenge (client-edge-spec.md
2299
+ * §1.10): proves ownership of `channelId` without moving any value or
2300
+ * advancing the channel's nonce — this is a READ, not a claim. Read the
2301
+ * connector's answer for the actual credited/available balance (toon-meta#262
2302
+ * decision 9); this signature only unlocks the read.
2303
+ *
2304
+ * @param params.expires - Unix seconds the signature stops verifying.
2305
+ * Reissue with a fresh value whenever an outstanding one should stop
2306
+ * being trusted — the endpoint has no other replay bound.
2344
2307
  */
2345
- connectorEdge?: ConnectorEdgeClient;
2308
+ signClaimStateChallenge(params: {
2309
+ chainId: number;
2310
+ tokenNetworkAddress: string;
2311
+ channelId: string;
2312
+ expires: number;
2313
+ }): Promise<string>;
2346
2314
  /**
2347
- * Called with the parsed challenge whenever a `402` body is parsed —
2348
- * before the pay/pass-through decision, so it fires whether or not a
2349
- * `toon-channel` entry is offered or a claim resolver is configured. The
2350
- * one-shot `fetch()` return is a plain `Response`; this is how a caller
2351
- * (e.g. `ToonClient.getLastX402Terms`) reaches the negotiated terms —
2352
- * including the `extra` bag (issue #506) — without re-issuing the probe
2353
- * itself.
2315
+ * Builds an EVMClaimMessage from a signed balance proof.
2316
+ * Static so it can be called without an EvmSigner instance.
2317
+ *
2318
+ * @param proof - Signed balance proof (includes chainId and tokenNetworkAddress)
2319
+ * @param senderId - Nostr pubkey or identifier of the sender
2320
+ * @returns EVMClaimMessage compatible with BTP_CLAIM_PROTOCOL
2354
2321
  */
2355
- onChallenge?: ChallengeHandler;
2322
+ static buildClaimMessage(proof: SignedBalanceProof, senderId: string): EVMClaimMessage;
2356
2323
  }
2324
+
2357
2325
  /**
2358
- * Reusable h402 fetch engine. `ToonClient.h402Fetch` is a thin wrapper that
2359
- * constructs this with the live claim/channel plumbing.
2326
+ * Plain token transfer — send the settlement token or native gas from the
2327
+ * caller's own configured key to an ARBITRARY address, on any chain this
2328
+ * client already supports (evm/solana/mina). This is the missing primitive
2329
+ * underneath provisioning a buzz agent (toon-protocol/buzz#74): before a
2330
+ * derived agent address can open a payment channel, the owner's treasury has
2331
+ * to send it USDC and native gas.
2332
+ *
2333
+ * `@toon-protocol/client` was built around payment CHANNELS, not transfers —
2334
+ * `faucet.ts` is the only prior funding path, and it only reaches the devnet
2335
+ * faucet. This module is a direct, non-custodial send: the caller's own key
2336
+ * signs its own transaction/payment, straight to `to`.
2337
+ *
2338
+ * Every send is confirmed by an OBSERVED balance delta at the destination,
2339
+ * never by the send call/transaction merely landing. The devnet faucet's
2340
+ * Solana leg has been seen returning success with a REAL transaction
2341
+ * signature while delivering 0 lamports (toon-protocol/connector#691) — a
2342
+ * send that trusted its own receipt would report a funded agent that in fact
2343
+ * holds nothing. {@link TransferNotDeliveredError} is exactly that failure
2344
+ * mode, made loud instead of silent.
2360
2345
  */
2361
- declare class Http402Client {
2362
- private readonly fetchImpl;
2363
- private readonly resolveClaim?;
2364
- private readonly createIlpClient;
2365
- private readonly needsDuplex;
2366
- private readonly connectorEdge;
2367
- private readonly onChallenge?;
2368
- constructor(config?: Http402ClientConfig);
2369
- /**
2370
- * `fetch()`-like entry point. Issues the request; on `402` parses the x402
2371
- * challenge and — when a usable `toon-channel` offer is present and a claim
2372
- * resolver is configured — pays over TOON and returns the reconstructed
2373
- * `Response`. Otherwise returns the original 402 unchanged (AC5).
2374
- */
2375
- fetch(url: string, opts?: H402FetchOptions): Promise<Response>;
2376
- /**
2377
- * Open/reuse a channel (via the injected claim resolver), seal the request
2378
- * envelope to the terminating connector, send it to `POST /ilp` with the
2379
- * claim and the matching condition, and open the answer.
2380
- *
2381
- * The identity is fetched BEFORE a packet is formed, and there is no default
2382
- * to fall back to: sealing to the wrong key is a confidentiality failure
2383
- * that merely presents as an undeliverable packet (ADR 0018).
2384
- */
2385
- private payOverToon;
2346
+
2347
+ /** Chains this client can send a plain transfer on. */
2348
+ type TransferChain = 'evm' | 'solana' | 'mina';
2349
+ /** `'native'` — the chain's own gas token. `'token'` — the settlement token. */
2350
+ type TransferAssetKind = 'native' | 'token';
2351
+ interface SendTransferParams {
2352
+ chain: TransferChain;
2353
+ asset: TransferAssetKind;
2354
+ /** Destination address, in the target chain's native format. */
2355
+ to: string;
2356
+ /** Amount to send, in the asset's base units (wei / lamports+SPL / nanomina). */
2357
+ amount: string | bigint;
2386
2358
  /**
2387
- * Send the sealed PREPARE over the selected transport.
2388
- *
2389
- * - `http` / `http-upgradable`: stateless one-shot `POST /ilp` with the claim.
2390
- * - `http-upgradable` additionally exercises {@link HttpIlpClient.upgradeToBtp}
2391
- * for the duplex/streaming path (AC4). v1 still drives the actual write over
2392
- * the one-shot HTTP method even after upgrading — full duplex body streaming
2393
- * is a documented follow-up — but the upgrade call path is wired here.
2394
- * - `btp`: not reachable from h402 (the x402 offer only carries an
2395
- * `httpEndpoint`); guarded for completeness.
2359
+ * How long to wait for the destination's observed balance to reflect the
2360
+ * transfer before giving up with {@link TransferNotDeliveredError}. Defaults
2361
+ * are chain-specific (EVM/Solana 30s, Mina 5 min — Mina block inclusion is
2362
+ * materially slower).
2396
2363
  */
2397
- private sendOverChoice;
2364
+ confirmTimeoutMs?: number;
2365
+ /** Poll interval (ms) while waiting for the balance delta. Default 2000. */
2366
+ confirmPollIntervalMs?: number;
2367
+ }
2368
+ interface SendTransferResult {
2369
+ chain: TransferChain;
2370
+ asset: TransferAssetKind;
2371
+ to: string;
2372
+ /** Base units actually requested (echoed back as a decimal string). */
2373
+ amount: string;
2374
+ /** Transaction hash / signature of the send. */
2375
+ txHash: string;
2376
+ /** Destination's observed balance immediately before the send. */
2377
+ balanceBefore: string;
2378
+ /** Destination's observed balance once the delta was confirmed. */
2379
+ balanceAfter: string;
2380
+ }
2381
+ /** Per-chain config a caller supplies to {@link sendTransfer}. */
2382
+ interface EvmTransferConfig {
2383
+ /** Chain key, e.g. `'evm:base-sepolia:84532'` (used for chainId + RPC). */
2384
+ chainKey: string;
2385
+ rpcUrl: string;
2386
+ signer: EvmSigner;
2387
+ /** ERC-20 settlement-token address. Required only for `asset: 'token'`. */
2388
+ tokenAddress?: string;
2389
+ }
2390
+ interface SolanaTransferConfig {
2391
+ rpcUrl: string;
2392
+ /** Ed25519 signing seed (32 bytes) or a 64-byte seed||pubkey keypair. */
2393
+ keypair: Uint8Array;
2394
+ /** SPL settlement-token mint. Required only for `asset: 'token'`. */
2395
+ tokenMint?: string;
2396
+ }
2397
+ interface MinaTransferConfig {
2398
+ graphqlUrl: string;
2399
+ /** Big-endian hex scalar (as `deriveFullIdentity` emits) or `EK…` base58. */
2400
+ privateKey: string;
2401
+ /** Mina network id for the signature domain separator. Default `'devnet'`. */
2402
+ networkId?: 'devnet' | 'mainnet';
2403
+ /** Transaction fee, nanomina. Default 1_000_000 (0.001 MINA). */
2404
+ fee?: string;
2405
+ /** Injectable fetch (tests). */
2406
+ fetchImpl?: typeof fetch;
2407
+ }
2408
+ interface TransferConfig {
2409
+ evm?: EvmTransferConfig;
2410
+ solana?: SolanaTransferConfig;
2411
+ mina?: MinaTransferConfig;
2398
2412
  }
2399
2413
  /**
2400
- * Parse a 402 `Response` body into a {@link ParsedX402Challenge}, selecting the
2401
- * first usable `toon-channel` entry. Reads every field defensively; a malformed
2402
- * body, a non-JSON body, or an entry missing its `destination`/`httpEndpoint`
2403
- * yields `{ toonChannel: undefined }` so the caller falls back to the vanilla
2404
- * 402 rather than throwing.
2405
- */
2406
- declare function parseX402Challenge(response: Response): Promise<ParsedX402Challenge>;
2407
- /**
2408
- * Pure parser over an already-decoded x402 body (testable without a Response).
2414
+ * Send `params.amount` base units of `params.asset` to `params.to` on
2415
+ * `params.chain`, using whichever chain config in `config` matches. Confirms
2416
+ * delivery by re-reading the destination's balance (see module docs) rather
2417
+ * than trusting the send call's own success signal.
2409
2418
  *
2410
- * `baseUrl`, when given, is the absolute URL of the resource that answered
2411
- * `402`; a relative `httpEndpoint` is resolved against it. Omitting it keeps
2412
- * the old behaviour of passing the endpoint through verbatim.
2419
+ * @throws {UnknownChainError} `params.chain` is unrecognized, or this client
2420
+ * has no configuration for it.
2421
+ * @throws {InvalidAddressError} `params.to` is malformed for the chain.
2422
+ * @throws {InsufficientBalanceError} the sender cannot cover the amount
2423
+ * (plus fees, where applicable) — checked before anything is submitted.
2424
+ * @throws {TransferNotDeliveredError} the send was accepted (a landed,
2425
+ * non-reverted transaction / a node-accepted payment) but the destination
2426
+ * balance never reflected it within the wait window.
2427
+ * @throws {TransferUnsupportedError} this chain/asset combination isn't
2428
+ * implemented yet (currently: the Mina settlement token).
2413
2429
  */
2414
- declare function parseX402Body(body: unknown, baseUrl?: string): ParsedX402Challenge;
2430
+ declare function sendTransfer(config: TransferConfig, params: SendTransferParams): Promise<SendTransferResult>;
2415
2431
 
2416
2432
  /**
2417
2433
  * The persisted receive-side watermark for one swap target channel: the
@@ -2643,6 +2659,17 @@ declare class ToonClient {
2643
2659
  * {@link getLastX402Terms} without re-issuing the probe by hand.
2644
2660
  */
2645
2661
  private lastX402Terms?;
2662
+ /**
2663
+ * The most recently parsed `ConnectorRouteTerms`, from the last
2664
+ * `negotiateFromGreeting` call — the greeting parse that ordinary channel
2665
+ * bootstrap (`publishEvent`/`openChannel`/`adoptChannel`) already goes
2666
+ * through, with no separate `h402Fetch` probe needed (issue #509).
2667
+ * Captured whether or not the greeting carried settlement facts to
2668
+ * bootstrap from, so its `extra` bag (e.g. `session_lease_ttl_ms`) is
2669
+ * readable via {@link getLastConnectorRouteTerms} even when the bootstrap
2670
+ * declined to open a channel from that greeting.
2671
+ */
2672
+ private lastConnectorRouteTerms?;
2646
2673
  private readonly evmSigner?;
2647
2674
  private solanaSigner?;
2648
2675
  /**
@@ -2912,6 +2939,19 @@ declare class ToonClient {
2912
2939
  * negotiated terms without re-issuing a probe by hand.
2913
2940
  */
2914
2941
  getLastX402Terms(): ToonChannelAccept | undefined;
2942
+ /**
2943
+ * The `ConnectorRouteTerms` from the most recent ordinary channel
2944
+ * bootstrap (`publishEvent`/`openChannel`/`adoptChannel`, via
2945
+ * `negotiateFromGreeting`) — including its `extra` bag (issue #509, e.g.
2946
+ * `extra.session_lease_ttl_ms`, connector#722) — or `undefined` if no
2947
+ * greeting has been parsed on this path yet. Unlike
2948
+ * {@link getLastX402Terms}, this populates from a client that only ever
2949
+ * calls `start()`/`publishEvent()`: `ConnectorEdgeClient.getRouteTerms` is
2950
+ * the parser the live path actually negotiates through, so a caller does
2951
+ * not need to issue a separate `h402Fetch` probe purely to read the lease
2952
+ * TTL.
2953
+ */
2954
+ getLastConnectorRouteTerms(): ConnectorRouteTerms | undefined;
2915
2955
  /**
2916
2956
  * Sends a raw swap ILP packet (Story 12.5) to a swap peer with an attached
2917
2957
  * balance-proof claim. This is a lower-level surface than `publishEvent`:
@@ -6763,4 +6803,4 @@ declare function readExchangeOutcome(result: {
6763
6803
  /** Read a response header, case-insensitively; the first match wins. */
6764
6804
  declare function envelopeHeader(response: EnvelopeResponse, name: string): string | undefined;
6765
6805
 
6766
- 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 ChallengeHandler, 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, type X402ChannelExtra, 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 };
6806
+ 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 ChallengeHandler, 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, type ConnectorChainSettlementTerms, ConnectorEdgeClient, type ConnectorEdgeClientConfig, ConnectorEdgeError, type ConnectorEdgeErrorCode, ConnectorError, type ConnectorIdentity, type ConnectorRoutePrice, type ConnectorRouteTerms, type ConnectorSettlementTerms, type ConnectorSolanaSettlementTerms, 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, type X402ChannelExtra, 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, parseConnectorRouteTerms, 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 };