@toon-protocol/client 0.21.2 → 0.22.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
@@ -123,6 +123,115 @@ interface WalletBalanceSources {
123
123
  */
124
124
  declare function readWalletBalances(sources: WalletBalanceSources): Promise<WalletChainBalances[]>;
125
125
 
126
+ /**
127
+ * The structured envelope (ADR 0018): what a packet carries between a
128
+ * connector and the app behind it, encoded with the same OER primitives an ILP
129
+ * packet already uses rather than as HTTP text.
130
+ *
131
+ * A faithful port of `connector_domain::envelope`
132
+ * (`crates/connector-domain/src/envelope.rs`) — a method, target, ordered
133
+ * headers and body going in; a two-byte big-endian status, headers and body
134
+ * coming back. `vectors/wire-vectors.json` is the contract this is checked
135
+ * against, and `wire-vectors.test.ts` is where that check happens; the prose
136
+ * here describes the same thing but the bytes decide.
137
+ *
138
+ * ─── Why not HTTP text ─────────────────────────────────────────────────────
139
+ * `utils/store-envelope.ts` builds latin1 HTTP/1.1 request text and
140
+ * `utils/fulfill-http.ts` hand-parses a status line and scans for `\r\n\r\n`,
141
+ * which is how they acquired leniencies nobody chose: a missing header/body
142
+ * separator yielding an empty body, blank header lines skipped, spaces
143
+ * tolerated inside the target. A structured encoding has exactly one
144
+ * representation per message and nothing to smuggle. This module lands BESIDE
145
+ * those two rather than replacing them — the swap is a later child — so it can
146
+ * be reviewed against the vectors in isolation.
147
+ *
148
+ * ─── Headers are a list, not a map ─────────────────────────────────────────
149
+ * A count prefix then `(name, value)` pairs in order. Both header ORDER and
150
+ * DUPLICATE NAMES are meaningful on this wire and both survive a round trip; a
151
+ * `Record<string, string>` would silently destroy each.
152
+ *
153
+ * Pure: no keys, no I/O, no clock. `@noble/*` is not involved.
154
+ */
155
+ /**
156
+ * Every distinguishable way an envelope can fail to decode. These strings are
157
+ * the vector file's `expected_error` values verbatim — the same names
158
+ * `EnvelopeError` uses in `connector-domain` — so a replay compares reasons,
159
+ * not just "it threw".
160
+ *
161
+ * There is deliberately no catch-all: a decoder with an `Invalid` bucket is a
162
+ * decoder that can be lenient without anyone noticing.
163
+ */
164
+ declare enum EnvelopeErrorKind {
165
+ /** The buffer ends before the envelope does. */
166
+ BufferUnderflow = "buffer_underflow",
167
+ /** A length determinant that is not the minimal encoding of its value. */
168
+ NonCanonicalLength = "non_canonical_length",
169
+ /** A length determinant wider than eight bytes. */
170
+ LengthDeterminantOverflow = "length_determinant_overflow",
171
+ /** The type byte is not the one the requested direction requires. */
172
+ InvalidType = "invalid_type",
173
+ /** A field that must be UTF-8 is not. */
174
+ InvalidUtf8 = "invalid_utf8",
175
+ /** Bytes remain after a fully decoded envelope. */
176
+ TrailingBytes = "trailing_bytes"
177
+ }
178
+ /**
179
+ * A refusal to decode. `kind` is the machine-readable reason; `field` names
180
+ * the offending field for {@link EnvelopeErrorKind.InvalidUtf8}, matching
181
+ * `EnvelopeError::InvalidUtf8(&'static str)` on the Rust side.
182
+ */
183
+ declare class EnvelopeError extends Error {
184
+ readonly kind: EnvelopeErrorKind;
185
+ readonly field?: string | undefined;
186
+ constructor(kind: EnvelopeErrorKind, field?: string | undefined);
187
+ }
188
+ /** One `(name, value)` header, in wire order. Duplicates are legal. */
189
+ type EnvelopeHeader = readonly [name: string, value: string];
190
+ /** The request a connector is to make of the app behind a terminated route. */
191
+ interface EnvelopeRequest {
192
+ method: string;
193
+ target: string;
194
+ headers: readonly EnvelopeHeader[];
195
+ body: Uint8Array;
196
+ }
197
+ /** The app's response back to the connector. */
198
+ interface EnvelopeResponse {
199
+ /** HTTP status, two bytes big-endian on the wire (`0..=65535`). */
200
+ status: number;
201
+ headers: readonly EnvelopeHeader[];
202
+ body: Uint8Array;
203
+ }
204
+ /** Either direction, tagged — the shape the vector file's `decoded` carries. */
205
+ type Envelope = ({
206
+ direction: 'request';
207
+ } & EnvelopeRequest) | ({
208
+ direction: 'response';
209
+ } & EnvelopeResponse);
210
+ /** Encode a request envelope. The inverse of {@link decodeEnvelopeRequest}. */
211
+ declare function encodeEnvelopeRequest(request: EnvelopeRequest): Uint8Array;
212
+ /**
213
+ * Decode a request envelope, consuming the WHOLE buffer.
214
+ *
215
+ * @throws {EnvelopeError} and nothing else, for any input whatsoever.
216
+ */
217
+ declare function decodeEnvelopeRequest(buf: Uint8Array): EnvelopeRequest;
218
+ /** Encode a response envelope. The inverse of {@link decodeEnvelopeResponse}. */
219
+ declare function encodeEnvelopeResponse(response: EnvelopeResponse): Uint8Array;
220
+ /**
221
+ * Decode a response envelope, consuming the WHOLE buffer.
222
+ *
223
+ * @throws {EnvelopeError} and nothing else, for any input whatsoever.
224
+ */
225
+ declare function decodeEnvelopeResponse(buf: Uint8Array): EnvelopeResponse;
226
+ /** Encode either direction from its tagged form. */
227
+ declare function encodeEnvelope(envelope: Envelope): Uint8Array;
228
+ /**
229
+ * Decode as the named direction. The direction is an INPUT, never guessed from
230
+ * the type byte: a caller that asked for a request and got a response has been
231
+ * handed the wrong bytes, and `invalid_type` is the honest answer.
232
+ */
233
+ declare function decodeEnvelope(buf: Uint8Array, direction: 'request' | 'response'): Envelope;
234
+
126
235
  /**
127
236
  * Solana payment-channel parameters supplied via `ToonClientConfig.solanaChannel`.
128
237
  *
@@ -506,10 +615,26 @@ interface PublishEventResult {
506
615
  success: boolean;
507
616
  /** ID of the published event */
508
617
  eventId?: string;
509
- /** FULFILL response data (base64-encoded), e.g. Arweave tx ID from DVM */
510
- data?: string;
618
+ /**
619
+ * The destination's answer, opened from the sealed FULFILL: status, headers
620
+ * and body, exactly as the app behind the terminated route gave them.
621
+ *
622
+ * Present whenever the packet FULFILLED — including for a non-2xx status,
623
+ * which is envelope content rather than a packet outcome (ADR 0020): the
624
+ * answer arrived and value moved. Absent only when the packet was rejected.
625
+ */
626
+ response?: EnvelopeResponse;
511
627
  /** Error message if success is false */
512
628
  error?: string;
629
+ /**
630
+ * Who refused, when one did. `'destination'` is provable — the reject was
631
+ * sealed with this packet's own secret, which only the terminating
632
+ * connector could hold. `'path'` is a hop short of the termination, which
633
+ * shares no secret and so cannot authenticate anything it says.
634
+ */
635
+ refusedBy?: 'destination' | 'path';
636
+ /** The ILP reject code, when the packet was rejected. */
637
+ code?: string;
513
638
  }
514
639
  /**
515
640
  * Parameters for signing a balance proof.
@@ -677,22 +802,15 @@ declare function requestBlobStorage(client: ToonClient, secretKey: Uint8Array, p
677
802
  /**
678
803
  * Extract the Arweave tx ID from the FULFILL `data` of a successful blob upload.
679
804
  *
680
- * The deployed payment-proxy returns the DVM's verbatim HTTP/1.1 response inside
681
- * the FULFILL `data`. For a successful single-packet upload that response is:
682
- *
683
- * HTTP/1.1 200 OK\r\n
684
- * content-length: 189\r\n
685
- * \r\n
686
- * {"accept":true,"txId":"<43-char base64url>","data":"<base64 of txId>",...}
687
- *
688
- * We parse the HTTP envelope, fail on a non-2xx status or `accept:false`, then
689
- * read `txId` (preferred) from the JSON body — falling back to base64-decoding
690
- * the `data` field when `txId` is absent.
805
+ * The terminating connector seals the store's answer as a response envelope
806
+ * (ADR 0018), which `publishEvent` opens and hands back as
807
+ * `PublishEventResult.response`. For a successful single-packet upload its
808
+ * body is `{"accept":true,"txId":"<43-char base64url>","data":"<base64 of
809
+ * txId>",…}`.
691
810
  *
692
- * LEGACY FALLBACK: older / non-proxy providers returned the bare tx ID as
693
- * `base64(utf8(txId))` directly in the FULFILL data (no HTTP envelope). When the
694
- * payload is not HTTP-enveloped we preserve that original decode so non-HTTP
695
- * FULFILLs do not regress.
811
+ * We fail on a non-2xx status or `accept:false`, then read `txId` (preferred)
812
+ * from the JSON body — falling back to base64-decoding the `data` field when
813
+ * `txId` is absent.
696
814
  *
697
815
  * Exported for callers that drive `publishEvent` directly with a hand-built
698
816
  * kind:5094 event (e.g. git-object uploads carrying Git-SHA/Git-Type/Repo
@@ -702,7 +820,7 @@ declare function requestBlobStorage(client: ToonClient, secretKey: Uint8Array, p
702
820
  * @throws {Error} If the response is non-2xx, `accept:false`, the body is not
703
821
  * parseable JSON, or no valid Arweave tx ID can be extracted.
704
822
  */
705
- declare function extractArweaveTxId(base64Data: string): string;
823
+ declare function extractArweaveTxId(response: EnvelopeResponse): string;
706
824
 
707
825
  /**
708
826
  * Shared sender-side plumbing for sender-chosen execution conditions
@@ -870,8 +988,6 @@ declare class BtpRuntimeClient implements IlpClient {
870
988
 
871
989
  /** Header carrying the base64(JSON) payment-channel claim. */
872
990
  declare const ILP_CLAIM_HEADER = "ILP-Payment-Channel-Claim";
873
- /** Header carrying a NIP-59 wrapped (gift-wrapped) claim. */
874
- declare const ILP_CLAIM_WRAPPED_HEADER = "ILP-Payment-Channel-Claim-Wrapped";
875
991
  /** Header carrying the peer identity. */
876
992
  declare const ILP_PEER_ID_HEADER = "ILP-Peer-Id";
