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