@toon-protocol/client 0.29.6 → 0.29.8

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
@@ -65,6 +65,18 @@ var ConnectorError = class extends ToonClientError {
65
65
  this.name = "ConnectorError";
66
66
  }
67
67
  };
68
+ var Http402RequiresBtpError = class extends ToonClientError {
69
+ constructor(message2, cause) {
70
+ super(message2, "HTTP_402_REQUIRES_BTP", cause);
71
+ this.name = "Http402RequiresBtpError";
72
+ }
73
+ };
74
+ var Http401RequiresBtpError = class extends ToonClientError {
75
+ constructor(message2, cause) {
76
+ super(message2, "HTTP_401_REQUIRES_BTP", cause);
77
+ this.name = "Http401RequiresBtpError";
78
+ }
79
+ };
68
80
  var ValidationError = class extends ToonClientError {
69
81
  constructor(message2, cause) {
70
82
  super(message2, "VALIDATION_ERROR", cause);
@@ -3205,11 +3217,37 @@ var HttpIlpClient = class {
3205
3217
  return client;
3206
3218
  }
3207
3219
  // ─── Private ──────────────────────────────────────────────────────────────
3220
+ /**
3221
+ * The identity headers to present, if any.
3222
+ *
3223
+ * A peer id and its bearer secret are ONE credential, so both are sent or
3224
+ * neither is (issue #565). Presenting a `peerId` this client cannot back
3225
+ * with a secret is strictly WORSE than presenting nothing: the connector's
3226
+ * client edge resolves a PRESENTED identity first and answers `401` before
3227
+ * it ever looks at the route
3228
+ * (connector `crates/connector-client-edge/src/lib.rs`, whose own comment
3229
+ * reads "A request presenting no `ILP-Peer-Id` is unaffected here — it is
3230
+ * anonymous, resolved once the claim (if any) has been admitted"), whereas
3231
+ * anonymous + a valid payment-channel claim is the supported permissionless
3232
+ * path. The live devnet daemon shipped `ILP-Peer-Id: g.toon.client` with an
3233
+ * EMPTY token — an id no connector has a registration for — so every default
3234
+ * paid write over `POST /ilp` 401'd before the claim was read at all.
3235
+ *
3236
+ * An empty-string token is not a credential; `''` is falsy here on purpose.
3237
+ *
3238
+ * This REMOVES the 401 rather than recovering from it, so it complements
3239
+ * #569's {@link Http401RequiresBtpError} fallback instead of replacing it:
3240
+ * that fallback still catches a 401 with any other cause, but it costs a
3241
+ * failed round trip per write and can only rescue a client that has a BTP
3242
+ * uplink — a proxy-only client had no route to a paid write at all, even
3243
+ * though anonymous + claim is exactly the path that would have worked.
3244
+ */
3208
3245
  authHeaders() {
3209
- const headers = {};
3210
- if (this.peerId) headers[ILP_PEER_ID_HEADER] = this.peerId;
3211
- if (this.authToken) headers["Authorization"] = `Bearer ${this.authToken}`;
3212
- return headers;
3246
+ if (!this.peerId || !this.authToken) return {};
3247
+ return {
3248
+ [ILP_PEER_ID_HEADER]: this.peerId,
3249
+ Authorization: `Bearer ${this.authToken}`
3250
+ };
3213
3251
  }
3214
3252
  /**
3215
3253
  * Single attempt: serialize the PREPARE, POST it, and map the response.
@@ -3235,9 +3273,7 @@ var HttpIlpClient = class {
3235
3273
  ...this.authHeaders()
3236
3274
  };
3237
3275
  if (claim !== void 0) {
3238
- headers[ILP_CLAIM_HEADER] = toBase64(
3239
- encodeUtf8(JSON.stringify(claim))
3240
- );
3276
+ headers[ILP_CLAIM_HEADER] = toBase64(encodeUtf8(JSON.stringify(claim)));
3241
3277
  }
3242
3278
  const controller = new AbortController();
3243
3279
  const timeoutId = setTimeout(() => controller.abort(), requestTimeout);
@@ -3269,12 +3305,27 @@ var HttpIlpClient = class {
3269
3305
  if (response.ok) {
3270
3306
  const buf = new Uint8Array(await response.arrayBuffer());
3271
3307
  if (buf.length === 0) {
3272
- throw new ConnectorError("Empty 200 body from /ilp (expected OER ILP response)");
3308
+ throw new ConnectorError(
3309
+ "Empty 200 body from /ilp (expected OER ILP response)"
3310
+ );
3273
3311
  }
3274
3312
  return mapIlpResponse(deserializeIlpPacket(buf), sentCondition);
3275
3313
  }
3276
3314
  const body = await response.text().catch(() => "");
3277
3315
  const detail = body ? `: ${body}` : "";
3316
+ if (response.status === 402) {
3317
+ const requiredTransport = extractRequiredTransportFrom402Body(body);
3318
+ if (requiredTransport === "btp") {
3319
+ throw new Http402RequiresBtpError(
3320
+ `The connector at ${this.httpEndpoint} refused this paid write with 402, declaring requiredTransport: "btp" in its x402 challenge.`
3321
+ );
3322
+ }
3323
+ }
3324
+ if (response.status === 401) {
3325
+ throw new Http401RequiresBtpError(
3326
+ `The connector at ${this.httpEndpoint} refused this paid write with 401${detail}.`
3327
+ );
3328
+ }
3278
3329
  if (response.status >= 500) {
3279
3330
  throw new ConnectorError(
3280
3331
  `Connector transport error (${response.status} ${response.statusText})${detail}`
@@ -3285,14 +3336,24 @@ var HttpIlpClient = class {
3285
3336
  );
3286
3337
  }
3287
3338
  mapTransportError(error, requestTimeout) {
3288
- if (error instanceof ConnectorError || error instanceof NetworkError) {
3339
+ if (error instanceof ConnectorError || error instanceof NetworkError || // Thrown by `mapResponse` inside the same try — must pass through
3340
+ // unwrapped so a caller can retry over BTP (toon-client#561, #565).
3341
+ // Neither is a `ConnectorError` (a distinct code/type is the whole
3342
+ // point of those classes), so each needs its own check here.
3343
+ error instanceof Http402RequiresBtpError || error instanceof Http401RequiresBtpError) {
3289
3344
  return error;
3290
3345
  }
3291
3346
  if (error instanceof Error && error.name === "AbortError") {
3292
- return new NetworkError(`Request timeout after ${requestTimeout}ms`, error);
3347
+ return new NetworkError(
3348
+ `Request timeout after ${requestTimeout}ms`,
3349
+ error
3350
+ );
3293
3351
  }
3294
3352
  if (error instanceof TypeError && (error.message.includes("fetch failed") || error.message.includes("ECONNREFUSED") || error.message.includes("ECONNRESET") || error.message.includes("ETIMEDOUT") || error.message.includes("network"))) {
3295
- return new NetworkError(`Network connection failed: ${error.message}`, error);
3353
+ return new NetworkError(
3354
+ `Network connection failed: ${error.message}`,
3355
+ error
3356
+ );
3296
3357
  }
3297
3358
  return new ConnectorError(
3298
3359
  `Unexpected error during ILP-over-HTTP request: ${error instanceof Error ? error.message : String(error)}`,
@@ -3300,6 +3361,26 @@ var HttpIlpClient = class {
3300
3361
  );
3301
3362
  }
3302
3363
  };
3364
+ function extractRequiredTransportFrom402Body(body) {
3365
+ let parsed;
3366
+ try {
3367
+ parsed = JSON.parse(body);
3368
+ } catch {
3369
+ return void 0;
3370
+ }
3371
+ if (typeof parsed !== "object" || parsed === null) return void 0;
3372
+ const accepts = parsed["accepts"];
3373
+ if (!Array.isArray(accepts)) return void 0;
3374
+ for (const raw of accepts) {
3375
+ if (typeof raw !== "object" || raw === null) continue;
3376
+ const entry = raw;
3377
+ const extra = entry["extra"];
3378
+ const fromExtra = typeof extra === "object" && extra !== null ? extra["requiredTransport"] : void 0;
3379
+ const value = fromExtra ?? entry["requiredTransport"];
3380
+ if (typeof value === "string") return value;
3381
+ }
3382
+ return void 0;
3383
+ }
3303
3384
  function httpEndpointToBtpUrl(httpEndpoint) {
3304
3385
  return httpEndpoint.replace(/^https:\/\//i, "wss://").replace(/^http:\/\//i, "ws://");
3305
3386
  }
@@ -4842,7 +4923,7 @@ var OnChainChannelClient = class {
4842
4923
  chain
4843
4924
  });
4844
4925
  }
4845
- return { channelId, status: "opening" };
4926
+ return { channelId, status: "opening", depositTotal: deposit };
4846
4927
  }
4847
4928
  /**
4848
4929
  * Poll the TokenNetwork until it reports the just-opened channel (non-zero
@@ -5133,6 +5214,12 @@ async function initializeHttpMode(config, hooks = {}) {
5133
5214
  if (transportChoice && (transportChoice.kind === "http" || transportChoice.kind === "http-upgradable")) {
5134
5215
  httpIlpClient = new HttpIlpClient({
5135
5216
  httpEndpoint: transportChoice.httpEndpoint,
5217
+ // Carried for the BTP-upgrade auth frame; it only reaches the `POST
5218
+ // /ilp` wire as `ILP-Peer-Id` when a non-empty `btpAuthToken` backs it
5219
+ // (issue #565 — see `HttpIlpClient.authHeaders`). The BTP greeting is a
5220
+ // different contract: the connector accepts an unregistered id there and
5221
+ // resolves the payer from the claim, which is why `btpPeerId` stays the
5222
+ // per-client id `toon-client#503` made it.
5136
5223
  peerId: btpPeerId,
5137
5224
  ...config.btpAuthToken !== void 0 ? { authToken: config.btpAuthToken } : {},
5138
5225
  timeout: config.queryTimeout,
@@ -5823,8 +5910,11 @@ var ChannelManager = class _ChannelManager {
5823
5910
  };
5824
5911
  this.trackChannel(result.channelId, {
5825
5912
  ...context,
5826
- // On-chain depositTotal (Mina only) — needed so the Mina signer binds
5827
- // balanceB = depositTotal − balanceA (connector#133).
5913
+ // On-chain depositTotal, reported by every opener since issue #565
5914
+ // (it was Mina-only before, so an EVM channel's collateral read back
5915
+ // as 0). The Mina signer needs it to bind balanceB = depositTotal −
5916
+ // balanceA (connector#133); every chain needs it for the spendable
5917
+ // balance `depositTotal - cumulativeAmount`.
5828
5918
  depositTotal: result.depositTotal
5829
5919
  });
5830
5920
  this.peerChannels.set(key2, result.channelId);
@@ -5858,9 +5948,16 @@ var ChannelManager = class _ChannelManager {
5858
5948
  tokenAddress: negotiation.tokenAddress,
5859
5949
  recipient: negotiation.settlementAddress
5860
5950
  };
5861
- this.trackChannel(channelId, context);
5951
+ const bound = this.store?.loadBinding?.(key2);
5952
+ const deposited = bound?.channelId === channelId ? bound.depositTotal : void 0;
5953
+ this.trackChannel(channelId, {
5954
+ ...context,
5955
+ ...deposited !== void 0 ? { depositTotal: deposited } : {}
5956
+ });
5862
5957
  this.peerChannels.set(key2, channelId);
5863
- this.bindChannel(key2, channelId, context, {});
5958
+ this.bindChannel(key2, channelId, context, {
5959
+ ...deposited !== void 0 ? { depositTotal: deposited } : {}
5960
+ });
5864
5961
  this.adoptOnChainContext(channelId, negotiation);
5865
5962
  }
5866
5963
  /**
@@ -6104,6 +6201,10 @@ var ChannelManager = class _ChannelManager {
6104
6201
  * Update the tracked on-chain deposit total after a successful deposit, so the
6105
6202
  * available balance (`depositTotal - cumulativeAmount`) reflects the new
6106
6203
  * collateral on the next read.
6204
+ *
6205
+ * Also written through to the peer BINDING (issue #565) — the deposit is an
6206
+ * on-chain fact, so a restart must resume with the collateral that is
6207
+ * actually locked, not the amount recorded when the channel was first opened.
6107
6208
  */
6108
6209
  setDepositTotal(channelId, total) {
6109
6210
  const tracking = this.channels.get(channelId);
@@ -6111,6 +6212,23 @@ var ChannelManager = class _ChannelManager {
6111
6212
  throw new Error(`Channel "${channelId}" is not being tracked.`);
6112
6213
  }
6113
6214
  tracking.depositTotal = total;
6215
+ this.persistDepositTotal(channelId, total);
6216
+ }
6217
+ /**
6218
+ * Write `total` into whichever peer binding names `channelId`. No-op without
6219
+ * a store that persists bindings, or when no binding names this channel (an
6220
+ * untracked/foreign channel has no collateral of ours to record).
6221
+ */
6222
+ persistDepositTotal(channelId, total) {
6223
+ const store = this.store;
6224
+ if (!store?.saveBinding || !store.loadBinding) return;
6225
+ for (const [key2, bound] of this.peerChannels) {
6226
+ if (bound !== channelId) continue;
6227
+ const binding = store.loadBinding(key2);
6228
+ if (!binding) continue;
6229
+ store.saveBinding(key2, { ...binding, depositTotal: total });
6230
+ return;
6231
+ }
6114
6232
  }
6115
6233
  /** Persist a channel's full nonce/amount + withdraw-timer state to the store. */
6116
6234
  persist(channelId) {
@@ -7872,6 +7990,18 @@ function claimsTermination(peerInfo, address, destination) {
7872
7990
  function sendsClaims(candidate) {
7873
7991
  return typeof candidate?.sendIlpPacketWithClaim === "function";
7874
7992
  }
7993
+ function btpFallbackSignal(error) {
7994
+ if (error instanceof Http402RequiresBtpError) {
7995
+ return { error, reason: '402 response declared requiredTransport: "btp"' };
7996
+ }
7997
+ if (error instanceof Http401RequiresBtpError) {
7998
+ return {
7999
+ error,
8000
+ reason: "401 response rejected the discovered/unconfigured peer identity"
8001
+ };
8002
+ }
8003
+ return void 0;
8004
+ }
7875
8005
  function outranks(claim, best) {
7876
8006
  if (claim.segments !== best.segments) return claim.segments > best.segments;
7877
8007
  return claim.isPrimary && !best.isPrimary;
@@ -7881,7 +8011,7 @@ function resolveTerminatorHttpEndpoint(destination, peers) {
7881
8011
  }
7882
8012
  function findBestTerminatorClaim(destination, peers) {
7883
8013
  let best;
7884
- for (const { peerInfo, pubkey } of peers) {
8014
+ for (const { peerInfo, pubkey, peerId } of peers) {
7885
8015
  const httpEndpoint = peerInfo.httpEndpoint;
7886
8016
  if (!httpEndpoint) continue;
7887
8017
  const addresses = peerInfo.ilpAddresses ?? [peerInfo.ilpAddress];
@@ -7891,7 +8021,9 @@ function findBestTerminatorClaim(destination, peers) {
7891
8021
  endpoint: httpEndpoint,
7892
8022
  segments: address.split(".").length,
7893
8023
  isPrimary: index === 0,
7894
- pubkey
8024
+ pubkey,
8025
+ peerId,
8026
+ peerInfo
7895
8027
  };
7896
8028
  if (!best || outranks(claim, best)) best = claim;
7897
8029
  }
@@ -8210,32 +8342,12 @@ var ToonClient = class {
8210
8342
  tokenNetwork: r.tokenNetwork
8211
8343
  });
8212
8344
  } else if (result.registeredPeerId && !this.peerNegotiations.has(result.registeredPeerId)) {
8213
- const peerInfo = result.peerInfo;
8214
- const peerChains = peerInfo.supportedChains ?? [];
8215
- const ourChains = this.config.supportedChains ?? [];
8216
- const matchedChain = this.matchNegotiatedChain(
8217
- ourChains,
8218
- peerChains,
8345
+ const announced = this.negotiationFromAnnounce(
8346
+ result.peerInfo,
8219
8347
  result.registeredPeerId
8220
8348
  );
8221
- const peerAddr = peerInfo.settlementAddresses?.[matchedChain];
8222
- const parts = matchedChain.split(":");
8223
- const chainId = parts.length >= 3 ? parseInt(parts[2] ?? "0", 10) : parts.length >= 2 ? parseInt(parts[1] ?? "0", 10) : 0;
8224
- if (peerAddr) {
8225
- this.peerNegotiations.set(result.registeredPeerId, {
8226
- chain: matchedChain,
8227
- chainType: parts[0] ?? "evm",
8228
- chainId: isNaN(chainId) ? 0 : chainId,
8229
- settlementAddress: peerAddr,
8230
- tokenAddress: peerInfo.preferredTokens?.[matchedChain] ?? lookupByCanonicalChain(
8231
- this.config.preferredTokens,
8232
- matchedChain
8233
- ),
8234
- tokenNetwork: peerInfo.tokenNetworks?.[matchedChain] ?? lookupByCanonicalChain(
8235
- this.config.tokenNetworks,
8236
- matchedChain
8237
- )
8238
- });
8349
+ if (announced) {
8350
+ this.peerNegotiations.set(result.registeredPeerId, announced);
8239
8351
  }
8240
8352
  }
8241
8353
  if (this.channelManager && result.channelId && !this.channelManager.isTracking(result.channelId)) {
@@ -8367,7 +8479,9 @@ var ToonClient = class {
8367
8479
  BigInt(amount),
8368
8480
  options?.claim
8369
8481
  );
8370
- const response = await transport.sendIlpPacketWithClaim(
8482
+ const response = await this.sendClaimBearingPacket(
8483
+ destination,
8484
+ transport,
8371
8485
  {
8372
8486
  destination,
8373
8487
  amount,
@@ -8686,7 +8800,9 @@ var ToonClient = class {
8686
8800
  params.amount,
8687
8801
  params.claim
8688
8802
  );
8689
- return transport.sendIlpPacketWithClaim(
8803
+ return this.sendClaimBearingPacket(
8804
+ params.destination,
8805
+ transport,
8690
8806
  {
8691
8807
  destination: params.destination,
8692
8808
  amount: String(params.amount),
@@ -8793,6 +8909,59 @@ var ToonClient = class {
8793
8909
  "NO_ILP_TRANSPORT"
8794
8910
  );
8795
8911
  }
8912
+ /**
8913
+ * Sends a claim-bearing PREPARE over the ALREADY-RESOLVED `transport` (a
8914
+ * prior {@link getClaimTransport} call — kept as a separate argument so the
8915
+ * NO_ILP_TRANSPORT/BTP_REQUIRED failure modes of resolving a transport at
8916
+ * all still surface before any claim is resolved, matching every caller's
8917
+ * existing behavior), retrying once over the BTP uplink when it comes back
8918
+ * with a transport signal that says so — {@link btpFallbackSignal}.
8919
+ *
8920
+ * {@link Http402RequiresBtpError} (issue #561) is the first such signal.
8921
+ * `getClaimTransport`'s own `requiredTransport` check ({@link
8922
+ * terminatorRequiresBtp}) reads the peer's kind:10032 announce — but the
8923
+ * live devnet relay's announce never carries that field, only its `402`
8924
+ * response does, and only once a write has already been posted over HTTP.
8925
+ * So the announce-based guard alone is dead code against that fleet: this
8926
+ * is the fallback that actually avoids the repeat-402 loop, discovered
8927
+ * live rather than assumed from the announce.
8928
+ *
8929
+ * `Http401RequiresBtpError` (issue #565) is the same shape of problem from
8930
+ * a different connector generation: the rust edge live on the two-box
8931
+ * devnet answers a discovered/unconfigured peer identity with a bare `401`
8932
+ * rather than the 402 x402 greeting, so it gets the identical retry — both
8933
+ * error types are transport-signal-only and neither implies the write
8934
+ * itself was invalid.
8935
+ *
8936
+ * A retry is attempted only when the failing transport was not already the
8937
+ * BTP one (neither error can come from the BTP transport in the first
8938
+ * place — BTP has no HTTP status codes) and a BTP uplink is actually
8939
+ * configured; otherwise this throws the same `BTP_REQUIRED` error
8940
+ * `getClaimTransport` throws for the announce-based case, so callers see
8941
+ * one consistent code regardless of which guard caught it.
8942
+ *
8943
+ * @throws {ToonClientError} BTP_REQUIRED when the terminator's 401/402
8944
+ * response demands BTP but this client has no BTP uplink (`btpUrl`)
8945
+ * configured.
8946
+ */
8947
+ async sendClaimBearingPacket(destination, transport, params, claim) {
8948
+ try {
8949
+ return await transport.sendIlpPacketWithClaim(params, claim);
8950
+ } catch (error) {
8951
+ const signal = btpFallbackSignal(error);
8952
+ if (!signal) throw error;
8953
+ const uplink = this.state?.btpClient;
8954
+ const btp = sendsClaims(uplink) ? uplink : void 0;
8955
+ if (btp && btp !== transport) {
8956
+ return btp.sendIlpPacketWithClaim(params, claim);
8957
+ }
8958
+ throw new ToonClientError(
8959
+ `The connector terminating "${destination}" requires BTP for paid writes (its ${signal.reason}), but this client has no BTP uplink (\`btpUrl\`) configured.`,
8960
+ "BTP_REQUIRED",
8961
+ signal.error
8962
+ );
8963
+ }
8964
+ }
8796
8965
  /**
8797
8966
  * Shared claim-resolution logic used by `publishEvent` and `sendSwapPacket`.
8798
8967
  */
@@ -8802,7 +8971,7 @@ var ToonClient = class {
8802
8971
  }
8803
8972
  if (this.channelManager) {
8804
8973
  const peerId = this.peerIdForClaim(destination);
8805
- const negotiation = this.peerNegotiations.get(peerId) ?? await this.negotiateFromGreeting(destination, peerId);
8974
+ const negotiation = await this.negotiationFor(destination, peerId);
8806
8975
  if (!negotiation) {
8807
8976
  throw new ToonClientError(
8808
8977
  `No negotiation metadata for peer "${peerId}" \u2014 was bootstrap completed? (and the route's x402 greeting carried no settlement facts to bootstrap from)`,
@@ -8857,6 +9026,13 @@ var ToonClient = class {
8857
9026
  * can force the open. Idempotent — returns the existing channel ID for the
8858
9027
  * peer if one is already open.
8859
9028
  *
9029
+ * The counterparty is driven by `destination` (issue #565): the channel is
9030
+ * opened against the settlement address of whoever TERMINATES it — an
9031
+ * existing negotiation for that peer, else the terminating kind:10032
9032
+ * announce's own `settlementAddresses`, else the route's x402 greeting. Two
9033
+ * destinations that terminate at different nodes therefore get two channels,
9034
+ * each with the right counterparty.
9035
+ *
8860
9036
  * @param destination - Optional ILP destination address. Defaults to
8861
9037
  * `config.destinationAddress`.
8862
9038
  * @returns The channel ID of the (now) open channel.
@@ -8884,7 +9060,7 @@ var ToonClient = class {
8884
9060
  );
8885
9061
  }
8886
9062
  const peerId = this.peerIdForClaim(dest);
8887
- const negotiation = this.peerNegotiations.get(peerId) ?? await this.negotiateFromGreeting(dest, peerId);
9063
+ const negotiation = await this.negotiationFor(dest, peerId);
8888
9064
  if (!negotiation) {
8889
9065
  throw new ToonClientError(
8890
9066
  `No negotiation metadata for peer "${peerId}" \u2014 was bootstrap completed? (and the route's x402 greeting carried no settlement facts to bootstrap from)`,
@@ -8918,7 +9094,7 @@ var ToonClient = class {
8918
9094
  );
8919
9095
  }
8920
9096
  const peerId = this.peerIdForClaim(destination);
8921
- const negotiation = this.peerNegotiations.get(peerId) ?? await this.negotiateFromGreeting(destination, peerId);
9097
+ const negotiation = await this.negotiationFor(destination, peerId);
8922
9098
  if (!negotiation) {
8923
9099
  throw new ToonClientError(
8924
9100
  `No negotiation metadata for peer "${peerId}" \u2014 cannot adopt channel "${channelId}" without knowing its chain and token network.`,
@@ -8964,7 +9140,12 @@ var ToonClient = class {
8964
9140
  channelAccount: channelId,
8965
9141
  expires
8966
9142
  });
8967
- return { blockchain: "solana", channelAccount: channelId, expires, signature };
9143
+ return {
9144
+ blockchain: "solana",
9145
+ channelAccount: channelId,
9146
+ expires,
9147
+ signature
9148
+ };
8968
9149
  }
8969
9150
  return void 0;
8970
9151
  }
@@ -9457,17 +9638,19 @@ var ToonClient = class {
9457
9638
  return sendTransfer(config, params);
9458
9639
  }
9459
9640
  /**
9460
- * Resolves an ILP destination address to a peer ID.
9461
- * Convention: destination "g.toon.peer1" → peerId "peer1" (last segment).
9462
- * Falls back to first known peer if no match.
9463
- */
9464
- /**
9465
- * The peer id a claim for `destination` accounts under. Normally
9466
- * `resolvePeerId` — but where that throws `PEER_NOT_FOUND` (an empty
9467
- * negotiation map: nothing announced, nothing registered), the
9641
+ * The peer id a claim for `destination` accounts under — and therefore WHICH
9642
+ * counterparty's channel that claim is drawn on. Normally `resolvePeerId`,
9643
+ * which resolves by identity (an existing negotiation key, or the announce
9644
+ * that terminates `destination`) — but where that throws `PEER_NOT_FOUND`
9645
+ * (nothing announced, nothing registered, nothing unambiguous to guess), the
9468
9646
  * destination itself is the key, so the announce-less greeting bootstrap
9469
9647
  * (connector #617) has a stable identity to remember its synthesized
9470
9648
  * negotiation under.
9649
+ *
9650
+ * Never a positional guess across several peers (issue #565): keying a
9651
+ * second destination onto the first peer's negotiation opens the channel
9652
+ * against the WRONG settlement address, and the real terminator then rejects
9653
+ * every claim (F01 — "names a channel this connector has no record of").
9471
9654
  */
9472
9655
  peerIdForClaim(destination) {
9473
9656
  try {
@@ -9644,14 +9827,100 @@ var ToonClient = class {
9644
9827
  return peerId;
9645
9828
  }
9646
9829
  }
9647
- const firstPeerResult = this.peerNegotiations.keys().next();
9648
- if (!firstPeerResult.done && firstPeerResult.value)
9649
- return firstPeerResult.value;
9830
+ const claim = this.terminatorClaimFor(destination);
9831
+ if (claim) return claim.peerId;
9832
+ if (this.peerNegotiations.size === 1) {
9833
+ const only = this.peerNegotiations.keys().next();
9834
+ if (!only.done && only.value) return only.value;
9835
+ }
9650
9836
  throw new ToonClientError(
9651
9837
  `Cannot resolve peer for destination: ${destination}`,
9652
9838
  "PEER_NOT_FOUND"
9653
9839
  );
9654
9840
  }
9841
+ /**
9842
+ * The winning kind:10032 claim on `destination` from this client's discovery
9843
+ * tracker, or `undefined` when there is no tracker yet or no announce claims
9844
+ * it. Probed rather than assumed, exactly as {@link terminatorRequiresBtp}
9845
+ * does — a half-built state (a stub, a client mid-`start()`) simply has
9846
+ * nothing to resolve against, and a missing announce is a normal state, not
9847
+ * an error.
9848
+ */
9849
+ terminatorClaimFor(destination) {
9850
+ const tracker = this.state?.discoveryTracker;
9851
+ if (typeof tracker?.getAllDiscoveredPeers !== "function") return void 0;
9852
+ return findBestTerminatorClaim(
9853
+ destination,
9854
+ tracker.getAllDiscoveredPeers()
9855
+ );
9856
+ }
9857
+ /**
9858
+ * The negotiation to settle `destination` with, in order of authority
9859
+ * (issue #565):
9860
+ *
9861
+ * 1. an ALREADY-negotiated peer (bootstrap, or a host that injected one);
9862
+ * 2. the terminating announce's OWN settlement facts — the counterparty
9863
+ * states its `settlementAddresses`/`tokenNetworks` in the same
9864
+ * kind:10032 event that claims the destination, so this is the
9865
+ * counterparty naming itself rather than us inferring one;
9866
+ * 3. the route's x402 greeting ({@link negotiateFromGreeting}, connector
9867
+ * #617) for an announce-less route.
9868
+ *
9869
+ * Step 2 is what makes a SECOND destination openable at all: bootstrap only
9870
+ * negotiates with `knownPeers`, so a client seeded with the relay had no
9871
+ * negotiation for the store box and used to fall through to the relay's.
9872
+ */
9873
+ async negotiationFor(destination, peerId) {
9874
+ const known = this.peerNegotiations.get(peerId);
9875
+ if (known) return known;
9876
+ const claim = this.terminatorClaimFor(destination);
9877
+ if (claim && claim.peerId === peerId) {
9878
+ let announced;
9879
+ try {
9880
+ announced = this.negotiationFromAnnounce(claim.peerInfo, peerId);
9881
+ } catch {
9882
+ announced = void 0;
9883
+ }
9884
+ if (announced) {
9885
+ this.peerNegotiations.set(peerId, announced);
9886
+ return announced;
9887
+ }
9888
+ }
9889
+ return this.negotiateFromGreeting(destination, peerId);
9890
+ }
9891
+ /**
9892
+ * The {@link PeerNegotiation} a peer's own kind:10032 announce supports: the
9893
+ * chain both sides support, plus the settlement address / token / token
9894
+ * network THAT PEER advertises for it (falling back to this client's
9895
+ * configured maps only where the announce is silent).
9896
+ *
9897
+ * `undefined` when the announce names no settlement address for the matched
9898
+ * chain — there is nothing to open a channel against, and guessing one is how
9899
+ * a claim ends up unverifiable at the counterparty.
9900
+ *
9901
+ * @throws {ToonClientError} CHAIN_NOT_SUPPORTED when no mutually supported
9902
+ * chain exists (from {@link matchNegotiatedChain}) — bootstrap surfaces
9903
+ * this; the lazy per-destination path catches it.
9904
+ */
9905
+ negotiationFromAnnounce(peerInfo, peerId) {
9906
+ const matchedChain = this.matchNegotiatedChain(
9907
+ this.config.supportedChains ?? [],
9908
+ peerInfo.supportedChains ?? [],
9909
+ peerId
9910
+ );
9911
+ const peerAddr = peerInfo.settlementAddresses?.[matchedChain];
9912
+ if (!peerAddr) return void 0;
9913
+ const parts = matchedChain.split(":");
9914
+ const chainId = parts.length >= 3 ? parseInt(parts[2] ?? "0", 10) : parts.length >= 2 ? parseInt(parts[1] ?? "0", 10) : 0;
9915
+ return {
9916
+ chain: matchedChain,
9917
+ chainType: parts[0] ?? "evm",
9918
+ chainId: isNaN(chainId) ? 0 : chainId,
9919
+ settlementAddress: peerAddr,
9920
+ tokenAddress: peerInfo.preferredTokens?.[matchedChain] ?? lookupByCanonicalChain(this.config.preferredTokens, matchedChain),
9921
+ tokenNetwork: peerInfo.tokenNetworks?.[matchedChain] ?? lookupByCanonicalChain(this.config.tokenNetworks, matchedChain)
9922
+ };
9923
+ }
9655
9924
  /**
9656
9925
  * Extracts chain context (chainId + tokenNetworkAddress) from a chain key like 'evm:base:421614'.
9657
9926
  */
@@ -9763,7 +10032,9 @@ var ToonClient = class {
9763
10032
  }
9764
10033
  const transport = this.getClaimTransport(params.destination);
9765
10034
  const claimMessage = this.buildClaimMessageForProof(params.claim);
9766
- return transport.sendIlpPacketWithClaim(
10035
+ return this.sendClaimBearingPacket(
10036
+ params.destination,
10037
+ transport,
9767
10038
  ilpParams,
9768
10039
  claimMessage
9769
10040
  );