@toon-protocol/client 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -544,6 +544,231 @@ function isBase64(str) {
544
544
  return /^[A-Za-z0-9+/]*={0,2}$/.test(str);
545
545
  }
546
546
 
547
+ // src/btp/protocol.ts
548
+ var textEncoder = new TextEncoder();
549
+ var textDecoder = new TextDecoder();
550
+ var BTPMessageType = {
551
+ RESPONSE: 1,
552
+ ERROR: 2,
553
+ MESSAGE: 6
554
+ };
555
+ var ILPPacketType = {
556
+ PREPARE: 12,
557
+ FULFILL: 13,
558
+ REJECT: 14
559
+ };
560
+ function concat(...arrays) {
561
+ const totalLength = arrays.reduce((sum, a) => sum + a.length, 0);
562
+ const result = new Uint8Array(totalLength);
563
+ let offset = 0;
564
+ for (const a of arrays) {
565
+ result.set(a, offset);
566
+ offset += a.length;
567
+ }
568
+ return result;
569
+ }
570
+ function readUint8(buf, offset) {
571
+ if (offset >= buf.length) throw new Error("Buffer underflow reading uint8");
572
+ return buf[offset];
573
+ }
574
+ function readUint16BE(buf, offset) {
575
+ if (offset + 2 > buf.length)
576
+ throw new Error("Buffer underflow reading uint16");
577
+ return buf[offset] << 8 | buf[offset + 1];
578
+ }
579
+ function readUint32BE(buf, offset) {
580
+ if (offset + 4 > buf.length)
581
+ throw new Error("Buffer underflow reading uint32");
582
+ return (buf[offset] << 24 | buf[offset + 1] << 16 | buf[offset + 2] << 8 | buf[offset + 3]) >>> 0;
583
+ }
584
+ function writeUint8(value) {
585
+ return new Uint8Array([value]);
586
+ }
587
+ function writeUint16BE(value) {
588
+ return new Uint8Array([value >> 8 & 255, value & 255]);
589
+ }
590
+ function writeUint32BE(value) {
591
+ return new Uint8Array([
592
+ value >> 24 & 255,
593
+ value >> 16 & 255,
594
+ value >> 8 & 255,
595
+ value & 255
596
+ ]);
597
+ }
598
+ function sliceUtf8(buf, offset, length) {
599
+ return textDecoder.decode(buf.slice(offset, offset + length));
600
+ }
601
+ function encodeVarUInt(value) {
602
+ if (value >= 0n && value <= 127n) {
603
+ return new Uint8Array([Number(value)]);
604
+ }
605
+ const bytes = [];
606
+ let remaining = value;
607
+ while (remaining > 0n) {
608
+ bytes.unshift(Number(remaining & 0xffn));
609
+ remaining = remaining >> 8n;
610
+ }
611
+ return new Uint8Array([128 | bytes.length, ...bytes]);
612
+ }
613
+ function decodeVarUInt(buf, offset) {
614
+ const firstByte = readUint8(buf, offset);
615
+ if (firstByte <= 127) {
616
+ return { value: BigInt(firstByte), bytesRead: 1 };
617
+ }
618
+ const length = firstByte & 127;
619
+ if (offset + 1 + length > buf.length)
620
+ throw new Error("VarUInt buffer underflow");
621
+ let value = 0n;
622
+ for (let i = 0; i < length; i++) {
623
+ value = value << 8n | BigInt(buf[offset + 1 + i]);
624
+ }
625
+ return { value, bytesRead: 1 + length };
626
+ }
627
+ function encodeVarOctetString(data) {
628
+ return concat(encodeVarUInt(BigInt(data.length)), data);
629
+ }
630
+ function decodeVarOctetString(buf, offset) {
631
+ const { value: length, bytesRead: lenBytes } = decodeVarUInt(buf, offset);
632
+ const dataLen = Number(length);
633
+ const start = offset + lenBytes;
634
+ if (start + dataLen > buf.length)
635
+ throw new Error("VarOctetString buffer underflow");
636
+ return {
637
+ value: buf.slice(start, start + dataLen),
638
+ bytesRead: lenBytes + dataLen
639
+ };
640
+ }
641
+ function encodeGeneralizedTime(date) {
642
+ const y = date.getUTCFullYear().toString().padStart(4, "0");
643
+ const mo = (date.getUTCMonth() + 1).toString().padStart(2, "0");
644
+ const d = date.getUTCDate().toString().padStart(2, "0");
645
+ const h = date.getUTCHours().toString().padStart(2, "0");
646
+ const mi = date.getUTCMinutes().toString().padStart(2, "0");
647
+ const s = date.getUTCSeconds().toString().padStart(2, "0");
648
+ const ms = date.getUTCMilliseconds().toString().padStart(3, "0");
649
+ return textEncoder.encode(`${y}${mo}${d}${h}${mi}${s}.${ms}Z`);
650
+ }
651
+ function serializeIlpPrepare(packet) {
652
+ const condition = packet.executionCondition.length === 32 ? packet.executionCondition : new Uint8Array(32);
653
+ return concat(
654
+ writeUint8(ILPPacketType.PREPARE),
655
+ encodeVarUInt(packet.amount),
656
+ encodeGeneralizedTime(packet.expiresAt),
657
+ condition,
658
+ encodeVarOctetString(textEncoder.encode(packet.destination)),
659
+ encodeVarOctetString(packet.data)
660
+ );
661
+ }
662
+ function deserializeIlpPacket(buf) {
663
+ if (buf.length === 0) throw new Error("Empty ILP packet");
664
+ const type = buf[0];
665
+ if (type === ILPPacketType.FULFILL) return deserializeIlpFulfill(buf);
666
+ if (type === ILPPacketType.REJECT) return deserializeIlpReject(buf);
667
+ throw new Error(`Unknown ILP packet type: ${type}`);
668
+ }
669
+ function deserializeIlpFulfill(buf) {
670
+ let offset = 1;
671
+ if (buf.length < offset + 32) {
672
+ throw new Error("Buffer underflow reading FULFILL fulfillment");
673
+ }
674
+ const fulfillment = buf.slice(offset, offset + 32);
675
+ offset += 32;
676
+ const { value: data } = decodeVarOctetString(buf, offset);
677
+ return { type: ILPPacketType.FULFILL, fulfillment, data };
678
+ }
679
+ function deserializeIlpReject(buf) {
680
+ let offset = 1;
681
+ const code = sliceUtf8(buf, offset, 3);
682
+ offset += 3;
683
+ const { bytesRead: tbBytes } = decodeVarOctetString(buf, offset);
684
+ offset += tbBytes;
685
+ const { value: msgBuf, bytesRead: msgBytes } = decodeVarOctetString(
686
+ buf,
687
+ offset
688
+ );
689
+ offset += msgBytes;
690
+ const message = textDecoder.decode(msgBuf);
691
+ const { value: data } = decodeVarOctetString(buf, offset);
692
+ return { type: ILPPacketType.REJECT, code, message, data };
693
+ }
694
+ function serializeBtpMessage(message) {
695
+ const parts = [
696
+ writeUint8(message.type),
697
+ writeUint32BE(message.requestId)
698
+ ];
699
+ const data = message.data;
700
+ const protocolData = data.protocolData ?? [];
701
+ parts.push(writeUint8(protocolData.length));
702
+ for (const pd of protocolData) {
703
+ const nameBytes = textEncoder.encode(pd.protocolName);
704
+ parts.push(writeUint8(nameBytes.length));
705
+ parts.push(nameBytes);
706
+ parts.push(writeUint16BE(pd.contentType));
707
+ parts.push(writeUint32BE(pd.data.length));
708
+ if (pd.data.length > 0) parts.push(pd.data);
709
+ }
710
+ const ilpPacket = data.ilpPacket ?? new Uint8Array(0);
711
+ parts.push(writeUint32BE(ilpPacket.length));
712
+ if (ilpPacket.length > 0) parts.push(ilpPacket);
713
+ return concat(...parts);
714
+ }
715
+ function parseBtpMessage(buf) {
716
+ if (buf.length < 5) throw new Error("BTP message too short");
717
+ let offset = 0;
718
+ const type = readUint8(buf, offset);
719
+ offset += 1;
720
+ const requestId = readUint32BE(buf, offset);
721
+ offset += 4;
722
+ if (type === BTPMessageType.ERROR) {
723
+ const codeLen = readUint8(buf, offset);
724
+ offset += 1;
725
+ const code = sliceUtf8(buf, offset, codeLen);
726
+ offset += codeLen;
727
+ const nameLen = readUint8(buf, offset);
728
+ offset += 1;
729
+ const name = sliceUtf8(buf, offset, nameLen);
730
+ offset += nameLen;
731
+ const taLen = readUint8(buf, offset);
732
+ offset += 1;
733
+ const triggeredAt = sliceUtf8(buf, offset, taLen);
734
+ offset += taLen;
735
+ const dataLen = readUint32BE(buf, offset);
736
+ offset += 4;
737
+ const data = buf.slice(offset, offset + dataLen);
738
+ const message = textDecoder.decode(data);
739
+ return {
740
+ type,
741
+ requestId,
742
+ data: { code, name, triggeredAt, message, data }
743
+ };
744
+ }
745
+ const pdCount = readUint8(buf, offset);
746
+ offset += 1;
747
+ const protocolData = [];
748
+ for (let i = 0; i < pdCount; i++) {
749
+ const nameLen = readUint8(buf, offset);
750
+ offset += 1;
751
+ const protocolName = sliceUtf8(buf, offset, nameLen);
752
+ offset += nameLen;
753
+ const contentType = readUint16BE(buf, offset);
754
+ offset += 2;
755
+ const dataLen = readUint32BE(buf, offset);
756
+ offset += 4;
757
+ const data = buf.slice(offset, offset + dataLen);
758
+ offset += dataLen;
759
+ protocolData.push({ protocolName, contentType, data });
760
+ }
761
+ let ilpPacket;
762
+ if (offset + 4 <= buf.length) {
763
+ const ilpLen = readUint32BE(buf, offset);
764
+ offset += 4;
765
+ if (ilpLen > 0 && offset + ilpLen <= buf.length) {
766
+ ilpPacket = buf.slice(offset, offset + ilpLen);
767
+ }
768
+ }
769
+ return { type, requestId, data: { protocolData, ilpPacket } };
770
+ }
771
+
547
772
  // src/adapters/ConnectorEdgeClient.ts
