@toon-protocol/client 0.25.0 → 0.26.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
@@ -392,6 +392,69 @@ if (result.success) {
392
392
 
393
393
  ---
394
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
+
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
+ });
443
+ ```
444
+
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
+
395
458
  ## Payment Channels
396
459
 
397
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.
@@ -455,6 +518,56 @@ claims.
455
518
  > open. Drop the field to take the `'100000'` default, or set the amount you
456
519
  > actually mean in the token's base units.
457
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
+
458
571
  ### How It Works
459
572
 
460
573
  1. **Bootstrap**: Client discovers peers via NIP-02 and kind:10032 events, negotiating a settlement chain with each