877
993
  interface HttpIlpClientConfig {
@@ -916,6 +1032,13 @@ declare class HttpIlpClient implements IlpClient {
916
1032
  private readonly httpClient;
917
1033
  private readonly createWebSocket;
918
1034
  constructor(config: HttpIlpClientConfig);
1035
+ /**
1036
+ * The client edge this transport pays — the origin `GET /ilp/identity` and
1037
+ * `GET /ilp/routes/price` hang off (`ConnectorEdgeClient` normalizes the
1038
+ * trailing `/ilp` away). Exposed because a sealed write must ask the
1039
+ * connector it is ACTUALLY paying for its key, not a configured guess.
1040
+ */
1041
+ get clientEdgeEndpoint(): string;
919
1042
  /**
920
1043
  * Send an ILP PREPARE via `POST /ilp` WITHOUT a claim. The connector accepts
921
1044
  * this only on free/zero-amount routes; paid writes must use
@@ -979,6 +1102,241 @@ declare class HttpIlpClient implements IlpClient {
979
1102
  */
980
1103
  declare function httpEndpointToBtpUrl(httpEndpoint: string): string;
981
1104
 
1105
+ /**
1106
+ * Base error class for all TOON client errors.
1107
+ */
1108
+ declare class ToonClientError extends Error {
1109
+ readonly code: string;
1110
+ constructor(message: string, code: string, cause?: Error);
1111
+ }
1112
+ /**
1113
+ * Network error for connection failures (ECONNREFUSED, ETIMEDOUT).
1114
+ * These errors trigger retry logic with exponential backoff.
1115
+ */
1116
+ declare class NetworkError extends ToonClientError {
1117
+ constructor(message: string, cause?: Error);
1118
+ }
1119
+ /**
1120
+ * Connector error for 5xx server errors.
1121
+ * These errors indicate the connector is unavailable or malfunctioning.
1122
+ */
1123
+ declare class ConnectorError extends ToonClientError {
1124
+ constructor(message: string, cause?: Error);
1125
+ }
1126
+ /**
1127
+ * Validation error for invalid input parameters.
1128
+ * These errors are thrown before making any HTTP requests.
1129
+ */
1130
+ declare class ValidationError extends ToonClientError {
1131
+ constructor(message: string, cause?: Error);
1132
+ }
1133
+ /**
1134
+ * Thrown when the one-time on-chain payment-channel OPEN reverts because the
1135
+ * local settlement wallet has no native gas to pay for its own
1136
+ * approve/openChannel/setTotalDeposit transactions. This is the channel OPEN
1137
+ * only — per-write settlement rides ILP-over-HTTP and never spends gas. We
1138
+ * remap ONLY this case so callers get an actionable message (fund the wallet)
1139
+ * instead of the raw viem "...exceeds the balance of the account" string
1140
+ * (toon-meta#65). Retryable once the wallet is funded; the underlying viem/RPC
1141
+ * error is preserved as `cause`.
1142
+ */
1143
+ declare class ChannelFundingError extends ToonClientError {
1144
+ readonly retryable = true;
1145
+ constructor(message: string, cause?: Error);
1146
+ }
1147
+ /**
1148
+ * True when `err` (or any error in its nested `cause` chain) is an
1149
+ * insufficient-native-gas revert. viem wraps the node error one or more levels
1150
+ * deep, so the whole chain is flattened and scanned.
1151
+ */
1152
+ declare function isInsufficientGasError(err: unknown): boolean;
1153
+
1154
+ /**
1155
+ * Ask a terminating connector who it is and what it charges — the step that
1156
+ * has to happen BEFORE a packet can be formed at all.
1157
+ *
1158
+ * ADR 0018 makes holding the terminating connector's public key a
1159
+ * precondition of forming a packet: `Prepare.data` is sealed to that key, and
1160
+ * sealing to the wrong one is a confidentiality failure, not a delivery
1161
+ * failure. ADR 0022 says the connector *answers* — it never announces — so
1162
+ * both facts are fetched from the connector's own client edge, on the same
1163
+ * origin this client already POSTs `/ilp` to
1164
+ * (`docs/protocol/client-edge-spec.md` §1.7):
1165
+ *
1166
+ * - `GET /ilp/identity` → `{ "keyId": "...", "publicKey": "0x04..." }` — the
1167
+ * uncompressed secp256k1 key, 65 bytes, `0x`-prefixed hex.
1168
+ * - `GET /ilp/routes/price?destination=<ILP address>` →
1169
+ * `{ "destination": "...", "price": 100 }`, or `404` when no
1170
+ * locally-terminated route matches.
1171
+ *
1172
+ * Both are unauthenticated and neither changes state.
1173
+ *
1174
+ * ─── What this module refuses to do ────────────────────────────────────────
1175
+ * Unlike the 402-challenge parser next door (which degrades gracefully so an
1176
+ * unrecognised connector shape falls back to the vanilla 402), an identity is
1177
+ * parsed STRICTLY. A key that is the wrong length, not `0x04`-prefixed, or not
1178
+ * valid hex is refused with a distinguishable error rather than carried
1179
+ * forward: a half-understood key would be sealed to, and the failure would be
1180
+ * silent. There is no "best effort" reading of a public key.
1181
+ *
1182
+ * Pure transport + parsing: no keys are held, nothing is signed, and the only
1183
+ * state is the identity cache.
1184
+ */
1185
+
1186
+ /** The terminating connector's own identity, as reported by `GET /ilp/identity`. */
1187
+ interface ConnectorIdentity {
1188
+ /** The key id identifying the key (opaque to this client). */
1189
+ keyId: string;
1190
+ /** The uncompressed secp256k1 public key — exactly 65 raw bytes, leading `0x04`. */
1191
+ publicKey: Uint8Array;
1192
+ /** The key exactly as reported, `0x`-prefixed lowercase hex (65 bytes → 132 chars). */
1193
+ publicKeyHex: string;
1194
+ /** The normalized client-edge base URL this identity was read from. */
1195
+ endpoint: string;
1196
+ }
1197
+ /** What a locally-terminated route costs, as reported by `GET /ilp/routes/price`. */
1198
+ interface ConnectorRoutePrice {
1199
+ /** The ILP destination that was asked about (echoed by the connector). */
1200
+ destination: string;
1201
+ /** The price in ILP base units of the route `destination` matched. */
1202
+ price: bigint;
1203
+ }
1204
+ /**
1205
+ * Every distinguishable way asking a connector for its identity or terms can
1206
+ * fail. Each code names exactly one cause; there is no catch-all, because the
1207
+ * caller's next move differs per cause (retry a transport failure; never
1208
+ * retry a malformed key).
1209
+ */
1210
+ type ConnectorEdgeErrorCode =
1211
+ /** Non-2xx from `GET /ilp/identity`. */
1212
+ 'IDENTITY_HTTP_STATUS'
1213
+ /** `GET /ilp/identity` answered 2xx with a body that is not the documented object. */
1214
+ | 'IDENTITY_MALFORMED'
1215
+ /** `publicKey` is present but is not `0x`-prefixed even-length hex. */
1216
+ | 'IDENTITY_KEY_NOT_HEX'
1217
+ /** `publicKey` decodes, but not to exactly 65 bytes. */
1218
+ | 'IDENTITY_KEY_LENGTH'
1219
+ /** `publicKey` is 65 bytes but does not start with the SEC1 uncompressed tag `0x04`. */
1220
+ | 'IDENTITY_KEY_NOT_UNCOMPRESSED'
1221
+ /** Non-2xx, non-404 from `GET /ilp/routes/price` (404 is not an error — see below). */
1222
+ | 'ROUTE_PRICE_HTTP_STATUS'
1223
+ /** `GET /ilp/routes/price` answered 2xx with a body that is not the documented object. */
1224
+ | 'ROUTE_PRICE_MALFORMED'
1225
+ /** A destination that cannot be put in a query string was asked about. */
1226
+ | 'INVALID_DESTINATION';
1227
+ /**
1228
+ * A refusal to carry a connector's answer forward. Distinct from
1229
+ * {@link NetworkError} (which this module throws for a transport failure), so
1230
+ * "the connector is unreachable" and "the connector answered something I will
1231
+ * not seal to" are never confused.
1232
+ */
1233
+ declare class ConnectorEdgeError extends ToonClientError {
1234
+ /** Narrowed from `ToonClientError`'s `string`; type-only, no runtime field. */
1235
+ readonly code: ConnectorEdgeErrorCode;
1236
+ constructor(message: string, code: ConnectorEdgeErrorCode, cause?: Error);
1237
+ }
1238
+ /**
1239
+ * Normalize any client-edge URL a caller already holds into the base the
1240
+ * `/ilp/*` routes hang off.
1241
+ *
1242
+ * Callers reach this module holding whatever the x402 offer or their config
1243
+ * gave them — `https://apex.example`, `https://apex.example/`, or the
1244
+ * `POST /ilp` endpoint `https://apex.example/ilp` itself. All three name the
1245
+ * same client edge, so all three normalize to `https://apex.example`.
1246
+ */
1247
+ declare function connectorEdgeBaseUrl(endpoint: string): string;
1248
+ /**
1249
+ * Decode a `0x`-prefixed hex public key into its 65 raw bytes, refusing
1250
+ * anything that is not exactly one uncompressed secp256k1 key.
1251
+ */
1252
+ declare function decodeConnectorPublicKey(publicKeyHex: string): Uint8Array;
1253
+ /**
1254
+ * Parse an already-decoded `GET /ilp/identity` body. Exported so the shape the
1255
+ * connector actually emits can be pinned without standing up a server.
1256
+ */
1257
+ declare function parseConnectorIdentity(body: unknown, endpoint: string): ConnectorIdentity;
1258
+ /** Parse an already-decoded `GET /ilp/routes/price` 200 body. */
1259
+ declare function parseConnectorRoutePrice(body: unknown): ConnectorRoutePrice;
1260
+ interface ConnectorEdgeClientConfig {
1261
+ /** HTTP fetch implementation. Default: global `fetch`. Injectable for tests. */
1262
+ fetch?: typeof fetch;
1263
+ /** Per-request timeout in milliseconds. Default 10_000. */
1264
+ timeout?: number;
1265
+ }
1266
+ /**
1267
+ * Asks connectors for their identity and their terms, caching each identity
1268
+ * per client-edge endpoint and each route price per (endpoint, destination).
1269
+ *
1270
+ * The cache is per endpoint rather than per client instance because a sender
1271
+ * routinely speaks to several connectors, and re-fetching a key per packet
1272
+ * would put a network round trip in front of every send. Nothing here expires
1273
+ * on a timer: an operator key rotation, or a route being repriced, is a
1274
+ * deliberate event, so {@link invalidateIdentity} / {@link invalidateRoutePrice}
1275
+ * are how a stale answer is dropped.
1276
+ *
1277
+ * A price is cached the same way and for the same reason (toon-client#452):
1278
+ * under ADR 0020 a route's price is FLAT — one handler, one price — so it does
1279
+ * not vary with what is being sent, and asking again per packet would buy
1280
+ * nothing but latency.
1281
+ */
1282
+ declare class ConnectorEdgeClient {
1283
+ private readonly fetchImpl;
1284
+ private readonly timeout;
1285
+ private readonly identities;
1286
+ private readonly prices;
1287
+ constructor(config?: ConnectorEdgeClientConfig);
1288
+ /**
1289
+ * The terminating connector's public key, fetched once per endpoint.
1290
+ *
1291
+ * @param endpoint any client-edge URL (`https://apex`, `https://apex/ilp`).
1292
+ * @param options `forceRefresh` bypasses (and replaces) the cache entry.
1293
+ */
1294
+ getIdentity(endpoint: string, options?: {
1295
+ forceRefresh?: boolean;
1296
+ }): Promise<ConnectorIdentity>;
1297
+ /**
1298
+ * Drop a cached identity — one endpoint's, or every endpoint's when
1299
+ * `endpoint` is omitted. The way to react to a key rotation.
1300
+ */
1301
+ invalidateIdentity(endpoint?: string): void;
1302
+ /** Whether an identity for `endpoint` is already held (no request is made). */
1303
+ hasCachedIdentity(endpoint: string): boolean;
1304
+ /**
1305
+ * What `destination` costs at this connector, or `null` when the connector
1306
+ * answers `404` — no locally-terminated route matches it.
1307
+ *
1308
+ * `null` is the answer to "you do not terminate this", which is information;
1309
+ * a transport failure throws {@link NetworkError} instead, so a caller can
1310
+ * always tell "not mine" from "could not ask".
1311
+ *
1312
+ * Fetched once per (endpoint, destination) and reused. ADR 0020 makes a
1313
+ * price flat per handler, so it does not vary with the packet — a route
1314
+ * being repriced is an operator event, and {@link invalidateRoutePrice} is
1315
+ * how a caller reacts to one.
1316
+ *
1317
+ * @param options `forceRefresh` bypasses (and replaces) the cache entry.
1318
+ */
1319
+ getRoutePrice(endpoint: string, destination: string, options?: {
1320
+ forceRefresh?: boolean;
1321
+ }): Promise<ConnectorRoutePrice | null>;
1322
+ /**
1323
+ * Drop a cached route price — one (endpoint, destination)'s, every
1324
+ * destination's at one endpoint when `destination` is omitted, or all of
1325
+ * them when both are. The way to react to a route being repriced.
1326
+ */
1327
+ invalidateRoutePrice(endpoint?: string, destination?: string): void;
1328
+ /**
1329
+ * Whether a price for `(endpoint, destination)` is already held (no request
1330
+ * is made).
1331
+ */
1332
+ hasCachedRoutePrice(endpoint: string, destination: string): boolean;
1333
+ private fetchRoutePrice;
1334
+ private fetchIdentity;
1335
+ private readJson;
1336
+ /** GET with a timeout, mapping any transport failure onto {@link NetworkError}. */
1337
+ private get;
1338
+ }
1339
+
982
1340
  /**
983
1341
  * Payment-aware HTTP fetch over TOON (the "h402" flow).
984
1342
  *
@@ -993,44 +1351,74 @@ declare function httpEndpointToBtpUrl(httpEndpoint: string): string;
993
1351
  * from those bytes — the caller never sees ILP.
994
1352
  *
995
1353
  * ─── x402 wire contract (the 402 challenge body) ────────────────────────────
996
- * The connector side (the 402 greeting + the `accepts` entries) is a separate,
997
- * NOT-YET-BUILT dependency, so we parse DEFENSIVELY (mirroring
998
- * `readDiscoveredIlpPeer` in selectIlpTransport.ts): a slightly different
999
- * connector shape should degrade gracefully (fall back to the vanilla 402)
1000
- * rather than throw.
1354
+ * The shipped connector answers x402 **v2** terms (`client-edge-spec.md` §1.4,
1355
+ * `crates/connector-client-edge/src/lib.rs`), and that is the shape pinned by
1356
+ * `Http402Client.connectorTerms.test.ts`:
1001
1357
  *
1002
- * Expected 402 JSON body (x402 v1-ish):
1003
1358
  * ```jsonc
1004
1359
  * {
1005
- * "x402Version": 1,
1360
+ * "x402Version": 2,
1361
+ * "resource": { "url": "g.example.app" },
1006
1362
  * "accepts": [
1007
1363
  * {
1008
- * "scheme": "toon-channel", // REQUIRED — selects the TOON option.
1009
- * "network": "evm:base:8453", // optional — chain key (informational).
1010
- * "destination": "g.toon.apex", // ILP destination address to pay (the
1011
- * // connector route that fronts the URL).
1012
- * "amount": "1000", // price in ILP base units (string|number).
1013
- * "httpEndpoint": "https://apex/ilp", // the connector's POST /ilp URL.
1014
- * "supportsUpgrade": true // optional — host accepts the BTP upgrade.
1364
+ * "scheme": "toon-channel",
1365
+ * "network": "g.example.app",
1366
+ * "amount": "100",
1367
+ * "payTo": "g.example.app",
1368
+ * "maxTimeoutSeconds": 60,
1369
+ * "httpEndpoint": "/ilp", // RELATIVE to the resource's origin.
1370
+ * "extra": { "ilpAddress": "g.example.app", "endpoint": "/ilp", "price": "100" }
1015
1371
  * }
1016
1372
  * ]
1017
1373
  * }
1018
1374
  * ```
1019
1375
  *
1020
- * Field aliases read defensively (first present wins):
1021
- * - destination: `destination` | `ilpAddress` | `payTo` | `maxAmountRequired`'s
1022
- * sibling `payTo`. (We do NOT invent a value — a missing destination makes
1023
- * the entry unusable and we fall back to the vanilla 402.)
1024
- * - amount: `amount` | `price` | `maxAmountRequired`.
1025
- * - httpEndpoint:`httpEndpoint` | `ilpEndpoint` | `endpoint`.
1376
+ * Two things that shape forces, both easy to get wrong:
1377
+ * - The ILP address, the endpoint and the price live under **`extra`**. The
1378
+ * top-level `payTo` happens to equal the destination today, so reading it
1379
+ * appears to work — that is a coincidence of the connector's current code,
1380
+ * not a contract, so `extra` is read first.
1381
+ * - `httpEndpoint` is **relative**; it is resolved against the URL that
1382
+ * answered `402` (`Response.url`, or `parseX402Body`'s `baseUrl` argument).
1383
+ *
1384
+ * Everything is still parsed DEFENSIVELY (mirroring `readDiscoveredIlpPeer` in
1385
+ * selectIlpTransport.ts): an unrecognised connector shape degrades to the
1386
+ * vanilla 402 rather than throwing. Field aliases (first present wins):
1387
+ * - destination: `extra.ilpAddress` | `extra.destination` | `destination` |
1388
+ * `ilpAddress` | `payTo`. (We do NOT invent a value — a missing
1389
+ * destination makes the entry unusable and we fall back to the vanilla 402.)
1390
+ * - amount: `extra.price` | `extra.amount` | `amount` | `price` |
1391
+ * `maxAmountRequired`.
1392
+ * - httpEndpoint:`httpEndpoint` | `ilpEndpoint` | `extra.httpEndpoint` |
1393
+ * `extra.endpoint` | `endpoint`.
1026
1394
  * - upgrade: `supportsUpgrade` | `upgradable`.
1027
1395
  *
1028
- * ─── HTTP-in-ILP framing ────────────────────────────────────────────────────
1029
- * The raw HTTP request/response is serialized as minimal HTTP/1.1 wire bytes
1030
- * (request-line / status-line + headers + CRLFCRLF + body) and carried as the
1031
- * ILP packet `data` (base64). See {@link serializeHttpRequest} /
1032
- * {@link parseHttpResponse}. This keeps the connector free to forward the bytes
1033
- * verbatim and lets us rebuild a standard `Response`.
1396
+ * ─── What the paid request is made of ───────────────────────────────────────
1397
+ * The paid re-send is an OER `EnvelopeRequest` sealed to the terminating
1398
+ * connector's identity, under a condition derived from the secret that seal
1399
+ * carries — the same `sealExchange` / `readExchangeOutcome` pair
1400
+ * `ToonClient.publishEvent` uses (ADR 0018/0019, toon-client#450, #451). This
1401
+ * adapter used to carry its own HTTP/1.1 codec; it does not any more, and
1402
+ * `packages/client` now has exactly one encoder.
1403
+ *
1404
+ * Two consequences of the envelope replacing HTTP text, both deliberate:
1405
+ *
1406
+ * - **`Host` and `Content-Length` are not synthesised.** The old codec added
1407
+ * both. The connector strips them either way and lets its HTTP client
1408
+ * recompute them (`connector-runtime/src/app_client.rs` skips `host` and
1409
+ * `content-length` by name), and the envelope already carries the body
1410
+ * length as an OER length determinant, so emitting them was writing bytes
1411
+ * the far side throws away. A caller that sets either explicitly still has
1412
+ * it carried verbatim, and the connector still drops it.
1413
+ * - **A response has no reason phrase.** An `EnvelopeResponse` status is two
1414
+ * bytes; `HTTP/1.1 201 Created`'s "Created" has nowhere to live on this
1415
+ * wire. `Response.statusText` is therefore empty, and the status is the
1416
+ * fact to read.
1417
+ *
1418
+ * A malformed answer now fails the way it fails everywhere else in this
1419
+ * package — `SealedResponseError` from `readExchangeOutcome` — rather than
1420
+ * this file's old `ConnectorError` on a bad status line while `fulfill-http.ts`
1421
+ * quietly returned `{isHttp:false}` for the very same bytes.
1034
1422
  *
1035
1423
  * Claim signing/construction is owned by the CALLER (ToonClient wires the live
1036
1424
  * ChannelManager + signer). This adapter never builds or validates claims —
@@ -1111,6 +1499,14 @@ interface Http402ClientConfig {
1111
1499
  * returned session in a later iteration.
1112
1500
  */
1113
1501
  needsDuplex?: boolean;
1502
+ /**
1503
+ * Asks the connector named by the 402 offer for its identity key, so the
1504
+ * paid request can be sealed to it. Default: a fresh
1505
+ * {@link ConnectorEdgeClient} over this config's `fetch`. Injectable so a
1506
+ * caller that already holds one shares its identity cache rather than
1507
+ * re-fetching a key per paid request.
1508
+ */
1509
+ connectorEdge?: ConnectorEdgeClient;
1114
1510
  }
1115
1511
  /**
1116
1512
  * Reusable h402 fetch engine. `ToonClient.h402Fetch` is a thin wrapper that
@@ -1121,6 +1517,7 @@ declare class Http402Client {
1121
1517
  private readonly resolveClaim?;
1122
1518
  private readonly createIlpClient;
1123
1519
  private readonly needsDuplex;
1520
+ private readonly connectorEdge;
1124
1521
  constructor(config?: Http402ClientConfig);
1125
1522
  /**
1126
1523
  * `fetch()`-like entry point. Issues the request; on `402` parses the x402
@@ -1130,13 +1527,17 @@ declare class Http402Client {
1130
1527
  */
1131
1528
  fetch(url: string, opts?: H402FetchOptions): Promise<Response>;
1132
1529
  /**
1133
- * Open/reuse a channel (via the injected claim resolver), serialize the HTTP
1134
- * request into the ILP packet `data`, send it to `POST /ilp` with the claim,
1135
- * and reconstruct the origin `Response` from the FULFILL `data`.
1530
+ * Open/reuse a channel (via the injected claim resolver), seal the request
1531
+ * envelope to the terminating connector, send it to `POST /ilp` with the
1532
+ * claim and the matching condition, and open the answer.
1533
+ *
1534
+ * The identity is fetched BEFORE a packet is formed, and there is no default
1535
+ * to fall back to: sealing to the wrong key is a confidentiality failure
1536
+ * that merely presents as an undeliverable packet (ADR 0018).
1136
1537
  */
1137
1538
  private payOverToon;
1138
1539
  /**
1139
- * Send the serialized HTTP-in-ILP PREPARE over the selected transport.
1540
+ * Send the sealed PREPARE over the selected transport.
1140
1541
  *
1141
1542
  * - `http` / `http-upgradable`: stateless one-shot `POST /ilp` with the claim.
1142
1543
  * - `http-upgradable` additionally exercises {@link HttpIlpClient.upgradeToBtp}
@@ -1156,31 +1557,14 @@ declare class Http402Client {
1156
1557
  * 402 rather than throwing.
1157
1558
  */
1158
1559
  declare function parseX402Challenge(response: Response): Promise<ParsedX402Challenge>;
1159
- /** Pure parser over an already-decoded x402 body (testable without a Response). */
1160
- declare function parseX402Body(body: unknown): ParsedX402Challenge;
1161
- /**
1162
- * Serialize a raw HTTP request to HTTP/1.1 wire bytes:
1163
- * `METHOD path HTTP/1.1\r\n` + `Host:` + headers + `\r\n\r\n` + body.
1164
- *
1165
- * The request-line target is the URL's path+query (origin-form); we add a
1166
- * `Host` header from the URL authority and a `Content-Length` when there's a
1167
- * body, unless the caller already supplied them. Header names are matched
1168
- * case-insensitively so we never duplicate `Host`/`Content-Length`.
1169
- */
1170
- declare function serializeHttpRequest(req: {
1171
- method: string;
1172
- url: string;
1173
- headers?: Record<string, string>;
1174
- body?: string | Uint8Array;
1175
- }): Uint8Array;
1176
1560
  /**
1177
- * Parse HTTP/1.1 wire bytes (status-line + headers + CRLFCRLF + body) into a
1178
- * standard Web `Response`. Used to reconstruct the origin response from the ILP
1179
- * FULFILL `data`.
1561
+ * Pure parser over an already-decoded x402 body (testable without a Response).
1180
1562
  *
1181
- * @throws {ConnectorError} If the bytes are not a parseable HTTP/1.1 response.
1563
+ * `baseUrl`, when given, is the absolute URL of the resource that answered
1564
+ * `402`; a relative `httpEndpoint` is resolved against it. Omitting it keeps
1565
+ * the old behaviour of passing the endpoint through verbatim.
1182
1566
  */
1183
- declare function parseHttpResponse(bytes: Uint8Array): Response;
1567
+ declare function parseX402Body(body: unknown, baseUrl?: string): ParsedX402Challenge;
1184
1568
 
1185
1569
  /**
1186
1570
  * The persisted receive-side watermark for one swap target channel: the
@@ -1423,6 +1807,12 @@ declare class ToonClient {
1423
1807
  /** Concrete on-chain client, kept so deposit/withdraw can reach chain methods. */
1424
1808
  private onChainChannelClient?;
1425
1809
  private readonly peerNegotiations;
1810
+ /**
1811
+ * Asks terminating connectors for their identity key, caching one per
1812
+ * client edge. A packet cannot be formed without the key of the connector
1813
+ * that terminates it (ADR 0018), so this is reached on every paid write.
1814
+ */
1815
+ private readonly connectorEdge;
1426
1816
  /**
1427
1817
  * Creates a new ToonClient instance.
1428
1818
  *
@@ -1510,24 +1900,98 @@ declare class ToonClient {
1510
1900
  */
1511
1901
  start(): Promise<ToonStartResult>;
1512
1902
  /**
1513
- * Publishes a Nostr event to the relay via ILP payment.
1903
+ * Publishes a Nostr event through the connector that terminates
1904
+ * `destination`, as a sealed, condition-bearing paid write (ADR 0018/0019).
1905
+ *
1906
+ * What crosses the wire, in order:
1514
1907
  *
1515
- * The event must already be finalized (signed with id, pubkey, sig).
1908
+ * 1. **The terminating connector's identity is fetched first.** `data` is
1909
+ * sealed to that key, so a packet cannot be formed without it — and
1910
+ * there is no default to fall back to, because sealing to the wrong key
1911
+ * is a confidentiality failure that merely presents as undeliverable.
1912
+ * 2. **The price is ASKED for, not computed.** ADR 0020 makes a price flat
1913
+ * per handler, so `GET /ilp/routes/price` — the same longest-prefix
1914
+ * lookup the claim gate charges against — is the only thing that can
1915
+ * state what this write costs. `options.ilpAmount` still overrides.
1916
+ * 3. **The event becomes an OER `EnvelopeRequest`** — `POST <proxyPath>`
1917
+ * carrying `{"event": …}` — never HTTP text.
1918
+ * 4. **The PREPARE carries a real execution condition**, minted as
1919
+ * `sha256` of the fulfilment derived from the secret sealed inside the
1920
+ * wrap. The transport verifies the returned preimage against it, so a
1921
+ * FULFILL nobody could have earned is counted failed rather than
1922
+ * accepted.
1923
+ * 5. **The answer is opened with that same secret.** A FULFILL carries a
1924
+ * sealed response envelope; a REJECT sealed at the termination means the
1925
+ * destination refused, and a plaintext one means somebody on the path
1926
+ * did. `refusedBy` keeps those apart.
1927
+ *
1928
+ * An HTTP status inside the response envelope is envelope CONTENT, not a
1929
+ * packet outcome (ADR 0020): a 404 rides home on a FULFILL and value moved.
1930
+ * This method still reports a non-2xx as `success: false` — the event did
1931
+ * not persist — but `response` is populated either way, so a caller can see
1932
+ * exactly what it paid for.
1516
1933
  *
1517
1934
  * @param event - Signed Nostr event to publish
1518
- * @param options - Optional options including destination and signed balance proof claim
1519
- * @returns Result with success status and event ID
1520
- * @throws {ToonClientError} If client is not started
1521
- * @throws {ToonClientError} If event publishing fails
1935
+ * @param options - Optional destination, claim, amount and request target
1936
+ * @throws {ToonClientError} If the client is not started, the terminating
1937
+ * connector's identity or route price cannot be obtained, or the send
1938
+ * fails outright.
1522
1939
  */
1523
1940
  publishEvent(event: NostrEvent, options?: {
1524
1941
  destination?: string;
1525
1942
  claim?: SignedBalanceProof;
1526
1943
  ilpAmount?: bigint;
1527
- /** HTTP request-target the payment-proxy replays (default '/write', the
1528
- * relay; use '/store' for the Arweave store/DVM backend). */
1944
+ /** Request-target inside the envelope (default '/write', the relay;
1945
+ * use '/store' for the Arweave store backend). */
1529
1946
  proxyPath?: string;
1530
1947
  }): Promise<PublishEventResult>;
1948
+ /**
1949
+ * What a destination costs, asked of the connector that terminates it —
1950
+ * `null` when it terminates no route matching it.
1951
+ *
1952
+ * The public form of the lookup `publishEvent` makes, for callers that need
1953
+ * a price BEFORE they build a packet: a pre-push estimate that must equal
1954
+ * what the push will actually pay, a fee quote shown to a user for consent.
1955
+ * Since ADR 0020 a price is flat per handler, so the figure is the whole
1956
+ * fee for one packet to that destination — there is nothing to multiply it
1957
+ * by. Cached per destination, so this is cheap to call repeatedly.
1958
+ *
1959
+ * @throws {ToonClientError} NO_CONNECTOR_EDGE when no client edge is known.
1960
+ * @throws {ConnectorEdgeError} when the connector cannot be asked.
1961
+ */
1962
+ getRoutePrice(destination: string): Promise<bigint | null>;
1963
+ /**
1964
+ * What this destination costs, from the connector that terminates it.
1965
+ *
1966
+ * ADR 0020 makes a price flat per handler: one handler, one price, and an
1967
+ * app that wants to charge differently exposes more handlers. There is
1968
+ * therefore nothing to compute — the route table IS the price list, and
1969
+ * `GET /ilp/routes/price` is the same longest-prefix lookup the claim gate
1970
+ * charges against, so it can never state a price a real request would not
1971
+ * be charged.
1972
+ *
1973
+ * Cached per (edge, destination) by {@link ConnectorEdgeClient}, so this is
1974
+ * one round trip per destination rather than one per packet.
1975
+ *
1976
+ * @throws {ToonClientError} NO_TERMINATED_ROUTE when the connector answers
1977
+ * `404` — it does not terminate this destination. That is a refusal to
1978
+ * guess, not a zero: pricing an unroutable write at 0 (or at some local
1979
+ * fallback rate) would send a packet certain to be rejected, and report
1980
+ * the wrong reason for it.
1981
+ */
1982
+ private routePriceFor;
1983
+ /**
1984
+ * The client edge `/ilp/identity` and `/ilp/routes/price` hang off — the
1985
+ * same origin paid writes already POST `/ilp` to.
1986
+ *
1987
+ * Preferring the live transport's own endpoint over config is deliberate:
1988
+ * transport selection may have followed a discovered `httpEndpoint`, and
1989
+ * the identity must come from the connector actually being paid, not from
1990
+ * whatever URL was configured before discovery ran.
1991
+ *
1992
+ * @throws {ToonClientError} NO_CONNECTOR_EDGE when no origin is known.
1993
+ */
1994
+ private resolveClientEdgeEndpoint;
1531
1995
  /**
1532
1996
  * Payment-aware HTTP fetch over TOON (issue #50). A `fetch()`-like method that
1533
1997
  * makes paying for an HTTP resource transparent:
@@ -1838,55 +2302,6 @@ declare class ToonClient {
1838
2302
  getDiscoveredPeers(): _toon_protocol_core.DiscoveredPeer[];
1839
2303
  }
1840
2304
 
1841
- /**
1842
- * Base error class for all TOON client errors.
1843
- */
1844
- declare class ToonClientError extends Error {
1845
- readonly code: string;
1846
- constructor(message: string, code: string, cause?: Error);
1847
- }
1848
- /**
1849
- * Network error for connection failures (ECONNREFUSED, ETIMEDOUT).
1850
- * These errors trigger retry logic with exponential backoff.
1851
- */
1852
- declare class NetworkError extends ToonClientError {
1853
- constructor(message: string, cause?: Error);
1854
- }
1855
- /**
1856
- * Connector error for 5xx server errors.
1857
- * These errors indicate the connector is unavailable or malfunctioning.
1858
- */
1859
- declare class ConnectorError extends ToonClientError {
1860
- constructor(message: string, cause?: Error);
1861
- }
1862
- /**
1863
- * Validation error for invalid input parameters.
1864
- * These errors are thrown before making any HTTP requests.
1865
- */
1866
- declare class ValidationError extends ToonClientError {
1867
- constructor(message: string, cause?: Error);
1868
- }
1869
- /**
1870
- * Thrown when the one-time on-chain payment-channel OPEN reverts because the
1871
- * local settlement wallet has no native gas to pay for its own
1872
- * approve/openChannel/setTotalDeposit transactions. This is the channel OPEN
1873
- * only — per-write settlement rides ILP-over-HTTP and never spends gas. We
1874
- * remap ONLY this case so callers get an actionable message (fund the wallet)
1875
- * instead of the raw viem "...exceeds the balance of the account" string
1876
- * (toon-meta#65). Retryable once the wallet is funded; the underlying viem/RPC
1877
- * error is preserved as `cause`.
1878
- */
1879
- declare class ChannelFundingError extends ToonClientError {
1880
- readonly retryable = true;
1881
- constructor(message: string, cause?: Error);
1882
- }
1883
- /**
1884
- * True when `err` (or any error in its nested `cause` chain) is an
1885
- * insufficient-native-gas revert. viem wraps the node error one or more levels
1886
- * deep, so the whole chain is flattened and scanned.
1887
- */
1888
- declare function isInsufficientGasError(err: unknown): boolean;
1889
-
1890
2305
  /**
1891
2306
  * Configuration options for HttpRuntimeClient.
1892
2307
  */
@@ -3768,104 +4183,6 @@ interface RetryOptions {
3768
4183
  */
3769
4184
  declare function withRetry<T>(operation: () => Promise<T>, options: RetryOptions): Promise<T>;
3770
4185
 
3771
- /**
3772
- * Store-write HTTP envelope for the payment-proxy (HTTP-in-ILP) path.
3773
- *
3774
- * The deployed connector is a payment-proxy: it terminates a paid write by
3775
- * decoding the ILP PREPARE `data` as a literal RFC 7230 HTTP/1.1 request and
3776
- * reverse-proxying it to the relay store's `POST /write` (see the connector's
3777
- * `HttpProxyHandler.decodeHttpRequest`). The ILP `data` MUST therefore be a
3778
- * full HTTP request envelope:
3779
- *
3780
- * POST /write HTTP/1.1\r\n
3781
- * Host: relay\r\n
3782
- * Content-Type: application/json\r\n
3783
- * \r\n
3784
- * {"event": <signed nostr event object>}
3785
- *
3786
- * Sending the bare TOON-encoded event (no request-line) makes the proxy reject
3787
- * with `F01 - Invalid HTTP envelope: malformed request-line`. The relay's
3788
- * `/write` handler parses the body as JSON and reads `body.event` as a full
3789
- * signed Nostr event OBJECT (it runs `verifyEvent(event)` + `store(event)`), so
3790
- * the body carries the event object verbatim — NOT the TOON string.
3791
- *
3792
- * This helper is the single source of truth for that envelope so the proxy
3793
- * paid-write path (`ToonClient.publishEvent`) and any future caller stay
3794
- * byte-compatible with the deployed store. It is isomorphic (Node + browser):
3795
- * `JSON.stringify` escapes non-ASCII to `\uXXXX`, so the serialized envelope is
3796
- * pure ASCII and `encodeUtf8` matches the bytes the store expects.
3797
- */
3798
-
3799
- /**
3800
- * Wrap a signed Nostr event in the HTTP envelope the deployed payment-proxy
3801
- * reverse-proxies to its backend. Defaults to the relay's `POST /write`; pass
3802
- * `requestTarget: '/store'` for the Arweave store/DVM backend.
3803
- *
3804
- * @param event - A finalized (signed) Nostr event — passed through to the store
3805
- * as the JSON `event` field verbatim (the store re-verifies the signature).
3806
- * @param requestTarget - HTTP request-target the proxy replays (default `/write`).
3807
- * @returns The envelope bytes to use as the ILP PREPARE `data`.
3808
- */
3809
- declare function buildStoreWriteEnvelope(event: NostrEvent, requestTarget?: string): Uint8Array;
3810
-
3811
- /**
3812
- * Shared parser for the HTTP-over-ILP response carried in an ILP **FULFILL**
3813
- * packet's `data` field.
3814
- *
3815
- * The deployed connector is a payment-proxy (HTTP-in-ILP): a paid write/upload
3816
- * is reverse-proxied to the relay/DVM origin and the origin's reply is returned
3817
- * **verbatim as a full HTTP/1.1 response message** inside the FULFILL `data`:
3818
- *
3819
- * HTTP/1.1 200 OK\r\n
3820
- * content-length: 189\r\n
3821
- * \r\n
3822
- * {"accept":true,"txId":"4QcRav...","data":"<base64-txid>",...}
3823
- *
3824
- * Callers (`ToonClient.publishEvent`, `requestBlobStorage`) previously treated
3825
- * this `data` as opaque success bytes — `publishEvent` reported success on ANY
3826
- * FULFILL even when the embedded HTTP status was `404 Not Found`, and
3827
- * `requestBlobStorage` base64-decoded the WHOLE response as if it were the bare
3828
- * Arweave tx id. This module makes the HTTP envelope first-class so both paths
3829
- * can read the real status and body.
3830
- *
3831
- * The full Web-`Response` reconstruction used by the h402 fetch path lives in
3832
- * `adapters/Http402Client.ts` (`parseHttpResponse`); this is a smaller,
3833
- * dependency-free helper that returns the status code + raw body string, which
3834
- * is all the publish/upload paths need.
3835
- *
3836
- * DEFENSIVE: not every FULFILL is HTTP-enveloped (e.g. swap peer raw-TOON
3837
- * FULFILLs go through `sendSwapPacket`, not these paths). If the decoded data
3838
- * does not begin with an `HTTP/<v>` status line, `isHttp` is `false` and the
3839
- * caller should fall back to its prior (non-HTTP) interpretation rather than
3840
- * fail. This keeps non-HTTP FULFILLs from regressing.
3841
- */
3842
- /** Result of parsing FULFILL `data` as an HTTP/1.1 response. */
3843
- interface ParsedFulfillHttp {
3844
- /** Whether the data looked like an HTTP/1.1 response (status line present). */
3845
- isHttp: boolean;
3846
- /** HTTP status code (e.g. 200, 404). Only meaningful when `isHttp` is true. */
3847
- status: number;
3848
- /** Reason phrase from the status line (may be empty). */
3849
- statusText: string;
3850
- /** Decoded response body as a UTF-8 string (empty when none). */
3851
- body: string;
3852
- }
3853
- /**
3854
- * Parse FULFILL `data` bytes as an HTTP/1.1 response.
3855
- *
3856
- * Returns `{ isHttp: false, ... }` (without throwing) when the payload does not
3857
- * start with an `HTTP/<v>` status line, so callers can fall back to their
3858
- * legacy non-HTTP interpretation. When it IS an HTTP response, the status code
3859
- * and body are extracted; a present-but-malformed status line yields
3860
- * `isHttp: false` as well (treated as non-HTTP rather than throwing).
3861
- */
3862
- declare function parseFulfillHttpBytes(bytes: Uint8Array): ParsedFulfillHttp;
3863
- /**
3864
- * Convenience wrapper: decode a base64 FULFILL `data` string (the shape carried
3865
- * on `IlpSendResult.data`) and parse it as an HTTP/1.1 response.
3866
- */
3867
- declare function parseFulfillHttp(base64Data: string): ParsedFulfillHttp;
3868
-
3869
4186
  /**
3870
4187
  * Sender-chosen ILP execution conditions (toon-client#350, rolling-swap
3871
4188
  * prerequisite — toon-meta#145 §3 R1/R2).
@@ -4566,4 +4883,468 @@ declare function deployMinaChannelZkApp(params: DeployMinaZkAppParams): Promise<
4566
4883
  */
4567
4884
  declare function ensureOwnedMinaZkApp(params: EnsureOwnedMinaZkAppParams): Promise<EnsureOwnedMinaZkAppResult>;
4568
4885
 
4569
- export { type BackupPayload, type BalanceProofParams, BtpRuntimeClient, type BtpRuntimeClientConfig, type BuildSwapSettlementsParams, CLAIM_TYPEHASH, CONDITION_LENGTH, COOP_CLOSE_TYPEHASH, type ChainMetadata, type ChainSigner, ChannelFundingError, ChannelManager, type ClaimMessage, type ClaimResolver, type ClaimSignature, ConnectorError, type DeployMinaZkAppParams, type DiscoveredIlpPeer, type EVMClaimMessage, type EncryptedKeystore, type EnsureOwnedMinaZkAppParams, type EnsureOwnedMinaZkAppResult, type EvmClaimDomainContext, type EvmClaimMessage, type EvmClaimVerifyResult, type EvmCooperativeCloseMessage, EvmSigner, type ExecutionConditionPair, FULFILLMENT_MISMATCH_CODE, FULFILLMENT_MISMATCH_MESSAGE, type FaucetChain, type FundWalletOptions, type FundWalletResult, type H402FetchOptions, Http402Client, type Http402ClientConfig, HttpConnectorAdmin, type HttpConnectorAdminConfig, HttpIlpClient, type HttpIlpClientConfig, type HttpIlpClientFactory, HttpRuntimeClient, type HttpRuntimeClientConfig, ILP_CLAIM_HEADER, ILP_CLAIM_WRAPPED_HEADER, ILP_PEER_ID_HEADER, type IlpSendParams, type IlpSendResultWithFulfillment, type IlpTransportChoice, InMemoryPreimageRetentionStore, InMemoryReceivedClaimStore, type IngestAndRevealParams, type IngestAndRevealResult, type IngestReceivedClaimsParams, type IngestReceivedClaimsResult, JsonFileReceivedClaimStore, KeyManager, type KeyManagerConfig, MINA_CHANNEL_STATE, type MinaChannelStateReader, type MinaClaimMessage, type MinaClaimSubmitArgs, type MinaClaimSubmitter, type MinaCoSignInputs, type MinaCoSignedClaim, type MinaDepositReader, type MinaOnChainChannelState, type MinaSettlementContext, MinaSettlementError, type MinaSettlementErrorCode, type MinaSettlementResult, type MinaSignaturePair, MinaSigner, type MinaSignerOptions, type MinaZkAppDeployRecord, NetworkError, OnChainChannelClient, type OnChainChannelClientConfig, type ParsedFulfillHttp, type ParsedX402Challenge, type PasskeyInfo, type PreimageRetentionStore, type PublishEventResult, ROLLING_SWAP_DOMAIN_NAME, ROLLING_SWAP_DOMAIN_VERSION, type ReceivedClaimEntry, type ReceivedClaimRejection, type ReceivedClaimRejectionCode, type ReceivedClaimStore, type RequestBlobStorageParams, type RequestBlobStorageResult, type RetainedPreimage, type RetryOptions, type RevealDecision, type RevealFn, type RevealResult, type RevealedClaim, type RolledBackClaim, type SelectIlpTransportOptions, type SignedBalanceProof, type SolanaChannelClientOptions, type SolanaClaimMessage, SolanaSigner, type SubmitEvmSettlementParams, type SubmitEvmSettlementResult, type SwapSettlementBuild, type ToonChannelAccept, ToonClient, type ToonClientConfig, ToonClientError, type ToonIdentity, type ToonSigners, type ToonStartResult, ValidationError, type VaultData, type VerifiedReceivedClaim, type WalletBalance, type WalletBalanceSources, type WalletChainBalances, type WalletTokenAmount, applyDefaults, applyNetworkPresets, assertValidCondition, buildBackupEvent, buildBackupFilter, buildMinaCoSignedClaim, buildSettlementInfo, buildStoreWriteEnvelope, buildSwapSettlements, createO1jsMinaClaimSubmitter, decodeEvmSettlementTx, decryptMnemonic, defaultFaucetTimeout, deployMinaChannelZkApp, deriveFromNsec, deriveFullIdentity, deriveNostrKeyFromMnemonic, encryptMnemonic, ensureOwnedMinaZkApp, entryToAccumulatedClaim, evmClaimDigest, evmCooperativeCloseDigest, extractArweaveTxId, fulfillmentMatchesCondition, fundWallet, generateKeystore, generateMnemonic, generateRandomIdentity, getNetworkStatus, hasSettlementMetadata, httpEndpointToBtpUrl, importKeystore, ingestAndReveal, ingestReceivedClaims, isInsufficientGasError, isPrfSupported, isZeroCondition, loadKeystore, mintExecutionCondition, parseBackupPayload, parseEvmChainId, parseFulfillHttp, parseFulfillHttpBytes, parseHttpResponse, parseX402Body, parseX402Challenge, proxyIlpEndpoint, readDiscoveredIlpPeer, readEvmNativeBalance, readEvmTokenBalance, readMinaBalance, readMinaChannelState, readMinaDepositTotal, readSolanaNativeBalance, readSolanaTokenBalance, readWalletBalances, recoverEvmClaimSigner, requestBlobStorage, selectIlpTransport, serializeHttpRequest, submitEvmSettlement, submitMinaSettlement, validateConfig, validateMnemonic, verifyEvmClaimSignature, withRetry, writeKeystoreFile };
4886
+ /**
4887
+ * Canonical OER length primitives (RFC-0030), ported byte-for-byte from
4888
+ * `connector_domain::oer` so the Rust and TypeScript fleets agree on the wire.
4889
+ *
4890
+ * "Canonical" is the whole point (ADR 0023): every value has exactly ONE
4891
+ * encoding, and a decoder that quietly accepts a second spelling of the same
4892
+ * value is a decoder two implementations can disagree through. So a
4893
+ * determinant is refused unless the bytes it introduces are exactly what
4894
+ * {@link encodeVarUint} would have produced:
4895
+ *
4896
+ * - `0x81 0x03` — a long form for `3`, which `0x03` already encodes — is
4897
+ * {@link OerErrorKind.NonCanonicalLength}, not `3`.
4898
+ * - `0x80` — a zero-byte long form aliasing `0x00` — is
4899
+ * {@link OerErrorKind.NonCanonicalLength}, not `0`.
4900
+ * - `0x89 …` — nine length bytes, which cannot fit a `u64` without silently
4901
+ * discarding the high-order ones — is
4902
+ * {@link OerErrorKind.LengthDeterminantOverflow}, not a truncated read.
4903
+ *
4904
+ * Values are `bigint` because the wire type is `u64` and `number` cannot hold
4905
+ * one; the caller narrows.
4906
+ *
4907
+ * Pure: no I/O, no keys, no clock.
4908
+ */
4909
+ /** The three, and only three, ways a length determinant can be refused. */
4910
+ declare enum OerErrorKind {
4911
+ /** The buffer ends before the field it declares does. */
4912
+ BufferUnderflow = "buffer_underflow",
4913
+ /** A determinant that is not the minimal encoding of its own value. */
4914
+ NonCanonicalLength = "non_canonical_length",
4915
+ /** A determinant wider than eight bytes (cannot be a `u64`). */
4916
+ LengthDeterminantOverflow = "length_determinant_overflow"
4917
+ }
4918
+ /** A refusal from the length primitives, carrying which of the three it is. */
4919
+ declare class OerError extends Error {
4920
+ readonly kind: OerErrorKind;
4921
+ constructor(kind: OerErrorKind);
4922
+ }
4923
+ /** Encode a VarUInt: `0..=127` as one byte, `128+` as a length-prefixed BE value. */
4924
+ declare function encodeVarUint(value: bigint): Uint8Array;
4925
+ /** A decoded field: its value, and how many bytes it consumed. */
4926
+ interface Decoded<T> {
4927
+ value: T;
4928
+ consumed: number;
4929
+ }
4930
+ /**
4931
+ * Decode a VarUInt at `offset`, refusing any non-canonical spelling.
4932
+ *
4933
+ * @throws {OerError} and nothing else — arbitrary bytes never produce a
4934
+ * `RangeError`, a `TypeError`, or a plausible-but-wrong value.
4935
+ */
4936
+ declare function decodeVarUint(buf: Uint8Array, offset: number): Decoded<bigint>;
4937
+ /** Encode a VarOctetString: a VarUInt length prefix followed by the bytes. */
4938
+ declare function encodeVarOctetString(data: Uint8Array): Uint8Array;
4939
+ /**
4940
+ * Decode a VarOctetString at `offset`.
4941
+ *
4942
+ * @throws {OerError} and nothing else.
4943
+ */
4944
+ declare function decodeVarOctetString(buf: Uint8Array, offset: number): Decoded<Uint8Array>;
4945
+
4946
+ /**
4947
+ * The gift wrap (ADR 0018) and the fulfilment a shared secret derives (ADR
4948
+ * 0019): the seal around the {@link ./envelope.js | envelope}, so a packet
4949
+ * payload is readable only by the connector that terminates it and the
4950
+ * preimage that pays for it needs no app participation.
4951
+ *
4952
+ * A faithful port of `connector_signer::giftwrap`
4953
+ * (`crates/connector-signer/src/giftwrap.rs` on toon-protocol/connector `main`)
4954
+ * and of `connector_domain::condition::derive_condition`
4955
+ * (`crates/connector-domain/src/condition.rs:27`). `vectors/wire-vectors.json`'s
4956
+ * `giftwrap` and `fulfilment` sections are the contract, replayed byte-for-byte
4957
+ * in `wire-vectors.test.ts`; the prose here describes the same thing but the
4958
+ * bytes decide.
4959
+ *
4960
+ * ─── The mechanism, as read off the Rust ────────────────────────────────────
4961
+ * Recorded here because it cannot be inferred from the vector file's field
4962
+ * names, and because the acceptance criterion for toon-client#449 asks for it
4963
+ * in writing. Every line below is cited to
4964
+ * `crates/connector-signer/src/giftwrap.rs` unless stated otherwise.
4965
+ *
4966
+ * - **Curve and ECDH.** The receiver's identity key is secp256k1; the value a
4967
+ * real connector reports from `GET /ilp/identity` is its 65-byte
4968
+ * uncompressed form (`0x04 ‖ X ‖ Y`). The sender ECDHs a fresh, per-packet
4969
+ * ephemeral key against it and uses the **raw X-coordinate** of the
4970
+ * resulting point — `crypto.rs`'s `ecdh_x_coordinate` does
4971
+ * `tweak_mul_assign` then `serialize_compressed()[1..]`, deliberately *not*
4972
+ * `libsecp256k1::SharedSecret`'s digest-mixing variant. So: not hashed, and
4973
+ * not the 33-byte compressed point.
4974
+ * - **Key derivation.** `HKDF-SHA256`, **no salt** (`Hkdf::new(None, ikm)`,
4975
+ * i.e. HKDF-Extract with an all-zero salt), expanded to 32 bytes under one
4976
+ * of three fixed ASCII `info` strings — `giftwrap.rs`'s `hkdf_key`:
4977
+ * - `toon-giftwrap-request` — the request AEAD key, over the ECDH X.
4978
+ * - `toon-giftwrap-response` — the response AEAD key, over the shared secret.
4979
+ * - `toon-giftwrap-fulfillment` — the fulfilment, over the shared secret.
4980
+ * (American spelling on the wire; the vector *section* is `fulfilment`.)
4981
+ * These three strings are the only domain separation between two AEAD keys
4982
+ * and a payment preimage all derived from the same input, so one wrong
4983
+ * character silently yields bytes that decrypt nothing and satisfy no
4984
+ * condition.
4985
+ * - **AEAD.** ChaCha20-Poly1305 (RFC 8439), 12-byte nonce, **no** additional
4986
+ * authenticated data.
4987
+ * - **Request framing.** `0x01 ‖ ephemeral_public(65) ‖ nonce(12) ‖
4988
+ * ciphertext`, where the encrypted plaintext is `shared_secret(32) ‖
4989
+ * encoded_envelope`. The secret rides *inside* the sealed request, which is
4990
+ * what lets the response be sealed with no second key exchange.
4991
+ * - **Response framing.** `0x02 ‖ nonce(12) ‖ ciphertext`, the plaintext being
4992
+ * just the encoded envelope. Sealed directly with the request's shared
4993
+ * secret.
4994
+ * - **Fulfilment and condition.** `fulfilment = HKDF-SHA256(shared_secret,
4995
+ * "toon-giftwrap-fulfillment")`; the condition a sender mints is
4996
+ * `sha256(fulfilment)` — `condition.rs`'s `derive_condition`. A sender knows
4997
+ * the secret before it seals, so it can mint the condition first; the
4998
+ * terminating connector recovers the secret by opening the wrap and derives
4999
+ * the preimage without asking the app anything.
5000
+ * - **Telling a sealed reject from a plaintext one.** The leading type byte,
5001
+ * and only that (`looks_like_sealed_response`). A reject raised short of the
5002
+ * termination shares no secret with the sender and carries empty `data`; an
5003
+ * empty `data` is never sealed, so a sealed reject is positive proof that
5004
+ * the destination itself said no.
5005
+ *
5006
+ * ─── Two failure modes, two types ───────────────────────────────────────────
5007
+ * A wrap that cannot be OPENED throws {@link GiftWrapError}. A wrap that opens
5008
+ * cleanly but whose recovered plaintext is not a valid envelope throws
5009
+ * `EnvelopeError`, from `envelope.ts` — a different class entirely, raised
5010
+ * above this module rather than by it. The Rust keeps the same separation
5011
+ * (`GiftWrapError` vs `connector_domain::EnvelopeError`) for the same reason:
5012
+ * "I could not read this" and "I read this and it was malformed" are different
5013
+ * facts about a peer, and collapsing them loses the distinction at every call
5014
+ * site.
5015
+ *
5016
+ * ─── Additive ───────────────────────────────────────────────────────────────
5017
+ * Nothing in this client's live send path calls this yet — `publishEvent` is
5018
+ * still the latin1 HTTP framing in `utils/store-envelope.ts`. Rewiring it is a
5019
+ * later child (toon-client#450).
5020
+ */
5021
+ /** ChaCha20-Poly1305 nonce length. */
5022
+ declare const GIFTWRAP_NONCE_LENGTH = 12;
5023
+ /** The shared secret carried inside a sealed request, and the fulfilment. */
5024
+ declare const GIFTWRAP_SECRET_LENGTH = 32;
5025
+ /** The uncompressed secp256k1 public key a sealed request carries. */
5026
+ declare const GIFTWRAP_PUBLIC_KEY_LENGTH = 65;
5027
+ /** `TYPE_GIFTWRAP_REQUEST` — the leading byte of a sealed request. */
5028
+ declare const GIFTWRAP_TYPE_REQUEST = 1;
5029
+ /** `TYPE_GIFTWRAP_RESPONSE` — the leading byte of a sealed response. */
5030
+ declare const GIFTWRAP_TYPE_RESPONSE = 2;
5031
+ /**
5032
+ * Every distinguishable way a wrap can fail to open — the four variants of
5033
+ * `GiftWrapError` in `giftwrap.rs:57-71`, named the same way. There is
5034
+ * deliberately no catch-all: this module must never be able to fail "somehow".
5035
+ *
5036
+ * None of these ever carries decrypted plaintext, matching the Rust's own
5037
+ * guarantee.
5038
+ */
5039
+ declare enum GiftWrapErrorKind {
5040
+ /** The leading byte is not the one this direction requires. */
5041
+ InvalidType = "invalid_type",
5042
+ /** The bytes end before the framing does. */
5043
+ Truncated = "truncated",
5044
+ /** An ephemeral or receiver public key that is not a usable curve point. */
5045
+ InvalidKey = "invalid_key",
5046
+ /** The AEAD refused: wrong key, wrong nonce, or a tampered ciphertext. */
5047
+ OpenFailed = "open_failed"
5048
+ }
5049
+ /**
5050
+ * A refusal to open a wrap. `kind` is the machine-readable reason;
5051
+ * `expectedType` names the type byte that was required, for
5052
+ * {@link GiftWrapErrorKind.InvalidType} — mirroring
5053
+ * `GiftWrapError::InvalidType(u8)`.
5054
+ */
5055
+ declare class GiftWrapError extends Error {
5056
+ readonly kind: GiftWrapErrorKind;
5057
+ readonly expectedType?: number | undefined;
5058
+ constructor(kind: GiftWrapErrorKind, expectedType?: number | undefined);
5059
+ }
5060
+ /**
5061
+ * What sealing a request produces: the bytes to carry as `Prepare.data`, and
5062
+ * the shared secret that both derives this packet's fulfilment and opens the
5063
+ * answer. The sender must keep the secret — it is the only thing that opens
5064
+ * the response, and the only thing that proves the fulfilment it is paid
5065
+ * against was earned rather than guessed.
5066
+ */
5067
+ interface SealedRequest {
5068
+ /** `0x01 ‖ ephemeral_public(65) ‖ nonce(12) ‖ ciphertext`. */
5069
+ readonly wrapped: Uint8Array;
5070
+ /** The 32 random bytes sealed inside `wrapped`. */
5071
+ readonly sharedSecret: Uint8Array;
5072
+ }
5073
+ /** What opening a sealed request recovers. */
5074
+ interface OpenedRequest {
5075
+ /** The encoded envelope — feed to `decodeEnvelopeRequest`. */
5076
+ readonly envelopeBytes: Uint8Array;
5077
+ /** The 32-byte secret the sender chose, for the fulfilment and the answer. */
5078
+ readonly sharedSecret: Uint8Array;
5079
+ }
5080
+ /**
5081
+ * A key agreement that never hands out secret key material — the TypeScript
5082
+ * counterpart of `giftwrap.rs`'s dependency on `Signer::ecdh`, and the reason
5083
+ * {@link openRequest} takes this rather than a raw private key: a remote or
5084
+ * hardware-backed identity can open a wrap without its key leaving its own
5085
+ * boundary.
5086
+ *
5087
+ * Returns the raw 32-byte ECDH X-coordinate, or throws.
5088
+ */
5089
+ interface GiftWrapEcdh {
5090
+ ecdh(ephemeralPublicKey: Uint8Array): Uint8Array;
5091
+ }
5092
+ /**
5093
+ * The ordinary local case of {@link GiftWrapEcdh}: a 32-byte secp256k1 secret
5094
+ * key held in this process. `openRequest` accepts a bare key too and wraps it
5095
+ * in this.
5096
+ */
5097
+ declare function localGiftWrapEcdh(secretKey: Uint8Array): GiftWrapEcdh;
5098
+ /**
5099
+ * The deterministic core of {@link sealRequest}, parameterized on every value
5100
+ * a real seal draws at random — the counterpart of the Rust's
5101
+ * `seal_request_with_randomness`, which that crate gates behind a `test-util`
5102
+ * feature for a reason worth repeating: **reusing a (key, nonce) pair under
5103
+ * ChaCha20-Poly1305 is catastrophic**, so caller-supplied randomness is a
5104
+ * footgun, not a convenience. Use {@link sealRequest} unless you are replaying
5105
+ * a fixed vector.
5106
+ *
5107
+ * `receiverPublicKey` may be the 65-byte uncompressed form a connector's
5108
+ * `GET /ilp/identity` reports, or the 33-byte compressed form; the ECDH result
5109
+ * is the same point either way. The ephemeral key is always emitted
5110
+ * uncompressed, because that is what the framing pins.
5111
+ */
5112
+ declare function sealRequestWithRandomness(plaintext: Uint8Array, receiverPublicKey: Uint8Array, ephemeralSecretKey: Uint8Array, sharedSecret: Uint8Array, nonce: Uint8Array): Uint8Array;
5113
+ /**
5114
+ * Seal `plaintext` (an encoded envelope) to `receiverPublicKey`. A fresh
5115
+ * ephemeral key pair, shared secret and nonce are drawn for this call alone,
5116
+ * so no two sealed requests — even to the same receiver, even with the same
5117
+ * plaintext — share any of the three.
5118
+ *
5119
+ * Returns the wire bytes and the shared secret. Mint the packet's execution
5120
+ * condition as {@link deriveCondition}({@link deriveFulfillment}(secret))
5121
+ * before sending: the terminating connector recovers the same secret by
5122
+ * opening this wrap, so the preimage it is paid against is one it derived, not
5123
+ * one anybody handed it.
5124
+ */
5125
+ declare function sealRequest(plaintext: Uint8Array, receiverPublicKey: Uint8Array): SealedRequest;
5126
+ /**
5127
+ * Open a sealed request addressed to `identity`, recovering the encoded
5128
+ * envelope and the shared secret carried alongside it.
5129
+ *
5130
+ * `identity` is either a 32-byte secp256k1 secret key or a {@link GiftWrapEcdh}
5131
+ * that never exposes one. Nothing in this client terminates packets today, so
5132
+ * this exists to make the seal testable from both ends — and to make the
5133
+ * vectors' "opening it with the fixture's secret key must recover the envelope
5134
+ * and the secret exactly" a check this repo can actually run.
5135
+ */
5136
+ declare function openRequest(bytes: Uint8Array, identity: Uint8Array | GiftWrapEcdh): OpenedRequest;
5137
+ /**
5138
+ * The deterministic core of {@link sealResponse}, parameterized on the nonce.
5139
+ * Same footgun, same warning as {@link sealRequestWithRandomness}: a nonce
5140
+ * reused under one shared secret destroys the confidentiality of both
5141
+ * responses sealed with it.
5142
+ */
5143
+ declare function sealResponseWithRandomness(sharedSecret: Uint8Array, plaintext: Uint8Array, nonce: Uint8Array): Uint8Array;
5144
+ /**
5145
+ * Seal `plaintext` — an encoded response envelope, or a reject's diagnostic
5146
+ * bytes — with the request's own `sharedSecret`. No second key exchange: the
5147
+ * secret is bidirectional by construction, which is also why a sealed reject
5148
+ * can only have come from the termination.
5149
+ */
5150
+ declare function sealResponse(sharedSecret: Uint8Array, plaintext: Uint8Array): Uint8Array;
5151
+ /**
5152
+ * Open a sealed response with the shared secret {@link sealRequest} returned
5153
+ * for the request it answers. No signer, no key exchange, no identity key.
5154
+ */
5155
+ declare function openResponse(sharedSecret: Uint8Array, bytes: Uint8Array): Uint8Array;
5156
+ /**
5157
+ * Whether `bytes` is shaped like a sealed response — the leading type byte and
5158
+ * nothing else, exactly as `looks_like_sealed_response` does it. This is how a
5159
+ * sender tells a reject raised BY the destination from one raised on the way
5160
+ * to it, without holding the secret to try opening it.
5161
+ *
5162
+ * Empty `data`, which every reject raised short of a termination carries, is
5163
+ * never sealed.
5164
+ */
5165
+ declare function looksLikeSealedResponse(bytes: Uint8Array): boolean;
5166
+ /**
5167
+ * The fulfilment a request's shared secret derives (ADR 0019):
5168
+ * `HKDF-SHA256(shared_secret, "toon-giftwrap-fulfillment")`, 32 bytes.
5169
+ * Domain-separated by its own `info` string from both AEAD keys the same
5170
+ * secret also derives, so it can never collide with either.
5171
+ */
5172
+ declare function deriveFulfillment(sharedSecret: Uint8Array): Uint8Array;
5173
+ /**
5174
+ * The condition a `fulfillment` satisfies: `sha256(fulfillment)` —
5175
+ * `connector_domain::condition::derive_condition`. Hashing only ever runs in
5176
+ * this direction; there is deliberately no function here that goes from a
5177
+ * condition back to a fulfilment.
5178
+ *
5179
+ * The hash is the same one `utils/condition.ts` already uses; what ADR 0019
5180
+ * changes is where the preimage comes from. `mintExecutionCondition` there
5181
+ * draws a random preimage the sender must then carry to the FULFILL itself;
5182
+ * here the preimage is DERIVED from the secret sealed inside the packet, so
5183
+ * the terminating connector can produce it without the sender or the app
5184
+ * handing it over. Checking a returned fulfilment against a condition is
5185
+ * unchanged either way — use `fulfillmentMatchesCondition` from
5186
+ * `utils/condition.ts` for that rather than a second copy of it here.
5187
+ */
5188
+ declare function deriveCondition(fulfillment: Uint8Array): Uint8Array;
5189
+
5190
+ /**
5191
+ * One sealed request/answer exchange with a terminating connector (ADR 0018,
5192
+ * ADR 0019, ADR 0020) — the whole shape of a packet's payload, from the
5193
+ * envelope going out to the answer coming back, behind two functions.
5194
+ *
5195
+ * A sender's obligations on this wire are not independent of one another, and
5196
+ * getting any of them separately wrong is silent:
5197
+ *
5198
+ * - The `data` is a gift wrap addressed to the connector that TERMINATES the
5199
+ * route, around an OER envelope — never HTTP text, never a bare payload.
5200
+ * - The execution condition is `sha256` of the fulfilment DERIVED from the
5201
+ * very secret that wrap carries. A random condition would never be
5202
+ * fulfilled; an all-zero one is refused outright by the connector
5203
+ * (`connector-domain`'s `condition_is_present`), which is why the publish
5204
+ * path could not work against it at all before this module existed.
5205
+ * - The answer is sealed with that same secret, so opening it requires having
5206
+ * kept it from the seal.
5207
+ *
5208
+ * {@link sealExchange} produces all three from one call so they cannot drift
5209
+ * apart, and {@link readExchangeOutcome} is the only thing that reads the
5210
+ * answer. The secret is the token joining them.
5211
+ *
5212
+ * ─── Why the outcome is a tagged union ─────────────────────────────────────
5213
+ * ADR 0018 gives a sender something it never had: a REJECT sealed with the
5214
+ * request's own secret can ONLY have come from the termination, because only
5215
+ * the termination could recover that secret. A reject raised short of it is
5216
+ * necessarily plaintext — an intermediate hop shares no secret and cannot
5217
+ * seal. So "the destination said no" and "somebody on the path said no" are
5218
+ * now genuinely different facts, and flattening both into one error string
5219
+ * would throw away the distinction the seal was introduced to create.
5220
+ *
5221
+ * ADR 0020 draws the other line this union encodes: an HTTP status inside a
5222
+ * response envelope is envelope CONTENT, not a packet outcome. A 404 arrives
5223
+ * on a FULFILL and value moved. {@link ExchangeOutcome.Answered} therefore
5224
+ * carries any status at all, and it is the caller's business — not this
5225
+ * module's — whether a given status means its own operation succeeded.
5226
+ *
5227
+ * Pure: no I/O, no clock, no network. Randomness only through
5228
+ * {@link sealRequest}.
5229
+ */
5230
+
5231
+ /**
5232
+ * A sealed request, ready to become a PREPARE: what goes in `data`, what goes
5233
+ * on `executionCondition`, and the secret needed to read the answer.
5234
+ *
5235
+ * The three are produced together and belong together. Sending `data` under a
5236
+ * condition minted any other way produces a packet no honest connector can
5237
+ * fulfil; opening the answer with any other secret fails.
5238
+ */
5239
+ interface SealedExchange {
5240
+ /** The gift wrap to carry as the PREPARE's `data`. */
5241
+ readonly data: Uint8Array;
5242
+ /**
5243
+ * The PREPARE's `executionCondition`: `sha256(deriveFulfillment(secret))`.
5244
+ * Derived, never random and never caller-supplied — the terminating
5245
+ * connector recovers the same secret and derives the same fulfilment
5246
+ * without the app participating (ADR 0019).
5247
+ */
5248
+ readonly condition: Uint8Array;
5249
+ /**
5250
+ * The 32-byte secret sealed inside the wrap. Keep it until the answer is
5251
+ * read; it is the only thing that opens the response. Never send it
5252
+ * anywhere else, and never reuse it for a second packet.
5253
+ */
5254
+ readonly sharedSecret: Uint8Array;
5255
+ /**
5256
+ * The fulfilment the terminating connector will return. Held so a caller
5257
+ * can check the FULFILL preimage it actually got, rather than only that it
5258
+ * hashes to the condition.
5259
+ */
5260
+ readonly fulfillment: Uint8Array;
5261
+ }
5262
+ /**
5263
+ * How an exchange ended. Three outcomes, deliberately not two: a refusal's
5264
+ * ORIGIN is the fact ADR 0018 makes knowable for the first time.
5265
+ */
5266
+ type ExchangeOutcome =
5267
+ /**
5268
+ * The termination answered. `response` is whatever it said, at whatever
5269
+ * status — a non-2xx here is a real answer that was paid for (ADR 0020),
5270
+ * not a failure of the packet.
5271
+ */
5272
+ {
5273
+ readonly kind: 'answered';
5274
+ readonly response: EnvelopeResponse;
5275
+ }
5276
+ /**
5277
+ * The DESTINATION refused, provably: the reject's `data` was sealed with
5278
+ * this exchange's own secret, which only the terminating connector could
5279
+ * hold. `detail` is whatever it sealed alongside (often empty).
5280
+ */
5281
+ | {
5282
+ readonly kind: 'destination-refused';
5283
+ readonly code: string;
5284
+ readonly message: string;
5285
+ readonly detail: Uint8Array;
5286
+ }
5287
+ /**
5288
+ * Somebody ON THE PATH refused — no route, expiry, a ceiling, a rejected
5289
+ * claim — short of the termination, so nothing was sealed. Unauthenticated
5290
+ * by construction: any hop can produce this, and it should be read as a
5291
+ * hint, not a verdict from the destination.
5292
+ */
5293
+ | {
5294
+ readonly kind: 'path-refused';
5295
+ readonly code: string;
5296
+ readonly message: string;
5297
+ };
5298
+ /**
5299
+ * Why an answer that arrived could not be read. Distinct from an
5300
+ * {@link ExchangeOutcome}: these are not the destination's answer at all, but
5301
+ * bytes that failed to be one.
5302
+ */
5303
+ type SealedResponseErrorKind =
5304
+ /** A FULFILL whose `data` is absent, or does not begin with the sealed-response type byte. */
5305
+ 'not-sealed'
5306
+ /** The wrap is shaped right but does not open under this exchange's secret. */
5307
+ | 'unopenable'
5308
+ /** It opened, and what came out is not a response envelope. */
5309
+ | 'malformed-envelope';
5310
+ /** A refusal to read an answer. Never carries recovered plaintext. */
5311
+ declare class SealedResponseError extends Error {
5312
+ readonly kind: SealedResponseErrorKind;
5313
+ readonly cause?: Error | undefined;
5314
+ constructor(kind: SealedResponseErrorKind, message: string, cause?: Error | undefined);
5315
+ }
5316
+ /**
5317
+ * Seal `request` to `connectorPublicKey` — the identity of the connector that
5318
+ * TERMINATES the destination, as read from its own client edge
5319
+ * (`ConnectorEdgeClient`). Sealing to any other key is a confidentiality
5320
+ * failure that presents as an undeliverable packet.
5321
+ *
5322
+ * @param request the envelope to seal.
5323
+ * @param connectorPublicKey the terminating connector's 65-byte uncompressed
5324
+ * secp256k1 identity key.
5325
+ */
5326
+ declare function sealExchange(request: EnvelopeRequest, connectorPublicKey: Uint8Array): SealedExchange;
5327
+ /**
5328
+ * Read what came back.
5329
+ *
5330
+ * `accepted` distinguishes a FULFILL from a REJECT; `data` is the packet's
5331
+ * payload bytes, absent when it carried none. Both come straight off the
5332
+ * transport's result, so this stays testable without a socket.
5333
+ *
5334
+ * A FULFILL must be sealed and must decode: value moved, so bytes that are
5335
+ * neither are a broken counterparty, and this throws rather than inventing an
5336
+ * outcome. A REJECT is classified instead of thrown on — an unopenable one is
5337
+ * simply a path reject that happened to carry bytes.
5338
+ *
5339
+ * @throws {SealedResponseError} for a FULFILL that is not a readable sealed
5340
+ * response envelope.
5341
+ */
5342
+ declare function readExchangeOutcome(result: {
5343
+ accepted: boolean;
5344
+ code?: string;
5345
+ message?: string;
5346
+ }, data: Uint8Array | undefined, sharedSecret: Uint8Array): ExchangeOutcome;
5347
+ /** Read a response header, case-insensitively; the first match wins. */
5348
+ declare function envelopeHeader(response: EnvelopeResponse, name: string): string | undefined;
5349
+
5350
+ export { type BackupPayload, type BalanceProofParams, BtpRuntimeClient, type BtpRuntimeClientConfig, type BuildSwapSettlementsParams, CLAIM_TYPEHASH, CONDITION_LENGTH, COOP_CLOSE_TYPEHASH, type ChainMetadata, type ChainSigner, ChannelFundingError, ChannelManager, type ClaimMessage, type ClaimResolver, type ClaimSignature, ConnectorEdgeClient, type ConnectorEdgeClientConfig, ConnectorEdgeError, type ConnectorEdgeErrorCode, ConnectorError, type ConnectorIdentity, type ConnectorRoutePrice, type Decoded, type DeployMinaZkAppParams, type DiscoveredIlpPeer, type EVMClaimMessage, type EncryptedKeystore, type EnsureOwnedMinaZkAppParams, type EnsureOwnedMinaZkAppResult, type Envelope, EnvelopeError, EnvelopeErrorKind, type EnvelopeHeader, type EnvelopeRequest, type EnvelopeResponse, type EvmClaimDomainContext, type EvmClaimMessage, type EvmClaimVerifyResult, type EvmCooperativeCloseMessage, EvmSigner, type ExchangeOutcome, type ExecutionConditionPair, FULFILLMENT_MISMATCH_CODE, FULFILLMENT_MISMATCH_MESSAGE, type FaucetChain, type FundWalletOptions, type FundWalletResult, GIFTWRAP_NONCE_LENGTH, GIFTWRAP_PUBLIC_KEY_LENGTH, GIFTWRAP_SECRET_LENGTH, GIFTWRAP_TYPE_REQUEST, GIFTWRAP_TYPE_RESPONSE, type GiftWrapEcdh, GiftWrapError, GiftWrapErrorKind, type H402FetchOptions, Http402Client, type Http402ClientConfig, HttpConnectorAdmin, type HttpConnectorAdminConfig, HttpIlpClient, type HttpIlpClientConfig, type HttpIlpClientFactory, HttpRuntimeClient, type HttpRuntimeClientConfig, ILP_CLAIM_HEADER, ILP_PEER_ID_HEADER, type IlpSendParams, type IlpSendResultWithFulfillment, type IlpTransportChoice, InMemoryPreimageRetentionStore, InMemoryReceivedClaimStore, type IngestAndRevealParams, type IngestAndRevealResult, type IngestReceivedClaimsParams, type IngestReceivedClaimsResult, JsonFileReceivedClaimStore, KeyManager, type KeyManagerConfig, MINA_CHANNEL_STATE, type MinaChannelStateReader, type MinaClaimMessage, type MinaClaimSubmitArgs, type MinaClaimSubmitter, type MinaCoSignInputs, type MinaCoSignedClaim, type MinaDepositReader, type MinaOnChainChannelState, type MinaSettlementContext, MinaSettlementError, type MinaSettlementErrorCode, type MinaSettlementResult, type MinaSignaturePair, MinaSigner, type MinaSignerOptions, type MinaZkAppDeployRecord, NetworkError, OerError, OerErrorKind, OnChainChannelClient, type OnChainChannelClientConfig, type OpenedRequest, type ParsedX402Challenge, type PasskeyInfo, type PreimageRetentionStore, type PublishEventResult, ROLLING_SWAP_DOMAIN_NAME, ROLLING_SWAP_DOMAIN_VERSION, type ReceivedClaimEntry, type ReceivedClaimRejection, type ReceivedClaimRejectionCode, type ReceivedClaimStore, type RequestBlobStorageParams, type RequestBlobStorageResult, type RetainedPreimage, type RetryOptions, type RevealDecision, type RevealFn, type RevealResult, type RevealedClaim, type RolledBackClaim, type SealedExchange, type SealedRequest, SealedResponseError, type SealedResponseErrorKind, type SelectIlpTransportOptions, type SignedBalanceProof, type SolanaChannelClientOptions, type SolanaClaimMessage, SolanaSigner, type SubmitEvmSettlementParams, type SubmitEvmSettlementResult, type SwapSettlementBuild, type ToonChannelAccept, ToonClient, type ToonClientConfig, ToonClientError, type ToonIdentity, type ToonSigners, type ToonStartResult, ValidationError, type VaultData, type VerifiedReceivedClaim, type WalletBalance, type WalletBalanceSources, type WalletChainBalances, type WalletTokenAmount, applyDefaults, applyNetworkPresets, assertValidCondition, buildBackupEvent, buildBackupFilter, buildMinaCoSignedClaim, buildSettlementInfo, buildSwapSettlements, connectorEdgeBaseUrl, createO1jsMinaClaimSubmitter, decodeConnectorPublicKey, decodeEnvelope, decodeEnvelopeRequest, decodeEnvelopeResponse, decodeEvmSettlementTx, decodeVarOctetString, decodeVarUint, decryptMnemonic, defaultFaucetTimeout, deployMinaChannelZkApp, deriveCondition, deriveFromNsec, deriveFulfillment, deriveFullIdentity, deriveNostrKeyFromMnemonic, encodeEnvelope, encodeEnvelopeRequest, encodeEnvelopeResponse, encodeVarOctetString, encodeVarUint, encryptMnemonic, ensureOwnedMinaZkApp, entryToAccumulatedClaim, envelopeHeader, evmClaimDigest, evmCooperativeCloseDigest, extractArweaveTxId, fulfillmentMatchesCondition, fundWallet, generateKeystore, generateMnemonic, generateRandomIdentity, getNetworkStatus, hasSettlementMetadata, httpEndpointToBtpUrl, importKeystore, ingestAndReveal, ingestReceivedClaims, isInsufficientGasError, isPrfSupported, isZeroCondition, loadKeystore, localGiftWrapEcdh, looksLikeSealedResponse, mintExecutionCondition, openRequest, openResponse, parseBackupPayload, parseConnectorIdentity, parseConnectorRoutePrice, parseEvmChainId, parseX402Body, parseX402Challenge, proxyIlpEndpoint, readDiscoveredIlpPeer, readEvmNativeBalance, readEvmTokenBalance, readExchangeOutcome, readMinaBalance, readMinaChannelState, readMinaDepositTotal, readSolanaNativeBalance, readSolanaTokenBalance, readWalletBalances, recoverEvmClaimSigner, requestBlobStorage, sealExchange, sealRequest, sealRequestWithRandomness, sealResponse, sealResponseWithRandomness, selectIlpTransport, submitEvmSettlement, submitMinaSettlement, validateConfig, validateMnemonic, verifyEvmClaimSignature, withRetry, writeKeystoreFile };