@toon-protocol/client 0.23.0 → 0.25.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
@@ -413,7 +413,10 @@ const client = new ToonClient({
413
413
  chainRpcUrls: { 'evm:anvil:31337': 'http://localhost:8545' },
414
414
  settlementAddresses: { 'evm:anvil:31337': client.getEvmAddress()! },
415
415
  tokenNetworks: { 'evm:anvil:31337': '0xCafac3dD18aC6c6e92c921884f9E4176737C052c' },
416
- initialDeposit: '1000000000000000000', // 1 ETH in wei
416
+ // Collateral locked on-chain per channel open, in the SETTLEMENT TOKEN's base
417
+ // units (USDC has 6 decimals — this is 0.10 USDC), not in wei. Optional;
418
+ // '100000' is the default. See "Channel collateral" below.
419
+ initialDeposit: '100000',
417
420
  });
418
421
 
419
422
  await client.start();
@@ -428,6 +431,30 @@ const claim = await client.signBalanceProof(channelId, 1000n);
428
431
  await client.publishEvent(event, { claim });
429
432
  ```
430
433
 
434
+ ### Channel collateral
435
+
436
+ `initialDeposit` is the collateral locked on-chain when a channel opens, in the
437
+ **settlement token's base units** — for 6-decimal USDC, `'100000'` is 0.10 USDC.
438
+ It is not a native-coin amount and never in wei. The same value governs every
439
+ chain: EVM locks it with `setTotalDeposit`, Solana with the payment-channel
440
+ `deposit` instruction. A peer's negotiated deposit, when it states one, wins.
441
+
442
+ Off-chain claims are only worth what the channel is collateralized for, so an
443
+ under-funded channel signs claims that cannot be redeemed. The open therefore
444
+ fails fast — naming the wallet, the token and the shortfall — rather than
445
+ opening an uncollateralized channel; fund the settlement wallet or lower
446
+ `initialDeposit`. Setting `'0'` opts out explicitly and accepts unredeemable
447
+ claims.
448
+
449
+ > **Changed in 0.25.0** — `initialDeposit` (and `settlementTimeout`) were
450
+ > previously accepted by `ToonClient` and **silently ignored**; every open used
451
+ > the built-in defaults. They are honoured now, so a value that was inert before
452
+ > takes effect on upgrade. If you copied the old README example
453
+ > (`'1000000000000000000'`, described as "1 ETH in wei"), it is now a 1e18
454
+ > base-unit ERC-20 deposit — a trillion USDC — which will revert and fail the
455
+ > open. Drop the field to take the `'100000'` default, or set the amount you
456
+ > actually mean in the token's base units.
457
+
431
458
  ### How It Works
432
459
 
433
460
  1. **Bootstrap**: Client discovers peers via NIP-02 and kind:10032 events, negotiating a settlement chain with each
package/dist/index.d.ts CHANGED
@@ -252,10 +252,13 @@ interface SolanaChannelClientOptions {
252
252
  /** Challenge-period duration (seconds) for `initialize_channel`. */
253
253
  challengeDuration?: number;
254
254
  /**
255
- * Optional on-chain deposit when opening the channel: `amount` in base units
256
- * (string) drawn from `payerTokenAccount` (the client's funded SPL token
257
- * account / ATA, base58). When omitted, the channel is opened without a
258
- * deposit (connector accepts on `opened` status + participant membership).
255
+ * OVERRIDE for the on-chain deposit made when opening the channel: `amount`
256
+ * in base units (string) drawn from `payerTokenAccount` (the client's funded
257
+ * SPL token account / ATA, base58 — derived from owner+mint when empty).
258
+ *
259
+ * Normally left unset: the open locks {@link ToonClientConfig.initialDeposit},
260
+ * the same negotiated amount an EVM open locks. A 0 amount opts out and leaves
261
+ * the channel uncollateralized — its claims cannot be redeemed on-chain.
259
262
  */
260
263
  deposit?: {
261
264
  amount: string;
@@ -525,7 +528,13 @@ interface ToonClientConfig {
525
528
  destinationAddress?: string;
526
529
  /** Maps chain identifier to RPC URL (e.g., {"evm:anvil:31337": "http://localhost:8545"}) */
527
530
  chainRpcUrls?: Record<string, string>;
528
- /** Amount to deposit when opening channel (default: "0") */
531
+ /**
532
+ * Collateral (base units, string) locked on-chain when a channel is opened,
533
+ * on EVERY settlement chain (EVM `setTotalDeposit`, Solana `deposit`).
534
+ * Defaults to `"100000"` — 0.1 USDC at 6 decimals. A peer's negotiated
535
+ * `initialDeposit` still wins over this. Set `"0"` only if you accept
536
+ * uncollateralized claims (they cannot be redeemed for value on-chain).
537
+ */
529
538
  initialDeposit?: string;
530
539
  /** Challenge period in seconds (default: 86400) */
531
540
  settlementTimeout?: number;
@@ -1194,6 +1203,68 @@ interface ConnectorIdentity {
1194
1203
  /** The normalized client-edge base URL this identity was read from. */
1195
1204
  endpoint: string;
1196
1205
  }
1206
+ /**
1207
+ * The channel-opening facts a settling connector carries in its x402
1208
+ * greeting (connector #617): everything a buyer needs to OPEN a channel
1209
+ * with the node, learned by ASKING (ADR 0022) rather than from a
1210
+ * kind:10032 announce the Rust fleet never makes.
1211
+ */
1212
+ interface ConnectorSettlementTerms {
1213
+ /** `evm:<chainId>` — the chain the node's settlement backend runs on. */
1214
+ chain: string;
1215
+ /** The on-chain counterparty a buyer opens a channel WITH. */
1216
+ settlementAddress: string;
1217
+ /** The stable TokenNetworkRegistry factory address. */
1218
+ tokenNetworkRegistry: string;
1219
+ /** The resolved TokenNetwork — the EIP-712 verifyingContract. */
1220
+ tokenNetwork: string;
1221
+ tokenAddress: string;
1222
+ /** Informational; claims are already in base units. */
1223
+ decimals: number;
1224
+ }
1225
+ /**
1226
+ * The Solana twin of {@link ConnectorSettlementTerms} (connector #632): what
1227
+ * an unaffiliated buyer needs to open a channel against a Solana settlement
1228
+ * backend's deployed `payment-channel` program instance.
1229
+ */
1230
+ interface ConnectorSolanaSettlementTerms {
1231
+ /** Always `'solana'` — unlike EVM there is no chain id to append. */
1232
+ chain: string;
1233
+ /** The on-chain counterparty a buyer opens a channel WITH, base58. */
1234
+ settlementAddress: string;
1235
+ /** The deployed `payment-channel` program instance, base58. */
1236
+ programId: string;
1237
+ /** The SPL mint every channel this backend opens settles in, base58. */
1238
+ tokenAddress: string;
1239
+ /** Informational; claims are already in base units. */
1240
+ decimals: number;
1241
+ }
1242
+ /**
1243
+ * One chain's entry in the x402 greeting's per-chain `settlements` list
1244
+ * (connector #632). `kind` is added by this parser, not present on the wire
1245
+ * — the wire is untagged, disambiguated structurally (`tokenNetworkRegistry`
1246
+ * names EVM, `programId` names Solana).
1247
+ */
1248
+ type ConnectorChainSettlementTerms = ({
1249
+ kind: 'evm';
1250
+ } & ConnectorSettlementTerms) | ({
1251
+ kind: 'solana';
1252
+ } & ConnectorSolanaSettlementTerms);
1253
+ /**
1254
+ * A route's terms as the x402 greeting states them: the price, plus (from a
1255
+ * settling node) the channel-opening facts. `settlement` is absent exactly
1256
+ * when the node has no settlement backend — the wire's own shape. `settlements`
1257
+ * is the additive per-chain list (connector #632): one entry per chain the
1258
+ * node settles on, including the same EVM entry `settlement` already carries.
1259
+ * Absent — not an empty array — on a node with no settlement backend, or one
1260
+ * still answering the pre-#632 greeting shape.
1261
+ */
1262
+ interface ConnectorRouteTerms {
1263
+ destination: string;
1264
+ price: string;
1265
+ settlement?: ConnectorSettlementTerms;
1266
+ settlements?: ConnectorChainSettlementTerms[];
1267
+ }
1197
1268
  /** What a locally-terminated route costs, as reported by `GET /ilp/routes/price`. */
1198
1269
  interface ConnectorRoutePrice {
1199
1270
  /** The ILP destination that was asked about (echoed by the connector). */
@@ -1223,7 +1294,11 @@ type ConnectorEdgeErrorCode =
1223
1294
  /** `GET /ilp/routes/price` answered 2xx with a body that is not the documented object. */
1224
1295
  | 'ROUTE_PRICE_MALFORMED'
1225
1296
  /** A destination that cannot be put in a query string was asked about. */
1226
- | 'INVALID_DESTINATION';
1297
+ | 'INVALID_DESTINATION'
1298
+ /** A 402 greeting whose body is not the documented x402 shape (or whose
1299
+ * optional `settlement` facts are present but malformed — refused rather
1300
+ * than silently dropped, since they would be opened AGAINST). */
1301
+ | 'TERMS_MALFORMED';
1227
1302
  /**
1228
1303
  * A refusal to carry a connector's answer forward. Distinct from
1229
1304
  * {@link NetworkError} (which this module throws for a transport failure), so
@@ -1319,6 +1394,19 @@ declare class ConnectorEdgeClient {
1319
1394
  getRoutePrice(endpoint: string, destination: string, options?: {
1320
1395
  forceRefresh?: boolean;
1321
1396
  }): Promise<ConnectorRoutePrice | null>;
1397
+ /**
1398
+ * Ask a route for its full x402 terms — the greeting a claimless PREPARE
1399
+ * is answered with (client-edge-spec.md §1.4) — including, from a settling
1400
+ * node, the channel-opening facts (connector #617).
1401
+ *
1402
+ * This is a real `POST /ilp` carrying a minimal PREPARE with no claim
1403
+ * header. It is free by the wire's own contract: an unpaid request to a
1404
+ * priced route is answered with terms instead of performed, and nothing
1405
+ * is charged for asking. `null` when the connector does not price the
1406
+ * destination (the request would be routed or refused, not greeted) —
1407
+ * mapped from anything other than a 402 answer.
1408
+ */
1409
+ getRouteTerms(endpoint: string, destination: string): Promise<ConnectorRouteTerms | null>;
1322
1410
  /**
1323
1411
  * Drop a cached route price — one (endpoint, destination)'s, every
1324
1412
  * destination's at one endpoint when `destination` is omitted, or all of
@@ -1807,6 +1895,14 @@ declare class ToonClient {
1807
1895
  /** Concrete on-chain client, kept so deposit/withdraw can reach chain methods. */
1808
1896
  private onChainChannelClient?;
1809
1897
  private readonly peerNegotiations;
1898
+ /**
1899
+ * Peers whose x402 greeting advertised a Solana settlement leg that this
1900
+ * client could not weigh, because `config.solanaChannel` is unset and
1901
+ * {@link getBalances} therefore reports no Solana balance at all (issue
1902
+ * #474). The EVM leg was taken by default for these; if opening it then
1903
+ * fails for lack of funds, {@link withSolanaLegHint} says so.
1904
+ */
1905
+ private readonly unreadableSolanaLegs;
1810
1906
  /**
1811
1907
  * Asks terminating connectors for their identity key, caching one per
1812
1908
  * client edge. A packet cannot be formed without the key of the connector
@@ -2252,6 +2348,97 @@ declare class ToonClient {
2252
2348
  * Convention: destination "g.toon.peer1" → peerId "peer1" (last segment).
2253
2349
  * Falls back to first known peer if no match.
2254
2350
  */
2351
+ /**
2352
+ * The peer id a claim for `destination` accounts under. Normally
2353
+ * `resolvePeerId` — but where that throws `PEER_NOT_FOUND` (an empty
2354
+ * negotiation map: nothing announced, nothing registered), the
2355
+ * destination itself is the key, so the announce-less greeting bootstrap
2356
+ * (connector #617) has a stable identity to remember its synthesized
2357
+ * negotiation under.
2358
+ */
2359
+ private peerIdForClaim;
2360
+ /**
2361
+ * The announce-less channel bootstrap (connector #617): when nothing has
2362
+ * negotiated with this destination's peer — no kind:10032 announce, no
2363
+ * connector-admin registration — ask the route itself. A settling
2364
+ * connector's x402 greeting carries the channel-opening facts, and ADR
2365
+ * 0022 makes the greeting the ONLY place the Rust fleet will ever state
2366
+ * them. Synthesizes a {@link PeerNegotiation} from those facts, remembers
2367
+ * it, and returns it; `undefined` when there is no edge to ask or the
2368
+ * greeting carries no settlement facts this client can open a channel on.
2369
+ *
2370
+ * A two-chain greeting (connector #632's `extra.settlements`) prefers EVM
2371
+ * — the long-standing default — UNLESS the wallet holds Solana
2372
+ * settlement-token funds and holds none on EVM (issue #470), in which case
2373
+ * it opens the Solana leg instead: a wallet funded only with Solana devnet
2374
+ * assets can bootstrap exactly as an EVM one does. A Solana-only greeting
2375
+ * (no EVM leg at all) always opens Solana — there is nothing to compare
2376
+ * funds against.
2377
+ *
2378
+ * That comparison is only as good as what {@link getBalances} can SEE: with
2379
+ * no `solanaChannel` config it cannot read the Solana side at all, so a
2380
+ * Solana-funded client silently looks broke and takes the EVM leg (issue
2381
+ * #474). We cannot fix the read here — the config genuinely isn't there —
2382
+ * but we remember the peer so the resulting EVM funding failure names the
2383
+ * missing config instead of reading as a plain "fund your wallet".
2384
+ *
2385
+ * Never throws: this is a fallback on a path that already has a precise
2386
+ * error (`PEER_NOT_NEGOTIATED`), and a transport failure while ASKING
2387
+ * must not mask it.
2388
+ */
2389
+ private negotiateFromGreeting;
2390
+ /**
2391
+ * Build the EVM {@link PeerNegotiation} from the greeting's legacy
2392
+ * `settlement` object (connector #617). `undefined` when `chain` is not
2393
+ * the documented `evm:<chainId>` shape — the greeting is malformed rather
2394
+ * than a chain this client cannot open, so bootstrap declines instead of
2395
+ * opening against unverified facts.
2396
+ */
2397
+ private evmNegotiationFromSettlement;
2398
+ /**
2399
+ * Build the Solana {@link PeerNegotiation} from a `settlements` entry
2400
+ * (connector #632). Unlike the EVM leg there is no numeric chain id to
2401
+ * parse or validate — `chain` is always the literal `'solana'` — so,
2402
+ * unlike {@link evmNegotiationFromSettlement}, this cannot fail.
2403
+ */
2404
+ private solanaNegotiationFromSettlement;
2405
+ /**
2406
+ * Whether a two-chain greeting-bootstrap should open the Solana leg
2407
+ * instead of the default EVM one (issue #470): the wallet holds Solana
2408
+ * SETTLEMENT-TOKEN funds and holds none on EVM.
2409
+ *
2410
+ * Reads {@link getBalances}, which reports one balance per chain — the SPL
2411
+ * settlement token on Solana, NOT native SOL (issue #474). That is
2412
+ * deliberate: SOL alone cannot collateralize a channel, so a SOL-only
2413
+ * wallet must not steer the negotiation to Solana. The native SOL a fresh
2414
+ * open needs for rent + fees is checked separately, at open time, by the
2415
+ * Solana opener's funding preflight.
2416
+ *
2417
+ * `getBalances` is itself best-effort per chain (a missing config or failed
2418
+ * RPC read just omits that chain) — this never throws, degrading to "prefer
2419
+ * EVM" (the pre-existing default) on any read failure. When Solana is
2420
+ * omitted because `solanaChannel` is unset, see
2421
+ * {@link canReadSolanaBalance} / {@link unreadableSolanaLegs}.
2422
+ */
2423
+ private walletPrefersSolana;
2424
+ /**
2425
+ * Whether {@link getBalances} can report a Solana balance at all — the exact
2426
+ * condition that reader gates on. False means a Solana-funded wallet reads
2427
+ * as empty, so `walletPrefersSolana` cannot see its funds.
2428
+ */
2429
+ private canReadSolanaBalance;
2430
+ /**
2431
+ * Re-throw a channel-open failure with the missing-`solanaChannel` diagnosis
2432
+ * attached (issue #474).
2433
+ *
2434
+ * When the peer's greeting advertised a Solana leg this client could not
2435
+ * evaluate, "the EVM wallet has no funds/gas" is a symptom, not the cause:
2436
+ * the funds may be sitting on Solana, invisible because `solanaChannel` is
2437
+ * unconfigured. Only funding failures are rewritten — every other error is
2438
+ * returned untouched, since a transport/RPC/contract fault has nothing to do
2439
+ * with which chain was picked.
2440
+ */
2441
+ private withSolanaLegHint;
2255
2442
  private resolvePeerId;
2256
2443
  /**
2257
2444
  * Extracts chain context (chainId + tokenNetworkAddress) from a chain key like 'evm:base:421614'.
@@ -3013,6 +3200,12 @@ interface SolanaChannelConfig {
3013
3200
  * 32 bytes are the signing seed; the public key is derived from it.
3014
3201
  */
3015
3202
  keypair: Uint8Array;
3203
+ /**
3204
+ * DEFAULT payment-channel program id (base58). The per-channel negotiated
3205
+ * program (`OpenChannelParams.tokenNetwork`, i.e. the greeting's `programId`)
3206
+ * takes precedence when present — see {@link SolanaChannelConfig.tokenMint},
3207
+ * which works the same way.
3208
+ */
3016
3209
  programId: string;
3017
3210
  /**
3018
3211
  * SPL token mint (base58) for PDA derivation. Optional — the per-channel
@@ -3025,11 +3218,16 @@ interface SolanaChannelConfig {
3025
3218
  */
3026
3219
  challengeDuration?: number;
3027
3220
  /**
3028
- * Optional deposit amount (base units, string) + the payer's funded SPL token
3029
- * account (ATA, base58). When omitted, the channel is opened (initialized)
3030
- * without an on-chain deposit — the connector accepts the claim on channel
3031
- * `opened` status + participant membership; deposit is only consumed at
3032
- * on-chain claim/settle time.
3221
+ * OVERRIDE for the on-chain deposit made at open time: `amount` in base units
3222
+ * and/or `payerTokenAccount`, the payer's funded SPL token account (ATA,
3223
+ * base58; derived from owner+mint when left empty).
3224
+ *
3225
+ * Normally left unset — the open deposits `OpenChannelParams.initialDeposit`,
3226
+ * the same negotiated amount the EVM opener locks. Set this only to pin a
3227
+ * different amount or a non-ATA source account. A 0 amount opts out of the
3228
+ * deposit entirely and leaves the channel UNCOLLATERALIZED: the connector
3229
+ * accepts claims on channel `opened` status + participant membership, but
3230
+ * those claims cannot be redeemed for value on-chain (connector#646).
3033
3231
  */
3034
3232
  deposit?: {
3035
3233
  amount: string;
@@ -3182,6 +3380,12 @@ declare class OnChainChannelClient implements ConnectorChannelClient {
3182
3380
  * vault. Incremental on-chain (the program adds `amount`), so the new total is
3183
3381
  * the caller-tracked current plus the delta. Requires the funded payer token
3184
3382
  * account (the funded ATA) from the Solana channel config.
3383
+ *
3384
+ * `channel` carries the program and mint the channel was actually OPENED
3385
+ * with (the greeting's, when it named them — see
3386
+ * {@link OnChainChannelClient.openSolanaChannel}), NOT
3387
+ * `solanaConfig.programId`/`tokenMint`. Both PDAs this deposit addresses are
3388
+ * derived from those: the vault from the program, the payer ATA from the mint.
3185
3389
  */
3186
3390
  private depositSolana;
3187
3391
  /**
@@ -3248,12 +3452,19 @@ declare class OnChainChannelClient implements ConnectorChannelClient {
3248
3452
  *
3249
3453
  * Derives the connector-parity channel PDA
3250
3454
  * (`[b"channel", min_pubkey, max_pubkey, token_mint]`), submits the
3251
- * `initialize_channel` instruction (+ optional `deposit`) to the deployed
3252
- * payment-channel program, and returns the base58 PDA as the channel id. That
3455
+ * `initialize_channel` instruction plus the `deposit` that collateralizes the
3456
+ * channel, and returns the base58 PDA as the channel id. That
3253
3457
  * PDA is what the claim carries as `channelAccount`, and the on-chain channel
3254
3458
  * is what the connector's `verifySolanaClaim` reads via
3255
3459
  * `provider.getChannelState` before accepting the claim.
3256
3460
  *
3461
+ * Both PDA seeds are NEGOTIATED, not configured: the mint is
3462
+ * `OpenChannelParams.token` and the program is `OpenChannelParams.tokenNetwork`
3463
+ * — the greeting's `tokenAddress`/`programId` as threaded through by
3464
+ * `ChannelManager.ensureChannel` — each falling back to the `solanaConfig`
3465
+ * default only when the negotiation named none. That is what keeps the channel
3466
+ * this opens and the channel the signed claim asserts the same object (#473).
3467
+ *
3257
3468
  * Mirrors `openEvmChannel`'s open(+deposit) structure. Idempotent: if the
3258
3469
  * channel account already exists on-chain, returns its PDA without
3259
3470
  * re-initializing.
@@ -3332,6 +3543,11 @@ interface ChannelStore {
3332
3543
  }
3333
3544
 
3334
3545
  interface ChannelManagerConfig {
3546
+ /**
3547
+ * Collateral (base units) locked on-chain by {@link ChannelManager.ensureChannel}
3548
+ * when it opens a channel, on every settlement chain. Default `'100000'`
3549
+ * (0.1 USDC at 6 decimals); a peer's negotiated `initialDeposit` wins over it.
3550
+ */
3335
3551
  initialDeposit?: string;
3336
3552
  settlementTimeout?: number;
3337
3553
  }