@toon-protocol/client 0.29.8 → 2.1.1

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
@@ -1,648 +1,54 @@
1
1
  # @toon-protocol/client
2
2
 
3
- The **client library** for TOON Protocol — _pay-to-write Nostr over Interledger (ILP)_. Use it to **pay for and publish** writes to a network of service nodes. **Reads are free; writes cost a signed EIP-712 payment-channel claim** against an on-chain deposit.
3
+ Pay for an HTTP request, per request, in stablecoin. A **connector** is a paid reverse proxy:
4
+ it fronts an ordinary HTTP app, charges a flat price per route, and hands that app a request
5
+ that was already paid for. This package is the payer, as a library and as the `toon` CLI.
4
6
 
5
- > **`client` vs `relay`.** This package (`@toon-protocol/client`) is what an _app or end user_ uses to **pay** and publish. It does **not** run any relay or node. The nodes are operated separately by **`@toon-protocol/relay`** (the operator product, which runs an _apex_ connector plus `relay` / `swap` / `store` children). Don't confuse the **client** (pays) with **`@toon-protocol/relay`** (operates a node cluster), or the **relay** child node (a single Nostr-WS node) with the full **relay** operator stack.
6
-
7
- ## Which call pays which node
8
-
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
-
11
- | Client call | Node type | What it does |
12
- | --------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
13
- | `client.publishEvent(event)` | **relay** | Publish a Nostr event (e.g. `kind:1`) to the relay. |
14
- | `requestBlobStorage(client, …)` | **store** | NIP-90 compute/storage. Builds and publishes a `kind:5094` event that uploads a blob to Arweave — the job request **is** the payment — and decodes the Arweave tx ID from the FULFILL response. |
15
- | `client.sendSwapPacket(…)` | **swap** | Multi-chain token swap (low-level). Most callers use the higher-level `streamSwap()` from `@toon-protocol/sdk`, which is built on `sendSwapPacket`. |
16
-
17
- ## What It Does
18
-
19
- This client handles:
20
-
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)
23
- - **Payment Channels**: Automatic on-chain channel creation with off-chain settlement via signed balance proofs
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
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))
26
- - **Multi-Hop Routing**: Publish to any destination address (`destination` / `destinationAddress`), not just your direct peer
27
- - **Network Bootstrap**: Automatically discover and register with ILP peers via NIP-02 follow lists
28
- - **TOON Encoding**: Native binary format for agent-friendly event encoding
29
-
30
- ## Installation
7
+ ## Install
31
8
 
32
9
  ```bash
33
- pnpm add @toon-protocol/client @toon-protocol/core @toon-protocol/relay nostr-tools
34
-
35
- # Optional — only needed to derive/sign on Mina (Pallas):
36
- pnpm add mina-signer
10
+ npm install @toon-protocol/client
37
11
  ```
38
12
 
