@toon-protocol/client 0.21.3 → 0.23.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: