@toon-protocol/client 0.27.0 → 0.29.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/dist/index.js CHANGED
@@ -1532,8 +1532,10 @@ function parseConnectorRouteTerms(body) {
1532
1532
  );
1533
1533
  }
1534
1534
  const destination = typeof greeting.resource?.url === "string" ? greeting.resource.url : "";
1535
- const extra = option["extra"];
1536
- const rawSettlements = extra?.settlements;
1535
+ const rawExtra = option["extra"];
1536
+ const extra = typeof rawExtra === "object" && rawExtra !== null ? rawExtra : void 0;
1537
+ const extraForReads = extra ?? {};
1538
+ const rawSettlements = extraForReads["settlements"];
1537
1539
  let settlements;
1538
1540
  if (rawSettlements !== void 0) {
1539
1541
  if (!Array.isArray(rawSettlements)) {
@@ -1544,12 +1546,13 @@ function parseConnectorRouteTerms(body) {
1544
1546
  }
1545
1547
  settlements = rawSettlements.map(parseChainSettlementEntry);
1546
1548
  }
1547
- const rawSettlement = extra?.settlement;
1549
+ const rawSettlement = extraForReads["settlement"];
1548
1550
  if (rawSettlement === void 0) {
1549
1551
  return {
1550
1552
  destination,
1551
1553
  price: option["amount"],
1552
- ...settlements ? { settlements } : {}
1554
+ ...settlements ? { settlements } : {},
1555
+ ...extra !== void 0 ? { extra } : {}
1553
1556
  };
1554
1557
  }
1555
1558
  if (typeof rawSettlement !== "object" || rawSettlement === null) {
@@ -1564,7 +1567,8 @@ function parseConnectorRouteTerms(body) {
1564
1567
  settlement: parseEvmSettlementTerms(
1565
1568
  rawSettlement
1566
1569
  ),
1567
- ...settlements ? { settlements } : {}
1570
+ ...settlements ? { settlements } : {},
1571
+ ...extra !== void 0 ? { extra } : {}
1568
1572
  };
1569
1573
  }
1570
1574
 
@@ -2553,12 +2557,27 @@ var IsomorphicBtpClient = class {
2553
2557
  });
2554
2558
  this.ws.send(btpMessage);
2555
2559
  }
2560
+ /**
2561
+ * Re-sends the auth greeting on the EXISTING session — no socket
2562
+ * reconnect — so a channel that became known (or changed) after the
2563
+ * initial `connect()` is declared on the live session. The connector
2564
+ * treats a second auth as a rebind under a fresh generation, so no new
2565
+ * message type is needed (toon-client#513). A no-op when not connected;
2566
+ * the next `connect()`/reconnect already re-declares via
2567
+ * `getChannelDeclaration`.
2568
+ */
2569
+ async reauthenticate() {
2570
+ if (!this._isConnected || !this.ws) return;
2571
+ await this.authenticate();
2572
+ }
2556
2573
  // ─── Private ────────────────────────────────────────────────────────────
