@toon-protocol/client 2.2.0 → 3.1.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.
@@ -317,12 +317,11 @@ function decodeGeneralizedTime(buf, offset) {
317
317
  return { value, bytesRead: GENERALIZED_TIME_LENGTH };
318
318
  }
319
319
  function serializeIlpPrepare(packet) {
320
- const condition = packet.executionCondition.length === 32 ? packet.executionCondition : new Uint8Array(32);
321
320
  return concat(
322
321
  writeUint8(ILPPacketType.PREPARE),
323
322
  encodeVarUInt(packet.amount),
324
323
  encodeGeneralizedTime(packet.expiresAt),
325
- condition,
324
+ writeUint8(packet.greeting ? 1 : 0),
326
325
  encodeVarOctetString(textEncoder.encode(packet.destination)),
327
326
  encodeVarOctetString(packet.data)
328
327
  );
@@ -341,11 +340,17 @@ function deserializeIlpPrepare(buf) {
341
340
  offset
342
341
  );
343
342
  offset += timeBytes;
344
- if (offset + 32 > buf.length) {
345
- throw new Error("Buffer underflow reading PREPARE executionCondition");
343
+ if (offset >= buf.length) {
344
+ throw new Error("Buffer underflow reading PREPARE greeting flag");
346
345
  }
347
- const executionCondition = buf.slice(offset, offset + 32);
348
- offset += 32;
346
+ const greetingByte = buf[offset];
347
+ if (greetingByte !== 0 && greetingByte !== 1) {
348
+ throw new Error(
349
+ `Malformed PREPARE greeting flag: expected 0x00 or 0x01, got 0x${greetingByte.toString(16).padStart(2, "0")}`
350
+ );
351
+ }
352
+ const greeting = greetingByte === 1;
353
+ offset += 1;
349
354
  const { value: destinationBytes, bytesRead: destBytes } = decodeVarOctetString(buf, offset);
350
355
  offset += destBytes;
351
356
  const destination = textDecoder.decode(destinationBytes);
@@ -354,7 +359,7 @@ function deserializeIlpPrepare(buf) {
354
359
  type: ILPPacketType.PREPARE,
355
360
  amount,
356
361
  destination,
357
- executionCondition,
362
+ greeting,
358
363
  expiresAt,
359
364
  data
360
365
  };
@@ -532,10 +537,12 @@ function parseBtpMessage(buf) {
532
537
  }
533
538
 
534
539
  // src/connector/self-description.ts
540
+ var BYTES_PER_KIB = 1024n;
535
541
  function chargeFor(terms, sealedBytes) {
536
542
  const perKib = terms.pricePerKib;
537
543
  if (perKib === void 0 || perKib === 0n) return terms.price;
538
- 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;
539
546
  return terms.price + perKib * units;
540
547
  }
541
548
  function readString(obj, key) {
@@ -681,39 +688,30 @@ function decodeUtf8(bytes) {
681
688
  return new TextDecoder().decode(bytes);
682
689
  }
683
690
 
684
- // src/utils/condition.ts
685
- import { sha256 } from "@noble/hashes/sha2.js";
686
- import { randomBytes } from "@noble/hashes/utils.js";
687
- var CONDITION_LENGTH = 32;
688
- function isZeroCondition(condition) {
689
- if (condition === void 0) return true;
690
- for (const byte of condition) {
691
- if (byte !== 0) return false;
691
+ // src/utils/fulfillment.ts
692
+ var FULFILLMENT_LENGTH = 32;
693
+ function fulfillmentMatches(returned, expected) {
694
+ if (returned === void 0 || returned.length !== FULFILLMENT_LENGTH) {
695
+ return false;
696
+ }
697
+ if (expected.length !== FULFILLMENT_LENGTH) return false;
698
+ for (let i = 0; i < FULFILLMENT_LENGTH; i++) {
699
+ if (returned[i] !== expected[i]) return false;
692
700
  }
693
701
  return true;
694
702
  }
695
- function assertValidCondition(condition) {
696
- if (condition.length !== CONDITION_LENGTH) {
703
+ function assertValidFulfillment(fulfillment) {
704
+ if (fulfillment.length !== FULFILLMENT_LENGTH) {
697
705
  throw new Error(
698
- `executionCondition must be exactly ${CONDITION_LENGTH} bytes, got ${condition.length}`
706
+ `an expected fulfillment must be exactly ${FULFILLMENT_LENGTH} bytes, got ${fulfillment.length}`
699
707
  );
700
708
  }
701
709
  }
702
- function fulfillmentMatchesCondition(fulfillment, condition) {
703
- if (fulfillment === void 0 || fulfillment.length !== CONDITION_LENGTH) {
704
- return false;
705
- }
706
- const digest = sha256(fulfillment);
707
- for (let i = 0; i < CONDITION_LENGTH; i++) {
708
- if (digest[i] !== condition[i]) return false;
709
- }
710
- return true;
711
- }
712
710
 
713
711
  // src/ilp/ilp-send.ts
714
- function resolveExecutionCondition(condition) {
715
- if (condition === void 0) return void 0;
716
- return typeof condition === "string" ? fromBase64(condition) : condition;
712
+ function resolveExpectedFulfillment(fulfillment) {
713
+ if (fulfillment === void 0) return void 0;
714
+ return typeof fulfillment === "string" ? fromBase64(fulfillment) : fulfillment;
717
715
  }
718
716
  var PACKET_EXPIRY_HEADROOM_MS = 15e3;
719
717
  function resolveExpiresAt(expiresAt, timeoutMs) {
@@ -721,14 +719,14 @@ function resolveExpiresAt(expiresAt, timeoutMs) {
721
719
  return expiresAt instanceof Date ? new Date(expiresAt.getTime()) : new Date(expiresAt);
722
720
  }
723
721
  var FULFILLMENT_MISMATCH_CODE = "F99";
724
- var FULFILLMENT_MISMATCH_MESSAGE = "FULFILL fulfillment does not match execution condition (sha256(fulfillment) != executionCondition) \u2014 packet counted failed";
725
- function mapIlpResponse(packet, sentCondition) {
722
+ var FULFILLMENT_MISMATCH_MESSAGE = "FULFILL fulfillment is not the one this packet's sealed secret derives (ADR 0019) \u2014 packet counted failed";
723
+ function mapIlpResponse(packet, expectedFulfillment) {
726
724
  if (packet.type === ILPPacketType.FULFILL) {
727
725
  const dataField = packet.data.length > 0 ? { data: toBase64(packet.data) } : {};
728
- if (sentCondition === void 0 || isZeroCondition(sentCondition)) {
726
+ if (expectedFulfillment === void 0) {
729
727
  return { accepted: true, ...dataField };
730
728
  }
731
- if (!fulfillmentMatchesCondition(packet.fulfillment, sentCondition)) {
729
+ if (!fulfillmentMatches(packet.fulfillment, expectedFulfillment)) {
732
730
  return {
733
731
  accepted: false,
734
732
  code: FULFILLMENT_MISMATCH_CODE,
@@ -1326,11 +1324,10 @@ var BtpRuntimeClient = class {
1326
1324
  * Sends an ILP packet via BTP with auto-reconnect on connection errors.
1327
1325
  * Satisfies IlpClient interface.
1328
1326
  *
1329
- * `params` may carry a sender-chosen `executionCondition` and an explicit
1330
- * `expiresAt` (toon-client#350); omitting both is the legacy zero-condition
1331
- * path, unchanged. With a non-zero condition the FULFILL preimage is
1332
- * verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced
1333
- * as a failed result — see `mapIlpResponse`.
1327
+ * `params` may carry an `expectedFulfillment` (the sender's end-to-end
1328
+ * check, ADR 0069), a `greeting` flag and an explicit `expiresAt`. With an
1329
+ * expected fulfilment the FULFILL preimage is compared against it and a
1330
+ * mismatch is surfaced as a failed result — see `mapIlpResponse`.
1334
1331
  */
1335
1332
  async sendIlpPacket(params) {
1336
1333
  return withRetry(() => this._sendIlpPacketOnce(params), {
@@ -1347,8 +1344,8 @@ var BtpRuntimeClient = class {
1347
1344
  * Sends a balance proof claim via BTP protocol data, then sends an ILP packet.
1348
1345
  * Auto-reconnects on connection errors.
1349
1346
  *
1350
- * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are
1351
- * identical to {@link sendIlpPacket}.
1347
+ * `expectedFulfillment` / `greeting` / `expiresAt` semantics are identical
1348
+ * to {@link sendIlpPacket}.
1352
1349
  */
1353
1350
  async sendIlpPacketWithClaim(params, claim) {
1354
1351
  return withRetry(() => this._sendIlpPacketWithClaimOnce(params, claim), {
@@ -1392,27 +1389,29 @@ var BtpRuntimeClient = class {
1392
1389
  );
1393
1390
  }
1394
1391
  /**
1395
- * Build the ILP PREPARE for a send, applying the sender-chosen condition /
1396
- * explicit expiry when provided (toon-client#350) and validating that a
1397
- * non-zero condition is exactly 32 bytes (the OER serializer would
1398
- * otherwise silently zero-fill it, downgrading the packet to the legacy
1399
- * unverified class).
1392
+ * Build the ILP PREPARE for a send, applying the
1393
+ * explicit expiry when provided, carrying the `greeting` flag ADR 0069 put
1394
+ * where the execution condition used to be, and validating that an expected
1395
+ * fulfilment is exactly 32 bytes (a wrong-length one could never match a
1396
+ * real FULFILL, so every delivery would be counted failed).
1400
1397
  */
1401
1398
  buildPrepare(params) {
1402
- const condition = resolveExecutionCondition(params.executionCondition);
1403
- if (condition !== void 0 && !isZeroCondition(condition)) {
1404
- assertValidCondition(condition);
1399
+ const expectedFulfillment = resolveExpectedFulfillment(
1400
+ params.expectedFulfillment
1401
+ );
1402
+ if (expectedFulfillment !== void 0) {
1403
+ assertValidFulfillment(expectedFulfillment);
1405
1404
  }
1406
1405
  return {
1407
1406
  prepare: {
1408
1407
  type: 12,
1409
1408
  amount: BigInt(params.amount),
1410
1409
  destination: params.destination,
1411
- executionCondition: condition ?? new Uint8Array(32),
1410
+ greeting: params.greeting ?? false,
1412
1411
  expiresAt: resolveExpiresAt(params.expiresAt, params.timeout ?? 3e4),
1413
1412
  data: fromBase64(params.data)
1414
1413
  },
1415
- condition
1414
+ expectedFulfillment
1416
1415
  };
1417
1416
  }
1418
1417
  /**
@@ -1422,10 +1421,10 @@ var BtpRuntimeClient = class {
1422
1421
  if (!this._isConnected) {
1423
1422
  await this.reconnect();
1424
1423
  }
1425
- const { prepare, condition } = this.buildPrepare(params);
1424
+ const { prepare, expectedFulfillment } = this.buildPrepare(params);
1426
1425
  const response = await this.btpClient.sendPacket(prepare);
1427
1426
  return {
1428
- ...mapIlpResponse(response.packet, condition),
1427
+ ...mapIlpResponse(response.packet, expectedFulfillment),
1429
1428
  ...readResponseMeta(response.protocolData)
1430
1429
  };
1431
1430
  }
@@ -1446,10 +1445,10 @@ var BtpRuntimeClient = class {
1446
1445
  data: encodeUtf8(JSON.stringify(claim))
1447
1446
  }
1448
1447
  ];
1449
- const { prepare, condition } = this.buildPrepare(params);
1448
+ const { prepare, expectedFulfillment } = this.buildPrepare(params);
1450
1449
  const response = await this.btpClient.sendPacket(prepare, protocolData);
1451
1450
  return {
1452
- ...mapIlpResponse(response.packet, condition),
1451
+ ...mapIlpResponse(response.packet, expectedFulfillment),
1453
1452
  ...readResponseMeta(response.protocolData)
1454
1453
  };
1455
1454
  }
@@ -1617,11 +1616,10 @@ var HttpIlpClient = class {
1617
1616
  * this only on free/zero-amount routes; paid writes must use
1618
1617
  * {@link sendIlpPacketWithClaim}. Satisfies the IlpClient interface.
1619
1618
  *
1620
- * `params` may carry a sender-chosen `executionCondition` and an explicit
1621
- * `expiresAt` (toon-client#350); omitting both is the legacy zero-condition
1622
- * path, unchanged. With a non-zero condition the FULFILL preimage is
1623
- * verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced
1624
- * as a failed result — see {@link mapIlpResponse}.
1619
+ * `params` may carry an `expectedFulfillment` (the sender's end-to-end
1620
+ * check, ADR 0069), a `greeting` flag and an explicit `expiresAt`. With an
1621
+ * expected fulfilment the FULFILL preimage is compared against it and a
1622
+ * mismatch is surfaced as a failed result — see {@link mapIlpResponse}.
1625
1623
  */
1626
1624
  async sendIlpPacket(params) {
1627
1625
  return withRetry(() => this.postPrepare(params), {
@@ -1637,8 +1635,8 @@ var HttpIlpClient = class {
1637
1635
  * the BTP path attaches as the `payment-channel-claim` protocolData entry —
1638
1636
  * we base64(JSON.stringify(claim)) it, byte-for-byte identical to BTP.
1639
1637
  *
1640
- * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are
1641
- * identical to {@link sendIlpPacket}.
1638
+ * `expectedFulfillment` / `greeting` / `expiresAt` semantics are identical
1639
+ * to {@link sendIlpPacket}.
1642
1640
  */
1643
1641
  async sendIlpPacketWithClaim(params, claim) {
1644
1642
  return withRetry(() => this.postPrepare(params, claim), {
@@ -1716,15 +1714,17 @@ var HttpIlpClient = class {
1716
1714
  */
1717
1715
  async postPrepare(params, claim) {
1718
1716
  const requestTimeout = params.timeout ?? this.timeout;
1719
- const condition = resolveExecutionCondition(params.executionCondition);
1720
- if (condition !== void 0 && !isZeroCondition(condition)) {
1721
- assertValidCondition(condition);
1717
+ const expectedFulfillment = resolveExpectedFulfillment(
1718
+ params.expectedFulfillment
1719
+ );
1720
+ if (expectedFulfillment !== void 0) {
1721
+ assertValidFulfillment(expectedFulfillment);
1722
1722
  }
1723
1723
  const prepare = serializeIlpPrepare({
1724
1724
  type: ILPPacketType.PREPARE,
1725
1725
  amount: BigInt(params.amount),
1726
1726
  destination: params.destination,
1727
- executionCondition: condition ?? new Uint8Array(32),
1727
+ greeting: params.greeting ?? false,
1728
1728
  expiresAt: resolveExpiresAt(params.expiresAt, requestTimeout),
1729
1729
  data: fromBase64(params.data)
1730
1730
  });
@@ -1746,7 +1746,7 @@ var HttpIlpClient = class {
1746
1746
  signal: controller.signal
1747
1747
  });
1748
1748
  clearTimeout(timeoutId);
1749
- return await this.mapResponse(response, condition);
1749
+ return await this.mapResponse(response, expectedFulfillment);
1750
1750
  } catch (error) {
1751
1751
  clearTimeout(timeoutId);
1752
1752
  throw this.mapTransportError(error, requestTimeout);
@@ -1757,11 +1757,11 @@ var HttpIlpClient = class {
1757
1757
  * to a transport error. Per the wire contract, ILP-level rejects arrive as a
1758
1758
  * 200 + REJECT body — only HTTP non-2xx means a transport-layer failure.
1759
1759
  *
1760
- * When `sentCondition` is non-zero the FULFILL preimage is verified against
1761
- * it; a mismatch yields `accepted: false` (shared `mapIlpResponse` logic,
1762
- * identical to the BTP path).
1760
+ * When `expectedFulfillment` is given the FULFILL preimage is compared
1761
+ * against it; a mismatch yields `accepted: false` (shared `mapIlpResponse`
1762
+ * logic, identical to the BTP path).
1763
1763
  */
1764
- async mapResponse(response, sentCondition) {
1764
+ async mapResponse(response, expectedFulfillment) {
1765
1765
  if (response.ok) {
1766
1766
  const buf = new Uint8Array(await response.arrayBuffer());
1767
1767
  if (buf.length === 0) {
@@ -1770,7 +1770,7 @@ var HttpIlpClient = class {
1770
1770
  );
1771
1771
  }
1772
1772
  return {
1773
- ...mapIlpResponse(deserializeIlpPacket(buf), sentCondition),
1773
+ ...mapIlpResponse(deserializeIlpPacket(buf), expectedFulfillment),
1774
1774
  ...readResponseMeta2(response.headers)
1775
1775
  };
1776
1776
  }
@@ -2225,16 +2225,18 @@ var ConnectorEdgeClient = class {
2225
2225
  async probe(endpoint, params, claim) {
2226
2226
  const base = connectorEdgeBaseUrl(endpoint);
2227
2227
  const url = `${base}/ilp/probe`;
2228
- const condition = resolveExecutionCondition(params.executionCondition);
2229
- if (condition !== void 0 && !isZeroCondition(condition)) {
2230
- assertValidCondition(condition);
2228
+ const expectedFulfillment = resolveExpectedFulfillment(
2229
+ params.expectedFulfillment
2230
+ );
2231
+ if (expectedFulfillment !== void 0) {
2232
+ assertValidFulfillment(expectedFulfillment);
2231
2233
  }
2232
2234
  const timeout = params.timeout ?? this.timeout;
2233
2235
  const prepare = serializeIlpPrepare({
2234
2236
  type: ILPPacketType.PREPARE,
2235
2237
  amount: BigInt(params.amount),
2236
2238
  destination: params.destination,
2237
- executionCondition: condition ?? new Uint8Array(32),
2239
+ greeting: params.greeting ?? false,
2238
2240
  expiresAt: resolveExpiresAt(params.expiresAt, timeout),
2239
2241
  data: fromBase64(params.data)
2240
2242
  });
@@ -2282,7 +2284,7 @@ var ConnectorEdgeClient = class {
2282
2284
  );
2283
2285
  }
2284
2286
  return {
2285
- ...mapIlpResponse(deserializeIlpPacket(body), condition),
2287
+ ...mapIlpResponse(deserializeIlpPacket(body), expectedFulfillment),
2286
2288
  ...readResponseMeta2(response.headers)
2287
2289
  };
2288
2290
  }
@@ -2342,13 +2344,11 @@ var ConnectorEdgeClient = class {
2342
2344
  );
2343
2345
  }
2344
2346
  const base = connectorEdgeBaseUrl(endpoint);
2345
- const condition = new Uint8Array(32);
2346
- condition[0] = 1;
2347
2347
  const prepare = serializeIlpPrepare({
2348
2348
  type: ILPPacketType.PREPARE,
2349
2349
  amount: 0n,
2350
2350
  destination,
2351
- executionCondition: condition,
2351
+ greeting: false,
2352
2352
  expiresAt: new Date(Date.now() + 3e4),
2353
2353
  data: new Uint8Array(0)
2354
2354
  });
@@ -3298,6 +3298,11 @@ var ChannelManager = class _ChannelManager {
3298
3298
  tokenAddress: chainContext?.tokenAddress,
3299
3299
  recipient: chainContext?.recipient,
3300
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 } : {},
3301
3306
  // Resume the withdraw-flow timers so a restart mid-grace doesn't
3302
3307
  // strand funds (the settle gate can't be evaluated without them).
3303
3308
  ...persisted.closedAt !== void 0 ? { closedAt: persisted.closedAt } : {},
@@ -3340,6 +3345,9 @@ var ChannelManager = class _ChannelManager {
3340
3345
  }
3341
3346
  tracking.nonce += 1;
3342
3347
  tracking.cumulativeAmount += additionalAmount;
3348
+ if (tracking.signedCeiling === void 0 || tracking.cumulativeAmount > tracking.signedCeiling) {
3349
+ tracking.signedCeiling = tracking.cumulativeAmount;
3350
+ }
3343
3351
  this.persist(channelId);
3344
3352
  const signer = this.chainSigners.get(tracking.chainType);
3345
3353
  if (signer && tracking.chainType !== "evm") {
@@ -3391,6 +3399,11 @@ var ChannelManager = class _ChannelManager {
3391
3399
  * Re-signing at the next nonce with the restored cumulative is exactly what the
3392
3400
  * spec's own remedy for an over-deposit refusal describes.
3393
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
+ *
3394
3407
  * Clamped at zero, and a no-op for an untracked channel: this runs on error
3395
3408
  * paths, and an error path that throws its own error hides the original.
3396
3409
  */
@@ -3400,6 +3413,92 @@ var ChannelManager = class _ChannelManager {
3400
3413
  tracking.cumulativeAmount = tracking.cumulativeAmount > amount ? tracking.cumulativeAmount - amount : 0n;
3401
3414
  this.persist(channelId);
3402
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
+ }
3403
3502
  buildMetadata(tracking) {
3404
3503
  if (tracking.chainType === "solana") {
3405
3504
  return { chainType: "solana", programId: tracking.tokenNetworkAddress };
@@ -3455,6 +3554,8 @@ var ChannelManager = class _ChannelManager {
3455
3554
  this.store.save(channelId, {
3456
3555
  nonce: t.nonce,
3457
3556
  cumulativeAmount: t.cumulativeAmount,
3557
+ ...t.signedCeiling !== void 0 ? { signedCeiling: t.signedCeiling } : {},
3558
+ ...t.watermarkUncertain ? { watermarkUncertain: true } : {},
3458
3559
  ...t.closedAt !== void 0 ? { closedAt: t.closedAt } : {},
3459
3560
  ...t.settleableAt !== void 0 ? { settleableAt: t.settleableAt } : {},
3460
3561
  ...t.settledAt !== void 0 ? { settledAt: t.settledAt } : {}
@@ -4149,7 +4250,7 @@ function sleep2(ms) {
4149
4250
 
4150
4251
  // src/channel/solana/payment-channel.ts
4151
4252
  import { ed25519 } from "@noble/curves/ed25519.js";
4152
- import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
4253
+ import { sha256 } from "@noble/hashes/sha2.js";
4153
4254
  var TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
4154
4255
  var SYSTEM_PROGRAM_ID = "11111111111111111111111111111111";
4155
4256
  var RENT_SYSVAR_ID = "SysvarRent111111111111111111111111111111111";
@@ -4244,7 +4345,7 @@ function findProgramAddress(seeds, programId) {
4244
4345
  input.set(programId, offset);
4245
4346
  offset += programId.length;
4246
4347
  input.set(PDA_MARKER, offset);
4247
- const hash = sha2562(input);
4348
+ const hash = sha256(input);
4248
4349
  if (!isOnCurve(hash)) return { pda: hash, bump };
4249
4350
  }
4250
4351
  throw new Error("Could not find a viable PDA bump seed");
@@ -5766,8 +5867,8 @@ function decodeEnvelope(buf, direction) {
5766
5867
  import { secp256k1 } from "@noble/curves/secp256k1.js";
5767
5868
  import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
5768
5869
  import { hkdf } from "@noble/hashes/hkdf.js";
5769
- import { sha256 as sha2563 } from "@noble/hashes/sha2.js";
5770
- import { randomBytes as randomBytes2 } from "@noble/hashes/utils.js";
5870
+ import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
5871
+ import { randomBytes } from "@noble/hashes/utils.js";
5771
5872
  var GIFTWRAP_NONCE_LENGTH = 12;
5772
5873
  var GIFTWRAP_SECRET_LENGTH = 32;
5773
5874
  var GIFTWRAP_PUBLIC_KEY_LENGTH = 65;
@@ -5813,7 +5914,7 @@ function concat3(parts) {
5813
5914
  return out;
5814
5915
  }
5815
5916
  function hkdfKey(ikm, info) {
5816
- return hkdf(sha2563, ikm, void 0, info, 32);
5917
+ return hkdf(sha2562, ikm, void 0, info, 32);
5817
5918
  }
5818
5919
  function encryptWithNonce(key, plaintext, nonce) {
5819
5920
  return concat3([nonce, chacha20poly1305(key, nonce).encrypt(plaintext)]);
@@ -5880,8 +5981,8 @@ function sealRequestWithRandomness(plaintext, receiverPublicKey, ephemeralSecret
5880
5981
  }
5881
5982
  function sealRequest(plaintext, receiverPublicKey) {
5882
5983
  const ephemeralSecretKey = secp256k1.utils.randomSecretKey();
5883
- const sharedSecret = randomBytes2(GIFTWRAP_SECRET_LENGTH);
5884
- const nonce = randomBytes2(GIFTWRAP_NONCE_LENGTH);
5984
+ const sharedSecret = randomBytes(GIFTWRAP_SECRET_LENGTH);
5985
+ const nonce = randomBytes(GIFTWRAP_NONCE_LENGTH);
5885
5986
  return {
5886
5987
  wrapped: sealRequestWithRandomness(
5887
5988
  plaintext,
@@ -5940,7 +6041,7 @@ function sealResponse(sharedSecret, plaintext) {
5940
6041
  return sealResponseWithRandomness(
5941
6042
  sharedSecret,
5942
6043
  plaintext,
5943
- randomBytes2(GIFTWRAP_NONCE_LENGTH)
6044
+ randomBytes(GIFTWRAP_NONCE_LENGTH)
5944
6045
  );
5945
6046
  }
5946
6047
  function openResponse(sharedSecret, bytes) {
@@ -5967,9 +6068,6 @@ function deriveFulfillment(sharedSecret) {
5967
6068
  }
5968
6069
  return hkdfKey(sharedSecret, FULFILLMENT_INFO);
5969
6070
  }
5970
- function deriveCondition(fulfillment) {
5971
- return sha2563(fulfillment);
5972
- }
5973
6071
 
5974
6072
  // src/wire/sealed-exchange.ts
5975
6073
  var SealedResponseError = class extends Error {
@@ -5987,12 +6085,10 @@ function sealExchange(request, connectorPublicKey) {
5987
6085
  encodeEnvelopeRequest(request),
5988
6086
  connectorPublicKey
5989
6087
  );
5990
- const fulfillment = deriveFulfillment(sharedSecret);
5991
6088
  return {
5992
6089
  data: wrapped,
5993
- condition: deriveCondition(fulfillment),
5994
6090
  sharedSecret,
5995
- fulfillment
6091
+ fulfillment: deriveFulfillment(sharedSecret)
5996
6092
  };
5997
6093
  }
5998
6094
  function readExchangeOutcome(result, data, sharedSecret) {
@@ -6082,6 +6178,8 @@ var JsonFileChannelStore = class {
6082
6178
  data[channelId] = {
6083
6179
  nonce: tracking.nonce,
6084
6180
  cumulativeAmount: tracking.cumulativeAmount.toString(),
6181
+ ...tracking.signedCeiling !== void 0 ? { signedCeiling: tracking.signedCeiling.toString() } : {},
6182
+ ...tracking.watermarkUncertain ? { watermarkUncertain: true } : {},
6085
6183
  ...tracking.closedAt !== void 0 ? { closedAt: tracking.closedAt.toString() } : {},
6086
6184
  ...tracking.settleableAt !== void 0 ? { settleableAt: tracking.settleableAt.toString() } : {},
6087
6185
  ...tracking.settledAt !== void 0 ? { settledAt: tracking.settledAt.toString() } : {}
@@ -6095,6 +6193,8 @@ var JsonFileChannelStore = class {
6095
6193
  return {
6096
6194
  nonce: entry.nonce,
6097
6195
  cumulativeAmount: BigInt(entry.cumulativeAmount),
6196
+ ...entry.signedCeiling !== void 0 ? { signedCeiling: BigInt(entry.signedCeiling) } : {},
6197
+ ...entry.watermarkUncertain ? { watermarkUncertain: true } : {},
6098
6198
  ...entry.closedAt !== void 0 ? { closedAt: BigInt(entry.closedAt) } : {},
6099
6199
  ...entry.settleableAt !== void 0 ? { settleableAt: BigInt(entry.settleableAt) } : {},
6100
6200
  ...entry.settledAt !== void 0 ? { settledAt: BigInt(entry.settledAt) } : {}
@@ -7551,6 +7651,7 @@ async function send(context, destination, request = {}, options = {}) {
7551
7651
  async function attempt(context, params) {
7552
7652
  if (params.amount === 0n) return attemptUnpaid(context, params);
7553
7653
  const channelId = await context.ensureChannel(params.description);
7654
+ await settleWatermarkDoubt(context, channelId);
7554
7655
  const proof = await context.channels.signBalanceProof(channelId, params.amount);
7555
7656
  const signer = context.channels.getSignerForChannel(channelId);
7556
7657
  const claim = signer.buildClaimMessage(proof, context.senderId);
@@ -7568,7 +7669,7 @@ async function attempt(context, params) {
7568
7669
  destination: params.destination,
7569
7670
  amount: params.amount.toString(),
7570
7671
  data: toBase64(params.exchange.data),
7571
- executionCondition: params.exchange.condition,
7672
+ expectedFulfillment: params.exchange.fulfillment,
7572
7673
  timeout: params.timeoutMs
7573
7674
  },
7574
7675
  claim
@@ -7577,10 +7678,14 @@ async function attempt(context, params) {
7577
7678
  context.channels.rollbackAmount(channelId, params.amount);
7578
7679
  const greeting = asGreeting(error, params.carriage.kind, summary);
7579
7680
  if (greeting) return { result: greeting, channelId };
7681
+ context.channels.markWatermarkUncertain(channelId);
7580
7682
  throw error;
7581
7683
  }
7582
7684
  if (claimWasRefused(result)) {
7583
7685
  context.channels.rollbackAmount(channelId, params.amount);
7686
+ context.channels.markWatermarkUncertain(channelId);
7687
+ } else {
7688
+ context.channels.markWatermarkCertain(channelId);
7584
7689
  }
7585
7690
  return {
7586
7691
  result: toSendResult(result, params, summary),
@@ -7592,11 +7697,22 @@ async function attemptUnpaid(context, params) {
7592
7697
  destination: params.destination,
7593
7698
  amount: params.amount.toString(),
7594
7699
  data: toBase64(params.exchange.data),
7595
- executionCondition: params.exchange.condition,
7700
+ expectedFulfillment: params.exchange.fulfillment,
7596
7701
  timeout: params.timeoutMs
7597
7702
  });
7598
7703
  return { result: toSendResult(result, params, void 0), channelId: void 0 };
7599
7704
  }
7705
+ async function settleWatermarkDoubt(context, channelId) {
7706
+ if (context.reconcileWatermark === void 0) return;
7707
+ if (!context.channels.isWatermarkUncertain(channelId)) return;
7708
+ try {
7709
+ await context.reconcileWatermark(channelId);
7710
+ } catch (error) {
7711
+ (context.warn ?? console.warn)(
7712
+ `[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.`
7713
+ );
7714
+ }
7715
+ }
7600
7716
  async function maybeRetryStaleChannel(context, first, params) {
7601
7717
  const result = first.result;
7602
7718
  if (result.fulfilled) return void 0;
@@ -7902,7 +8018,7 @@ var ToonClient = class _ToonClient {
7902
8018
  destination,
7903
8019
  amount: "0",
7904
8020
  data: toBase64(exchange.data),
7905
- executionCondition: exchange.condition,
8021
+ expectedFulfillment: exchange.fulfillment,
7906
8022
  timeout: this.config.timeoutMs
7907
8023
  },
7908
8024
  claim
@@ -8010,6 +8126,7 @@ var ToonClient = class _ToonClient {
8010
8126
  ensureChannel: (description) => this.channelFacade.ensure(description),
8011
8127
  evictChannel: (channelId) => this.evictChannel(channelId),
8012
8128
  channels: this.channels,
8129
+ reconcileWatermark: (channelId) => this.reconcileWatermark(channelId),
8013
8130
  transport: (description) => this.transportFor(description),
8014
8131
  senderId: this.identity.senderId,
8015
8132
  chain: this.chain,
@@ -8035,6 +8152,36 @@ var ToonClient = class _ToonClient {
8035
8152
  const identity = await this.edge.getIdentity(endpoint);
8036
8153
  return identity.publicKey;
8037
8154
  }
8155
+ /**
8156
+ * Re-read the connector's own watermark for one channel and adopt it
8157
+ * (toon-client#671).
8158
+ *
8159
+ * Called by {@link send} before signing a claim on a channel whose last claim
8160
+ * was signed and never confirmed — a transport error, a timeout, or a refusal.
8161
+ * A packet that timed out on a long path may have been delivered and banked
8162
+ * anyway, and the local figure would then be one claim behind for good: every
8163
+ * later claim under-advances and is refused. The connector's figure is the one
8164
+ * that decides, so it is asked, and {@link ChannelManager.adoptConnectorWatermark}
8165
+ * takes it (clamped to what this client has actually signed).
8166
+ *
8167
+ * A channel the connector cannot verify (`ok: false`) leaves the doubt in
8168
+ * place rather than resolving it wrongly — `"unverified"` covers "no such
8169
+ * channel" and "bad signature" identically, and neither is a watermark.
8170
+ */
8171
+ async reconcileWatermark(channelId) {
8172
+ const entry = (await this.claimState([channelId])).find(
8173
+ (e) => e.ok && (e.channelId ?? e.channelAccount ?? channelId) === channelId
8174
+ );
8175
+ if (entry === void 0) return;
8176
+ const adoption = this.channels.adoptConnectorWatermark(channelId, {
8177
+ nonce: entry.nonce,
8178
+ cumulativeClaimed: BigInt(entry.cumulativeClaimed)
8179
+ });
8180
+ if (!adoption.adopted || adoption.moved === 0n) return;
8181
+ console.warn(
8182
+ `[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()}.` : "")
8183
+ );
8184
+ }
8038
8185
  /**
8039
8186
  * Retire the binding a refused claim was drawn on. `false` when there is
8040
8187
  * nothing to retire, which is {@link send}'s signal not to retry.
@@ -8297,7 +8444,7 @@ export {
8297
8444
  toHex,
8298
8445
  encodeUtf8,
8299
8446
  decodeUtf8,
8300
- resolveExecutionCondition,
8447
+ resolveExpectedFulfillment,
8301
8448
  PACKET_EXPIRY_HEADROOM_MS,
8302
8449
  resolveExpiresAt,
8303
8450
  FULFILLMENT_MISMATCH_CODE,
@@ -8382,7 +8529,6 @@ export {
8382
8529
  openResponse,
8383
8530
  looksLikeSealedResponse,
8384
8531
  deriveFulfillment,
8385
- deriveCondition,
8386
8532
  SealedResponseError,
8387
8533
  sealExchange,
8388
8534
  readExchangeOutcome,
@@ -8412,4 +8558,4 @@ export {
8412
8558
  toEnvelopeRequest,
8413
8559
  ToonClient
8414
8560
  };
8415
- //# sourceMappingURL=chunk-A3JKQOWQ.js.map
8561
+ //# sourceMappingURL=chunk-M54FLOSJ.js.map