548
773
  var ConnectorEdgeError = class extends ToonClientError {
549
774
  constructor(message, code, cause) {
@@ -738,6 +963,67 @@ var ConnectorEdgeClient = class {
738
963
  this.prices.set(key2, inFlight);
739
964
  return inFlight;
740
965
  }
966
+ /**
967
+ * Ask a route for its full x402 terms — the greeting a claimless PREPARE
968
+ * is answered with (client-edge-spec.md §1.4) — including, from a settling
969
+ * node, the channel-opening facts (connector #617).
970
+ *
971
+ * This is a real `POST /ilp` carrying a minimal PREPARE with no claim
972
+ * header. It is free by the wire's own contract: an unpaid request to a
973
+ * priced route is answered with terms instead of performed, and nothing
974
+ * is charged for asking. `null` when the connector does not price the
975
+ * destination (the request would be routed or refused, not greeted) —
976
+ * mapped from anything other than a 402 answer.
977
+ */
978
+ async getRouteTerms(endpoint, destination) {
979
+ if (typeof destination !== "string" || destination.trim().length === 0) {
980
+ throw new ConnectorEdgeError(
981
+ "route terms need a non-empty ILP destination",
982
+ "INVALID_DESTINATION"
983
+ );
984
+ }
985
+ const base = connectorEdgeBaseUrl(endpoint);
986
+ const condition = new Uint8Array(32);
987
+ condition[0] = 1;
988
+ const prepare = serializeIlpPrepare({
989
+ type: ILPPacketType.PREPARE,
990
+ amount: 0n,
991
+ destination,
992
+ executionCondition: condition,
993
+ expiresAt: new Date(Date.now() + 3e4),
994
+ data: new Uint8Array(0)
995
+ });
996
+ const controller = new AbortController();
997
+ const timer = setTimeout(() => controller.abort(), this.timeout);
998
+ let response;
999
+ try {
1000
+ response = await this.fetchImpl(`${base}/ilp`, {
1001
+ method: "POST",
1002
+ headers: { "content-type": "application/octet-stream" },
1003
+ body: prepare.slice(),
1004
+ signal: controller.signal
1005
+ });
1006
+ } catch (error) {
1007
+ throw new NetworkError(
1008
+ `could not reach the connector client edge at ${base}/ilp`,
1009
+ error instanceof Error ? error : void 0
1010
+ );
1011
+ } finally {
1012
+ clearTimeout(timer);
1013
+ }
1014
+ if (response.status !== 402) return null;
1015
+ let body;
1016
+ try {
1017
+ body = await response.json();
1018
+ } catch (error) {
1019
+ throw new ConnectorEdgeError(
1020
+ "connector answered 402 with a body that is not JSON",
1021
+ "TERMS_MALFORMED",
1022
+ error instanceof Error ? error : void 0
1023
+ );
1024
+ }
1025
+ return parseConnectorRouteTerms(body);
1026
+ }
741
1027
  /**
742
1028
  * Drop a cached route price — one (endpoint, destination)'s, every
743
1029
  * destination's at one endpoint when `destination` is omitted, or all of
@@ -823,8 +1109,69 @@ var ConnectorEdgeClient = class {
823
1109
  } finally {
824
1110
  clearTimeout(timer);
825
1111
  }
826
- }
827
- };
1112
+ }
1113
+ };
1114
+ function parseConnectorRouteTerms(body) {
1115
+ if (typeof body !== "object" || body === null) {
1116
+ throw new ConnectorEdgeError(
1117
+ "x402 greeting is not an object",
1118
+ "TERMS_MALFORMED"
1119
+ );
1120
+ }
1121
+ const greeting = body;
1122
+ const accepts = Array.isArray(greeting.accepts) ? greeting.accepts : [];
1123
+ const option = accepts.find(
1124
+ (entry) => typeof entry === "object" && entry !== null && entry.scheme === "toon-channel"
1125
+ );
1126
+ if (!option || typeof option["amount"] !== "string") {
1127
+ throw new ConnectorEdgeError(
1128
+ "x402 greeting carries no toon-channel option",
1129
+ "TERMS_MALFORMED"
1130
+ );
1131
+ }
1132
+ const destination = typeof greeting.resource?.url === "string" ? greeting.resource.url : "";
1133
+ const extra = option["extra"];
1134
+ const rawSettlement = extra?.settlement;
1135
+ if (rawSettlement === void 0) {
1136
+ return { destination, price: option["amount"] };
1137
+ }
1138
+ if (typeof rawSettlement !== "object" || rawSettlement === null) {
1139
+ throw new ConnectorEdgeError(
1140
+ "x402 greeting settlement facts are malformed",
1141
+ "TERMS_MALFORMED"
1142
+ );
1143
+ }
1144
+ const s = rawSettlement;
1145
+ const str = (key2) => {
1146
+ const value = s[key2];
1147
+ if (typeof value !== "string" || value.length === 0) {
1148
+ throw new ConnectorEdgeError(
1149
+ `x402 greeting settlement facts lack '${key2}'`,
1150
+ "TERMS_MALFORMED"
1151
+ );
1152
+ }
1153
+ return value;
1154
+ };
1155
+ const decimals = s["decimals"];
1156
+ if (typeof decimals !== "number") {
1157
+ throw new ConnectorEdgeError(
1158
+ "x402 greeting settlement facts lack 'decimals'",
1159
+ "TERMS_MALFORMED"
1160
+ );
1161
+ }
1162
+ return {
1163
+ destination,
1164
+ price: option["amount"],
1165
+ settlement: {
1166
+ chain: str("chain"),
1167
+ settlementAddress: str("settlementAddress"),
1168
+ tokenNetworkRegistry: str("tokenNetworkRegistry"),
1169
+ tokenNetwork: str("tokenNetwork"),
1170
+ tokenAddress: str("tokenAddress"),
1171
+ decimals
1172
+ }
1173
+ };
1174
+ }
828
1175
 
829
1176
  // src/wire/oer.ts
830
1177
  var OerErrorKind = /* @__PURE__ */ ((OerErrorKind2) => {
@@ -884,14 +1231,14 @@ function decodeVarUint(buf, offset) {
884
1231
  }
885
1232
  return { value, consumed };
886
1233
  }
887
- function encodeVarOctetString(data) {
1234
+ function encodeVarOctetString2(data) {
888
1235
  const prefix = encodeVarUint(BigInt(data.length));
889
1236
  const out = new Uint8Array(prefix.length + data.length);
890
1237
  out.set(prefix, 0);
891
1238
  out.set(data, prefix.length);
892
1239
  return out;
893
1240
  }
894
- function decodeVarOctetString(buf, offset) {
1241
+ function decodeVarOctetString2(buf, offset) {
895
1242
  const { value: length, consumed: lengthBytes } = decodeVarUint(buf, offset);
896
1243
  if (length > BigInt(buf.length)) {
897
1244
  throw new OerError("buffer_underflow" /* BufferUnderflow */);
@@ -954,7 +1301,7 @@ function fromOerError(error) {
954
1301
  }
955
1302
  function decodeOctets(buf, offset) {
956
1303
  try {
957
- return decodeVarOctetString(buf, offset);
1304
+ return decodeVarOctetString2(buf, offset);
958
1305
  } catch (error) {
959
1306
  throw fromOerError(error);
960
1307
  }
@@ -984,7 +1331,7 @@ function checkTypeByte(buf, expected) {
984
1331
  }
985
1332
  return 1;
986
1333
  }
987
- function concat(parts) {
1334
+ function concat2(parts) {
988
1335
  const total = parts.reduce((sum, part) => sum + part.length, 0);
989
1336
  const out = new Uint8Array(total);
990
1337
  let offset = 0;
@@ -997,10 +1344,10 @@ function concat(parts) {
997
1344
  function encodeHeaders(headers) {
998
1345
  const parts = [encodeVarUint(BigInt(headers.length))];
999
1346
  for (const [name, value] of headers) {
1000
- parts.push(encodeVarOctetString(UTF8_ENCODER.encode(name)));
1001
- parts.push(encodeVarOctetString(UTF8_ENCODER.encode(value)));
1347
+ parts.push(encodeVarOctetString2(UTF8_ENCODER.encode(name)));
1348
+ parts.push(encodeVarOctetString2(UTF8_ENCODER.encode(value)));
1002
1349
  }
1003
- return concat(parts);
1350
+ return concat2(parts);
1004
1351
  }
1005
1352
  function decodeHeaders(buf, offset) {
1006
1353
  const { value: count, consumed: countBytes } = decodeCount(buf, offset);
@@ -1019,12 +1366,12 @@ function decodeHeaders(buf, offset) {
1019
1366
  return { value: headers, consumed };
1020
1367
  }
1021
1368
  function encodeEnvelopeRequest(request) {
1022
- return concat([
1369
+ return concat2([
1023
1370
  Uint8Array.of(TYPE_ENVELOPE_REQUEST),
1024
- encodeVarOctetString(UTF8_ENCODER.encode(request.method)),
1025
- encodeVarOctetString(UTF8_ENCODER.encode(request.target)),
1371
+ encodeVarOctetString2(UTF8_ENCODER.encode(request.method)),
1372
+ encodeVarOctetString2(UTF8_ENCODER.encode(request.target)),
1026
1373
  encodeHeaders(request.headers),
1027
- encodeVarOctetString(request.body)
1374
+ encodeVarOctetString2(request.body)
1028
1375
  ]);
1029
1376
  }
1030
1377
  function decodeEnvelopeRequest(buf) {
@@ -1053,14 +1400,14 @@ function encodeEnvelopeResponse(response) {
1053
1400
  `envelope status must fit two bytes, got ${response.status}`
1054
1401
  );
1055
1402
  }
1056
- return concat([
1403
+ return concat2([
1057
1404
  Uint8Array.of(
1058
1405
  TYPE_ENVELOPE_RESPONSE,
1059
1406
  response.status >> 8 & 255,
1060
1407
  response.status & 255
1061
1408
  ),
1062
1409
  encodeHeaders(response.headers),
1063
- encodeVarOctetString(response.body)
1410
+ encodeVarOctetString2(response.body)
1064
1411
  ]);
1065
1412
  }
1066
1413
  function decodeEnvelopeResponse(buf) {
@@ -1128,7 +1475,7 @@ var GiftWrapError = class extends Error {
1128
1475
  kind;
1129
1476
  expectedType;
1130
1477
  };
1131
- function concat2(parts) {
1478
+ function concat3(parts) {
1132
1479
  const total = parts.reduce((sum, part) => sum + part.length, 0);
1133
1480
  const out = new Uint8Array(total);
1134
1481
  let offset = 0;
@@ -1142,7 +1489,7 @@ function hkdfKey(ikm, info) {
1142
1489
  return hkdf(sha256, ikm, void 0, info, 32);
1143
1490
  }
1144
1491
  function encryptWithNonce(key2, plaintext, nonce) {
1145
- return concat2([nonce, chacha20poly1305(key2, nonce).encrypt(plaintext)]);
1492
+ return concat3([nonce, chacha20poly1305(key2, nonce).encrypt(plaintext)]);
1146
1493
  }
1147
1494
  function decrypt(key2, nonceAndCiphertext) {
1148
1495
  if (nonceAndCiphertext.length < GIFTWRAP_NONCE_LENGTH) {
@@ -1190,8 +1537,8 @@ function sealRequestWithRandomness(plaintext, receiverPublicKey, ephemeralSecret
1190
1537
  ecdhXCoordinate(ephemeralSecretKey, receiverPublicKey),
1191
1538
  REQUEST_INFO
1192
1539
  );
1193
- const inner = concat2([sharedSecret, plaintext]);
1194
- return concat2([
1540
+ const inner = concat3([sharedSecret, plaintext]);
1541
+ return concat3([
1195
1542
  Uint8Array.of(GIFTWRAP_TYPE_REQUEST),
1196
1543
  ephemeralPublicKey,
1197
1544
  encryptWithNonce(aeadKey, inner, nonce)
@@ -1250,7 +1597,7 @@ function sealResponseWithRandomness(sharedSecret, plaintext, nonce) {
1250
1597
  if (nonce.length !== GIFTWRAP_NONCE_LENGTH) {
1251
1598
  throw new GiftWrapError("truncated" /* Truncated */);
1252
1599
  }
1253
- return concat2([
1600
+ return concat3([
1254
1601
  Uint8Array.of(GIFTWRAP_TYPE_RESPONSE),
1255
1602
  encryptWithNonce(hkdfKey(sharedSecret, RESPONSE_INFO), plaintext, nonce)
1256
1603
  ]);
@@ -1568,231 +1915,6 @@ var HttpRuntimeClient = class {
1568
1915
  }
1569
1916
  };
1570
1917
 
1571
- // src/btp/protocol.ts
1572
- var textEncoder = new TextEncoder();
1573
- var textDecoder = new TextDecoder();
1574
- var BTPMessageType = {
1575
- RESPONSE: 1,
1576
- ERROR: 2,
1577
- MESSAGE: 6
1578
- };
1579
- var ILPPacketType = {
1580
- PREPARE: 12,
1581
- FULFILL: 13,
1582
- REJECT: 14
1583
- };
1584
- function concat3(...arrays) {
1585
- const totalLength = arrays.reduce((sum, a) => sum + a.length, 0);
1586
- const result = new Uint8Array(totalLength);
1587
- let offset = 0;
1588
- for (const a of arrays) {
1589
- result.set(a, offset);
1590
- offset += a.length;
1591
- }
1592
- return result;
1593
- }
1594
- function readUint8(buf, offset) {
1595
- if (offset >= buf.length) throw new Error("Buffer underflow reading uint8");
1596
- return buf[offset];
1597
- }
1598
- function readUint16BE(buf, offset) {
1599
- if (offset + 2 > buf.length)
1600
- throw new Error("Buffer underflow reading uint16");
1601
- return buf[offset] << 8 | buf[offset + 1];
1602
- }
1603
- function readUint32BE(buf, offset) {
1604
- if (offset + 4 > buf.length)
1605
- throw new Error("Buffer underflow reading uint32");
1606
- return (buf[offset] << 24 | buf[offset + 1] << 16 | buf[offset + 2] << 8 | buf[offset + 3]) >>> 0;
1607
- }
1608
- function writeUint8(value) {
1609
- return new Uint8Array([value]);
1610
- }
1611
- function writeUint16BE(value) {
1612
- return new Uint8Array([value >> 8 & 255, value & 255]);
1613
- }
1614
- function writeUint32BE(value) {
1615
- return new Uint8Array([
1616
- value >> 24 & 255,
1617
- value >> 16 & 255,
1618
- value >> 8 & 255,
1619
- value & 255
1620
- ]);
1621
- }
1622
- function sliceUtf8(buf, offset, length) {
1623
- return textDecoder.decode(buf.slice(offset, offset + length));
1624
- }
1625
- function encodeVarUInt(value) {
1626
- if (value >= 0n && value <= 127n) {
1627
- return new Uint8Array([Number(value)]);
1628
- }
1629
- const bytes = [];
1630
- let remaining = value;
1631
- while (remaining > 0n) {
1632
- bytes.unshift(Number(remaining & 0xffn));
1633
- remaining = remaining >> 8n;
1634
- }
1635
- return new Uint8Array([128 | bytes.length, ...bytes]);
1636
- }
1637
- function decodeVarUInt(buf, offset) {
1638
- const firstByte = readUint8(buf, offset);
1639
- if (firstByte <= 127) {
1640
- return { value: BigInt(firstByte), bytesRead: 1 };
1641
- }
1642
- const length = firstByte & 127;
1643
- if (offset + 1 + length > buf.length)
1644
- throw new Error("VarUInt buffer underflow");
1645
- let value = 0n;
1646
- for (let i = 0; i < length; i++) {
1647
- value = value << 8n | BigInt(buf[offset + 1 + i]);
1648
- }
1649
- return { value, bytesRead: 1 + length };
1650
- }
1651
- function encodeVarOctetString2(data) {
1652
- return concat3(encodeVarUInt(BigInt(data.length)), data);
1653
- }
1654
- function decodeVarOctetString2(buf, offset) {
1655
- const { value: length, bytesRead: lenBytes } = decodeVarUInt(buf, offset);
1656
- const dataLen = Number(length);
1657
- const start = offset + lenBytes;
1658
- if (start + dataLen > buf.length)
1659
- throw new Error("VarOctetString buffer underflow");
1660
- return {
1661
- value: buf.slice(start, start + dataLen),
1662
- bytesRead: lenBytes + dataLen
1663
- };
1664
- }
1665
- function encodeGeneralizedTime(date) {
1666
- const y = date.getUTCFullYear().toString().padStart(4, "0");
1667
- const mo = (date.getUTCMonth() + 1).toString().padStart(2, "0");
1668
- const d = date.getUTCDate().toString().padStart(2, "0");
1669
- const h = date.getUTCHours().toString().padStart(2, "0");
1670
- const mi = date.getUTCMinutes().toString().padStart(2, "0");
1671
- const s = date.getUTCSeconds().toString().padStart(2, "0");
1672
- const ms = date.getUTCMilliseconds().toString().padStart(3, "0");
1673
- return textEncoder.encode(`${y}${mo}${d}${h}${mi}${s}.${ms}Z`);
1674
- }
1675
- function serializeIlpPrepare(packet) {
1676
- const condition = packet.executionCondition.length === 32 ? packet.executionCondition : new Uint8Array(32);
1677
- return concat3(
1678
- writeUint8(ILPPacketType.PREPARE),
1679
- encodeVarUInt(packet.amount),
1680
- encodeGeneralizedTime(packet.expiresAt),
1681
- condition,
1682
- encodeVarOctetString2(textEncoder.encode(packet.destination)),
1683
- encodeVarOctetString2(packet.data)
1684
- );
1685
- }
1686
- function deserializeIlpPacket(buf) {
1687
- if (buf.length === 0) throw new Error("Empty ILP packet");
1688
- const type = buf[0];
1689
- if (type === ILPPacketType.FULFILL) return deserializeIlpFulfill(buf);
1690
- if (type === ILPPacketType.REJECT) return deserializeIlpReject(buf);
1691
- throw new Error(`Unknown ILP packet type: ${type}`);
1692
- }
1693
- function deserializeIlpFulfill(buf) {
1694
- let offset = 1;
1695
- if (buf.length < offset + 32) {
1696
- throw new Error("Buffer underflow reading FULFILL fulfillment");
1697
- }
1698
- const fulfillment = buf.slice(offset, offset + 32);
1699
- offset += 32;
1700
- const { value: data } = decodeVarOctetString2(buf, offset);
1701
- return { type: ILPPacketType.FULFILL, fulfillment, data };
1702
- }
1703
- function deserializeIlpReject(buf) {
1704
- let offset = 1;
1705
- const code = sliceUtf8(buf, offset, 3);
1706
- offset += 3;
1707
- const { bytesRead: tbBytes } = decodeVarOctetString2(buf, offset);
1708
- offset += tbBytes;
1709
- const { value: msgBuf, bytesRead: msgBytes } = decodeVarOctetString2(
1710
- buf,
1711
- offset
1712
- );
1713
- offset += msgBytes;
1714
- const message = textDecoder.decode(msgBuf);
1715
- const { value: data } = decodeVarOctetString2(buf, offset);
1716
- return { type: ILPPacketType.REJECT, code, message, data };
1717
- }
1718
- function serializeBtpMessage(message) {
1719
- const parts = [
1720
- writeUint8(message.type),
1721
- writeUint32BE(message.requestId)
1722
- ];
1723
- const data = message.data;
1724
- const protocolData = data.protocolData ?? [];
1725
- parts.push(writeUint8(protocolData.length));
1726
- for (const pd of protocolData) {
1727
- const nameBytes = textEncoder.encode(pd.protocolName);
1728
- parts.push(writeUint8(nameBytes.length));
1729
- parts.push(nameBytes);
1730
- parts.push(writeUint16BE(pd.contentType));
1731
- parts.push(writeUint32BE(pd.data.length));
1732
- if (pd.data.length > 0) parts.push(pd.data);
1733
- }
1734
- const ilpPacket = data.ilpPacket ?? new Uint8Array(0);
1735
- parts.push(writeUint32BE(ilpPacket.length));
1736
- if (ilpPacket.length > 0) parts.push(ilpPacket);
1737
- return concat3(...parts);
1738
- }
1739
- function parseBtpMessage(buf) {
1740
- if (buf.length < 5) throw new Error("BTP message too short");
1741
- let offset = 0;
1742
- const type = readUint8(buf, offset);
1743
- offset += 1;
1744
- const requestId = readUint32BE(buf, offset);
1745
- offset += 4;
1746
- if (type === BTPMessageType.ERROR) {
1747
- const codeLen = readUint8(buf, offset);
1748
- offset += 1;
1749
- const code = sliceUtf8(buf, offset, codeLen);
1750
- offset += codeLen;
1751
- const nameLen = readUint8(buf, offset);
1752
- offset += 1;
1753
- const name = sliceUtf8(buf, offset, nameLen);
1754
- offset += nameLen;
1755
- const taLen = readUint8(buf, offset);
1756
- offset += 1;
1757
- const triggeredAt = sliceUtf8(buf, offset, taLen);
1758
- offset += taLen;
1759
- const dataLen = readUint32BE(buf, offset);
1760
- offset += 4;
1761
- const data = buf.slice(offset, offset + dataLen);
1762
- const message = textDecoder.decode(data);
1763
- return {
1764
- type,
1765
- requestId,
1766
- data: { code, name, triggeredAt, message, data }
1767
- };
1768
- }
1769
- const pdCount = readUint8(buf, offset);
1770
- offset += 1;
1771
- const protocolData = [];
1772
- for (let i = 0; i < pdCount; i++) {
1773
- const nameLen = readUint8(buf, offset);
1774
- offset += 1;
1775
- const protocolName = sliceUtf8(buf, offset, nameLen);
1776
- offset += nameLen;
1777
- const contentType = readUint16BE(buf, offset);
1778
- offset += 2;
1779
- const dataLen = readUint32BE(buf, offset);
1780
- offset += 4;
1781
- const data = buf.slice(offset, offset + dataLen);
1782
- offset += dataLen;
1783
- protocolData.push({ protocolName, contentType, data });
1784
- }
1785
- let ilpPacket;
1786
- if (offset + 4 <= buf.length) {
1787
- const ilpLen = readUint32BE(buf, offset);
1788
- offset += 4;
1789
- if (ilpLen > 0 && offset + ilpLen <= buf.length) {
1790
- ilpPacket = buf.slice(offset, offset + ilpLen);
1791
- }
1792
- }
1793
- return { type, requestId, data: { protocolData, ilpPacket } };
1794
- }
1795
-
1796
1918
  // src/btp/IsomorphicBtpClient.ts
1797
1919
  var textEncoder2 = new TextEncoder();
1798
1920
  var BtpConnectionError = class extends Error {
@@ -4745,10 +4867,21 @@ function parseEvmChainId(chainKey) {
4745
4867
  if (!Number.isFinite(id)) throw new Error(`Invalid EVM chain key "${chainKey}".`);
4746
4868
  return id;
4747
4869
  }
4870
+ var RPC_TIMEOUT_ENV = "TOON_WALLET_RPC_TIMEOUT_MS";
4871
+ var DEFAULT_RPC_TIMEOUT_MS = 8e3;
4872
+ function rpcTimeoutMs() {
4873
+ const raw = typeof process !== "undefined" ? process.env?.[RPC_TIMEOUT_ENV] : void 0;
4874
+ const n = raw === void 0 || raw === "" ? NaN : Number(raw);
4875
+ return Number.isFinite(n) && n >= 0 ? n : DEFAULT_RPC_TIMEOUT_MS;
4876
+ }
4877
+ function rpcAbortSignal() {
4878
+ const ms = rpcTimeoutMs();
4879
+ return ms > 0 ? AbortSignal.timeout(ms) : void 0;
4880
+ }
4748
4881
  async function readEvmTokenBalance(opts) {
4749
4882
  const chainId = parseEvmChainId(opts.chainKey);
4750
4883
  const client = createPublicClient2({
4751
- transport: http2(opts.rpcUrl),
4884
+ transport: http2(opts.rpcUrl, { timeout: rpcTimeoutMs() || void 0, retryCount: 1 }),
4752
4885
  chain: defineChain2({
4753
4886
  id: chainId,
4754
4887
  name: opts.chainKey,
@@ -4771,7 +4904,7 @@ async function readEvmTokenBalance(opts) {
4771
4904
  async function readEvmNativeBalance(opts) {
4772
4905
  const chainId = parseEvmChainId(opts.chainKey);
4773
4906
  const client = createPublicClient2({
4774
- transport: http2(opts.rpcUrl),
4907
+ transport: http2(opts.rpcUrl, { timeout: rpcTimeoutMs() || void 0, retryCount: 1 }),
4775
4908
  chain: defineChain2({
4776
4909
  id: chainId,
4777
4910
  name: opts.chainKey,
@@ -4792,7 +4925,8 @@ async function readSolanaNativeBalance(opts) {
4792
4925
  id: 1,
4793
4926
  method: "getBalance",
4794
4927
  params: [opts.owner, { commitment: "confirmed" }]
4795
- })
4928
+ }),
4929
+ signal: rpcAbortSignal()
4796
4930
  });
4797
4931
  if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);
4798
4932
  const json = await res.json();
@@ -4810,7 +4944,8 @@ async function readSolanaTokenBalance(opts) {
4810
4944
  id: 1,
4811
4945
  method: "getTokenAccountsByOwner",
4812
4946
  params: [opts.owner, { mint: opts.mint }, { encoding: "jsonParsed", commitment: "confirmed" }]
4813
- })
4947
+ }),
4948
+ signal: rpcAbortSignal()
4814
4949
  });
4815
4950
  if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);
4816
4951
  const json = await res.json();
@@ -4832,7 +4967,8 @@ async function readMinaBalance(opts) {
4832
4967
  const res = await fetchImpl(opts.graphqlUrl, {
4833
4968
  method: "POST",
4834
4969
  headers: { "content-type": "application/json" },
4835
- body: JSON.stringify({ query, variables: { pk: opts.owner } })
4970
+ body: JSON.stringify({ query, variables: { pk: opts.owner } }),
4971
+ signal: rpcAbortSignal()
4836
4972
  });
4837
4973
  if (!res.ok) throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);
4838
4974
  const json = await res.json();
@@ -4888,7 +5024,8 @@ async function readMinaTokenBalance(opts) {
4888
5024
  const res = await fetchImpl(opts.graphqlUrl, {
4889
5025
  method: "POST",
4890
5026
  headers: { "content-type": "application/json" },
4891
- body: JSON.stringify({ query, variables: { pk: opts.owner, t: token } })
5027
+ body: JSON.stringify({ query, variables: { pk: opts.owner, t: token } }),
5028
+ signal: rpcAbortSignal()
4892
5029
  });
4893
5030
  if (!res.ok) throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);
4894
5031
  const json = await res.json();
@@ -4900,7 +5037,10 @@ async function readMinaTokenBalance(opts) {
4900
5037
  address: opts.owner,
4901
5038
  amount: String(json.data?.account?.balance?.total ?? "0"),
4902
5039
  asset: "USDC",
4903
- assetScale: 9
5040
+ // TOON's settlement USDC is 6-decimal on every chain (assetScale 6), unlike
5041
+ // native MINA's 9. The Mina custom-token amount is a raw u64, so scale it at
5042
+ // 6 — otherwise a 50 USDC balance (50_000000) misreads as 0.05.
5043
+ assetScale: 6
4904
5044
  };
4905
5045
  }
4906
5046
  var errText = (e) => e instanceof Error ? e.message : String(e);
@@ -5032,9 +5172,12 @@ async function requestBlobStorage(client, secretKey, params) {
5032
5172
  const result = await client.publishEvent(event, {
5033
5173
  destination: params.destination,
5034
5174
  claim: params.claim,
5035
- ilpAmount: params.ilpAmount,
5036
- // The store/DVM backend serves POST /store (not the relay's /write).
5037
- proxyPath: "/store"
5175
+ ilpAmount: params.ilpAmount
5176
+ // No proxyPath: the store DESTINATION's route already terminates at the
5177
+ // store backend's own endpoint, and ADR 0025 resolves the envelope
5178
+ // target strictly beneath that handler path — '' (the default) means
5179
+ // "the handler's own path". The old absolute '/store' is refused by the
5180
+ // connector as an escape attempt (F00).
5038
5181
  });
5039
5182
  if (!result.success) {
5040
5183
  return {
@@ -5302,7 +5445,9 @@ function toEnvelopeRequest(url, method, opts) {
5302
5445
  );
5303
5446
  return {
5304
5447
  method: method.toUpperCase(),
5305
- target: `${u.pathname}${u.search}` || "/",
5448
+ // Strip the leading '/' — ADR 0025 targets are handler-relative, and
5449
+ // the empty string ('' + no search) is exactly "the handler's path".
5450
+ target: `${u.pathname.replace(/^\/+/, "")}${u.search}`,
5306
5451
  headers,
5307
5452
  body: bodyToBytes(opts.body)
5308
5453
  };
@@ -6076,7 +6221,15 @@ var ToonClient = class {
6076
6221
  const exchange = sealExchange(
6077
6222
  {
6078
6223
  method: "POST",
6079
- target: options?.proxyPath ?? "/write",
6224
+ // ADR 0025 (connector #596): the envelope target is resolved
6225
+ // STRICTLY BENEATH the route's configured handler path — it can
6226
+ // extend that path, never replace it. '' means "the handler's own
6227
+ // path", which is the whole answer for a route that terminates at
6228
+ // exactly one endpoint (g.rust.relay → …/write, g.rust.store →
6229
+ // …/store): the DESTINATION picks the endpoint, not the target.
6230
+ // An absolute target like '/write' is refused as an escape
6231
+ // attempt (F00) before the app is ever reached.
6232
+ target: options?.proxyPath ?? "",
6080
6233
  headers: [["content-type", "application/json"]],
6081
6234
  body: encodeUtf8(JSON.stringify({ event }))
6082
6235
  },
@@ -6134,7 +6287,7 @@ var ToonClient = class {
6134
6287
  String(error),
6135
6288
  error instanceof Error ? error.stack : ""
6136
6289
  );
6137
- if (error instanceof ToonClientError && (error.code === "NO_TERMINATED_ROUTE" || error.code === "NO_CONNECTOR_EDGE")) {
6290
+ if (error instanceof ToonClientError && (error.code === "NO_TERMINATED_ROUTE" || error.code === "NO_CONNECTOR_EDGE" || error.code === "PEER_NOT_NEGOTIATED")) {
6138
6291
  throw error;
6139
6292
  }
6140
6293
  throw new ToonClientError(
@@ -6391,11 +6544,11 @@ var ToonClient = class {
6391
6544
  return this.buildClaimMessageForProof(explicitClaim);
6392
6545
  }
6393
6546
  if (this.channelManager) {
6394
- const peerId = this.resolvePeerId(destination);
6395
- const negotiation = this.peerNegotiations.get(peerId);
6547
+ const peerId = this.peerIdForClaim(destination);
6548
+ const negotiation = this.peerNegotiations.get(peerId) ?? await this.negotiateFromGreeting(destination, peerId);
6396
6549
  if (!negotiation) {
6397
6550
  throw new ToonClientError(
6398
- `No negotiation metadata for peer "${peerId}" \u2014 was bootstrap completed?`,
6551
+ `No negotiation metadata for peer "${peerId}" \u2014 was bootstrap completed? (and the route's x402 greeting carried no settlement facts to bootstrap from)`,
6399
6552
  "PEER_NOT_NEGOTIATED"
6400
6553
  );
6401
6554
  }
@@ -6468,11 +6621,11 @@ var ToonClient = class {
6468
6621
  "NO_DESTINATION"
6469
6622
  );
6470
6623
  }
6471
- const peerId = this.resolvePeerId(dest);
6472
- const negotiation = this.peerNegotiations.get(peerId);
6624
+ const peerId = this.peerIdForClaim(dest);
6625
+ const negotiation = this.peerNegotiations.get(peerId) ?? await this.negotiateFromGreeting(dest, peerId);
6473
6626
  if (!negotiation) {
6474
6627
  throw new ToonClientError(
6475
- `No negotiation metadata for peer "${peerId}" \u2014 was bootstrap completed?`,
6628
+ `No negotiation metadata for peer "${peerId}" \u2014 was bootstrap completed? (and the route's x402 greeting carried no settlement facts to bootstrap from)`,
6476
6629
  "PEER_NOT_NEGOTIATED"
6477
6630
  );
6478
6631
  }
@@ -6826,6 +6979,69 @@ var ToonClient = class {
6826
6979
  * Convention: destination "g.toon.peer1" → peerId "peer1" (last segment).
6827
6980
  * Falls back to first known peer if no match.
6828
6981
  */
6982
+ /**
6983
+ * The peer id a claim for `destination` accounts under. Normally
6984
+ * `resolvePeerId` — but where that throws `PEER_NOT_FOUND` (an empty
6985
+ * negotiation map: nothing announced, nothing registered), the
6986
+ * destination itself is the key, so the announce-less greeting bootstrap
6987
+ * (connector #617) has a stable identity to remember its synthesized
6988
+ * negotiation under.
6989
+ */
6990
+ peerIdForClaim(destination) {
6991
+ try {
6992
+ return this.resolvePeerId(destination);
6993
+ } catch {
6994
+ return destination;
6995
+ }
6996
+ }
6997
+ /**
6998
+ * The announce-less channel bootstrap (connector #617): when nothing has
6999
+ * negotiated with this destination's peer — no kind:10032 announce, no
7000
+ * connector-admin registration — ask the route itself. A settling
7001
+ * connector's x402 greeting carries the channel-opening facts, and ADR
7002
+ * 0022 makes the greeting the ONLY place the Rust fleet will ever state
7003
+ * them. Synthesizes a {@link PeerNegotiation} from those facts, remembers
7004
+ * it, and returns it; `undefined` when there is no edge to ask, the
7005
+ * greeting carries no settlement facts, or the chain is not one this
7006
+ * client opens channels on (EVM only today — Solana/Mina channel opening
7007
+ * still needs announce-shaped metadata).
7008
+ *
7009
+ * Never throws: this is a fallback on a path that already has a precise
7010
+ * error (`PEER_NOT_NEGOTIATED`), and a transport failure while ASKING
7011
+ * must not mask it.
7012
+ */
7013
+ async negotiateFromGreeting(destination, peerId) {
7014
+ let edge;
7015
+ try {
7016
+ edge = this.resolveClientEdgeEndpoint();
7017
+ } catch {
7018
+ return void 0;
7019
+ }
7020
+ try {
7021
+ const terms = await this.connectorEdge.getRouteTerms(edge, destination);
7022
+ const settlement = terms?.settlement;
7023
+ if (!settlement) return void 0;
7024
+ const [chainType, chainIdText] = settlement.chain.split(":");
7025
+ const chainId = Number(chainIdText);
7026
+ if (chainType !== "evm" || !Number.isFinite(chainId)) return void 0;
7027
+ const negotiation = {
7028
+ chain: settlement.chain,
7029
+ chainType,
7030
+ chainId,
7031
+ settlementAddress: settlement.settlementAddress,
7032
+ tokenAddress: settlement.tokenAddress,
7033
+ tokenNetwork: settlement.tokenNetwork
7034
+ };
7035
+ this.peerNegotiations.set(peerId, negotiation);
7036
+ return negotiation;
7037
+ } catch (error) {
7038
+ console.warn(
7039
+ "[ToonClient] channel bootstrap from the x402 greeting failed:",
7040
+ String(error)
7041
+ );
7042
+ return void 0;
7043
+ }
7044
+ }
6829
7045
  resolvePeerId(destination) {
6830
7046
  const segments = destination.split(".");
6831
7047
  const lastSegment = segments[segments.length - 1] ?? "";
@@ -8920,7 +9136,7 @@ export {
8920
9136
  decodeEnvelopeRequest,
8921
9137
  decodeEnvelopeResponse,
8922
9138
  decodeEvmSettlementTx,
8923
- decodeVarOctetString,
9139
+ decodeVarOctetString2 as decodeVarOctetString,
8924
9140
  decodeVarUint,
8925
9141
  decryptMnemonic2 as decryptMnemonic,
8926
9142
  defaultFaucetTimeout,
@@ -8934,7 +9150,7 @@ export {
8934
9150
  encodeEnvelope,
8935
9151
  encodeEnvelopeRequest,
8936
9152
  encodeEnvelopeResponse,
8937
- encodeVarOctetString,
9153
+ encodeVarOctetString2 as encodeVarOctetString,
8938
9154
  encodeVarUint,
8939
9155
  encryptMnemonic2 as encryptMnemonic,
8940
9156
  ensureOwnedMinaZkApp,