@toon-protocol/client 0.22.0 → 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:
package/dist/index.d.ts CHANGED
@@ -1941,8 +1941,10 @@ declare class ToonClient {
1941
1941
  destination?: string;
1942
1942
  claim?: SignedBalanceProof;
1943
1943
  ilpAmount?: bigint;
1944
- /** Request-target inside the envelope (default '/write', the relay;
1945
- * use '/store' for the Arweave store backend). */
1944
+ /** Sub-path resolved strictly BENEATH the route's handler path (ADR
1945
+ * 0025). Default '' — the handler's own path, correct whenever the
1946
+ * destination terminates at exactly one endpoint. Never absolute:
1947
+ * a leading '/' is refused by the connector (F00). */
1946
1948
  proxyPath?: string;
1947
1949
  }): Promise<PublishEventResult>;
1948
1950
  /**
package/dist/index.js CHANGED
@@ -4745,10 +4745,21 @@ function parseEvmChainId(chainKey) {
4745
4745
  if (!Number.isFinite(id)) throw new Error(`Invalid EVM chain key "${chainKey}".`);
4746
4746
  return id;
4747
4747
  }
4748
+ var RPC_TIMEOUT_ENV = "TOON_WALLET_RPC_TIMEOUT_MS";
4749
+ var DEFAULT_RPC_TIMEOUT_MS = 8e3;
4750
+ function rpcTimeoutMs() {
4751
+ const raw = typeof process !== "undefined" ? process.env?.[RPC_TIMEOUT_ENV] : void 0;
4752
+ const n = raw === void 0 || raw === "" ? NaN : Number(raw);
4753
+ return Number.isFinite(n) && n >= 0 ? n : DEFAULT_RPC_TIMEOUT_MS;
4754
+ }
4755
+ function rpcAbortSignal() {
4756
+ const ms = rpcTimeoutMs();
4757
+ return ms > 0 ? AbortSignal.timeout(ms) : void 0;
4758
+ }
4748
4759
  async function readEvmTokenBalance(opts) {
4749
4760
  const chainId = parseEvmChainId(opts.chainKey);
4750
4761
  const client = createPublicClient2({
4751
- transport: http2(opts.rpcUrl),
4762
+ transport: http2(opts.rpcUrl, { timeout: rpcTimeoutMs() || void 0, retryCount: 1 }),
4752
4763
  chain: defineChain2({
4753
4764
  id: chainId,
4754
4765
  name: opts.chainKey,
@@ -4771,7 +4782,7 @@ async function readEvmTokenBalance(opts) {
4771
4782
  async function readEvmNativeBalance(opts) {
4772
4783
  const chainId = parseEvmChainId(opts.chainKey);
4773
4784
  const client = createPublicClient2({
4774
- transport: http2(opts.rpcUrl),
4785
+ transport: http2(opts.rpcUrl, { timeout: rpcTimeoutMs() || void 0, retryCount: 1 }),
4775
4786
  chain: defineChain2({
4776
4787
  id: chainId,
4777
4788
  name: opts.chainKey,
@@ -4792,7 +4803,8 @@ async function readSolanaNativeBalance(opts) {
4792
4803
  id: 1,
4793
4804
  method: "getBalance",
4794
4805
  params: [opts.owner, { commitment: "confirmed" }]
4795
- })
4806
+ }),
4807
+ signal: rpcAbortSignal()
4796
4808
  });
4797
4809
  if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);
4798
4810
  const json = await res.json();
@@ -4810,7 +4822,8 @@ async function readSolanaTokenBalance(opts) {
4810
4822
  id: 1,
4811
4823
  method: "getTokenAccountsByOwner",
4812
4824
  params: [opts.owner, { mint: opts.mint }, { encoding: "jsonParsed", commitment: "confirmed" }]
4813
- })
4825
+ }),
4826
+ signal: rpcAbortSignal()
4814
4827
  });
4815
4828
  if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);
4816
4829
  const json = await res.json();
@@ -4832,7 +4845,8 @@ async function readMinaBalance(opts) {
4832
4845
  const res = await fetchImpl(opts.graphqlUrl, {
4833
4846
  method: "POST",
4834
4847
  headers: { "content-type": "application/json" },
4835
- body: JSON.stringify({ query, variables: { pk: opts.owner } })
4848
+ body: JSON.stringify({ query, variables: { pk: opts.owner } }),
4849
+ signal: rpcAbortSignal()
4836
4850
  });
4837
4851
  if (!res.ok) throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);
4838
4852
  const json = await res.json();
@@ -4888,7 +4902,8 @@ async function readMinaTokenBalance(opts) {
4888
4902
  const res = await fetchImpl(opts.graphqlUrl, {
4889
4903
  method: "POST",
4890
4904
  headers: { "content-type": "application/json" },
4891
- body: JSON.stringify({ query, variables: { pk: opts.owner, t: token } })
4905
+ body: JSON.stringify({ query, variables: { pk: opts.owner, t: token } }),
4906
+ signal: rpcAbortSignal()
4892
4907
  });
4893
4908
  if (!res.ok) throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);
4894
4909
  const json = await res.json();
@@ -4900,7 +4915,10 @@ async function readMinaTokenBalance(opts) {
4900
4915
  address: opts.owner,
4901
4916
  amount: String(json.data?.account?.balance?.total ?? "0"),
4902
4917
  asset: "USDC",
4903
- assetScale: 9
4918
+ // TOON's settlement USDC is 6-decimal on every chain (assetScale 6), unlike
4919
+ // native MINA's 9. The Mina custom-token amount is a raw u64, so scale it at
4920
+ // 6 — otherwise a 50 USDC balance (50_000000) misreads as 0.05.
4921
+ assetScale: 6
4904
4922
  };
4905
4923
  }
4906
4924
  var errText = (e) => e instanceof Error ? e.message : String(e);
@@ -5032,9 +5050,12 @@ async function requestBlobStorage(client, secretKey, params) {
5032
5050
  const result = await client.publishEvent(event, {
5033
5051
  destination: params.destination,
5034
5052
  claim: params.claim,
5035
- ilpAmount: params.ilpAmount,
5036
- // The store/DVM backend serves POST /store (not the relay's /write).
5037
- proxyPath: "/store"
5053
+ ilpAmount: params.ilpAmount
5054
+ // No proxyPath: the store DESTINATION's route already terminates at the
5055
+ // store backend's own endpoint, and ADR 0025 resolves the envelope
5056
+ // target strictly beneath that handler path — '' (the default) means
5057
+ // "the handler's own path". The old absolute '/store' is refused by the
5058
+ // connector as an escape attempt (F00).
5038
5059
  });
5039
5060
  if (!result.success) {
5040
5061
  return {
@@ -5302,7 +5323,9 @@ function toEnvelopeRequest(url, method, opts) {
5302
5323
  );
5303
5324
  return {
5304
5325
  method: method.toUpperCase(),
5305
- target: `${u.pathname}${u.search}` || "/",
5326
+ // Strip the leading '/' — ADR 0025 targets are handler-relative, and
5327
+ // the empty string ('' + no search) is exactly "the handler's path".
5328
+ target: `${u.pathname.replace(/^\/+/, "")}${u.search}`,
5306
5329
  headers,
5307
5330
  body: bodyToBytes(opts.body)
5308
5331
  };
@@ -6076,7 +6099,15 @@ var ToonClient = class {
6076
6099
  const exchange = sealExchange(
6077
6100
  {
6078
6101
  method: "POST",
6079
- target: options?.proxyPath ?? "/write",
6102
+ // ADR 0025 (connector #596): the envelope target is resolved
6103
+ // STRICTLY BENEATH the route's configured handler path — it can
6104
+ // extend that path, never replace it. '' means "the handler's own
6105
+ // path", which is the whole answer for a route that terminates at
6106
+ // exactly one endpoint (g.rust.relay → …/write, g.rust.store →
6107
+ // …/store): the DESTINATION picks the endpoint, not the target.
6108
+ // An absolute target like '/write' is refused as an escape
6109
+ // attempt (F00) before the app is ever reached.
6110
+ target: options?.proxyPath ?? "",
6080
6111
  headers: [["content-type", "application/json"]],
6081
6112
  body: encodeUtf8(JSON.stringify({ event }))
6082
6113
  },