2557
2574
  async authenticate() {
2558
2575
  if (!this.ws) throw new BtpAuthError("WebSocket not connected");
2576
+ const declaration = await this.config.getChannelDeclaration?.();
2559
2577
  const authData = JSON.stringify({
2560
2578
  peerId: this.config.peerId,
2561
- secret: this.config.authToken
2579
+ secret: this.config.authToken,
2580
+ ...declaration ?? {}
2562
2581
  });
2563
2582
  const requestId = this.nextRequestId();
2564
2583
  const authMessage = serializeBtpMessage({
@@ -2894,11 +2913,22 @@ var BtpRuntimeClient = class {
2894
2913
  createWebSocket: this.config.createWebSocket,
2895
2914
  onMessage: this.config.onMessage,
2896
2915
  onTransfer: this.config.onTransfer,
2897
- onInboundError: this.config.onInboundError
2916
+ onInboundError: this.config.onInboundError,
2917
+ getChannelDeclaration: this.config.getChannelDeclaration
2898
2918
  });
2899
2919
  await this.btpClient.connect();
2900
2920
  this._isConnected = true;
2901
2921
  }
2922
+ /**
2923
+ * Re-sends the auth greeting on the EXISTING session — no reconnect — so a
2924
+ * channel that became known (or changed) after `connect()` is declared on
2925
+ * the live session (toon-client#513). A no-op when not connected; the next
2926
+ * `connect()`/`reconnect()` already re-declares via `getChannelDeclaration`.
2927
+ */
2928
+ async reauthenticate() {
2929
+ if (!this._isConnected || !this.btpClient) return;
2930
+ await this.btpClient.reauthenticate();
2931
+ }
2902
2932
  /**
2903
2933
  * Attempts to reconnect by creating a fresh client and connecting.
2904
2934
  */
@@ -5021,7 +5051,7 @@ var EvmSigner = class {
5021
5051
  };
5022
5052
 
5023
5053
  // src/modes/http.ts
5024
- async function initializeHttpMode(config) {
5054
+ async function initializeHttpMode(config, hooks = {}) {
5025
5055
  const effectiveBtpUrl = config.btpUrl;
5026
5056
  const effectiveConnectorUrl = config.connectorUrl;
5027
5057
  const settlementInfo = buildSettlementInfo(config);
@@ -5042,7 +5072,8 @@ async function initializeHttpMode(config) {
5042
5072
  // MESSAGE carrying a PREPARE is answered by the configured handler.
5043
5073
  // Unset `jobHandler` leaves `onMessage` unset too, so an inbound job
5044
5074
  // MESSAGE is dropped unanswered — unchanged from the pre-#494 default.
5045
- ...config.jobHandler ? { onMessage: createJobMessageHandler(config.jobHandler) } : {}
5075
+ ...config.jobHandler ? { onMessage: createJobMessageHandler(config.jobHandler) } : {},
5076
+ ...hooks.getChannelDeclaration ? { getChannelDeclaration: hooks.getChannelDeclaration } : {}
5046
5077
  });
5047
5078
  await btpClient.connect();
5048
5079
  }
@@ -5111,6 +5142,7 @@ async function initializeHttpMode(config) {
5111
5142
  runtimeClient,
5112
5143
  adminClient: null,
5113
5144
  btpClient: paidWriteBtpClient,
5145
+ btpSession: btpClient,
5114
5146
  onChainChannelClient
5115
5147
  };
5116
5148
  }