39
- ## Prerequisites
40
-
41
- **Reading is free** — to subscribe/query you need nothing but this package. To **write (pay)** you need:
42
-
43
- - **Node.js ≥ 20** — these packages are ESM.
44
- - **A TOON apex to pay.** You don't run any node yourself; you connect to a running
45
- [`@toon-protocol/relay`](https://www.npmjs.com/package/@toon-protocol/relay) apex (or any
46
- TOON connector) and pay it. From its operator you need:
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;
52
- - a **settlement-chain RPC URL** and a **funded key** on that chain, so the client can open a
53
- payment channel and sign EIP-712 claims;
54
- - the **token** and **TokenNetwork** contract addresses that apex accepts on that chain (e.g. USDC).
55
-
56
- These coordinates go straight into the [`ToonClient` config](#quick-start) below.
13
+ ## Example
57
14
 
58
- > **Local development (from a clone of this repo, not the npm package).** To try the client
59
- > end-to-end against a throwaway local network — Anvil + two peer nodes + relays — see
60
- > [`packages/client/tests/e2e/README.md`](tests/e2e/README.md) for the service topology and manual
61
- > testing snippet. Its automated setup steps assume the monorepo's `scripts/sdk-e2e-infra.sh`
62
- > wrapper and a `docker-compose-sdk-e2e.yml`, neither of which ships in this extracted repo; treat
63
- > those steps as a reference for provisioning the equivalent infrastructure yourself.
64
- >
65
- > | Service | Port | Purpose |
66
- > | ---------------- | ----- | --------------------------------------------------- |
67
- > | **Anvil** | 18545 | Local EVM chain (chain ID 31337) |
68
- > | **Peer 1 BLS** | 19100 | Validates events, calculates pricing, stores events |
69
- > | **Peer 1 Relay** | 19700 | WebSocket relay for peer discovery (kind:10032) |
70
- > | **Peer 2 BLS** | 19110 | Validates events, calculates pricing, stores events |
71
- > | **Peer 2 Relay** | 19710 | WebSocket relay for peer discovery (kind:10032) |
72
- >
73
- > The Quick Start below is wired for this local stack (chain `evm:anvil:31337`, TokenNetwork
74
- > `0xCafac3dD…052c`); swap in your apex's real coordinates for any other network.
75
-
76
- ---
77
-
78
- ## Quick Start
79
-
80
- ```typescript
15
+ ```ts
81
16
  import { ToonClient } from '@toon-protocol/client';
82
- import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure';
83
- import { encodeEventToToon, decodeEventFromToon } from '@toon-protocol/relay';
84
-
85
- // 1. Generate identity — one key gives you both Nostr and EVM identities
86
- const secretKey = generateSecretKey();
87
- const pubkey = getPublicKey(secretKey);
88
-
89
- // 2. Create client
90
- const client = new ToonClient({
91
- connectorUrl: 'http://localhost:8080',
92
- secretKey,
93
- ilpInfo: {
94
- pubkey,
95
- ilpAddress: `g.toon.${pubkey.slice(0, 8)}`,
96
- btpEndpoint: 'ws://localhost:3000',
97
- },
98
- toonEncoder: encodeEventToToon,
99
- toonDecoder: decodeEventFromToon,
100
- });
101
-
102
- // 3. Start (bootstrap network, discover peers)
103
- await client.start();
104
-
105
- // Your EVM address is derived from the same key — no separate config needed
106
- console.log(`EVM address: ${client.getEvmAddress()}`);
107
-
108
- // 4. Publish event to relay via ILP payment
109
- const event = finalizeEvent(
110
- { kind: 1, content: 'Hello from TOON!', tags: [], created_at: Math.floor(Date.now() / 1000) },
111
- secretKey,
112
- );
113
-
114
- const result = await client.publishEvent(event);
115
- if (result.success) {
116
- console.log(`Published: ${result.eventId}`);
117
- }
118
-
119
- // 5. Clean up
120
- await client.stop();
121
- ```
122
-
123
- ---
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
17
 
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)
18
+ const client = await ToonClient.create({
19
+ connector: 'https://proxy.ario.devnet.toonprotocol.dev',
20
+ mnemonic: process.env.TOON_MNEMONIC,
21
+ channelStore: `${process.env.HOME}/.toon/channels.json`,
285
22
  });
286
23
 
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
-
318
- ## Identity & Multi-Chain Settlement
319
-
320
- There are two ways to give the client an identity:
321
-
322
- ### 1. Raw `secretKey` — Nostr + EVM (secp256k1)
323
-
324
- A 32-byte Nostr key. Because Nostr and EVM both use secp256k1, the same key provides your EVM identity automatically. This is the path shown in the Quick Start, and it only supports EVM settlement.
325
-
326
- ### 2. `mnemonic` — full multi-chain identity (recommended for non-EVM)
327
-
328
- A single BIP-39 phrase derives **all** chain identities: Nostr (NIP-06) + EVM (secp256k1), Solana (Ed25519), and Mina (Pallas). This is required to settle on Solana or Mina — a raw secp256k1 `secretKey` cannot represent those curves.
329
-
330
- ```typescript
331
- import { ToonClient, generateMnemonic, deriveFullIdentity } from '@toon-protocol/client';
332
- import { encodeEventToToon, decodeEventFromToon } from '@toon-protocol/relay';
333
-
334
- const mnemonic = generateMnemonic(); // or restore an existing 12-word phrase
335
- const { nostr } = await deriveFullIdentity(mnemonic); // peek at the derived keys if needed
336
-
337
- const client = new ToonClient({
338
- connectorUrl: 'http://localhost:8080',
339
- mnemonic, // derives Nostr/EVM synchronously; Solana/Mina during start()
340
- ilpInfo: {
341
- pubkey: nostr.pubkey,
342
- ilpAddress: `g.toon.${nostr.pubkey.slice(0, 8)}`,
343
- btpEndpoint: 'ws://localhost:3000',
344
- },
345
- toonEncoder: encodeEventToToon,
346
- toonDecoder: decodeEventFromToon,
347
- });
348
-
349
- await client.start();
350
-
351
- // EVM is available before start(); Solana/Mina are derived during start()
352
- console.log('Nostr: ', client.getPublicKey());
353
- console.log('EVM: ', client.getEvmAddress());
354
- console.log('Solana:', client.getSolanaAddress()); // base58, after start()
355
- console.log('Mina: ', client.getMinaAddress()); // base58, after start() (needs mina-signer)
356
- ```
357
-
358
- **Notes & rules:**
359
-
360
- - **Precedence**: `mnemonic` and `secretKey` are mutually exclusive (a separate `secretKey` would split the Nostr identity from the Solana/Mina identity — the client rejects it). An `evmPrivateKey` override **is** allowed alongside `mnemonic` (e.g. a hardware-wallet EVM key while still deriving Solana/Mina from the phrase).
361
- - **Solana/Mina addresses** (`getSolanaAddress()`, `getMinaAddress()`) are only available **after `start()`** — those keys are derived asynchronously. `getEvmAddress()`/`getPublicKey()` work before `start()`.
362
- - **Mina is optional**: it requires the `mina-signer` peer dependency (see Installation). Without it, the client still works for Nostr/EVM/Solana and `getMinaAddress()` returns `undefined`.
363
- - **Security**: JavaScript strings can't be zeroed from memory, so a `mnemonic` may linger in the heap. For high-security contexts, derive keys yourself (e.g. via `KeyManager`) and pass a pre-derived `secretKey`.
364
- - **Per-chain claim formats.** Each publish carries a balance-proof claim in the format that destination chain's connector verifier expects — EVM via EIP-712, Solana as a raw Ed25519 message over the on-chain payment-channel message (`channel_pda ‖ nonce ‖ transferredAmount`), Mina as a Pallas-Schnorr claim over a Poseidon `balanceCommitment`. `ToonClient` selects the right signer for the negotiated channel automatically; you do not pick the format. Canonical layouts live in `@toon-protocol/core` (`packages/core/src/settlement/`) so client signers and connector verifiers cannot drift.
365
- - **On-chain redemption is automatic, and driven by the apex — not the client.** You sign off-chain claims; the relay apex validates them, fulfills, and (once a per-channel threshold is crossed) submits the on-chain redemption itself. EVM and Solana credit the recipient on-chain (Solana at channel close, `SETTLE_CHANNEL`). On **Mina** each paid publish redeems on-chain (`claimFromChannel`, the apex co-signs the counterparty signature; the zkApp nonce and balance commitment advance), and **the recipient's tokens are credited at channel close** via the Story 34.4 fund-custody zkApp (`@toon-protocol/connector` ≥3.10.0): the deposit is escrowed on the zkApp account and `settle()` drains it to the participants (recipient + depositor refund). Verified against `@toon-protocol/connector` 3.10.0.
366
-
367
- ---
24
+ await client.channel.open({ deposit: 100_000n }); // 100000 base units (0.10 USDC)
368
25
 
369
- ## Uploading a blob to a DVM (Arweave storage)
370
-
371
- To store a blob permanently on Arweave, pay a **store** node with a `kind:5094` NIP-90 request. The `requestBlobStorage` helper builds the signed event, publishes it through your `ToonClient` (reusing its claim/channel plumbing), and decodes the Arweave transaction ID from the FULFILL response:
372
-
373
- ```typescript
374
- import { ToonClient, requestBlobStorage } from '@toon-protocol/client';
375
-
376
- // `client` is a started ToonClient (see Quick Start). `secretKey` signs the kind:5094 event.
377
- const result = await requestBlobStorage(client, secretKey, {
378
- blobData: new Uint8Array([1, 2, 3, 4]),
379
- contentType: 'application/octet-stream',
380
- ilpAmount: 50_000n, // USDC micro-units; also used as the event's `bid` if `bid` is omitted
381
- destination: 'g.toon.peer1', // the store node's ILP address (defaults to the client's destinationAddress)
382
- });
383
-
384
- if (result.success) {
385
- console.log(`Stored on Arweave: https://arweave.net/${result.txId}`);
26
+ const answer = await client.send({ body: 'hello' });
27
+ if (answer.fulfilled) {
28
+ console.log(answer.status, answer.text()); // the app's own HTTP response
29
+ console.log(answer.claim.amount); // 1000n base units (0.001 USDC)
386
30
  } else {
387
- console.error(`Upload failed: ${result.error}`);
31
+ console.log(answer.code, answer.message); // a refusal, not an exception
388
32
  }
389
- ```
390
-
391
- `requestBlobStorage(client, secretKey, params)` returns `{ success, txId?, eventId?, error? }` (`RequestBlobStorageParams` / `RequestBlobStorageResult` are exported for typing). It covers the **single-packet** case; for large chunked uploads, drive `client.publishEvent()` with `kind:5094` events directly.
392
-
393
- ---
394
-
395
- ## Hashlock delivery (factory job increments)
396
-
397
- Factory job increments (`toon-meta#262` decision 5, `docs/factory-job-protocol.md` §4 in `toon-meta`) are delivered atomically: the provider encrypts the increment's artifact and sets the ILP `executionCondition` to `sha256(key)`. Revealing `key` to claim payment and handing the buyer the decryption key are the same act — neither party moves first. `encryptArtifact` / `fulfillIncrement` / `decryptArtifact` / `buildIncrementPrepare` are the only place this join is implemented, so a caller cannot accidentally derive a condition from anything other than the key that decrypts the artifact:
398
-
399
- ```typescript
400
- import {
401
- encryptArtifact,
402
- fulfillIncrement,
403
- decryptArtifact,
404
- buildIncrementPrepare,
405
- } from '@toon-protocol/client';
406
33
 
407
- // Provider: encrypt the increment, upload `ciphertext` to Arweave, advertise
408
- // `toHex(condition)` on the kind:7000 offer's `condition` tag.
409
- const { ciphertext, key, condition } = encryptArtifact(artifactBytes);
410
-
411
- // Buyer: turn the offer's advertised `condition`/`amount` tags into PREPARE
412
- // fields, then pay with client.sendSwapPacket({ destination, ...prepare, toonData }).
413
- const prepare = buildIncrementPrepare({ conditionHex, amountUsdc });
414
-
415
- // Provider: reveal `key` as the FULFILL's fulfillment.
416
- const fulfillment = fulfillIncrement(key);
417
-
418
- // Buyer: verify against the condition it actually PAID (not one re-derived
419
- // from `key`), then decrypt.
420
- const artifact = decryptArtifact(ciphertext, fulfillment, prepare.executionCondition);
421
- ```
422
-
423
- `decryptArtifact` throws `HashlockConditionMismatchError` when `sha256(key)` doesn't match the paid condition, and `HashlockDecryptError` on a tampered/corrupted ciphertext — neither error ever carries the key.
424
-
425
- ---
426
-
427
- ## Earning: serve paid jobs and read credited balance
428
-
429
- `toon-meta#262` ("agents earning") is the other direction: registering as a provider, receiving a job, and reading what it earned. The connector originates a BTP MESSAGE carrying a PREPARE for this client's own ILP address (RFC-0023's symmetric grammar) instead of the client always being the one to send one.
430
-
431
- **Serving a job.** Configure `jobHandler` — a plain function, never a payments integration (the app stays payment-oblivious, mirroring `connector-runtime/src/app_client.rs`'s handler contract). It receives the job's data and returns the fulfillment preimage it already minted at quote time (reuse `encryptArtifact`/`fulfillIncrement` above — this library never derives a condition/preimage relationship a second time):
432
-
433
- ```typescript
434
- const client = new ToonClient({
435
- // ...
436
- btpUrl: 'wss://apex.example/ilp/btp',
437
- jobHandler: async (job) => {
438
- // job: { amount, destination, executionCondition, expiresAt, data }
439
- const key = lookUpKeyForThisIncrement(job); // minted earlier via encryptArtifact
440
- return { fulfillment: fulfillIncrement(key), data: answerBytes };
441
- },
442
- });
34
+ await client.close();
443
35
  ```
444
36
 
445
- A handler that throws, or whose fulfillment does not satisfy `job.executionCondition`, answers the PREPARE with an `F99` REJECT (RFC-0027's own "Application Error" code) — never left unanswered. An already-expired PREPARE is refused `R00` without ever invoking the handler.
446
-
447
- **Reading the credited balance.** Earnings net off-chain on the same channel a client spends from (decision 9) — there is no separate "earned" ledger to read. `getClaimState()` asks the connector's `POST /ilp/claim-state` (the same runway source of truth `#261` already established) for the netted deposit/claimed/available position of one or more tracked channels:
448
-
449
- ```typescript
450
- const state = await client.getClaimState(); // every tracked channel
451
- // [{ blockchain: 'evm', channelId, ok: true, depositTotal, cumulativeClaimed, available, nonce, lastClaimTime }, ...]
452
- ```
453
-
454
- There is no agent-published money-report event (decision 4/15 forbid self-reported balances) — this is always a live read from the connector.
455
-
456
- ---
457
-
458
- ## Payment Channels
459
-
460
- The client supports payment channels for off-chain settlement on EVM, Solana, and Mina. With a raw `secretKey` you get EVM only; construct from a `mnemonic` (above) to settle on Solana/Mina. Your EVM identity is derived automatically — no separate EVM key needed.
461
-
462
- ### Enabling Payment Channels
463
-
464
- To use payment channels, add chain configuration. The client already has your EVM identity from `secretKey`:
465
-
466
- ```typescript
467
- const client = new ToonClient({
468
- connectorUrl: 'http://localhost:8080',
469
- secretKey,
470
- ilpInfo: { pubkey, ilpAddress: `g.toon.${pubkey.slice(0, 8)}`, btpEndpoint: 'ws://localhost:3000' },
471
- toonEncoder: encodeEventToToon,
472
- toonDecoder: decodeEventFromToon,
473
-
474
- // Add chain config to enable payment channels
475
- supportedChains: ['evm:anvil:31337'],
476
- chainRpcUrls: { 'evm:anvil:31337': 'http://localhost:8545' },
477
- settlementAddresses: { 'evm:anvil:31337': client.getEvmAddress()! },
478
- tokenNetworks: { 'evm:anvil:31337': '0xCafac3dD18aC6c6e92c921884f9E4176737C052c' },
479
- // Collateral locked on-chain per channel open, in the SETTLEMENT TOKEN's base
480
- // units (USDC has 6 decimals — this is 0.10 USDC), not in wei. Optional;
481
- // '100000' is the default. See "Channel collateral" below.
482
- initialDeposit: '100000',
483
- });
484
-
485
- await client.start();
486
-
487
- // Channels are created automatically during bootstrap
488
- const channels = client.getTrackedChannels();
489
- console.log(`Tracking ${channels.length} payment channels`);
490
-
491
- // Publish with signed balance proof
492
- const channelId = channels[0];
493
- const claim = await client.signBalanceProof(channelId, 1000n);
494
- await client.publishEvent(event, { claim });
495
- ```
496
-
497
- ### Channel collateral
498
-
499
- `initialDeposit` is the collateral locked on-chain when a channel opens, in the
500
- **settlement token's base units** — for 6-decimal USDC, `'100000'` is 0.10 USDC.
501
- It is not a native-coin amount and never in wei. The same value governs every
502
- chain: EVM locks it with `setTotalDeposit`, Solana with the payment-channel
503
- `deposit` instruction. A peer's negotiated deposit, when it states one, wins.
504
-
505
- Off-chain claims are only worth what the channel is collateralized for, so an
506
- under-funded channel signs claims that cannot be redeemed. The open therefore
507
- fails fast — naming the wallet, the token and the shortfall — rather than
508
- opening an uncollateralized channel; fund the settlement wallet or lower
509
- `initialDeposit`. Setting `'0'` opts out explicitly and accepts unredeemable
510
- claims.
511
-
512
- > **Changed in 0.25.0** — `initialDeposit` (and `settlementTimeout`) were
513
- > previously accepted by `ToonClient` and **silently ignored**; every open used
514
- > the built-in defaults. They are honoured now, so a value that was inert before
515
- > takes effect on upgrade. If you copied the old README example
516
- > (`'1000000000000000000'`, described as "1 ETH in wei"), it is now a 1e18
517
- > base-unit ERC-20 deposit — a trillion USDC — which will revert and fail the
518
- > open. Drop the field to take the `'100000'` default, or set the amount you
519
- > actually mean in the token's base units.
520
-
521
- ### Resuming a channel across restarts
522
-
523
- Set **`channelStorePath`** whenever the process can restart (a daemon, a CLI, an
524
- agent with its own wallet). It persists two things:
525
-
526
- | File | Contents |
527
- | --- | --- |
528
- | `channels.json` (`channelStorePath`) | the claim watermark — nonce + cumulative amount — per channel |
529
- | `channels.peers.json` (sibling) | which on-chain channel this identity holds with each peer, per chain + token network |
530
-
531
- With both, `openChannel()` / the lazy open on the first paid write **resume** the
532
- existing channel instead of opening a new one. Without them, every restart locks
533
- a fresh deposit: Solana happened to survive this (its channel id is a
534
- deterministic PDA, so the re-open re-derived the same channel), but EVM's
535
- `TokenNetwork.openChannel` mints a new `bytes32` per call — one abandoned channel,
536
- and its collateral, per restart. That is multiplied by N when every agent runs
537
- its own wallet.
538
-
539
- ```typescript
540
- const client = new ToonClient({
541
- /* … */
542
- channelStorePath: `${process.env.HOME}/.toon-client/channels.json`,
543
- });
544
- ```
545
-
546
- Rules of the road:
547
-
548
- - **Never delete these files for a live channel.** The collateral stays locked
549
- on-chain and the watermark is unrecoverable. If the watermark for a bound
550
- channel goes missing, the client throws `ChannelResumeError` rather than
551
- silently restarting the nonce at 0 — which the connector would reject for
552
- every subsequent claim.
553
- - A host that persists the channel id itself can hand it back with
554
- `await client.adoptChannel(destination, channelId)`; the client then treats it
555
- as the peer's channel for later writes, deposits and closes.
556
- - A channel that entered the withdraw flow (closed/settled) is not resumed — the
557
- next open is a fresh channel.
558
-
559
- ### Choosing an EVM RPC
560
-
561
- `chainRpcUrls` must point at a **read-after-write consistent** endpoint. Base
562
- Sepolia's public `https://sepolia.base.org` is a load balancer: the
563
- `setTotalDeposit` that follows a just-confirmed `openChannel` can land on a
564
- replica that has not seen the open and reverts `InvalidChannelState()`
565
- (`0xf806e9d9`), leaving an open channel with no collateral. The client now polls
566
- the channel back before depositing and retries that specific revert, and gives up
567
- with a `StaleRpcReadError` naming the endpoint — but the cure is a consistent
568
- RPC. `https://base-sepolia-rpc.publicnode.com` behaves correctly and is what
569
- `@toon-protocol/core`'s `base-sepolia` preset carries.
570
-
571
- ### How It Works
572
-
573
- 1. **Bootstrap**: Client discovers peers via NIP-02 and kind:10032 events, negotiating a settlement chain with each
574
- 2. **Channel Creation**: Opens an on-chain payment channel on the negotiated chain — using your derived EVM address (EVM), the Ed25519 channel PDA (Solana), or the deployed zkApp account (Mina) when the matching `solanaChannel` / `minaChannel` config is provided
575
- 3. **Off-chain Payments**: Signed balance proofs (chain-appropriate format) settle payments off-chain
576
- 4. **Auto-tracking**: ChannelManager automatically tracks channels and increments nonces
577
- 5. **On-chain redemption**: A relay apex auto-redeems claims on-chain once a per-channel threshold is crossed (see [Multi-Chain Settlement](#identity--multi-chain-settlement) for the EVM/Solana/Mina specifics and the Mina credit-at-close deferral)
578
-
579
- ### Using a Separate EVM Key (Advanced)
580
-
581
- If you need a different EVM identity than your Nostr key (e.g., hardware wallet or custodial key), pass `evmPrivateKey` explicitly:
582
-
583
- ```typescript
584
- const client = new ToonClient({
585
- // ... required config ...
586
- evmPrivateKey: '0x...', // Overrides the default derivation from secretKey
587
- });
588
- ```
589
-
590
- ---
591
-
592
37
  ## Documentation
593
38
 
594
- - **[API Reference](docs/api-reference.md)** — Constructor, config interface, and all methods
595
- - **[Error Handling](docs/error-handling.md)** — Error class hierarchy, codes, and usage patterns
596
- - **[HTTP Adapters](docs/adapters.md)** — Low-level `HttpRuntimeClient`, `HttpConnectorAdmin`, and `withRetry`
597
- - **[Troubleshooting](docs/troubleshooting.md)** — Common issues and solutions
598
-
599
- ---
600
-
601
- ## Testing
602
-
603
- ### Unit & Integration Tests
604
-
605
- ```bash
606
- cd packages/client
607
- pnpm test # Run all unit/integration tests
608
- pnpm test:coverage # Run with coverage report
609
- ```
610
-
611
- ### E2E Tests
612
-
613
- E2E tests require Docker Compose infrastructure. See
614
- [tests/e2e/README.md](tests/e2e/README.md) for the service topology — note its automated setup
615
- script isn't included in this extracted repo either (see the Prerequisites section above), so
616
- provision the equivalent infrastructure manually, then run:
617
-
618
- ```bash
619
- cd packages/client
620
- pnpm test:e2e
621
- ```
622
-
623
- ---
624
-
625
- ## Examples
626
-
627
- See [examples/](examples/) for standalone client examples:
628
-
629
- - **Basic Publish** (`basic-publish.ts`): Publish a Nostr event to the TOON network
630
- - **Publish and Verify** (`publish-and-verify.ts`): Publish an event and verify via connector logs
631
- - **Publish to Peer1** (`publish-to-peer1.ts`): Multi-hop ILP routing via a peer connector
632
- - **Multi-Hop Routing** (`multi-hop-routing.ts`): Route an event through peer1 to the genesis relay
633
- - **With Payment Channels** (`with-payment-channels.ts`): Configure EVM payment channels and publish with a signed balance proof
634
-
635
- ---
636
-
637
- ## Related Packages
638
-
639
- - **[@toon-protocol/core](https://www.npmjs.com/package/@toon-protocol/core)** — Core protocol (peer discovery, bootstrap, `buildBlobStorageRequest`)
640
- - **[@toon-protocol/relay](https://www.npmjs.com/package/@toon-protocol/relay)** — Operator product running the apex connector plus relay/swap/store nodes; also exports `encodeEventToToon` / `decodeEventFromToon` for event encoding
641
- - **[@toon-protocol/sdk](https://www.npmjs.com/package/@toon-protocol/sdk)** — Higher-level helpers including `streamSwap()` for multi-chain swaps via a **swap**
642
- - **[@toon-protocol/bls](https://www.npmjs.com/package/@toon-protocol/bls)** — Business Logic Server (pricing, validation, storage)
643
-
644
- ---
645
-
646
- ## License
647
-
648
- MIT
39
+ | Document | What is in it |
40
+ | --- | --- |
41
+ | [Getting started](https://github.com/toon-protocol/toon-client/blob/main/docs/getting-started.md) | Nothing to a paid request, step by step |
42
+ | [Library API](https://github.com/toon-protocol/toon-client/blob/main/docs/api.md) | `ToonClient`, its configuration, and every type it returns |
43
+ | [CLI reference](https://github.com/toon-protocol/toon-client/blob/main/docs/cli.md) | Every command, resolution order, `--json`, exit codes |
44
+ | [Payment channels](https://github.com/toon-protocol/toon-client/blob/main/docs/channels.md) | Collateral, the lifecycle on both chains, the watermark |
45
+ | [How a paid packet works](https://github.com/toon-protocol/toon-client/blob/main/docs/how-a-paid-packet-works.md) | The wire, top to bottom |
46
+ | [Devnet reference](https://github.com/toon-protocol/toon-client/blob/main/docs/devnet.md) | Endpoints, routes, prices, contract addresses, faucet |
47
+ | [Errors and reject codes](https://github.com/toon-protocol/toon-client/blob/main/docs/errors.md) | What each code means and what to do about it |
48
+ | [Troubleshooting](https://github.com/toon-protocol/toon-client/blob/main/docs/troubleshooting.md) | Symptom, cause, fix |
49
+
50
+ The wire is defined by the Rust connector, not by this package:
51
+ [toon-protocol/connector](https://github.com/toon-protocol/connector) and its committed wire
52
+ vectors are the authority, and this client replays them as its own conformance suite.
53
+
54
+ MIT.