@toon-protocol/client 3.0.0 → 3.1.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.
@@ -537,10 +537,12 @@ function parseBtpMessage(buf) {
537
537
  }
538
538
 
539
539
  // src/connector/self-description.ts
540
+ var BYTES_PER_KIB = 1024n;
540
541
  function chargeFor(terms, sealedBytes) {
541
542
  const perKib = terms.pricePerKib;
542
543
  if (perKib === void 0 || perKib === 0n) return terms.price;
543
- const units = BigInt(Math.floor(Math.max(0, sealedBytes) / 1024) + 1);
544
+ const bytes = BigInt(Math.max(0, Math.trunc(sealedBytes)));
545
+ const units = (bytes + BYTES_PER_KIB - 1n) / BYTES_PER_KIB;
544
546
  return terms.price + perKib * units;
545
547
  }
546
548
  function readString(obj, key) {
@@ -3296,6 +3298,11 @@ var ChannelManager = class _ChannelManager {
3296
3298
  tokenAddress: chainContext?.tokenAddress,
3297
3299
  recipient: chainContext?.recipient,
3298
3300
  depositTotal: chainContext?.depositTotal,
3301
+ // A timeout in one process desyncs the next one, so the doubt — and
3302
+ // the ceiling that bounds how it may be settled — is resumed with the
3303
+ // watermark it is about.
3304
+ ...persisted.signedCeiling !== void 0 ? { signedCeiling: persisted.signedCeiling } : {},
3305
+ ...persisted.watermarkUncertain ? { watermarkUncertain: true } : {},
3299
3306
  // Resume the withdraw-flow timers so a restart mid-grace doesn't
3300
3307
  // strand funds (the settle gate can't be evaluated without them).
3301
3308
  ...persisted.closedAt !== void 0 ? { closedAt: persisted.closedAt } : {},
@@ -3338,6 +3345,9 @@ var ChannelManager = class _ChannelManager {
3338
3345
  }
3339
3346
  tracking.nonce += 1;
3340
3347
  tracking.cumulativeAmount += additionalAmount;
3348
+ if (tracking.signedCeiling === void 0 || tracking.cumulativeAmount > tracking.signedCeiling) {
3349
+ tracking.signedCeiling = tracking.cumulativeAmount;
3350
+ }
3341
3351
  this.persist(channelId);
3342
3352
  const signer = this.chainSigners.get(tracking.chainType);
3343
3353
  if (signer && tracking.chainType !== "evm") {
@@ -3389,6 +3399,11 @@ var ChannelManager = class _ChannelManager {
3389
3399
  * Re-signing at the next nonce with the restored cumulative is exactly what the
3390
3400
  * spec's own remedy for an over-deposit refusal describes.
3391
3401
  *
3402
+ * **The signed ceiling is not rolled back either.** What was signed was
3403
+ * signed, and the ceiling exists to remember exactly that — it bounds what
3404
+ * {@link ChannelManager.adoptConnectorWatermark} will believe the connector
3405
+ * when it reports having banked.
3406
+ *
3392
3407
  * Clamped at zero, and a no-op for an untracked channel: this runs on error
3393
3408
  * paths, and an error path that throws its own error hides the original.
3394
3409
  */
@@ -3398,6 +3413,92 @@ var ChannelManager = class _ChannelManager {
3398
3413
  tracking.cumulativeAmount = tracking.cumulativeAmount > amount ? tracking.cumulativeAmount - amount : 0n;
3399
3414
  this.persist(channelId);
3400
3415
  }
3416
+ /**
3417
+ * Record that this channel's watermark is in DOUBT: the last claim signed on
3418
+ * it was either sent into a transport error or a timeout — where the packet
3419
+ * may have been delivered and banked regardless of what this end saw — or was
3420
+ * refused by the connector. Either way our figure and the connector's may no
3421
+ * longer agree, and guessing which way costs a refused claim per request
3422
+ * (toon-client#671).
3423
+ *
3424
+ * The doubt is recorded rather than resolved, because resolving it here would
3425
+ * mean a second network round trip bolted onto a request that has already
3426
+ * failed, to a connector that may be exactly what is unreachable. It is
3427
+ * resolved instead at the one moment the answer is actually needed — before
3428
+ * the NEXT claim is signed — by {@link ChannelManager.adoptConnectorWatermark}
3429
+ * with what `POST /ilp/claim-state` reports.
3430
+ *
3431
+ * Persisted, and a no-op for an untracked channel: this runs on error paths.
3432
+ */
3433
+ markWatermarkUncertain(channelId) {
3434
+ const tracking = this.channels.get(channelId);
3435
+ if (!tracking || tracking.watermarkUncertain === true) return;
3436
+ tracking.watermarkUncertain = true;
3437
+ this.persist(channelId);
3438
+ }
3439
+ /**
3440
+ * Record that this channel's watermark is known good again: the connector
3441
+ * banked the claim we signed, at the figure we signed it at, so the two agree
3442
+ * by construction.
3443
+ *
3444
+ * The cheap half of the reconciliation — a banked claim is proof, and proof
3445
+ * costs nothing, where {@link ChannelManager.adoptConnectorWatermark} costs a
3446
+ * round trip. Without it a channel that once timed out would re-read the
3447
+ * connector's watermark before every later claim.
3448
+ */
3449
+ markWatermarkCertain(channelId) {
3450
+ const tracking = this.channels.get(channelId);
3451
+ if (!tracking || tracking.watermarkUncertain !== true) return;
3452
+ tracking.watermarkUncertain = false;
3453
+ this.persist(channelId);
3454
+ }
3455
+ /** Whether the next claim on `channelId` must reconcile before it is signed. */
3456
+ isWatermarkUncertain(channelId) {
3457
+ return this.channels.get(channelId)?.watermarkUncertain === true;
3458
+ }
3459
+ /**
3460
+ * Adopt the connector's OWN watermark for a channel, and clear the doubt
3461
+ * {@link ChannelManager.markWatermarkUncertain} recorded.
3462
+ *
3463
+ * The connector's figure is the one that decides — a claim is validated
3464
+ * against what IT has banked (`client-edge-spec.md` §1.3) — so on a
3465
+ * disagreement it is adopted rather than argued with. Two guards make that
3466
+ * safe to do with a number that arrived over the network:
3467
+ *
3468
+ * - **The cumulative is clamped to {@link ChannelTracking.signedCeiling}**,
3469
+ * the highest figure this client has ever signed. A connector can only bank
3470
+ * a claim it holds our signature for, so a report above that ceiling is not
3471
+ * a fact about this channel and must not become one: adopting it would sign
3472
+ * away value that was never spent. The clamp is the whole reason the ceiling
3473
+ * is tracked.
3474
+ * - **The nonce only ever rises.** A claim is a bearer instrument and a nonce
3475
+ * is the only thing that stops one being re-issued, so the local nonce moves
3476
+ * to whichever of the two figures is higher — never down to the connector's,
3477
+ * even when the connector's is lower because a claim we signed never reached
3478
+ * it.
3479
+ *
3480
+ * @returns what was adopted, and how far the cumulative moved (negative when
3481
+ * the connector had banked LESS than we had recorded), so a caller can say
3482
+ * so out loud.
3483
+ */
3484
+ adoptConnectorWatermark(channelId, connector) {
3485
+ const tracking = this.channels.get(channelId);
3486
+ if (!tracking) return { adopted: false, moved: 0n };
3487
+ const ceiling = tracking.signedCeiling ?? tracking.cumulativeAmount;
3488
+ const cumulative = connector.cumulativeClaimed > ceiling ? ceiling : connector.cumulativeClaimed;
3489
+ const moved = cumulative - tracking.cumulativeAmount;
3490
+ tracking.cumulativeAmount = cumulative;
3491
+ tracking.nonce = Math.max(tracking.nonce, connector.nonce);
3492
+ tracking.watermarkUncertain = false;
3493
+ this.persist(channelId);
3494
+ return {
3495
+ adopted: true,
3496
+ moved,
3497
+ cumulative,
3498
+ nonce: tracking.nonce,
3499
+ ...connector.cumulativeClaimed > ceiling ? { clampedTo: ceiling } : {}
3500
+ };
3501
+ }
3401
3502
  buildMetadata(tracking) {
3402
3503
  if (tracking.chainType === "solana") {
3403
3504
  return { chainType: "solana", programId: tracking.tokenNetworkAddress };
@@ -3453,6 +3554,8 @@ var ChannelManager = class _ChannelManager {
3453
3554
  this.store.save(channelId, {
3454
3555
  nonce: t.nonce,
3455
3556
  cumulativeAmount: t.cumulativeAmount,
3557
+ ...t.signedCeiling !== void 0 ? { signedCeiling: t.signedCeiling } : {},
3558
+ ...t.watermarkUncertain ? { watermarkUncertain: true } : {},
3456
3559
  ...t.closedAt !== void 0 ? { closedAt: t.closedAt } : {},
3457
3560
  ...t.settleableAt !== void 0 ? { settleableAt: t.settleableAt } : {},
3458
3561
  ...t.settledAt !== void 0 ? { settledAt: t.settledAt } : {}
@@ -6075,6 +6178,8 @@ var JsonFileChannelStore = class {
6075
6178
  data[channelId] = {
6076
6179
  nonce: tracking.nonce,
6077
6180
  cumulativeAmount: tracking.cumulativeAmount.toString(),
6181
+ ...tracking.signedCeiling !== void 0 ? { signedCeiling: tracking.signedCeiling.toString() } : {},
6182
+ ...tracking.watermarkUncertain ? { watermarkUncertain: true } : {},
6078
6183
  ...tracking.closedAt !== void 0 ? { closedAt: tracking.closedAt.toString() } : {},
6079
6184
  ...tracking.settleableAt !== void 0 ? { settleableAt: tracking.settleableAt.toString() } : {},
6080
6185
  ...tracking.settledAt !== void 0 ? { settledAt: tracking.settledAt.toString() } : {}
@@ -6088,6 +6193,8 @@ var JsonFileChannelStore = class {
6088
6193
  return {
6089
6194
  nonce: entry.nonce,
6090
6195
  cumulativeAmount: BigInt(entry.cumulativeAmount),
6196
+ ...entry.signedCeiling !== void 0 ? { signedCeiling: BigInt(entry.signedCeiling) } : {},
6197
+ ...entry.watermarkUncertain ? { watermarkUncertain: true } : {},
6091
6198
  ...entry.closedAt !== void 0 ? { closedAt: BigInt(entry.closedAt) } : {},
6092
6199
  ...entry.settleableAt !== void 0 ? { settleableAt: BigInt(entry.settleableAt) } : {},
6093
6200
  ...entry.settledAt !== void 0 ? { settledAt: BigInt(entry.settledAt) } : {}
@@ -6522,6 +6629,7 @@ var ClientChannelFacade = class {
6522
6629
  const existing = channels.resolveChannel(config.connector, terms);
6523
6630
  if (existing !== void 0) {
6524
6631
  this.current = { channelId: existing, terms };
6632
+ this.adoptOnChain(existing, terms);
6525
6633
  return existing;
6526
6634
  }
6527
6635
  if (!config.autoOpenChannel) {
@@ -7544,6 +7652,7 @@ async function send(context, destination, request = {}, options = {}) {
7544
7652
  async function attempt(context, params) {
7545
7653
  if (params.amount === 0n) return attemptUnpaid(context, params);
7546
7654
  const channelId = await context.ensureChannel(params.description);
7655
+ await settleWatermarkDoubt(context, channelId);
7547
7656
  const proof = await context.channels.signBalanceProof(channelId, params.amount);
7548
7657
  const signer = context.channels.getSignerForChannel(channelId);
7549
7658
  const claim = signer.buildClaimMessage(proof, context.senderId);
@@ -7570,10 +7679,14 @@ async function attempt(context, params) {
7570
7679
  context.channels.rollbackAmount(channelId, params.amount);
7571
7680
  const greeting = asGreeting(error, params.carriage.kind, summary);
7572
7681
  if (greeting) return { result: greeting, channelId };
7682
+ context.channels.markWatermarkUncertain(channelId);
7573
7683
  throw error;
7574
7684
  }
7575
7685
  if (claimWasRefused(result)) {
7576
7686
  context.channels.rollbackAmount(channelId, params.amount);
7687
+ context.channels.markWatermarkUncertain(channelId);
7688
+ } else {
7689
+ context.channels.markWatermarkCertain(channelId);
7577
7690
  }
7578
7691
  return {
7579
7692
  result: toSendResult(result, params, summary),
@@ -7590,6 +7703,17 @@ async function attemptUnpaid(context, params) {
7590
7703
  });
7591
7704
  return { result: toSendResult(result, params, void 0), channelId: void 0 };
7592
7705
  }
7706
+ async function settleWatermarkDoubt(context, channelId) {
7707
+ if (context.reconcileWatermark === void 0) return;
7708
+ if (!context.channels.isWatermarkUncertain(channelId)) return;
7709
+ try {
7710
+ await context.reconcileWatermark(channelId);
7711
+ } catch (error) {
7712
+ (context.warn ?? console.warn)(
7713
+ `[toon] could not re-read the connector's watermark for channel ${channelId} (${error instanceof Error ? error.message : String(error)}). The last claim on it was signed and never confirmed, so this one may under-advance and be refused; the next attempt will ask again.`
7714
+ );
7715
+ }
7716
+ }
7593
7717
  async function maybeRetryStaleChannel(context, first, params) {
7594
7718
  const result = first.result;
7595
7719
  if (result.fulfilled) return void 0;
@@ -8003,6 +8127,7 @@ var ToonClient = class _ToonClient {
8003
8127
  ensureChannel: (description) => this.channelFacade.ensure(description),
8004
8128
  evictChannel: (channelId) => this.evictChannel(channelId),
8005
8129
  channels: this.channels,
8130
+ reconcileWatermark: (channelId) => this.reconcileWatermark(channelId),
8006
8131
  transport: (description) => this.transportFor(description),
8007
8132
  senderId: this.identity.senderId,
8008
8133
  chain: this.chain,
@@ -8028,6 +8153,36 @@ var ToonClient = class _ToonClient {
8028
8153
  const identity = await this.edge.getIdentity(endpoint);
8029
8154
  return identity.publicKey;
8030
8155
  }
8156
+ /**
8157
+ * Re-read the connector's own watermark for one channel and adopt it
8158
+ * (toon-client#671).
8159
+ *
8160
+ * Called by {@link send} before signing a claim on a channel whose last claim
8161
+ * was signed and never confirmed — a transport error, a timeout, or a refusal.
8162
+ * A packet that timed out on a long path may have been delivered and banked
8163
+ * anyway, and the local figure would then be one claim behind for good: every
8164
+ * later claim under-advances and is refused. The connector's figure is the one
8165
+ * that decides, so it is asked, and {@link ChannelManager.adoptConnectorWatermark}
8166
+ * takes it (clamped to what this client has actually signed).
8167
+ *
8168
+ * A channel the connector cannot verify (`ok: false`) leaves the doubt in
8169
+ * place rather than resolving it wrongly — `"unverified"` covers "no such
8170
+ * channel" and "bad signature" identically, and neither is a watermark.
8171
+ */
8172
+ async reconcileWatermark(channelId) {
8173
+ const entry = (await this.claimState([channelId])).find(
8174
+ (e) => e.ok && (e.channelId ?? e.channelAccount ?? channelId) === channelId
8175
+ );
8176
+ if (entry === void 0) return;
8177
+ const adoption = this.channels.adoptConnectorWatermark(channelId, {
8178
+ nonce: entry.nonce,
8179
+ cumulativeClaimed: BigInt(entry.cumulativeClaimed)
8180
+ });
8181
+ if (!adoption.adopted || adoption.moved === 0n) return;
8182
+ console.warn(
8183
+ `[toon] the connector's watermark for channel ${channelId} was ${adoption.moved > 0n ? "ahead of" : "behind"} this client's by ${(adoption.moved < 0n ? -adoption.moved : adoption.moved).toString()} (a claim was signed and never confirmed). Adopted its figure \u2014 cumulative ${adoption.cumulative.toString()}, nonce ${adoption.nonce} \u2014 so this request pays the right amount rather than being refused.` + (adoption.clampedTo !== void 0 ? ` It reported more than this client has ever signed, so the figure was clamped to ${adoption.clampedTo.toString()}.` : "")
8184
+ );
8185
+ }
8031
8186
  /**
8032
8187
  * Retire the binding a refused claim was drawn on. `false` when there is
8033
8188
  * nothing to retire, which is {@link send}'s signal not to retry.
@@ -8404,4 +8559,4 @@ export {
8404
8559
  toEnvelopeRequest,
8405
8560
  ToonClient
8406
8561
  };
8407
- //# sourceMappingURL=chunk-GDWZ736I.js.map
8562
+ //# sourceMappingURL=chunk-KQE6S23B.js.map