@toon-protocol/client 0.24.0 → 0.25.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
@@ -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;
@@ -1213,15 +1222,48 @@ interface ConnectorSettlementTerms {
1213
1222
  /** Informational; claims are already in base units. */
1214
1223
  decimals: number;
1215
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);
1216
1253
  /**
1217
1254
  * A route's terms as the x402 greeting states them: the price, plus (from a
1218
1255
  * settling node) the channel-opening facts. `settlement` is absent exactly
1219
- * when the node has no settlement backend — the wire's own shape.
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.
1220
1261
  */
1221
1262
  interface ConnectorRouteTerms {
1222
1263
  destination: string;
1223
1264
  price: string;
1224
1265
  settlement?: ConnectorSettlementTerms;
1266
+ settlements?: ConnectorChainSettlementTerms[];
1225
1267
  }
1226
1268
  /** What a locally-terminated route costs, as reported by `GET /ilp/routes/price`. */
1227
1269
  interface ConnectorRoutePrice {
@@ -1853,6 +1895,14 @@ declare class ToonClient {
1853
1895
  /** Concrete on-chain client, kept so deposit/withdraw can reach chain methods. */
1854
1896
  private onChainChannelClient?;
1855
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;
1856
1906
  /**
1857
1907
  * Asks terminating connectors for their identity key, caching one per
1858
1908
  * client edge. A packet cannot be formed without the key of the connector
@@ -2314,16 +2364,81 @@ declare class ToonClient {
2314
2364
  * connector's x402 greeting carries the channel-opening facts, and ADR
2315
2365
  * 0022 makes the greeting the ONLY place the Rust fleet will ever state
2316
2366
  * them. Synthesizes a {@link PeerNegotiation} from those facts, remembers
2317
- * it, and returns it; `undefined` when there is no edge to ask, the
2318
- * greeting carries no settlement facts, or the chain is not one this
2319
- * client opens channels on (EVM only today — Solana/Mina channel opening
2320
- * still needs announce-shaped metadata).
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".
2321
2384
  *
2322
2385
  * Never throws: this is a fallback on a path that already has a precise
2323
2386
  * error (`PEER_NOT_NEGOTIATED`), and a transport failure while ASKING
2324
2387
  * must not mask it.
2325
2388
  */
2326
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;
2327
2442
  private resolvePeerId;
2328
2443
  /**
2329
2444
  * Extracts chain context (chainId + tokenNetworkAddress) from a chain key like 'evm:base:421614'.
@@ -3085,6 +3200,12 @@ interface SolanaChannelConfig {
3085
3200
  * 32 bytes are the signing seed; the public key is derived from it.
3086
3201
  */
3087
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
+ */
3088
3209
  programId: string;
3089
3210
  /**
3090
3211
  * SPL token mint (base58) for PDA derivation. Optional — the per-channel
@@ -3097,11 +3218,16 @@ interface SolanaChannelConfig {
3097
3218
  */
3098
3219
  challengeDuration?: number;
3099
3220
  /**
3100
- * Optional deposit amount (base units, string) + the payer's funded SPL token
3101
- * account (ATA, base58). When omitted, the channel is opened (initialized)
3102
- * without an on-chain deposit — the connector accepts the claim on channel
3103
- * `opened` status + participant membership; deposit is only consumed at
3104
- * 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).
3105
3231
  */
3106
3232
  deposit?: {
3107
3233
  amount: string;
@@ -3254,6 +3380,12 @@ declare class OnChainChannelClient implements ConnectorChannelClient {
3254
3380
  * vault. Incremental on-chain (the program adds `amount`), so the new total is
3255
3381
  * the caller-tracked current plus the delta. Requires the funded payer token
3256
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.
3257
3389
  */
3258
3390
  private depositSolana;
3259
3391
  /**
@@ -3320,12 +3452,19 @@ declare class OnChainChannelClient implements ConnectorChannelClient {
3320
3452
  *
3321
3453
  * Derives the connector-parity channel PDA
3322
3454
  * (`[b"channel", min_pubkey, max_pubkey, token_mint]`), submits the
3323
- * `initialize_channel` instruction (+ optional `deposit`) to the deployed
3324
- * 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
3325
3457
  * PDA is what the claim carries as `channelAccount`, and the on-chain channel
3326
3458
  * is what the connector's `verifySolanaClaim` reads via
3327
3459
  * `provider.getChannelState` before accepting the claim.
3328
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
+ *
3329
3468
  * Mirrors `openEvmChannel`'s open(+deposit) structure. Idempotent: if the
3330
3469
  * channel account already exists on-chain, returns its PDA without
3331
3470
  * re-initializing.
@@ -3404,6 +3543,11 @@ interface ChannelStore {
3404
3543
  }
3405
3544
 
3406
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
+ */
3407
3551
  initialDeposit?: string;
3408
3552
  settlementTimeout?: number;
3409
3553
  }