@toon-protocol/client 0.22.0 → 0.24.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/README.md CHANGED
@@ -6,7 +6,7 @@ The **client library** for TOON Protocol — _pay-to-write Nostr over Interledge
6
6
 
7
7
  ## Which call pays which node
8
8
 
9
- Every write is an ILP packet carrying a signed payment-channel claim. The client reaches all node types **through a relay apex** (`g.proxy`): the apex validates the claim, takes its fee, and forwards the packet to the destination node, which returns FULFILL (accepted) or REJECT. The method you call determines which node type you pay:
9
+ Every write is an ILP packet carrying a signed payment-channel claim, and its payload is **sealed to the connector that terminates the destination** (see [How a paid write works](#how-a-paid-write-works-the-sealed-wire)). The client reaches all node types **through a relay apex** (`g.proxy`): the apex validates the claim, takes its fee, and forwards the packet to the destination node, which returns FULFILL (accepted) or REJECT. The method you call determines which node type you pay:
10
10
 
11
11
  | Client call | Node type | What it does |
12
12
  | --------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -19,6 +19,7 @@ Every write is an ILP packet carrying a signed payment-channel claim. The client
19
19
  This client handles:
20
20
 
21
21
  - **ILP Micropayments**: Pay to publish Nostr events (reads are free)
22
+ - **The sealed wire**: Every paid write is an OER envelope gift-wrapped to the terminating connector's identity key, under an execution condition derived from the secret inside that wrap — see [How a paid write works](#how-a-paid-write-works-the-sealed-wire)
22
23
  - **Payment Channels**: Automatic on-chain channel creation with off-chain settlement via signed balance proofs
23
24
  - **Unified Identity**: One Nostr key = one EVM address (both secp256k1, derived automatically) — or a single BIP-39 **mnemonic** to derive a full multi-chain identity
24
25
  - **Multi-Chain Settlement**: Sign payment-channel claims on EVM (EIP-712), Solana (Ed25519), and Mina (Pallas) from one mnemonic. A relay apex validates the claim and redeems it on-chain on the matching chain (EVM/Solana credit the recipient; Mina redeems each claim on-chain with recipient credit-at-close deferred — see [Multi-Chain Settlement notes](#identity--multi-chain-settlement))
@@ -43,7 +44,11 @@ pnpm add mina-signer
43
44
  - **A TOON apex to pay.** You don't run any node yourself; you connect to a running
44
45
  [`@toon-protocol/relay`](https://www.npmjs.com/package/@toon-protocol/relay) apex (or any
45
46
  TOON connector) and pay it. From its operator you need:
46
- - a **connector endpoint** — an HTTP `connectorUrl` and/or a BTP WebSocket `btpUrl`;
47
+ - a **connector endpoint** — an HTTP `connectorUrl` (or `proxyUrl`), optionally plus a BTP
48
+ WebSocket `btpUrl`. The HTTP client edge is **required even when packets travel over BTP**:
49
+ the identity a payload is sealed to and the price of a route are read from `GET /ilp/identity`
50
+ and `GET /ilp/routes/price` on it. Without one, `publishEvent` raises `NO_CONNECTOR_EDGE`
51
+ before forming a packet;
47
52
  - a **settlement-chain RPC URL** and a **funded key** on that chain, so the client can open a
48
53
  payment channel and sign EIP-712 claims;
49
54
  - the **token** and **TokenNetwork** contract addresses that apex accepts on that chain (e.g. USDC).
@@ -117,6 +122,199 @@ await client.stop();
117
122
 
118
123
  ---
119
124
 
125
+ ## How a paid write works (the sealed wire)
126
+
127
+ `publishEvent` does all of this for you. It is spelled out because every step shows up in
128
+ the result, and because each piece is exported for anyone forming a packet by hand.
129
+
130
+ A paid write used to be an HTTP/1.1 request as **text** in `Prepare.data`, under an all-zero
131
+ execution condition. Both are gone. A write is now an **OER envelope, gift-wrapped to the
132
+ identity of the connector that terminates the destination**, under a condition **derived from
133
+ the secret inside that wrap**. The rules come from the connector's ADRs — sealing
134
+ ([0018](https://github.com/toon-protocol/connector/blob/main/docs/adr/0018-a-payload-is-sealed-to-the-terminating-connector.md)),
135
+ fulfilment derivation
136
+ ([0019](https://github.com/toon-protocol/connector/blob/main/docs/adr/0019-a-terminating-connector-derives-the-fulfilment.md)),
137
+ flat pricing
138
+ ([0020](https://github.com/toon-protocol/connector/blob/main/docs/adr/0020-a-price-is-flat-and-attaches-to-a-handler.md)),
139
+ vectors as the normative contract
140
+ ([0021](https://github.com/toon-protocol/connector/blob/main/docs/adr/0021-vectors-are-normative-prose-is-not.md)),
141
+ and answering-but-not-announcing
142
+ ([0022](https://github.com/toon-protocol/connector/blob/main/docs/adr/0022-a-connector-answers-it-does-not-announce.md)).
143
+
144
+ The ILP layer around it is unchanged: same `POST /ilp`, same PREPARE/FULFILL/REJECT, same
145
+ `ILP-Payment-Channel-Claim` header, same channels and watermarks. Only `data` and the
146
+ condition changed.
147
+
148
+ ### 1. Ask the connector who it is
149
+
150
+ A packet cannot be formed without the terminating connector's public key, and there is no
151
+ default to fall back on: sealing to the wrong key is a **confidentiality** failure that merely
152
+ _presents_ as an undeliverable packet. A connector answers when asked and never announces, so
153
+ the key is read straight off its client edge — the same origin the client `POST`s `/ilp` to.
154
+
155
+ ```typescript
156
+ import { ConnectorEdgeClient } from '@toon-protocol/client';
157
+
158
+ const edge = new ConnectorEdgeClient(); // { fetch?, timeout? }
159
+
160
+ // GET /ilp/identity — cached per endpoint; 'http://apex/ilp' and 'http://apex' are the same edge
161
+ const identity = await edge.getIdentity('http://localhost:8080');
162
+ identity.publicKey; // Uint8Array, exactly 65 bytes, SEC1-uncompressed secp256k1 (leading 0x04)
163
+ identity.keyId; // opaque to this client
164
+ ```
165
+
166
+ A key of the wrong length, without the `0x04` tag, or not `0x`-hex is refused with a
167
+ `ConnectorEdgeError` (`IDENTITY_KEY_LENGTH`, `IDENTITY_KEY_NOT_UNCOMPRESSED`,
168
+ `IDENTITY_KEY_NOT_HEX`) rather than carried forward — there is no best-effort reading of a
169
+ public key. An unreachable edge throws `NetworkError` instead, so "will not seal to that" and
170
+ "could not ask" are never confused. Rotation is a deliberate event, so nothing expires on a
171
+ timer: `invalidateIdentity(endpoint?)` is how a stale key is dropped.
172
+
173
+ ### 2. Ask the route what it costs
174
+
175
+ There is no per-byte rate to multiply any more. A price is **flat per handler** — one handler,
176
+ one price, and an app that wants to charge differently exposes more handlers — so the route
177
+ table *is* the price list and only the connector can state it:
178
+
179
+ ```typescript
180
+ // GET /ilp/routes/price?destination= — cached per (endpoint, destination)
181
+ const quote = await edge.getRoutePrice('http://localhost:8080', 'g.proxy.relay');
182
+ quote?.price; // bigint, in ILP base units — the whole fee for ONE packet
183
+
184
+ // Or, from a started client, against the edge it already resolved:
185
+ const price = await client.getRoutePrice('g.proxy.relay'); // bigint | null
186
+ ```
187
+
188
+ `null` means the connector terminates no route matching that destination — an answer, not a
189
+ failure, and distinct from the `NetworkError` an unreachable edge throws. `publishEvent`
190
+ raises `NO_TERMINATED_ROUTE` on it before any packet exists. This is the same longest-prefix
191
+ lookup the claim gate charges against, so it cannot quote a price a real request would not be
192
+ charged; use it for a pre-write estimate that is guaranteed to equal what the write pays.
193
+
194
+ ### 3. Seal the envelope and mint the condition together
195
+
196
+ `sealExchange` produces the wrap, the condition and the secret in one call, because getting
197
+ any of them separately wrong is silent. A random condition would never be fulfilled; an
198
+ all-zero one the connector refuses outright.
199
+
200
+ ```typescript
201
+ import { sealExchange } from '@toon-protocol/client';
202
+
203
+ const exchange = sealExchange(
204
+ {
205
+ method: 'POST',
206
+ target: '/write', // the terminated route's handler; '/store' for the Arweave store
207
+ headers: [['content-type', 'application/json']],
208
+ body: new TextEncoder().encode(JSON.stringify({ event })),
209
+ },
210
+ identity.publicKey,
211
+ );
212
+
213
+ exchange.data; // Uint8Array — the gift wrap, to carry as the PREPARE's `data`
214
+ exchange.condition; // Uint8Array — sha256(deriveFulfillment(sharedSecret))
215
+ exchange.sharedSecret; // Uint8Array(32) — keep it; nothing else opens the answer
216
+ exchange.fulfillment; // Uint8Array — the preimage the connector will return
217
+ ```
218
+
219
+ The condition is exactly `deriveCondition(deriveFulfillment(secret))`, and both are exported
220
+ if you want to check the derivation yourself:
221
+
222
+ ```typescript
223
+ import { deriveCondition, deriveFulfillment } from '@toon-protocol/client';
224
+
225
+ // deriveFulfillment = HKDF-SHA256(sharedSecret, "toon-giftwrap-fulfillment"), 32 bytes
226
+ // deriveCondition = sha256 of that fulfilment
227
+ deriveCondition(deriveFulfillment(exchange.sharedSecret)); // === exchange.condition
228
+ ```
229
+
230
+ The terminating connector opens the wrap, recovers the same secret and derives the same
231
+ preimage — **the app behind the route supplies nothing and holds no key**, which is what keeps
232
+ "any HTTP service is a TOON node app" true. Never reuse a secret for a second packet.
233
+
234
+ ### 4. Send it, then open the answer with the same secret
235
+
236
+ `exchange.data` goes on the PREPARE as base64 `data` and `exchange.condition` as its
237
+ `executionCondition`; the claim rides in the `ILP-Payment-Channel-Claim` header as before.
238
+ Whatever comes back — a FULFILL or a REJECT — is read by one function:
239
+
240
+ ```typescript
241
+ import { readExchangeOutcome, envelopeHeader } from '@toon-protocol/client';
242
+
243
+ // `sent` is the transport's `{ accepted, code?, message? }`; `payload` is the packet's
244
+ // data bytes (`undefined` when it carried none).
245
+ const outcome = readExchangeOutcome(sent, payload, exchange.sharedSecret);
246
+
247
+ switch (outcome.kind) {
248
+ case 'answered':
249
+ outcome.response.status; // number — any status; a non-2xx is still a paid answer
250
+ outcome.response.headers; // readonly [name, value][]
251
+ outcome.response.body; // Uint8Array
252
+ envelopeHeader(outcome.response, 'content-type'); // case-insensitive lookup
253
+ break;
254
+ case 'destination-refused': // provable: only the termination could have sealed this
255
+ outcome.code, outcome.message, outcome.detail;
256
+ break;
257
+ case 'path-refused': // unauthenticated by construction — a hint, not a verdict
258
+ outcome.code, outcome.message;
259
+ break;
260
+ }
261
+ ```
262
+
263
+ A FULFILL
264
+ that is not a readable sealed response envelope throws `SealedResponseError`, whose `kind` is
265
+ `'not-sealed'`, `'unopenable'` or `'malformed-envelope'` — value moved, so bytes that are none
266
+ of those mean a broken counterparty rather than an outcome to invent.
267
+
268
+ **A reject raised short of the termination is plaintext, and that is distinguishable.** Only
269
+ the terminating connector holds the shared secret, so only it can seal a refusal; an
270
+ intermediate hop rejecting for no-route, expiry, a ceiling or a rejected claim shares no secret
271
+ and cannot seal anything. A reject whose `data` actually **opens** under this packet's secret
272
+ is therefore proof the destination said no — a leading type byte alone is a claim, not
273
+ evidence, and one that fails to open is classified as a path reject. This distinction did not
274
+ exist before the seal, and it is why the outcome is a three-way union rather than one error
275
+ string.
276
+
277
+ ### What `publishEvent` returns
278
+
279
+ ```typescript
280
+ const result = await client.publishEvent(event, {
281
+ destination: 'g.proxy.relay', // defaults to config.destinationAddress
282
+ claim, // optional pre-signed balance proof; otherwise auto-signed
283
+ ilpAmount: 1000n, // optional override — skips the route-price lookup entirely
284
+ proxyPath: '/write', // request-target inside the envelope ('/store' for the store)
285
+ });
286
+
287
+ result.success; // false for a rejected packet AND for a non-2xx answer
288
+ result.eventId; // set on success
289
+ result.response; // EnvelopeResponse — the opened answer; present whenever the packet FULFILLED
290
+ result.refusedBy; // 'destination' (provable) | 'path' (unauthenticated), when rejected
291
+ result.code; // the ILP reject code, when rejected
292
+ ```
293
+
294
+ An HTTP status inside the response envelope is envelope **content**, not a packet outcome: a
295
+ 404 rides home on a FULFILL and value moved. `publishEvent` still reports that as
296
+ `success: false` — the event did not persist — but `response` is populated either way, so you
297
+ can see exactly what you paid for.
298
+
299
+ ### Conformance
300
+
301
+ `src/wire/` is held to the connector's committed cross-repo vector set, vendored at
302
+ [`src/wire/vectors/`](src/wire/vectors/README.md) and SHA-256 pinned: reproducing those bytes
303
+ is what conformance means here. `pnpm --filter @toon-protocol/client vectors:check` compares
304
+ the vendored copy against connector `main`, and a CI job runs it daily and on any PR touching
305
+ `src/wire/**`.
306
+
307
+ ### Removed with the plaintext path
308
+
309
+ `buildStoreWriteEnvelope`, `parseFulfillHttp`, `parseFulfillHttpBytes`, `ParsedFulfillHttp`,
310
+ `serializeHttpRequest`, `parseHttpResponse` and `ILP_CLAIM_WRAPPED_HEADER` are gone — no HTTP
311
+ text is serialised or parsed anywhere in this package. `PublishEventResult.data` (raw base64
312
+ FULFILL bytes) became `response`, and `extractArweaveTxId` now takes that `EnvelopeResponse`
313
+ rather than a base64 string. Per-byte pricing is gone with them: `basePricePerByte`,
314
+ `uploadFeePerByte`, `minUploadFee` and `flooredUploadFee` have no successor.
315
+
316
+ ---
317
+
120
318
  ## Identity & Multi-Chain Settlement
121
319
 
122
320
  There are two ways to give the client an identity:
package/dist/index.d.ts CHANGED
@@ -1194,6 +1194,35 @@ interface ConnectorIdentity {
1194
1194
  /** The normalized client-edge base URL this identity was read from. */
1195
1195
  endpoint: string;
1196
1196
  }
1197
+ /**
1198
+ * The channel-opening facts a settling connector carries in its x402
1199
+ * greeting (connector #617): everything a buyer needs to OPEN a channel
1200
+ * with the node, learned by ASKING (ADR 0022) rather than from a
1201
+ * kind:10032 announce the Rust fleet never makes.
1202
+ */
1203
+ interface ConnectorSettlementTerms {
1204
+ /** `evm:<chainId>` — the chain the node's settlement backend runs on. */
1205
+ chain: string;
1206
+ /** The on-chain counterparty a buyer opens a channel WITH. */
1207
+ settlementAddress: string;
1208
+ /** The stable TokenNetworkRegistry factory address. */
1209
+ tokenNetworkRegistry: string;
1210
+ /** The resolved TokenNetwork — the EIP-712 verifyingContract. */
1211
+ tokenNetwork: string;
1212
+ tokenAddress: string;
1213
+ /** Informational; claims are already in base units. */
1214
+ decimals: number;
1215
+ }
1216
+ /**
1217
+ * A route's terms as the x402 greeting states them: the price, plus (from a
1218
+ * settling node) the channel-opening facts. `settlement` is absent exactly
1219
+ * when the node has no settlement backend — the wire's own shape.
1220
+ */
1221
+ interface ConnectorRouteTerms {
1222
+ destination: string;
1223
+ price: string;
1224
+ settlement?: ConnectorSettlementTerms;
1225
+ }
1197
1226
  /** What a locally-terminated route costs, as reported by `GET /ilp/routes/price`. */
1198
1227
  interface ConnectorRoutePrice {
1199
1228
  /** The ILP destination that was asked about (echoed by the connector). */
@@ -1223,7 +1252,11 @@ type ConnectorEdgeErrorCode =
1223
1252
  /** `GET /ilp/routes/price` answered 2xx with a body that is not the documented object. */
1224
1253
  | 'ROUTE_PRICE_MALFORMED'
1225
1254
  /** A destination that cannot be put in a query string was asked about. */
1226
- | 'INVALID_DESTINATION';
1255
+ | 'INVALID_DESTINATION'
1256
+ /** A 402 greeting whose body is not the documented x402 shape (or whose
1257
+ * optional `settlement` facts are present but malformed — refused rather
1258
+ * than silently dropped, since they would be opened AGAINST). */
1259
+ | 'TERMS_MALFORMED';
1227
1260
  /**
1228
1261
  * A refusal to carry a connector's answer forward. Distinct from
1229
1262
  * {@link NetworkError} (which this module throws for a transport failure), so
@@ -1319,6 +1352,19 @@ declare class ConnectorEdgeClient {
1319
1352
  getRoutePrice(endpoint: string, destination: string, options?: {
1320
1353
  forceRefresh?: boolean;
1321
1354
  }): Promise<ConnectorRoutePrice | null>;
1355
+ /**
1356
+ * Ask a route for its full x402 terms — the greeting a claimless PREPARE
1357
+ * is answered with (client-edge-spec.md §1.4) — including, from a settling
1358
+ * node, the channel-opening facts (connector #617).
1359
+ *
1360
+ * This is a real `POST /ilp` carrying a minimal PREPARE with no claim
1361
+ * header. It is free by the wire's own contract: an unpaid request to a
1362
+ * priced route is answered with terms instead of performed, and nothing
1363
+ * is charged for asking. `null` when the connector does not price the
1364
+ * destination (the request would be routed or refused, not greeted) —
1365
+ * mapped from anything other than a 402 answer.
1366
+ */
1367
+ getRouteTerms(endpoint: string, destination: string): Promise<ConnectorRouteTerms | null>;
1322
1368
  /**
1323
1369
  * Drop a cached route price — one (endpoint, destination)'s, every
1324
1370
  * destination's at one endpoint when `destination` is omitted, or all of
@@ -1941,8 +1987,10 @@ declare class ToonClient {
1941
1987
  destination?: string;
1942
1988
  claim?: SignedBalanceProof;
1943
1989
  ilpAmount?: bigint;
1944
- /** Request-target inside the envelope (default '/write', the relay;
1945
- * use '/store' for the Arweave store backend). */
1990
+ /** Sub-path resolved strictly BENEATH the route's handler path (ADR
1991
+ * 0025). Default '' — the handler's own path, correct whenever the
1992
+ * destination terminates at exactly one endpoint. Never absolute:
1993
+ * a leading '/' is refused by the connector (F00). */
1946
1994
  proxyPath?: string;
1947
1995
  }): Promise<PublishEventResult>;
1948
1996
  /**
@@ -2250,6 +2298,32 @@ declare class ToonClient {
2250
2298
  * Convention: destination "g.toon.peer1" → peerId "peer1" (last segment).
2251
2299
  * Falls back to first known peer if no match.
2252
2300
  */
2301
+ /**
2302
+ * The peer id a claim for `destination` accounts under. Normally
2303
+ * `resolvePeerId` — but where that throws `PEER_NOT_FOUND` (an empty
2304
+ * negotiation map: nothing announced, nothing registered), the
2305
+ * destination itself is the key, so the announce-less greeting bootstrap
2306
+ * (connector #617) has a stable identity to remember its synthesized
2307
+ * negotiation under.
2308
+ */
2309
+ private peerIdForClaim;
2310
+ /**
2311
+ * The announce-less channel bootstrap (connector #617): when nothing has
2312
+ * negotiated with this destination's peer — no kind:10032 announce, no
2313
+ * connector-admin registration — ask the route itself. A settling
2314
+ * connector's x402 greeting carries the channel-opening facts, and ADR
2315
+ * 0022 makes the greeting the ONLY place the Rust fleet will ever state
2316
+ * them. Synthesizes a {@link PeerNegotiation} from those facts, remembers
2317
+ * it, and returns it; `undefined` when there is no edge to ask, the
2318
+ * greeting carries no settlement facts, or the chain is not one this
2319
+ * client opens channels on (EVM only today — Solana/Mina channel opening
2320
+ * still needs announce-shaped metadata).
2321
+ *
2322
+ * Never throws: this is a fallback on a path that already has a precise
2323
+ * error (`PEER_NOT_NEGOTIATED`), and a transport failure while ASKING
2324
+ * must not mask it.
2325
+ */
2326
+ private negotiateFromGreeting;
2253
2327
  private resolvePeerId;
2254
2328
  /**
2255
2329
  * Extracts chain context (chainId + tokenNetworkAddress) from a chain key like 'evm:base:421614'.