@@ -7750,6 +7782,26 @@ var ToonClient = class {
7750
7782
  * {@link getLastX402Terms} without re-issuing the probe by hand.
7751
7783
  */
7752
7784
  lastX402Terms;
7785
+ /**
7786
+ * The most recently parsed `ConnectorRouteTerms`, from the last
7787
+ * `negotiateFromGreeting` call — the greeting parse that ordinary channel
7788
+ * bootstrap (`publishEvent`/`openChannel`/`adoptChannel`) already goes
7789
+ * through, with no separate `h402Fetch` probe needed (issue #509).
7790
+ * Captured whether or not the greeting carried settlement facts to
7791
+ * bootstrap from, so its `extra` bag (e.g. `session_lease_ttl_ms`) is
7792
+ * readable via {@link getLastConnectorRouteTerms} even when the bootstrap
7793
+ * declined to open a channel from that greeting.
7794
+ */
7795
+ lastConnectorRouteTerms;
7796
+ /**
7797
+ * The channel most recently opened (via `openChannel()`) or adopted (via
7798
+ * `adoptChannel()`) — the one declared on the BTP session so a connector
7799
+ * crediting earned increments knows which channel to pay (toon-client#513,
7800
+ * connector#790). Read by `buildChannelDeclaration`'s `getChannelDeclaration`
7801
+ * hook on every auth greeting, including a reconnect's, so a fresh session
7802
+ * re-declares it without this client tracking reconnects itself.
7803
+ */
7804
+ declaredChannelId;
7753
7805
  evmSigner;
7754
7806
  solanaSigner;
7755
7807
  /**
@@ -7948,8 +8000,16 @@ var ToonClient = class {
7948
8000
  );
7949
8001
  }
7950
8002
  }
7951
- const initialization = await initializeHttpMode(this.config);
7952
- const { bootstrapService, discoveryTracker, runtimeClient, btpClient } = initialization;
8003
+ const initialization = await initializeHttpMode(this.config, {
8004
+ getChannelDeclaration: () => this.buildChannelDeclaration()
8005
+ });
8006
+ const {
8007
+ bootstrapService,
8008
+ discoveryTracker,
8009
+ runtimeClient,
8010
+ btpClient,
8011
+ btpSession
8012
+ } = initialization;
7953
8013
  if (this.channelManager) {
7954
8014
  const cm = this.channelManager;
7955
8015
  const nostrPubkey = this.getPublicKey();
@@ -8047,7 +8107,8 @@ var ToonClient = class {
8047
8107
  discoveryTracker,
8048
8108
  runtimeClient,
8049
8109
  peersDiscovered: bootstrapResults.length,
8050
- btpClient: btpClient ?? void 0
8110
+ btpClient: btpClient ?? void 0,
8111
+ btpSession: btpSession ?? void 0
8051
8112
  };
8052
8113
  return {
8053
8114
  peersDiscovered: bootstrapResults.length,
@@ -8324,6 +8385,21 @@ var ToonClient = class {
8324
8385
  getLastX402Terms() {
8325
8386
  return this.lastX402Terms;
8326
8387
  }
8388
+ /**
8389
+ * The `ConnectorRouteTerms` from the most recent ordinary channel
8390
+ * bootstrap (`publishEvent`/`openChannel`/`adoptChannel`, via
8391
+ * `negotiateFromGreeting`) — including its `extra` bag (issue #509, e.g.
8392
+ * `extra.session_lease_ttl_ms`, connector#722) — or `undefined` if no
8393
+ * greeting has been parsed on this path yet. Unlike
8394
+ * {@link getLastX402Terms}, this populates from a client that only ever
8395
+ * calls `start()`/`publishEvent()`: `ConnectorEdgeClient.getRouteTerms` is
8396
+ * the parser the live path actually negotiates through, so a caller does
8397
+ * not need to issue a separate `h402Fetch` probe purely to read the lease
8398
+ * TTL.
8399
+ */
8400
+ getLastConnectorRouteTerms() {
8401
+ return this.lastConnectorRouteTerms;
8402
+ }
8327
8403
  /**
8328
8404
  * Sends a raw swap ILP packet (Story 12.5) to a swap peer with an attached
8329
8405
  * balance-proof claim. This is a lower-level surface than `publishEvent`:
@@ -8548,11 +8624,14 @@ var ToonClient = class {
8548
8624
  "PEER_NOT_NEGOTIATED"
8549
8625
  );
8550
8626
  }
8627
+ let channelId;
8551
8628
  try {
8552
- return await this.channelManager.ensureChannel(peerId, negotiation);
8629
+ channelId = await this.channelManager.ensureChannel(peerId, negotiation);
8553
8630
  } catch (error) {
8554
8631
  throw this.withSolanaLegHint(peerId, error);
8555
8632
  }
8633
+ await this.declareChannelOnBtpSession(channelId);
8634
+ return channelId;
8556
8635
  }
8557
8636
  /**
8558
8637
  * Adopt an ALREADY-OPEN payment channel for `destination` — the restart path
@@ -8580,6 +8659,7 @@ var ToonClient = class {
8580
8659
  );
8581
8660
  }
8582
8661
  this.channelManager.adoptChannel(peerId, negotiation, channelId);
8662
+ await this.declareChannelOnBtpSession(channelId);
8583
8663
  }
8584
8664
  /**
8585
8665
  * Gets list of tracked payment channel IDs.
@@ -8594,6 +8674,63 @@ var ToonClient = class {
8594
8674
  if (!this.channelManager) throw new Error("ChannelManager not initialized");
8595
8675
  return this.channelManager.getNonce(channelId);
8596
8676
  }
8677
+ /**
8678
+ * Signs a claim-state-challenge declaration for one channel — the shared
8679
+ * scheme both `getClaimState` and `buildChannelDeclaration` (toon-client#513)
8680
+ * use to prove channel ownership without moving value or advancing a nonce,
8681
+ * so it can never be replayed as a payment. `undefined` for a chain type
8682
+ * neither signer covers (Mina, or any chain this client has no signer for)
8683
+ * — matching `getClaimState`'s existing evm/solana-only posture.
8684
+ */
8685
+ async signClaimStateChallenge(channelId, context, expires) {
8686
+ if (context.chainType === "evm" && this.evmSigner) {
8687
+ const signature = await this.evmSigner.signClaimStateChallenge({
8688
+ chainId: context.chainId,
8689
+ tokenNetworkAddress: context.tokenNetworkAddress,
8690
+ channelId,
8691
+ expires
8692
+ });
8693
+ return { blockchain: "evm", channelId, expires, signature };
8694
+ }
8695
+ if (context.chainType === "solana" && this.solanaSigner) {
8696
+ const signature = await this.solanaSigner.signClaimStateChallenge({
8697
+ channelAccount: channelId,
8698
+ expires
8699
+ });
8700
+ return { blockchain: "solana", channelAccount: channelId, expires, signature };
8701
+ }
8702
+ return void 0;
8703
+ }
8704
+ /**
8705
+ * Signs a claim-state-challenge declaration for `this.declaredChannelId`
8706
+ * (toon-client#513). Wired as the BTP session's `getChannelDeclaration`
8707
+ * hook, so it is called on every auth greeting (initial connect, explicit
8708
+ * reauthenticate, and every reconnect) — `undefined` (no declared channel
8709
+ * yet, or a chain this endpoint doesn't cover) leaves that greeting
8710
+ * exactly as it was before this feature existed.
8711
+ */
8712
+ async buildChannelDeclaration() {
8713
+ const channelId = this.declaredChannelId;
8714
+ if (!channelId || !this.channelManager) return void 0;
8715
+ const context = this.channelManager.getChannelContext(channelId);
8716
+ if (!context) return void 0;
8717
+ const expires = Math.floor(Date.now() / 1e3) + 300;
8718
+ return this.signClaimStateChallenge(channelId, context, expires);
8719
+ }
8720
+ /**
8721
+ * Declares `channelId` as this client's channel on its live BTP session
8722
+ * (toon-client#513) — called after `openChannel()`/`adoptChannel()`
8723
+ * establish or resume one, so a connector crediting earned increments
8724
+ * learns the association without this client ever paying. Re-sends the
8725
+ * auth greeting on the EXISTING session; does not reconnect the socket.
8726
+ * A no-op when no BTP session is live (e.g. `btpUrl` not configured, or
8727
+ * the session is momentarily down) — the next reconnect's own greeting
8728
+ * already re-declares via `buildChannelDeclaration`.
8729
+ */
8730
+ async declareChannelOnBtpSession(channelId) {
8731
+ this.declaredChannelId = channelId;
8732
+ await this.state?.btpSession?.reauthenticate();
8733
+ }
8597
8734
  /**
8598
8735
  * Gets the cumulative transferred amount for a tracked channel.
8599
8736
  */
@@ -8635,25 +8772,7 @@ var ToonClient = class {
8635
8772
  ids.map(async (channelId) => {
8636
8773
  const context = channelManager.getChannelContext(channelId);
8637
8774
  if (!context) return null;
8638
- if (context.chainType === "evm") {
8639
- if (!this.evmSigner) return null;
8640
- const signature = await this.evmSigner.signClaimStateChallenge({
8641
- chainId: context.chainId,
8642
- tokenNetworkAddress: context.tokenNetworkAddress,
8643
- channelId,
8644
- expires
8645
- });
8646
- return { blockchain: "evm", channelId, expires, signature };
8647
- }
8648
- if (context.chainType === "solana") {
8649
- if (!this.solanaSigner) return null;
8650
- const signature = await this.solanaSigner.signClaimStateChallenge({
8651
- channelAccount: channelId,
8652
- expires
8653
- });
8654
- return { blockchain: "solana", channelAccount: channelId, expires, signature };
8655
- }
8656
- return null;
8775
+ return await this.signClaimStateChallenge(channelId, context, expires) ?? null;
8657
8776
  })
8658
8777
  );
8659
8778
  const requests = entries.filter(
@@ -9128,6 +9247,7 @@ var ToonClient = class {
9128
9247
  }
9129
9248
  try {
9130
9249
  const terms = await this.connectorEdge.getRouteTerms(edge, destination);
9250
+ this.lastConnectorRouteTerms = terms ?? void 0;
9131
9251
  const evmSettlement = terms?.settlement;
9132
9252
  const solanaSettlement = terms?.settlements?.find(
9133
9253
  (entry) => entry.kind === "solana"
@@ -11544,6 +11664,7 @@ export {
11544
11664
  parseClaimStateResponse,
11545
11665
  parseConnectorIdentity,
11546
11666
  parseConnectorRoutePrice,
11667
+ parseConnectorRouteTerms,
11547
11668
  parseEvmChainId2 as parseEvmChainId,
11548
11669
  parseUiCoordinate,
11549
11670
  parseX402Body,