@toon-protocol/client 0.28.0 → 0.29.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/dist/index.d.ts CHANGED
@@ -161,6 +161,26 @@ interface InboundBtpTransfer {
161
161
  amount: bigint;
162
162
  protocolData: BTPProtocolData[];
163
163
  }
164
+ /**
165
+ * The client's payment channel, declared on the BTP auth greeting so a
166
+ * connector that credits earned increments knows which channel to pay
167
+ * (toon-client#513, connector#790). `signature` is a
168
+ * `signClaimStateChallenge` signature over `(channelId, expires)` —
169
+ * deliberately the SAME domain-separated scheme `POST /ilp/claim-state`
170
+ * already uses to prove channel ownership, never a real balance proof, so it
171
+ * can never be replayed as a payment.
172
+ */
173
+ type BtpChannelDeclaration = {
174
+ blockchain: 'evm';
175
+ channelId: string;
176
+ expires: number;
177
+ signature: string;
178
+ } | {
179
+ blockchain: 'solana';
180
+ channelAccount: string;
181
+ expires: number;
182
+ signature: string;
183
+ };
164
184
  /** What an inbound handler answers with — becomes the RESPONSE frame's body. */
165
185
  interface BtpHandlerResponse {
166
186
  protocolData?: BTPProtocolData[];
@@ -246,6 +266,13 @@ interface BtpRuntimeClientConfig {
246
266
  onTransfer?: BtpTransferHandler;
247
267
  /** Surfaces in-flight inbound work orphaned by a disconnect instead of silently vanishing. */
248
268
  onInboundError?: (error: Error, requestId: number) => void;
269
+ /**
270
+ * Called on every `connect()`/`reconnect()` and every explicit
271
+ * {@link BtpRuntimeClient.reauthenticate} to fetch the caller's current
272
+ * channel to declare on the greeting. Additive: unset (or an `undefined`
273
+ * result) leaves the greeting unchanged (toon-client#513).
274
+ */
275
+ getChannelDeclaration?: () => Promise<BtpChannelDeclaration | undefined> | BtpChannelDeclaration | undefined;
249
276
  }
250
277
  /**
251
278
  * BTP transport implementing IlpClient.
@@ -260,6 +287,13 @@ declare class BtpRuntimeClient implements IlpClient {
260
287
  * Connects to the BTP peer via WebSocket.
261
288
  */
262
289
  connect(): Promise<void>;
290
+ /**
291
+ * Re-sends the auth greeting on the EXISTING session — no reconnect — so a
292
+ * channel that became known (or changed) after `connect()` is declared on
293
+ * the live session (toon-client#513). A no-op when not connected; the next
294
+ * `connect()`/`reconnect()` already re-declares via `getChannelDeclaration`.
295
+ */
296
+ reauthenticate(): Promise<void>;
263
297
  /**
264
298
  * Attempts to reconnect by creating a fresh client and connecting.
265
299
  */
@@ -2670,6 +2704,15 @@ declare class ToonClient {
2670
2704
  * declined to open a channel from that greeting.
2671
2705
  */
2672
2706
  private lastConnectorRouteTerms?;
2707
+ /**
2708
+ * The channel most recently opened (via `openChannel()`) or adopted (via
2709
+ * `adoptChannel()`) — the one declared on the BTP session so a connector
2710
+ * crediting earned increments knows which channel to pay (toon-client#513,
2711
+ * connector#790). Read by `buildChannelDeclaration`'s `getChannelDeclaration`
2712
+ * hook on every auth greeting, including a reconnect's, so a fresh session
2713
+ * re-declares it without this client tracking reconnects itself.
2714
+ */
2715
+ private declaredChannelId?;
2673
2716
  private readonly evmSigner?;
2674
2717
  private solanaSigner?;
2675
2718
  /**
@@ -3088,6 +3131,35 @@ declare class ToonClient {
3088
3131
  * Gets the current nonce for a tracked channel.
3089
3132
  */
3090
3133
  getChannelNonce(channelId: string): number;
3134
+ /**
3135
+ * Signs a claim-state-challenge declaration for one channel — the shared
3136
+ * scheme both `getClaimState` and `buildChannelDeclaration` (toon-client#513)
3137
+ * use to prove channel ownership without moving value or advancing a nonce,
3138
+ * so it can never be replayed as a payment. `undefined` for a chain type
3139
+ * neither signer covers (Mina, or any chain this client has no signer for)
3140
+ * — matching `getClaimState`'s existing evm/solana-only posture.
3141
+ */
3142
+ private signClaimStateChallenge;
3143
+ /**
3144
+ * Signs a claim-state-challenge declaration for `this.declaredChannelId`
3145
+ * (toon-client#513). Wired as the BTP session's `getChannelDeclaration`
3146
+ * hook, so it is called on every auth greeting (initial connect, explicit
3147
+ * reauthenticate, and every reconnect) — `undefined` (no declared channel
3148
+ * yet, or a chain this endpoint doesn't cover) leaves that greeting
3149
+ * exactly as it was before this feature existed.
3150
+ */
3151
+ private buildChannelDeclaration;
3152
+ /**
3153
+ * Declares `channelId` as this client's channel on its live BTP session
3154
+ * (toon-client#513) — called after `openChannel()`/`adoptChannel()`
3155
+ * establish or resume one, so a connector crediting earned increments
3156
+ * learns the association without this client ever paying. Re-sends the
3157
+ * auth greeting on the EXISTING session; does not reconnect the socket.
3158
+ * A no-op when no BTP session is live (e.g. `btpUrl` not configured, or
3159
+ * the session is momentarily down) — the next reconnect's own greeting
3160
+ * already re-declares via `buildChannelDeclaration`.
3161
+ */
3162
+ private declareChannelOnBtpSession;
3091
3163
  /**
3092
3164
  * Gets the cumulative transferred amount for a tracked channel.
3093
3165
  */
@@ -6803,4 +6875,4 @@ declare function readExchangeOutcome(result: {
6803
6875
  /** Read a response header, case-insensitively; the first match wins. */
6804
6876
  declare function envelopeHeader(response: EnvelopeResponse, name: string): string | undefined;
6805
6877
 
6806
- export { type BackupPayload, type BalanceProofParams, BtpPaidWriteTransport, type BtpPaidWriteTransportConfig, BtpRuntimeClient, type BtpRuntimeClientConfig, type BuildSwapSettlementsParams, CLAIM_TYPEHASH, CONDITION_LENGTH, COOP_CLOSE_TYPEHASH, type ChainMetadata, type ChainSigner, type ChallengeHandler, type ChannelBinding, type ChannelBindingContext, ChannelFundingError, ChannelManager, ChannelResumeError, type ChannelStore, type ChannelStoreEntry, type ClaimMessage, type ClaimResolver, type ClaimSendingTransport, type ClaimSignature, type ClaimStateFailed, type ClaimStateOk, type ClaimStateRequestEntry, type ClaimStateResult, type ConnectorChainSettlementTerms, ConnectorEdgeClient, type ConnectorEdgeClientConfig, ConnectorEdgeError, type ConnectorEdgeErrorCode, ConnectorError, type ConnectorIdentity, type ConnectorRoutePrice, type ConnectorRouteTerms, type ConnectorSettlementTerms, type ConnectorSolanaSettlementTerms, type Decoded, type DeployMinaZkAppParams, type DiscoveredIlpPeer, type EVMClaimMessage, type EncryptedArtifact, type EncryptedKeystore, type EnsureOwnedMinaZkAppParams, type EnsureOwnedMinaZkAppResult, type Envelope, EnvelopeError, EnvelopeErrorKind, type EnvelopeHeader, type EnvelopeRequest, type EnvelopeResponse, type EvmClaimDomainContext, type EvmClaimMessage, type EvmClaimVerifyResult, type EvmCooperativeCloseMessage, type EvmReadConsistencyConfig, EvmSigner, type EvmTransferConfig, type ExchangeOutcome, type ExecutionConditionPair, FULFILLMENT_MISMATCH_CODE, FULFILLMENT_MISMATCH_MESSAGE, type FaucetChain, type FundWalletOptions, type FundWalletResult, GIFTWRAP_NONCE_LENGTH, GIFTWRAP_PUBLIC_KEY_LENGTH, GIFTWRAP_SECRET_LENGTH, GIFTWRAP_TYPE_REQUEST, GIFTWRAP_TYPE_RESPONSE, GIFT_WRAP_KIND, GiftWrapAddressError, GiftWrapDecryptError, type GiftWrapEcdh, GiftWrapError, GiftWrapErrorKind, type H402FetchOptions, HashlockConditionMismatchError, HashlockDecryptError, Http402Client, type Http402ClientConfig, HttpConnectorAdmin, type HttpConnectorAdminConfig, HttpIlpClient, type HttpIlpClientConfig, type HttpIlpClientFactory, HttpRuntimeClient, type HttpRuntimeClientConfig, ILP_CLAIM_HEADER, ILP_PEER_ID_HEADER, type IlpSendParams, type IlpSendResultWithFulfillment, type IlpTransportChoice, InMemoryChannelStore, InMemoryPreimageRetentionStore, InMemoryReceivedClaimStore, type IncrementOfferTags, type IncrementPrepare, type IngestAndRevealParams, type IngestAndRevealResult, type IngestReceivedClaimsParams, type IngestReceivedClaimsResult, InsufficientBalanceError, InvalidAddressError, type JobAnswer, type JobHandler, type JobRequest, JsonFileChannelStore, JsonFileReceivedClaimStore, KeyManager, type KeyManagerConfig, MINA_CHANNEL_STATE, type MinaChannelStateReader, type MinaClaimMessage, type MinaClaimSubmitArgs, type MinaClaimSubmitter, type MinaCoSignInputs, type MinaCoSignedClaim, type MinaDepositReader, type MinaOnChainChannelState, type MinaSettlementContext, MinaSettlementError, type MinaSettlementErrorCode, type MinaSettlementResult, type MinaSignaturePair, MinaSigner, type MinaSignerOptions, type MinaTransferConfig, type MinaZkAppDeployRecord, NetworkError, OerError, OerErrorKind, OnChainChannelClient, type OnChainChannelClientConfig, type OpenedRequest, type OrderedBtpSession, type ParsedX402Challenge, type PasskeyInfo, type PreimageRetentionStore, type PublishEventResult, ROLLING_SWAP_DOMAIN_NAME, ROLLING_SWAP_DOMAIN_VERSION, type ReceivedClaimEntry, type ReceivedClaimRejection, type ReceivedClaimRejectionCode, type ReceivedClaimStore, type RequestBlobStorageParams, type RequestBlobStorageResult, type RetainedPreimage, type RetryOptions, type RevealDecision, type RevealFn, type RevealResult, type RevealedClaim, type RolledBackClaim, SEAL_KIND, type SealedExchange, type SealedRequest, SealedResponseError, type SealedResponseErrorKind, type SelectIlpTransportOptions, type SendTransferParams, type SendTransferResult, type SignedBalanceProof, type SolanaChannelClientOptions, type SolanaClaimMessage, SolanaSigner, type SolanaTransferConfig, StaleRpcReadError, type SubmitEvmSettlementParams, type SubmitEvmSettlementResult, type SwapSettlementBuild, type ToonChannelAccept, ToonClient, type ToonClientConfig, ToonClientError, type ToonIdentity, type ToonSigners, type ToonStartResult, type TransferAssetKind, type TransferChain, type TransferConfig, TransferNotDeliveredError, TransferUnsupportedError, UnknownChainError, type UnwrappedGiftWrap, ValidationError, type VaultData, type VerifiedReceivedClaim, type WalletBalance, type WalletBalanceSources, type WalletChainBalances, type WalletTokenAmount, type X402ChannelExtra, applyDefaults, applyNetworkPresets, assertValidCondition, buildBackupEvent, buildBackupFilter, buildIncrementPrepare, buildMinaCoSignedClaim, buildSettlementInfo, buildSwapSettlements, connectorEdgeBaseUrl, createJobMessageHandler, createO1jsMinaClaimSubmitter, decodeConnectorPublicKey, decodeEnvelope, decodeEnvelopeRequest, decodeEnvelopeResponse, decodeEvmSettlementTx, decodeVarOctetString, decodeVarUint, decryptArtifact, decryptMnemonic, defaultFaucetTimeout, deployMinaChannelZkApp, deriveCondition, deriveFromNsec, deriveFulfillment, deriveFullIdentity, deriveNostrKeyFromMnemonic, encodeEnvelope, encodeEnvelopeRequest, encodeEnvelopeResponse, encodeVarOctetString, encodeVarUint, encryptArtifact, encryptMnemonic, ensureOwnedMinaZkApp, entryToAccumulatedClaim, envelopeHeader, evmClaimDigest, evmCooperativeCloseDigest, extractArweaveTxId, fulfillIncrement, fulfillmentMatchesCondition, fundWallet, generateKeystore, generateMnemonic, generateRandomIdentity, getNetworkStatus, hasSettlementMetadata, httpEndpointToBtpUrl, importKeystore, ingestAndReveal, ingestReceivedClaims, isInsufficientGasError, isPrfSupported, isZeroCondition, loadKeystore, localGiftWrapEcdh, looksLikeSealedResponse, mintExecutionCondition, openRequest, openResponse, parseBackupPayload, parseClaimStateResponse, parseConnectorIdentity, parseConnectorRoutePrice, parseConnectorRouteTerms, parseEvmChainId, parseX402Body, parseX402Challenge, proxyIlpEndpoint, readDiscoveredIlpPeer, readEvmNativeBalance, readEvmTokenBalance, readExchangeOutcome, readMinaBalance, readMinaChannelState, readMinaDepositTotal, readSolanaNativeBalance, readSolanaTokenBalance, readWalletBalances, recoverEvmClaimSigner, requestBlobStorage, sealExchange, sealRequest, sealRequestWithRandomness, sealResponse, sealResponseWithRandomness, selectIlpTransport, sendTransfer, submitEvmSettlement, submitMinaSettlement, unwrapGiftWrapWithKey, validateConfig, validateMnemonic, verifyEvmClaimSignature, withRetry, writeKeystoreFile };
6878
+ export { type BackupPayload, type BalanceProofParams, type BtpChannelDeclaration, BtpPaidWriteTransport, type BtpPaidWriteTransportConfig, BtpRuntimeClient, type BtpRuntimeClientConfig, type BuildSwapSettlementsParams, CLAIM_TYPEHASH, CONDITION_LENGTH, COOP_CLOSE_TYPEHASH, type ChainMetadata, type ChainSigner, type ChallengeHandler, type ChannelBinding, type ChannelBindingContext, ChannelFundingError, ChannelManager, ChannelResumeError, type ChannelStore, type ChannelStoreEntry, type ClaimMessage, type ClaimResolver, type ClaimSendingTransport, type ClaimSignature, type ClaimStateFailed, type ClaimStateOk, type ClaimStateRequestEntry, type ClaimStateResult, type ConnectorChainSettlementTerms, ConnectorEdgeClient, type ConnectorEdgeClientConfig, ConnectorEdgeError, type ConnectorEdgeErrorCode, ConnectorError, type ConnectorIdentity, type ConnectorRoutePrice, type ConnectorRouteTerms, type ConnectorSettlementTerms, type ConnectorSolanaSettlementTerms, type Decoded, type DeployMinaZkAppParams, type DiscoveredIlpPeer, type EVMClaimMessage, type EncryptedArtifact, type EncryptedKeystore, type EnsureOwnedMinaZkAppParams, type EnsureOwnedMinaZkAppResult, type Envelope, EnvelopeError, EnvelopeErrorKind, type EnvelopeHeader, type EnvelopeRequest, type EnvelopeResponse, type EvmClaimDomainContext, type EvmClaimMessage, type EvmClaimVerifyResult, type EvmCooperativeCloseMessage, type EvmReadConsistencyConfig, EvmSigner, type EvmTransferConfig, type ExchangeOutcome, type ExecutionConditionPair, FULFILLMENT_MISMATCH_CODE, FULFILLMENT_MISMATCH_MESSAGE, type FaucetChain, type FundWalletOptions, type FundWalletResult, GIFTWRAP_NONCE_LENGTH, GIFTWRAP_PUBLIC_KEY_LENGTH, GIFTWRAP_SECRET_LENGTH, GIFTWRAP_TYPE_REQUEST, GIFTWRAP_TYPE_RESPONSE, GIFT_WRAP_KIND, GiftWrapAddressError, GiftWrapDecryptError, type GiftWrapEcdh, GiftWrapError, GiftWrapErrorKind, type H402FetchOptions, HashlockConditionMismatchError, HashlockDecryptError, Http402Client, type Http402ClientConfig, HttpConnectorAdmin, type HttpConnectorAdminConfig, HttpIlpClient, type HttpIlpClientConfig, type HttpIlpClientFactory, HttpRuntimeClient, type HttpRuntimeClientConfig, ILP_CLAIM_HEADER, ILP_PEER_ID_HEADER, type IlpSendParams, type IlpSendResultWithFulfillment, type IlpTransportChoice, InMemoryChannelStore, InMemoryPreimageRetentionStore, InMemoryReceivedClaimStore, type IncrementOfferTags, type IncrementPrepare, type IngestAndRevealParams, type IngestAndRevealResult, type IngestReceivedClaimsParams, type IngestReceivedClaimsResult, InsufficientBalanceError, InvalidAddressError, type JobAnswer, type JobHandler, type JobRequest, JsonFileChannelStore, JsonFileReceivedClaimStore, KeyManager, type KeyManagerConfig, MINA_CHANNEL_STATE, type MinaChannelStateReader, type MinaClaimMessage, type MinaClaimSubmitArgs, type MinaClaimSubmitter, type MinaCoSignInputs, type MinaCoSignedClaim, type MinaDepositReader, type MinaOnChainChannelState, type MinaSettlementContext, MinaSettlementError, type MinaSettlementErrorCode, type MinaSettlementResult, type MinaSignaturePair, MinaSigner, type MinaSignerOptions, type MinaTransferConfig, type MinaZkAppDeployRecord, NetworkError, OerError, OerErrorKind, OnChainChannelClient, type OnChainChannelClientConfig, type OpenedRequest, type OrderedBtpSession, type ParsedX402Challenge, type PasskeyInfo, type PreimageRetentionStore, type PublishEventResult, ROLLING_SWAP_DOMAIN_NAME, ROLLING_SWAP_DOMAIN_VERSION, type ReceivedClaimEntry, type ReceivedClaimRejection, type ReceivedClaimRejectionCode, type ReceivedClaimStore, type RequestBlobStorageParams, type RequestBlobStorageResult, type RetainedPreimage, type RetryOptions, type RevealDecision, type RevealFn, type RevealResult, type RevealedClaim, type RolledBackClaim, SEAL_KIND, type SealedExchange, type SealedRequest, SealedResponseError, type SealedResponseErrorKind, type SelectIlpTransportOptions, type SendTransferParams, type SendTransferResult, type SignedBalanceProof, type SolanaChannelClientOptions, type SolanaClaimMessage, SolanaSigner, type SolanaTransferConfig, StaleRpcReadError, type SubmitEvmSettlementParams, type SubmitEvmSettlementResult, type SwapSettlementBuild, type ToonChannelAccept, ToonClient, type ToonClientConfig, ToonClientError, type ToonIdentity, type ToonSigners, type ToonStartResult, type TransferAssetKind, type TransferChain, type TransferConfig, TransferNotDeliveredError, TransferUnsupportedError, UnknownChainError, type UnwrappedGiftWrap, ValidationError, type VaultData, type VerifiedReceivedClaim, type WalletBalance, type WalletBalanceSources, type WalletChainBalances, type WalletTokenAmount, type X402ChannelExtra, applyDefaults, applyNetworkPresets, assertValidCondition, buildBackupEvent, buildBackupFilter, buildIncrementPrepare, buildMinaCoSignedClaim, buildSettlementInfo, buildSwapSettlements, connectorEdgeBaseUrl, createJobMessageHandler, createO1jsMinaClaimSubmitter, decodeConnectorPublicKey, decodeEnvelope, decodeEnvelopeRequest, decodeEnvelopeResponse, decodeEvmSettlementTx, decodeVarOctetString, decodeVarUint, decryptArtifact, decryptMnemonic, defaultFaucetTimeout, deployMinaChannelZkApp, deriveCondition, deriveFromNsec, deriveFulfillment, deriveFullIdentity, deriveNostrKeyFromMnemonic, encodeEnvelope, encodeEnvelopeRequest, encodeEnvelopeResponse, encodeVarOctetString, encodeVarUint, encryptArtifact, encryptMnemonic, ensureOwnedMinaZkApp, entryToAccumulatedClaim, envelopeHeader, evmClaimDigest, evmCooperativeCloseDigest, extractArweaveTxId, fulfillIncrement, fulfillmentMatchesCondition, fundWallet, generateKeystore, generateMnemonic, generateRandomIdentity, getNetworkStatus, hasSettlementMetadata, httpEndpointToBtpUrl, importKeystore, ingestAndReveal, ingestReceivedClaims, isInsufficientGasError, isPrfSupported, isZeroCondition, loadKeystore, localGiftWrapEcdh, looksLikeSealedResponse, mintExecutionCondition, openRequest, openResponse, parseBackupPayload, parseClaimStateResponse, parseConnectorIdentity, parseConnectorRoutePrice, parseConnectorRouteTerms, parseEvmChainId, parseX402Body, parseX402Challenge, proxyIlpEndpoint, readDiscoveredIlpPeer, readEvmNativeBalance, readEvmTokenBalance, readExchangeOutcome, readMinaBalance, readMinaChannelState, readMinaDepositTotal, readSolanaNativeBalance, readSolanaTokenBalance, readWalletBalances, recoverEvmClaimSigner, requestBlobStorage, sealExchange, sealRequest, sealRequestWithRandomness, sealResponse, sealResponseWithRandomness, selectIlpTransport, sendTransfer, submitEvmSettlement, submitMinaSettlement, unwrapGiftWrapWithKey, validateConfig, validateMnemonic, verifyEvmClaimSignature, withRetry, writeKeystoreFile };
package/dist/index.js CHANGED
@@ -2557,12 +2557,27 @@ var IsomorphicBtpClient = class {
2557
2557
  });
2558
2558
  this.ws.send(btpMessage);
2559
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
+ }
2560
2573
  // ─── Private ────────────────────────────────────────────────────────────
2561
2574
  async authenticate() {
2562
2575
  if (!this.ws) throw new BtpAuthError("WebSocket not connected");
2576
+ const declaration = await this.config.getChannelDeclaration?.();
2563
2577
  const authData = JSON.stringify({
2564
2578
  peerId: this.config.peerId,
2565
- secret: this.config.authToken
2579
+ secret: this.config.authToken,
2580
+ ...declaration ?? {}
2566
2581
  });
2567
2582
  const requestId = this.nextRequestId();
2568
2583
  const authMessage = serializeBtpMessage({
@@ -2898,11 +2913,22 @@ var BtpRuntimeClient = class {
2898
2913
  createWebSocket: this.config.createWebSocket,
2899
2914
  onMessage: this.config.onMessage,
2900
2915
  onTransfer: this.config.onTransfer,
2901
- onInboundError: this.config.onInboundError
2916
+ onInboundError: this.config.onInboundError,
2917
+ getChannelDeclaration: this.config.getChannelDeclaration
2902
2918
  });
2903
2919
  await this.btpClient.connect();
2904
2920
  this._isConnected = true;
2905
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
+ }
2906
2932
  /**
2907
2933
  * Attempts to reconnect by creating a fresh client and connecting.
2908
2934
  */
@@ -5025,7 +5051,7 @@ var EvmSigner = class {
5025
5051
  };
5026
5052
 
5027
5053
  // src/modes/http.ts
5028
- async function initializeHttpMode(config) {
5054
+ async function initializeHttpMode(config, hooks = {}) {
5029
5055
  const effectiveBtpUrl = config.btpUrl;
5030
5056
  const effectiveConnectorUrl = config.connectorUrl;
5031
5057
  const settlementInfo = buildSettlementInfo(config);
@@ -5046,7 +5072,8 @@ async function initializeHttpMode(config) {
5046
5072
  // MESSAGE carrying a PREPARE is answered by the configured handler.
5047
5073
  // Unset `jobHandler` leaves `onMessage` unset too, so an inbound job
5048
5074
  // MESSAGE is dropped unanswered — unchanged from the pre-#494 default.
5049
- ...config.jobHandler ? { onMessage: createJobMessageHandler(config.jobHandler) } : {}
5075
+ ...config.jobHandler ? { onMessage: createJobMessageHandler(config.jobHandler) } : {},
5076
+ ...hooks.getChannelDeclaration ? { getChannelDeclaration: hooks.getChannelDeclaration } : {}
5050
5077
  });
5051
5078
  await btpClient.connect();
5052
5079
  }
@@ -5115,6 +5142,7 @@ async function initializeHttpMode(config) {
5115
5142
  runtimeClient,
5116
5143
  adminClient: null,
5117
5144
  btpClient: paidWriteBtpClient,
5145
+ btpSession: btpClient,
5118
5146
  onChainChannelClient
5119
5147
  };
5120
5148
  }
@@ -7765,6 +7793,15 @@ var ToonClient = class {
7765
7793
  * declined to open a channel from that greeting.
7766
7794
  */
7767
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;
7768
7805
  evmSigner;
7769
7806
  solanaSigner;
7770
7807
  /**
@@ -7963,8 +8000,16 @@ var ToonClient = class {
7963
8000
  );
7964
8001
  }
7965
8002
  }
7966
- const initialization = await initializeHttpMode(this.config);
7967
- 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;
7968
8013
  if (this.channelManager) {
7969
8014
  const cm = this.channelManager;
7970
8015
  const nostrPubkey = this.getPublicKey();
@@ -8062,7 +8107,8 @@ var ToonClient = class {
8062
8107
  discoveryTracker,
8063
8108
  runtimeClient,
8064
8109
  peersDiscovered: bootstrapResults.length,
8065
- btpClient: btpClient ?? void 0
8110
+ btpClient: btpClient ?? void 0,
8111
+ btpSession: btpSession ?? void 0
8066
8112
  };
8067
8113
  return {
8068
8114
  peersDiscovered: bootstrapResults.length,
@@ -8578,11 +8624,14 @@ var ToonClient = class {
8578
8624
  "PEER_NOT_NEGOTIATED"
8579
8625
  );
8580
8626
  }
8627
+ let channelId;
8581
8628
  try {
8582
- return await this.channelManager.ensureChannel(peerId, negotiation);
8629
+ channelId = await this.channelManager.ensureChannel(peerId, negotiation);
8583
8630
  } catch (error) {
8584
8631
  throw this.withSolanaLegHint(peerId, error);
8585
8632
  }
8633
+ await this.declareChannelOnBtpSession(channelId);
8634
+ return channelId;
8586
8635
  }
8587
8636
  /**
8588
8637
  * Adopt an ALREADY-OPEN payment channel for `destination` — the restart path
@@ -8610,6 +8659,7 @@ var ToonClient = class {
8610
8659
  );
8611
8660
  }
8612
8661
  this.channelManager.adoptChannel(peerId, negotiation, channelId);
8662
+ await this.declareChannelOnBtpSession(channelId);
8613
8663
  }
8614
8664
  /**
8615
8665
  * Gets list of tracked payment channel IDs.
@@ -8624,6 +8674,63 @@ var ToonClient = class {
8624
8674
  if (!this.channelManager) throw new Error("ChannelManager not initialized");
8625
8675
  return this.channelManager.getNonce(channelId);
8626
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
+ }
8627
8734
  /**
8628
8735
  * Gets the cumulative transferred amount for a tracked channel.
8629
8736
  */
@@ -8665,25 +8772,7 @@ var ToonClient = class {
8665
8772
  ids.map(async (channelId) => {
8666
8773
  const context = channelManager.getChannelContext(channelId);
8667
8774
  if (!context) return null;
8668
- if (context.chainType === "evm") {
8669
- if (!this.evmSigner) return null;
8670
- const signature = await this.evmSigner.signClaimStateChallenge({
8671
- chainId: context.chainId,
8672
- tokenNetworkAddress: context.tokenNetworkAddress,
8673
- channelId,
8674
- expires
8675
- });
8676
- return { blockchain: "evm", channelId, expires, signature };
8677
- }
8678
- if (context.chainType === "solana") {
8679
- if (!this.solanaSigner) return null;
8680
- const signature = await this.solanaSigner.signClaimStateChallenge({
8681
- channelAccount: channelId,
8682
- expires
8683
- });
8684
- return { blockchain: "solana", channelAccount: channelId, expires, signature };
8685
- }
8686
- return null;
8775
+ return await this.signClaimStateChallenge(channelId, context, expires) ?? null;
8687
8776
  })
8688
8777
  );
8689
8778
  const requests = entries.filter(