@toon-protocol/client 0.23.0 → 0.25.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
@@ -825,15 +1111,127 @@ var ConnectorEdgeClient = class {
825
1111
  }
826
1112
  }
827
1113
  };
828
-
829
- // src/wire/oer.ts
830
- var OerErrorKind = /* @__PURE__ */ ((OerErrorKind2) => {
831
- OerErrorKind2["BufferUnderflow"] = "buffer_underflow";
832
- OerErrorKind2["NonCanonicalLength"] = "non_canonical_length";
833
- OerErrorKind2["LengthDeterminantOverflow"] = "length_determinant_overflow";
834
- return OerErrorKind2;
835
- })(OerErrorKind || {});
836
- var OerError = class extends Error {
1114
+ function settlementStr(s, key2) {
1115
+ const value = s[key2];
1116
+ if (typeof value !== "string" || value.length === 0) {
1117
+ throw new ConnectorEdgeError(
1118
+ `x402 greeting settlement facts lack '${key2}'`,
1119
+ "TERMS_MALFORMED"
1120
+ );
1121
+ }
1122
+ return value;
1123
+ }
1124
+ function settlementDecimals(s) {
1125
+ const decimals = s["decimals"];
1126
+ if (typeof decimals !== "number") {
1127
+ throw new ConnectorEdgeError(
1128
+ "x402 greeting settlement facts lack 'decimals'",
1129
+ "TERMS_MALFORMED"
1130
+ );
1131
+ }
1132
+ return decimals;
1133
+ }
1134
+ function parseEvmSettlementTerms(s) {
1135
+ return {
1136
+ chain: settlementStr(s, "chain"),
1137
+ settlementAddress: settlementStr(s, "settlementAddress"),
1138
+ tokenNetworkRegistry: settlementStr(s, "tokenNetworkRegistry"),
1139
+ tokenNetwork: settlementStr(s, "tokenNetwork"),
1140
+ tokenAddress: settlementStr(s, "tokenAddress"),
1141
+ decimals: settlementDecimals(s)
1142
+ };
1143
+ }
1144
+ function parseSolanaSettlementTerms(s) {
1145
+ return {
1146
+ chain: settlementStr(s, "chain"),
1147
+ settlementAddress: settlementStr(s, "settlementAddress"),
1148
+ programId: settlementStr(s, "programId"),
1149
+ tokenAddress: settlementStr(s, "tokenAddress"),
1150
+ decimals: settlementDecimals(s)
1151
+ };
1152
+ }
1153
+ function parseChainSettlementEntry(raw) {
1154
+ if (typeof raw !== "object" || raw === null) {
1155
+ throw new ConnectorEdgeError(
1156
+ "x402 greeting settlements entry is not an object",
1157
+ "TERMS_MALFORMED"
1158
+ );
1159
+ }
1160
+ const s = raw;
1161
+ if (typeof s["programId"] === "string") {
1162
+ return { kind: "solana", ...parseSolanaSettlementTerms(s) };
1163
+ }
1164
+ if (typeof s["tokenNetworkRegistry"] === "string") {
1165
+ return { kind: "evm", ...parseEvmSettlementTerms(s) };
1166
+ }
1167
+ throw new ConnectorEdgeError(
1168
+ "x402 greeting settlements entry names neither an EVM ('tokenNetworkRegistry') nor a Solana ('programId') chain",
1169
+ "TERMS_MALFORMED"
1170
+ );
1171
+ }
1172
+ function parseConnectorRouteTerms(body) {
1173
+ if (typeof body !== "object" || body === null) {
1174
+ throw new ConnectorEdgeError(
1175
+ "x402 greeting is not an object",
1176
+ "TERMS_MALFORMED"
1177
+ );
1178
+ }
1179
+ const greeting = body;
1180
+ const accepts = Array.isArray(greeting.accepts) ? greeting.accepts : [];
1181
+ const option = accepts.find(
1182
+ (entry) => typeof entry === "object" && entry !== null && entry.scheme === "toon-channel"
1183
+ );
1184
+ if (!option || typeof option["amount"] !== "string") {
1185
+ throw new ConnectorEdgeError(
1186
+ "x402 greeting carries no toon-channel option",
1187
+ "TERMS_MALFORMED"
1188
+ );
1189
+ }
1190
+ const destination = typeof greeting.resource?.url === "string" ? greeting.resource.url : "";
1191
+ const extra = option["extra"];
1192
+ const rawSettlements = extra?.settlements;
1193
+ let settlements;
1194
+ if (rawSettlements !== void 0) {
1195
+ if (!Array.isArray(rawSettlements)) {
1196
+ throw new ConnectorEdgeError(
1197
+ "x402 greeting settlements is not an array",
1198
+ "TERMS_MALFORMED"
1199
+ );
1200
+ }
1201
+ settlements = rawSettlements.map(parseChainSettlementEntry);
1202
+ }
1203
+ const rawSettlement = extra?.settlement;
1204
+ if (rawSettlement === void 0) {
1205
+ return {
1206
+ destination,
1207
+ price: option["amount"],
1208
+ ...settlements ? { settlements } : {}
1209
+ };
1210
+ }
1211
+ if (typeof rawSettlement !== "object" || rawSettlement === null) {
1212
+ throw new ConnectorEdgeError(
1213
+ "x402 greeting settlement facts are malformed",
1214
+ "TERMS_MALFORMED"
1215
+ );
1216
+ }
1217
+ return {
1218
+ destination,
1219
+ price: option["amount"],
1220
+ settlement: parseEvmSettlementTerms(
1221
+ rawSettlement
1222
+ ),
1223
+ ...settlements ? { settlements } : {}
1224
+ };
1225
+ }
1226
+
1227
+ // src/wire/oer.ts
1228
+ var OerErrorKind = /* @__PURE__ */ ((OerErrorKind2) => {
1229
+ OerErrorKind2["BufferUnderflow"] = "buffer_underflow";
1230
+ OerErrorKind2["NonCanonicalLength"] = "non_canonical_length";
1231
+ OerErrorKind2["LengthDeterminantOverflow"] = "length_determinant_overflow";
1232
+ return OerErrorKind2;
1233
+ })(OerErrorKind || {});
1234
+ var OerError = class extends Error {
837
1235
  constructor(kind) {
838
1236
  super(OER_ERROR_MESSAGES[kind]);
839
1237
  this.kind = kind;
@@ -884,14 +1282,14 @@ function decodeVarUint(buf, offset) {
884
1282
  }
885
1283
  return { value, consumed };
886
1284
  }
887
- function encodeVarOctetString(data) {
1285
+ function encodeVarOctetString2(data) {
888
1286
  const prefix = encodeVarUint(BigInt(data.length));
889
1287
  const out = new Uint8Array(prefix.length + data.length);
890
1288
  out.set(prefix, 0);
891
1289
  out.set(data, prefix.length);
892
1290
  return out;
893
1291
  }
894
- function decodeVarOctetString(buf, offset) {
1292
+ function decodeVarOctetString2(buf, offset) {
895
1293
  const { value: length, consumed: lengthBytes } = decodeVarUint(buf, offset);
896
1294
  if (length > BigInt(buf.length)) {
897
1295
  throw new OerError("buffer_underflow" /* BufferUnderflow */);
@@ -954,7 +1352,7 @@ function fromOerError(error) {
954
1352
  }
955
1353
  function decodeOctets(buf, offset) {
956
1354
  try {
957
- return decodeVarOctetString(buf, offset);
1355
+ return decodeVarOctetString2(buf, offset);
958
1356
  } catch (error) {
959
1357
  throw fromOerError(error);
960
1358
  }
@@ -984,7 +1382,7 @@ function checkTypeByte(buf, expected) {
984
1382
  }
985
1383
  return 1;
986
1384
  }
987
- function concat(parts) {
1385
+ function concat2(parts) {
988
1386
  const total = parts.reduce((sum, part) => sum + part.length, 0);
989
1387
  const out = new Uint8Array(total);
990
1388
  let offset = 0;
@@ -997,10 +1395,10 @@ function concat(parts) {
997
1395
  function encodeHeaders(headers) {
998
1396
  const parts = [encodeVarUint(BigInt(headers.length))];
999
1397
  for (const [name, value] of headers) {
1000
- parts.push(encodeVarOctetString(UTF8_ENCODER.encode(name)));
1001
- parts.push(encodeVarOctetString(UTF8_ENCODER.encode(value)));
1398
+ parts.push(encodeVarOctetString2(UTF8_ENCODER.encode(name)));
1399
+ parts.push(encodeVarOctetString2(UTF8_ENCODER.encode(value)));
1002
1400
  }
1003
- return concat(parts);
1401
+ return concat2(parts);
1004
1402
  }
1005
1403
  function decodeHeaders(buf, offset) {
1006
1404
  const { value: count, consumed: countBytes } = decodeCount(buf, offset);
@@ -1019,12 +1417,12 @@ function decodeHeaders(buf, offset) {
1019
1417
  return { value: headers, consumed };
1020
1418
  }
1021
1419
  function encodeEnvelopeRequest(request) {
1022
- return concat([
1420
+ return concat2([
1023
1421
  Uint8Array.of(TYPE_ENVELOPE_REQUEST),
1024
- encodeVarOctetString(UTF8_ENCODER.encode(request.method)),
1025
- encodeVarOctetString(UTF8_ENCODER.encode(request.target)),
1422
+ encodeVarOctetString2(UTF8_ENCODER.encode(request.method)),
1423
+ encodeVarOctetString2(UTF8_ENCODER.encode(request.target)),
1026
1424
  encodeHeaders(request.headers),
1027
- encodeVarOctetString(request.body)
1425
+ encodeVarOctetString2(request.body)
1028
1426
  ]);
1029
1427
  }
1030
1428
  function decodeEnvelopeRequest(buf) {
@@ -1053,14 +1451,14 @@ function encodeEnvelopeResponse(response) {
1053
1451
  `envelope status must fit two bytes, got ${response.status}`
1054
1452
  );
1055
1453
  }
1056
- return concat([
1454
+ return concat2([
1057
1455
  Uint8Array.of(
1058
1456
  TYPE_ENVELOPE_RESPONSE,
1059
1457
  response.status >> 8 & 255,
1060
1458
  response.status & 255
1061
1459
  ),
1062
1460
  encodeHeaders(response.headers),
1063
- encodeVarOctetString(response.body)
1461
+ encodeVarOctetString2(response.body)
1064
1462
  ]);
1065
1463
  }
1066
1464
  function decodeEnvelopeResponse(buf) {
@@ -1128,7 +1526,7 @@ var GiftWrapError = class extends Error {
1128
1526
  kind;
1129
1527
  expectedType;
1130
1528
  };
1131
- function concat2(parts) {
1529
+ function concat3(parts) {
1132
1530
  const total = parts.reduce((sum, part) => sum + part.length, 0);
1133
1531
  const out = new Uint8Array(total);
1134
1532
  let offset = 0;
@@ -1142,7 +1540,7 @@ function hkdfKey(ikm, info) {
1142
1540
  return hkdf(sha256, ikm, void 0, info, 32);
1143
1541
  }
1144
1542
  function encryptWithNonce(key2, plaintext, nonce) {
1145
- return concat2([nonce, chacha20poly1305(key2, nonce).encrypt(plaintext)]);
1543
+ return concat3([nonce, chacha20poly1305(key2, nonce).encrypt(plaintext)]);
1146
1544
  }
1147
1545
  function decrypt(key2, nonceAndCiphertext) {
1148
1546
  if (nonceAndCiphertext.length < GIFTWRAP_NONCE_LENGTH) {
@@ -1190,8 +1588,8 @@ function sealRequestWithRandomness(plaintext, receiverPublicKey, ephemeralSecret
1190
1588
  ecdhXCoordinate(ephemeralSecretKey, receiverPublicKey),
1191
1589
  REQUEST_INFO
1192
1590
  );
1193
- const inner = concat2([sharedSecret, plaintext]);
1194
- return concat2([
1591
+ const inner = concat3([sharedSecret, plaintext]);
1592
+ return concat3([
1195
1593
  Uint8Array.of(GIFTWRAP_TYPE_REQUEST),
1196
1594
  ephemeralPublicKey,
1197
1595
  encryptWithNonce(aeadKey, inner, nonce)
@@ -1250,7 +1648,7 @@ function sealResponseWithRandomness(sharedSecret, plaintext, nonce) {
1250
1648
  if (nonce.length !== GIFTWRAP_NONCE_LENGTH) {
1251
1649
  throw new GiftWrapError("truncated" /* Truncated */);
1252
1650
  }
1253
- return concat2([
1651
+ return concat3([
1254
1652
  Uint8Array.of(GIFTWRAP_TYPE_RESPONSE),
1255
1653
  encryptWithNonce(hkdfKey(sharedSecret, RESPONSE_INFO), plaintext, nonce)
1256
1654
  ]);
@@ -1452,346 +1850,121 @@ var HttpRuntimeClient = class {
1452
1850
  if (!params.destination || params.destination.trim() === "") {
1453
1851
  throw new ValidationError("Destination cannot be empty");
1454
1852
  }
1455
- if (!params.destination.startsWith("g.")) {
1456
- throw new ValidationError(
1457
- `Invalid ILP address format: "${params.destination}" (must start with "g.")`
1458
- );
1459
- }
1460
- if (!params.amount || params.amount.trim() === "") {
1461
- throw new ValidationError("Amount cannot be empty");
1462
- }
1463
- try {
1464
- const amountBigInt = BigInt(params.amount);
1465
- if (amountBigInt <= 0n) {
1466
- throw new ValidationError(
1467
- `Amount must be positive: "${params.amount}"`
1468
- );
1469
- }
1470
- } catch (error) {
1471
- if (error instanceof ValidationError) throw error;
1472
- throw new ValidationError(
1473
- `Amount must be a valid integer: "${params.amount}"`,
1474
- error instanceof Error ? error : void 0
1475
- );
1476
- }
1477
- if (!params.data || params.data.trim() === "") {
1478
- throw new ValidationError("Data cannot be empty");
1479
- }
1480
- try {
1481
- if (!isBase64(params.data)) {
1482
- throw new ValidationError(
1483
- `Data must be valid Base64 encoding: "${params.data}"`
1484
- );
1485
- }
1486
- } catch (error) {
1487
- if (error instanceof ValidationError) throw error;
1488
- throw new ValidationError(
1489
- `Data must be valid Base64 encoding: "${params.data}"`,
1490
- error instanceof Error ? error : void 0
1491
- );
1492
- }
1493
- }
1494
- /**
1495
- * Send HTTP POST request to connector runtime API.
1496
- *
1497
- * @throws {NetworkError} On connection failures (ECONNREFUSED, ETIMEDOUT)
1498
- * @throws {ConnectorError} On 5xx server errors
1499
- * @returns IlpSendResult with acceptance status
1500
- */
1501
- async sendHttpRequest(params) {
1502
- const requestTimeout = params.timeout ?? this.timeout;
1503
- const controller = new AbortController();
1504
- const timeoutId = setTimeout(() => controller.abort(), requestTimeout);
1505
- try {
1506
- const response = await this.httpClient(
1507
- `${this.connectorUrl}/admin/ilp/send`,
1508
- {
1509
- method: "POST",
1510
- headers: {
1511
- "Content-Type": "application/json"
1512
- },
1513
- body: JSON.stringify({
1514
- destination: params.destination,
1515
- amount: params.amount,
1516
- data: params.data
1517
- }),
1518
- signal: controller.signal
1519
- }
1520
- );
1521
- clearTimeout(timeoutId);
1522
- if (response.ok) {
1523
- const result = await response.json();
1524
- return {
1525
- accepted: result["accepted"] ?? false,
1526
- data: result["data"],
1527
- code: result["code"],
1528
- message: result["message"]
1529
- };
1530
- } else if (response.status >= 400 && response.status < 500) {
1531
- const errorBody = await response.json().catch(() => ({}));
1532
- return {
1533
- accepted: false,
1534
- code: `HTTP_${response.status}`,
1535
- message: errorBody["message"] ?? errorBody["error"] ?? response.statusText
1536
- };
1537
- } else if (response.status >= 500 && response.status < 600) {
1538
- const errorBody = await response.json().catch(() => ({}));
1539
- throw new ConnectorError(
1540
- `Connector server error (${response.status}): ${errorBody["message"] ?? errorBody["error"] ?? response.statusText}`
1541
- );
1542
- }
1543
- throw new ConnectorError(
1544
- `Unexpected HTTP status: ${response.status} ${response.statusText}`
1545
- );
1546
- } catch (error) {
1547
- clearTimeout(timeoutId);
1548
- if (error instanceof Error && error.name === "AbortError") {
1549
- throw new NetworkError(
1550
- `Request timeout after ${requestTimeout}ms`,
1551
- error
1552
- );
1553
- }
1554
- if (error instanceof TypeError && (error.message.includes("fetch failed") || error.message.includes("ECONNREFUSED") || error.message.includes("ETIMEDOUT") || error.message.includes("network"))) {
1555
- throw new NetworkError(
1556
- `Network connection failed: ${error.message}`,
1557
- error
1558
- );
1559
- }
1560
- if (error instanceof NetworkError || error instanceof ConnectorError || error instanceof ValidationError) {
1561
- throw error;
1562
- }
1563
- throw new ConnectorError(
1564
- `Unexpected error during HTTP request: ${error instanceof Error ? error.message : String(error)}`,
1565
- error instanceof Error ? error : void 0
1566
- );
1567
- }
1568
- }
1569
- };
1570
-
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 });
1853
+ if (!params.destination.startsWith("g.")) {
1854
+ throw new ValidationError(
1855
+ `Invalid ILP address format: "${params.destination}" (must start with "g.")`
1856
+ );
1857
+ }
1858
+ if (!params.amount || params.amount.trim() === "") {
1859
+ throw new ValidationError("Amount cannot be empty");
1860
+ }
1861
+ try {
1862
+ const amountBigInt = BigInt(params.amount);
1863
+ if (amountBigInt <= 0n) {
1864
+ throw new ValidationError(
1865
+ `Amount must be positive: "${params.amount}"`
1866
+ );
1867
+ }
1868
+ } catch (error) {
1869
+ if (error instanceof ValidationError) throw error;
1870
+ throw new ValidationError(
1871
+ `Amount must be a valid integer: "${params.amount}"`,
1872
+ error instanceof Error ? error : void 0
1873
+ );
1874
+ }
1875
+ if (!params.data || params.data.trim() === "") {
1876
+ throw new ValidationError("Data cannot be empty");
1877
+ }
1878
+ try {
1879
+ if (!isBase64(params.data)) {
1880
+ throw new ValidationError(
1881
+ `Data must be valid Base64 encoding: "${params.data}"`
1882
+ );
1883
+ }
1884
+ } catch (error) {
1885
+ if (error instanceof ValidationError) throw error;
1886
+ throw new ValidationError(
1887
+ `Data must be valid Base64 encoding: "${params.data}"`,
1888
+ error instanceof Error ? error : void 0
1889
+ );
1890
+ }
1784
1891
  }
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);
1892
+ /**
1893
+ * Send HTTP POST request to connector runtime API.
1894
+ *
1895
+ * @throws {NetworkError} On connection failures (ECONNREFUSED, ETIMEDOUT)
1896
+ * @throws {ConnectorError} On 5xx server errors
1897
+ * @returns IlpSendResult with acceptance status
1898
+ */
1899
+ async sendHttpRequest(params) {
1900
+ const requestTimeout = params.timeout ?? this.timeout;
1901
+ const controller = new AbortController();
1902
+ const timeoutId = setTimeout(() => controller.abort(), requestTimeout);
1903
+ try {
1904
+ const response = await this.httpClient(
1905
+ `${this.connectorUrl}/admin/ilp/send`,
1906
+ {
1907
+ method: "POST",
1908
+ headers: {
1909
+ "Content-Type": "application/json"
1910
+ },
1911
+ body: JSON.stringify({
1912
+ destination: params.destination,
1913
+ amount: params.amount,
1914
+ data: params.data
1915
+ }),
1916
+ signal: controller.signal
1917
+ }
1918
+ );
1919
+ clearTimeout(timeoutId);
1920
+ if (response.ok) {
1921
+ const result = await response.json();
1922
+ return {
1923
+ accepted: result["accepted"] ?? false,
1924
+ data: result["data"],
1925
+ code: result["code"],
1926
+ message: result["message"]
1927
+ };
1928
+ } else if (response.status >= 400 && response.status < 500) {
1929
+ const errorBody = await response.json().catch(() => ({}));
1930
+ return {
1931
+ accepted: false,
1932
+ code: `HTTP_${response.status}`,
1933
+ message: errorBody["message"] ?? errorBody["error"] ?? response.statusText
1934
+ };
1935
+ } else if (response.status >= 500 && response.status < 600) {
1936
+ const errorBody = await response.json().catch(() => ({}));
1937
+ throw new ConnectorError(
1938
+ `Connector server error (${response.status}): ${errorBody["message"] ?? errorBody["error"] ?? response.statusText}`
1939
+ );
1940
+ }
1941
+ throw new ConnectorError(
1942
+ `Unexpected HTTP status: ${response.status} ${response.statusText}`
1943
+ );
1944
+ } catch (error) {
1945
+ clearTimeout(timeoutId);
1946
+ if (error instanceof Error && error.name === "AbortError") {
1947
+ throw new NetworkError(
1948
+ `Request timeout after ${requestTimeout}ms`,
1949
+ error
1950
+ );
1951
+ }
1952
+ if (error instanceof TypeError && (error.message.includes("fetch failed") || error.message.includes("ECONNREFUSED") || error.message.includes("ETIMEDOUT") || error.message.includes("network"))) {
1953
+ throw new NetworkError(
1954
+ `Network connection failed: ${error.message}`,
1955
+ error
1956
+ );
1957
+ }
1958
+ if (error instanceof NetworkError || error instanceof ConnectorError || error instanceof ValidationError) {
1959
+ throw error;
1960
+ }
1961
+ throw new ConnectorError(
1962
+ `Unexpected error during HTTP request: ${error instanceof Error ? error.message : String(error)}`,
1963
+ error instanceof Error ? error : void 0
1964
+ );
1791
1965
  }
1792
1966
  }
1793
- return { type, requestId, data: { protocolData, ilpPacket } };
1794
- }
1967
+ };
1795
1968
 
1796
1969
  // src/btp/IsomorphicBtpClient.ts
1797
1970
  var textEncoder2 = new TextEncoder();
@@ -2690,7 +2863,10 @@ function deriveAssociatedTokenAccount(owner, tokenMint) {
2690
2863
  padTo32(base58Decode(TOKEN_PROGRAM_ID2)),
2691
2864
  padTo32(base58Decode(tokenMint))
2692
2865
  ];
2693
- const { pda } = findProgramAddress(seeds, padTo32(base58Decode(ASSOCIATED_TOKEN_PROGRAM_ID)));
2866
+ const { pda } = findProgramAddress(
2867
+ seeds,
2868
+ padTo32(base58Decode(ASSOCIATED_TOKEN_PROGRAM_ID))
2869
+ );
2694
2870
  return base58Encode(pda);
2695
2871
  }
2696
2872
  function deriveVaultPDA(channelPDA, programId) {
@@ -2708,6 +2884,24 @@ function buildBalanceProofMessage(channelPDA, nonce, transferredAmount) {
2708
2884
  return message;
2709
2885
  }
2710
2886
  var rpcIdCounter = 1;
2887
+ var SolanaRpcError = class extends Error {
2888
+ constructor(method, code, rpcMessage) {
2889
+ super(`Solana RPC error [${method}]: ${rpcMessage} (code ${code})`);
2890
+ this.method = method;
2891
+ this.code = code;
2892
+ this.rpcMessage = rpcMessage;
2893
+ this.name = "SolanaRpcError";
2894
+ }
2895
+ method;
2896
+ code;
2897
+ rpcMessage;
2898
+ };
2899
+ function isAccountNotFoundError(err) {
2900
+ if (!(err instanceof SolanaRpcError)) return false;
2901
+ return /could not find account|account not found|account does not exist/i.test(
2902
+ err.rpcMessage
2903
+ );
2904
+ }
2711
2905
  async function solanaRpc(rpcUrl, method, params = []) {
2712
2906
  const res = await fetch(rpcUrl, {
2713
2907
  method: "POST",
@@ -2722,9 +2916,7 @@ async function solanaRpc(rpcUrl, method, params = []) {
2722
2916
  });
2723
2917
  const json = await res.json();
2724
2918
  if (json.error) {
2725
- throw new Error(
2726
- `Solana RPC error [${method}]: ${json.error.message} (code ${json.error.code})`
2727
- );
2919
+ throw new SolanaRpcError(method, json.error.code, json.error.message);
2728
2920
  }
2729
2921
  return json.result;
2730
2922
  }
@@ -2741,6 +2933,50 @@ async function getAccountInfo(rpcUrl, pubkey) {
2741
2933
  ]);
2742
2934
  return result.value;
2743
2935
  }
2936
+ async function getTokenAccountBalance(rpcUrl, tokenAccount) {
2937
+ try {
2938
+ const result = await solanaRpc(rpcUrl, "getTokenAccountBalance", [
2939
+ tokenAccount,
2940
+ { commitment: "confirmed" }
2941
+ ]);
2942
+ const amount = result?.value?.amount;
2943
+ return amount === void 0 ? null : BigInt(amount);
2944
+ } catch (err) {
2945
+ if (isAccountNotFoundError(err)) return null;
2946
+ throw err;
2947
+ }
2948
+ }
2949
+ async function getLamports(rpcUrl, pubkey) {
2950
+ const result = await solanaRpc(rpcUrl, "getBalance", [
2951
+ pubkey,
2952
+ { commitment: "confirmed" }
2953
+ ]);
2954
+ return BigInt(result?.value ?? 0);
2955
+ }
2956
+ var LAMPORTS_PER_SIGNATURE = 5000n;
2957
+ var MIN_LAMPORTS_FOR_CHANNEL_OPEN = 4179040n;
2958
+ var MIN_LAMPORTS_FOR_DEPOSIT = LAMPORTS_PER_SIGNATURE;
2959
+ async function assertOpenFunding(opts) {
2960
+ const { rpcUrl, payerPubkey, tokenMint, minLamports, deposit } = opts;
2961
+ const lamports = await getLamports(rpcUrl, payerPubkey);
2962
+ if (lamports < minLamports) {
2963
+ throw new ChannelFundingError(
2964
+ `Solana settlement wallet ${payerPubkey} holds ${lamports} lamports, below the ${minLamports} needed here (rent for the channel + vault accounts, plus signature fees). Native SOL is separate from the settlement token: holding the SPL token is not enough. Airdrop/fund SOL to that address and retry.`
2965
+ );
2966
+ }
2967
+ if (!deposit || deposit.amount <= 0n) return;
2968
+ const held = await getTokenAccountBalance(rpcUrl, deposit.payerTokenAccount);
2969
+ if (held === null) {
2970
+ throw new ChannelFundingError(
2971
+ `Solana token account ${deposit.payerTokenAccount} does not exist, so the ${deposit.amount} base-unit channel deposit of mint ${tokenMint} cannot be funded. Fund the settlement wallet with that token (which creates the associated token account) and retry.`
2972
+ );
2973
+ }
2974
+ if (held < deposit.amount) {
2975
+ throw new ChannelFundingError(
2976
+ `Solana token account ${deposit.payerTokenAccount} holds ${held} base units of mint ${tokenMint}, short of the ${deposit.amount} base-unit channel deposit. Fund the settlement wallet, or lower the deposit (\`solanaChannel.deposit.amount\` / \`initialDeposit\`), and retry.`
2977
+ );
2978
+ }
2979
+ }
2744
2980
  async function waitForConfirmation(rpcUrl, signature, timeoutMs = 3e4) {
2745
2981
  const start = Date.now();
2746
2982
  while (Date.now() - start < timeoutMs) {
@@ -2893,6 +3129,13 @@ async function buildAndSendTransaction(rpcUrl, feePayer, instructions, additiona
2893
3129
  return txSig;
2894
3130
  }
2895
3131
  var STATE_MAP = ["opened", "closed", "settled"];
3132
+ function readU64LE(data, offset) {
3133
+ let value = 0n;
3134
+ for (let i = 7; i >= 0; i--) {
3135
+ value = value << 8n | BigInt(data[offset + i] ?? 0);
3136
+ }
3137
+ return value;
3138
+ }
2896
3139
  async function getChannelAccountState(rpcUrl, channelPDA) {
2897
3140
  const info = await getAccountInfo(rpcUrl, channelPDA);
2898
3141
  if (!info) return { exists: false };
@@ -2905,9 +3148,53 @@ async function getChannelAccountState(rpcUrl, channelPDA) {
2905
3148
  exists: true,
2906
3149
  state: STATE_MAP[data[160] ?? 0] ?? "opened",
2907
3150
  participantA: base58Encode(data.slice(8, 40)),
2908
- participantB: base58Encode(data.slice(40, 72))
3151
+ participantB: base58Encode(data.slice(40, 72)),
3152
+ depositA: readU64LE(data, 104),
3153
+ depositB: readU64LE(data, 112)
2909
3154
  };
2910
3155
  }
3156
+ function ownDeposit(account, payerPubkey) {
3157
+ if (account.participantA === payerPubkey) return account.depositA ?? 0n;
3158
+ if (account.participantB === payerPubkey) return account.depositB ?? 0n;
3159
+ throw new Error(
3160
+ `Solana channel participants (${account.participantA}, ${account.participantB}) do not include the payer ${payerPubkey} \u2014 refusing to reason about its collateral.`
3161
+ );
3162
+ }
3163
+ async function topUpExistingChannel(opts) {
3164
+ const {
3165
+ rpcUrl,
3166
+ programId,
3167
+ tokenMint,
3168
+ channelPDA,
3169
+ payerPubkey,
3170
+ existing,
3171
+ deposit
3172
+ } = opts;
3173
+ if (!deposit || deposit.amount <= 0n) return {};
3174
+ const own = ownDeposit(existing, payerPubkey);
3175
+ if (own >= deposit.amount) return { depositTotal: own };
3176
+ const shortfall = deposit.amount - own;
3177
+ await assertOpenFunding({
3178
+ rpcUrl,
3179
+ payerPubkey,
3180
+ tokenMint,
3181
+ minLamports: MIN_LAMPORTS_FOR_DEPOSIT,
3182
+ deposit: {
3183
+ amount: shortfall,
3184
+ payerTokenAccount: deposit.payerTokenAccount
3185
+ }
3186
+ });
3187
+ const { depositTxSignature } = await depositSolanaChannel({
3188
+ rpcUrl,
3189
+ programId,
3190
+ channelPDA,
3191
+ payerSeed: opts.payerSeed,
3192
+ payerPubkey,
3193
+ payerTokenAccount: deposit.payerTokenAccount,
3194
+ amount: shortfall
3195
+ });
3196
+ return { depositTxSignature, depositTotal: own + shortfall };
3197
+ }
2911
3198
  async function openSolanaChannel(params) {
2912
3199
  const {
2913
3200
  rpcUrl,
@@ -2926,8 +3213,28 @@ async function openSolanaChannel(params) {
2926
3213
  );
2927
3214
  const existing = await getChannelAccountState(rpcUrl, channelPDA);
2928
3215
  if (existing.exists) {
2929
- return { channelPDA, opened: false };
3216
+ if (existing.state !== "opened") {
3217
+ return { channelPDA, opened: false };
3218
+ }
3219
+ const topUp = await topUpExistingChannel({
3220
+ rpcUrl,
3221
+ programId,
3222
+ tokenMint,
3223
+ channelPDA,
3224
+ payerSeed,
3225
+ payerPubkey,
3226
+ existing,
3227
+ deposit: params.deposit
3228
+ });
3229
+ return { channelPDA, opened: false, ...topUp };
2930
3230
  }
3231
+ await assertOpenFunding({
3232
+ rpcUrl,
3233
+ payerPubkey,
3234
+ tokenMint,
3235
+ minLamports: MIN_LAMPORTS_FOR_CHANNEL_OPEN,
3236
+ deposit: params.deposit
3237
+ });
2931
3238
  const payerPublicKey = padTo32(base58Decode(payerPubkey));
2932
3239
  const payer = { publicKey: payerPublicKey, privateKey: payerSeed };
2933
3240
  const { pda: vaultPDA } = deriveVaultPDA(channelPDA, programId);
@@ -2965,10 +3272,24 @@ async function openSolanaChannel(params) {
2965
3272
  amount: params.deposit.amount
2966
3273
  }));
2967
3274
  }
2968
- return { channelPDA, opened: true, initTxSignature, depositTxSignature };
3275
+ return {
3276
+ channelPDA,
3277
+ opened: true,
3278
+ initTxSignature,
3279
+ depositTxSignature,
3280
+ ...depositTxSignature ? { depositTotal: params.deposit?.amount } : {}
3281
+ };
2969
3282
  }
2970
3283
  async function depositSolanaChannel(params) {
2971
- const { rpcUrl, programId, channelPDA, payerSeed, payerPubkey, payerTokenAccount, amount } = params;
3284
+ const {
3285
+ rpcUrl,
3286
+ programId,
3287
+ channelPDA,
3288
+ payerSeed,
3289
+ payerPubkey,
3290
+ payerTokenAccount,
3291
+ amount
3292
+ } = params;
2972
3293
  if (amount <= 0n) throw new Error("Solana deposit amount must be positive.");
2973
3294
  const payer = {
2974
3295
  publicKey: padTo32(base58Decode(payerPubkey)),
@@ -3215,7 +3536,10 @@ var OnChainChannelClient = class {
3215
3536
  }
3216
3537
  const chainPrefix = ctx.chain.split(":")[0];
3217
3538
  if (chainPrefix === "solana") {
3218
- return this.depositSolana(channelId, amount, opts.currentDeposit);
3539
+ return this.depositSolana(channelId, amount, opts.currentDeposit, {
3540
+ programId: ctx.tokenNetworkAddress,
3541
+ ...ctx.tokenAddress ? { tokenMint: ctx.tokenAddress } : {}
3542
+ });
3219
3543
  }
3220
3544
  if (chainPrefix === "mina") {
3221
3545
  throw new Error(
@@ -3229,8 +3553,14 @@ var OnChainChannelClient = class {
3229
3553
  * vault. Incremental on-chain (the program adds `amount`), so the new total is
3230
3554
  * the caller-tracked current plus the delta. Requires the funded payer token
3231
3555
  * account (the funded ATA) from the Solana channel config.
3556
+ *
3557
+ * `channel` carries the program and mint the channel was actually OPENED
3558
+ * with (the greeting's, when it named them — see
3559
+ * {@link OnChainChannelClient.openSolanaChannel}), NOT
3560
+ * `solanaConfig.programId`/`tokenMint`. Both PDAs this deposit addresses are
3561
+ * derived from those: the vault from the program, the payer ATA from the mint.
3232
3562
  */
3233
- async depositSolana(channelId, amount, currentDeposit) {
3563
+ async depositSolana(channelId, amount, currentDeposit, channel) {
3234
3564
  if (!this.solanaConfig) {
3235
3565
  throw new Error("Solana channel config not set \u2014 cannot deposit.");
3236
3566
  }
@@ -3239,21 +3569,19 @@ var OnChainChannelClient = class {
3239
3569
  const payerPubkey = base58Encode2(
3240
3570
  new Uint8Array(ed255192.getPublicKey(payerSeed))
3241
3571
  );
3572
+ const tokenMint = channel.tokenMint ?? cfg.tokenMint;
3242
3573
  let payerTokenAccount = cfg.deposit?.payerTokenAccount;
3243
3574
  if (!payerTokenAccount) {
3244
- if (!cfg.tokenMint) {
3575
+ if (!tokenMint) {
3245
3576
  throw new Error(
3246
- "Solana deposit requires solanaConfig.deposit.payerTokenAccount or solanaConfig.tokenMint to derive the payer ATA."
3577
+ "Solana deposit requires solanaConfig.deposit.payerTokenAccount or a known channel mint to derive the payer ATA."
3247
3578
  );
3248
3579
  }
3249
- payerTokenAccount = deriveAssociatedTokenAccount(
3250
- payerPubkey,
3251
- cfg.tokenMint
3252
- );
3580
+ payerTokenAccount = deriveAssociatedTokenAccount(payerPubkey, tokenMint);
3253
3581
  }
3254
3582
  const { depositTxSignature } = await depositSolanaChannel({
3255
3583
  rpcUrl: cfg.rpcUrl,
3256
- programId: cfg.programId,
3584
+ programId: channel.programId,
3257
3585
  channelPDA: channelId,
3258
3586
  payerSeed,
3259
3587
  payerPubkey,
@@ -3437,12 +3765,19 @@ var OnChainChannelClient = class {
3437
3765
  *
3438
3766
  * Derives the connector-parity channel PDA
3439
3767
  * (`[b"channel", min_pubkey, max_pubkey, token_mint]`), submits the
3440
- * `initialize_channel` instruction (+ optional `deposit`) to the deployed
3441
- * payment-channel program, and returns the base58 PDA as the channel id. That
3768
+ * `initialize_channel` instruction plus the `deposit` that collateralizes the
3769
+ * channel, and returns the base58 PDA as the channel id. That
3442
3770
  * PDA is what the claim carries as `channelAccount`, and the on-chain channel
3443
3771
  * is what the connector's `verifySolanaClaim` reads via
3444
3772
  * `provider.getChannelState` before accepting the claim.
3445
3773
  *
3774
+ * Both PDA seeds are NEGOTIATED, not configured: the mint is
3775
+ * `OpenChannelParams.token` and the program is `OpenChannelParams.tokenNetwork`
3776
+ * — the greeting's `tokenAddress`/`programId` as threaded through by
3777
+ * `ChannelManager.ensureChannel` — each falling back to the `solanaConfig`
3778
+ * default only when the negotiation named none. That is what keeps the channel
3779
+ * this opens and the channel the signed claim asserts the same object (#473).
3780
+ *
3446
3781
  * Mirrors `openEvmChannel`'s open(+deposit) structure. Idempotent: if the
3447
3782
  * channel account already exists on-chain, returns its PDA without
3448
3783
  * re-initializing.
@@ -3464,6 +3799,7 @@ var OnChainChannelClient = class {
3464
3799
  "Solana channel requires a token mint (OpenChannelParams.token or solanaConfig.tokenMint)"
3465
3800
  );
3466
3801
  }
3802
+ const programId = params.tokenNetwork ?? cfg.programId;
3467
3803
  if (!params.peerAddress) {
3468
3804
  throw new Error(
3469
3805
  "Solana channel requires peerAddress (apex settlement pubkey, base58)"
@@ -3472,15 +3808,18 @@ var OnChainChannelClient = class {
3472
3808
  const challengeDuration = BigInt(
3473
3809
  cfg.challengeDuration ?? params.settlementTimeout ?? 86400
3474
3810
  );
3475
- const deposit = cfg.deposit ? {
3476
- amount: BigInt(cfg.deposit.amount),
3811
+ const depositAmount = BigInt(
3812
+ cfg.deposit?.amount ?? params.initialDeposit ?? "0"
3813
+ );
3814
+ const deposit = depositAmount > 0n ? {
3815
+ amount: depositAmount,
3477
3816
  // Derive the payer ATA (owner + channel mint) when not supplied — it is
3478
3817
  // deterministic, so the caller need not thread payerTokenAccount through.
3479
- payerTokenAccount: cfg.deposit.payerTokenAccount || deriveAssociatedTokenAccount(payerPubkey, tokenMint)
3818
+ payerTokenAccount: cfg.deposit?.payerTokenAccount || deriveAssociatedTokenAccount(payerPubkey, tokenMint)
3480
3819
  } : void 0;
3481
- const { channelPDA } = await openSolanaChannel({
3820
+ const { channelPDA, depositTotal } = await openSolanaChannel({
3482
3821
  rpcUrl: cfg.rpcUrl,
3483
- programId: cfg.programId,
3822
+ programId,
3484
3823
  tokenMint,
3485
3824
  payerSeed,
3486
3825
  payerPubkey,
@@ -3490,9 +3829,18 @@ var OnChainChannelClient = class {
3490
3829
  });
3491
3830
  this.channelContext.set(channelPDA, {
3492
3831
  chain: params.chain,
3493
- tokenNetworkAddress: cfg.programId
3832
+ tokenNetworkAddress: programId,
3833
+ tokenAddress: tokenMint
3494
3834
  });
3495
- return { channelId: channelPDA, status: "opening" };
3835
+ return {
3836
+ channelId: channelPDA,
3837
+ status: "opening",
3838
+ // Report the collateral now in the vault, when this call established it
3839
+ // (locked here on a fresh open, read from chain on a top-up). Reporting
3840
+ // only — no spend decision reads it; it exists so callers can show and
3841
+ // log real collateral instead of 0.
3842
+ ...depositTotal !== void 0 ? { depositTotal } : {}
3843
+ };
3496
3844
  }
3497
3845
  /**
3498
3846
  * Opens a REAL on-chain Mina payment channel on the deployed `PaymentChannel`
@@ -4663,7 +5011,8 @@ var ChannelManager = class {
4663
5011
  const t = this.channels.get(channelId);
4664
5012
  if (!t || t.closedAt === void 0) return "open";
4665
5013
  if (t.settledAt !== void 0) return "settled";
4666
- if (t.settleableAt !== void 0 && nowSec >= t.settleableAt) return "settleable";
5014
+ if (t.settleableAt !== void 0 && nowSec >= t.settleableAt)
5015
+ return "settleable";
4667
5016
  return "closing";
4668
5017
  }
4669
5018
  /**
@@ -5797,6 +6146,14 @@ var ToonClient = class {
5797
6146
  /** Concrete on-chain client, kept so deposit/withdraw can reach chain methods. */
5798
6147
  onChainChannelClient;
5799
6148
  peerNegotiations = /* @__PURE__ */ new Map();
6149
+ /**
6150
+ * Peers whose x402 greeting advertised a Solana settlement leg that this
6151
+ * client could not weigh, because `config.solanaChannel` is unset and
6152
+ * {@link getBalances} therefore reports no Solana balance at all (issue
6153
+ * #474). The EVM leg was taken by default for these; if opening it then
6154
+ * fails for lack of funds, {@link withSolanaLegHint} says so.
6155
+ */
6156
+ unreadableSolanaLegs = /* @__PURE__ */ new Set();
5800
6157
  /**
5801
6158
  * Asks terminating connectors for their identity key, caching one per
5802
6159
  * client edge. A packet cannot be formed without the key of the connector
@@ -5933,7 +6290,10 @@ var ToonClient = class {
5933
6290
  try {
5934
6291
  if (this.evmSigner) {
5935
6292
  const store = this.config.channelStorePath ? new JsonFileChannelStore(this.config.channelStorePath) : void 0;
5936
- this.channelManager = new ChannelManager(this.evmSigner, store);
6293
+ this.channelManager = new ChannelManager(this.evmSigner, store, {
6294
+ ...this.config.initialDeposit !== void 0 ? { initialDeposit: this.config.initialDeposit } : {},
6295
+ ...this.config.settlementTimeout !== void 0 ? { settlementTimeout: this.config.settlementTimeout } : {}
6296
+ });
5937
6297
  if (this.config.mnemonic) {
5938
6298
  await this.registerMnemonicChainSigners(
5939
6299
  this.config.mnemonic,
@@ -6165,7 +6525,7 @@ var ToonClient = class {
6165
6525
  String(error),
6166
6526
  error instanceof Error ? error.stack : ""
6167
6527
  );
6168
- if (error instanceof ToonClientError && (error.code === "NO_TERMINATED_ROUTE" || error.code === "NO_CONNECTOR_EDGE")) {
6528
+ if (error instanceof ToonClientError && (error.code === "NO_TERMINATED_ROUTE" || error.code === "NO_CONNECTOR_EDGE" || error.code === "PEER_NOT_NEGOTIATED" || error.code === "CHANNEL_FUNDING")) {
6169
6529
  throw error;
6170
6530
  }
6171
6531
  throw new ToonClientError(
@@ -6422,18 +6782,23 @@ var ToonClient = class {
6422
6782
  return this.buildClaimMessageForProof(explicitClaim);
6423
6783
  }
6424
6784
  if (this.channelManager) {
6425
- const peerId = this.resolvePeerId(destination);
6426
- const negotiation = this.peerNegotiations.get(peerId);
6785
+ const peerId = this.peerIdForClaim(destination);
6786
+ const negotiation = this.peerNegotiations.get(peerId) ?? await this.negotiateFromGreeting(destination, peerId);
6427
6787
  if (!negotiation) {
6428
6788
  throw new ToonClientError(
6429
- `No negotiation metadata for peer "${peerId}" \u2014 was bootstrap completed?`,
6789
+ `No negotiation metadata for peer "${peerId}" \u2014 was bootstrap completed? (and the route's x402 greeting carried no settlement facts to bootstrap from)`,
6430
6790
  "PEER_NOT_NEGOTIATED"
6431
6791
  );
6432
6792
  }
6433
- const channelId = await this.channelManager.ensureChannel(
6434
- peerId,
6435
- negotiation
6436
- );
6793
+ let channelId;
6794
+ try {
6795
+ channelId = await this.channelManager.ensureChannel(
6796
+ peerId,
6797
+ negotiation
6798
+ );
6799
+ } catch (error) {
6800
+ throw this.withSolanaLegHint(peerId, error);
6801
+ }
6437
6802
  const proof = await this.channelManager.signBalanceProof(
6438
6803
  channelId,
6439
6804
  amount
@@ -6499,15 +6864,19 @@ var ToonClient = class {
6499
6864
  "NO_DESTINATION"
6500
6865
  );
6501
6866
  }
6502
- const peerId = this.resolvePeerId(dest);
6503
- const negotiation = this.peerNegotiations.get(peerId);
6867
+ const peerId = this.peerIdForClaim(dest);
6868
+ const negotiation = this.peerNegotiations.get(peerId) ?? await this.negotiateFromGreeting(dest, peerId);
6504
6869
  if (!negotiation) {
6505
6870
  throw new ToonClientError(
6506
- `No negotiation metadata for peer "${peerId}" \u2014 was bootstrap completed?`,
6871
+ `No negotiation metadata for peer "${peerId}" \u2014 was bootstrap completed? (and the route's x402 greeting carried no settlement facts to bootstrap from)`,
6507
6872
  "PEER_NOT_NEGOTIATED"
6508
6873
  );
6509
6874
  }
6510
- return this.channelManager.ensureChannel(peerId, negotiation);
6875
+ try {
6876
+ return await this.channelManager.ensureChannel(peerId, negotiation);
6877
+ } catch (error) {
6878
+ throw this.withSolanaLegHint(peerId, error);
6879
+ }
6511
6880
  }
6512
6881
  /**
6513
6882
  * Gets list of tracked payment channel IDs.
@@ -6857,6 +7226,177 @@ var ToonClient = class {
6857
7226
  * Convention: destination "g.toon.peer1" → peerId "peer1" (last segment).
6858
7227
  * Falls back to first known peer if no match.
6859
7228
  */
7229
+ /**
7230
+ * The peer id a claim for `destination` accounts under. Normally
7231
+ * `resolvePeerId` — but where that throws `PEER_NOT_FOUND` (an empty
7232
+ * negotiation map: nothing announced, nothing registered), the
7233
+ * destination itself is the key, so the announce-less greeting bootstrap
7234
+ * (connector #617) has a stable identity to remember its synthesized
7235
+ * negotiation under.
7236
+ */
7237
+ peerIdForClaim(destination) {
7238
+ try {
7239
+ return this.resolvePeerId(destination);
7240
+ } catch {
7241
+ return destination;
7242
+ }
7243
+ }
7244
+ /**
7245
+ * The announce-less channel bootstrap (connector #617): when nothing has
7246
+ * negotiated with this destination's peer — no kind:10032 announce, no
7247
+ * connector-admin registration — ask the route itself. A settling
7248
+ * connector's x402 greeting carries the channel-opening facts, and ADR
7249
+ * 0022 makes the greeting the ONLY place the Rust fleet will ever state
7250
+ * them. Synthesizes a {@link PeerNegotiation} from those facts, remembers
7251
+ * it, and returns it; `undefined` when there is no edge to ask or the
7252
+ * greeting carries no settlement facts this client can open a channel on.
7253
+ *
7254
+ * A two-chain greeting (connector #632's `extra.settlements`) prefers EVM
7255
+ * — the long-standing default — UNLESS the wallet holds Solana
7256
+ * settlement-token funds and holds none on EVM (issue #470), in which case
7257
+ * it opens the Solana leg instead: a wallet funded only with Solana devnet
7258
+ * assets can bootstrap exactly as an EVM one does. A Solana-only greeting
7259
+ * (no EVM leg at all) always opens Solana — there is nothing to compare
7260
+ * funds against.
7261
+ *
7262
+ * That comparison is only as good as what {@link getBalances} can SEE: with
7263
+ * no `solanaChannel` config it cannot read the Solana side at all, so a
7264
+ * Solana-funded client silently looks broke and takes the EVM leg (issue
7265
+ * #474). We cannot fix the read here — the config genuinely isn't there —
7266
+ * but we remember the peer so the resulting EVM funding failure names the
7267
+ * missing config instead of reading as a plain "fund your wallet".
7268
+ *
7269
+ * Never throws: this is a fallback on a path that already has a precise
7270
+ * error (`PEER_NOT_NEGOTIATED`), and a transport failure while ASKING
7271
+ * must not mask it.
7272
+ */
7273
+ async negotiateFromGreeting(destination, peerId) {
7274
+ let edge;
7275
+ try {
7276
+ edge = this.resolveClientEdgeEndpoint();
7277
+ } catch {
7278
+ return void 0;
7279
+ }
7280
+ try {
7281
+ const terms = await this.connectorEdge.getRouteTerms(edge, destination);
7282
+ const evmSettlement = terms?.settlement;
7283
+ const solanaSettlement = terms?.settlements?.find(
7284
+ (entry) => entry.kind === "solana"
7285
+ );
7286
+ if (!evmSettlement && !solanaSettlement) return void 0;
7287
+ let negotiation;
7288
+ if (solanaSettlement && (!evmSettlement || await this.walletPrefersSolana())) {
7289
+ negotiation = this.solanaNegotiationFromSettlement(solanaSettlement);
7290
+ } else if (evmSettlement) {
7291
+ negotiation = this.evmNegotiationFromSettlement(evmSettlement);
7292
+ if (solanaSettlement && !this.canReadSolanaBalance()) {
7293
+ this.unreadableSolanaLegs.add(peerId);
7294
+ }
7295
+ }
7296
+ if (!negotiation) return void 0;
7297
+ this.peerNegotiations.set(peerId, negotiation);
7298
+ return negotiation;
7299
+ } catch (error) {
7300
+ console.warn(
7301
+ "[ToonClient] channel bootstrap from the x402 greeting failed:",
7302
+ String(error)
7303
+ );
7304
+ return void 0;
7305
+ }
7306
+ }
7307
+ /**
7308
+ * Build the EVM {@link PeerNegotiation} from the greeting's legacy
7309
+ * `settlement` object (connector #617). `undefined` when `chain` is not
7310
+ * the documented `evm:<chainId>` shape — the greeting is malformed rather
7311
+ * than a chain this client cannot open, so bootstrap declines instead of
7312
+ * opening against unverified facts.
7313
+ */
7314
+ evmNegotiationFromSettlement(settlement) {
7315
+ const [chainType, chainIdText] = settlement.chain.split(":");
7316
+ const chainId = Number(chainIdText);
7317
+ if (chainType !== "evm" || !Number.isFinite(chainId)) return void 0;
7318
+ return {
7319
+ chain: settlement.chain,
7320
+ chainType,
7321
+ chainId,
7322
+ settlementAddress: settlement.settlementAddress,
7323
+ tokenAddress: settlement.tokenAddress,
7324
+ tokenNetwork: settlement.tokenNetwork
7325
+ };
7326
+ }
7327
+ /**
7328
+ * Build the Solana {@link PeerNegotiation} from a `settlements` entry
7329
+ * (connector #632). Unlike the EVM leg there is no numeric chain id to
7330
+ * parse or validate — `chain` is always the literal `'solana'` — so,
7331
+ * unlike {@link evmNegotiationFromSettlement}, this cannot fail.
7332
+ */
7333
+ solanaNegotiationFromSettlement(settlement) {
7334
+ return {
7335
+ chain: "solana",
7336
+ chainType: "solana",
7337
+ chainId: "solana",
7338
+ settlementAddress: settlement.settlementAddress,
7339
+ tokenAddress: settlement.tokenAddress,
7340
+ tokenNetwork: settlement.programId
7341
+ };
7342
+ }
7343
+ /**
7344
+ * Whether a two-chain greeting-bootstrap should open the Solana leg
7345
+ * instead of the default EVM one (issue #470): the wallet holds Solana
7346
+ * SETTLEMENT-TOKEN funds and holds none on EVM.
7347
+ *
7348
+ * Reads {@link getBalances}, which reports one balance per chain — the SPL
7349
+ * settlement token on Solana, NOT native SOL (issue #474). That is
7350
+ * deliberate: SOL alone cannot collateralize a channel, so a SOL-only
7351
+ * wallet must not steer the negotiation to Solana. The native SOL a fresh
7352
+ * open needs for rent + fees is checked separately, at open time, by the
7353
+ * Solana opener's funding preflight.
7354
+ *
7355
+ * `getBalances` is itself best-effort per chain (a missing config or failed
7356
+ * RPC read just omits that chain) — this never throws, degrading to "prefer
7357
+ * EVM" (the pre-existing default) on any read failure. When Solana is
7358
+ * omitted because `solanaChannel` is unset, see
7359
+ * {@link canReadSolanaBalance} / {@link unreadableSolanaLegs}.
7360
+ */
7361
+ async walletPrefersSolana() {
7362
+ try {
7363
+ const balances = await this.getBalances();
7364
+ const hasFunds = (chain) => balances.some((b) => b.chain === chain && BigInt(b.amount) > 0n);
7365
+ return hasFunds("solana") && !hasFunds("evm");
7366
+ } catch {
7367
+ return false;
7368
+ }
7369
+ }
7370
+ /**
7371
+ * Whether {@link getBalances} can report a Solana balance at all — the exact
7372
+ * condition that reader gates on. False means a Solana-funded wallet reads
7373
+ * as empty, so `walletPrefersSolana` cannot see its funds.
7374
+ */
7375
+ canReadSolanaBalance() {
7376
+ const sol = this.config.solanaChannel;
7377
+ return Boolean(this.getSolanaAddress() && sol?.rpcUrl && sol.tokenMint);
7378
+ }
7379
+ /**
7380
+ * Re-throw a channel-open failure with the missing-`solanaChannel` diagnosis
7381
+ * attached (issue #474).
7382
+ *
7383
+ * When the peer's greeting advertised a Solana leg this client could not
7384
+ * evaluate, "the EVM wallet has no funds/gas" is a symptom, not the cause:
7385
+ * the funds may be sitting on Solana, invisible because `solanaChannel` is
7386
+ * unconfigured. Only funding failures are rewritten — every other error is
7387
+ * returned untouched, since a transport/RPC/contract fault has nothing to do
7388
+ * with which chain was picked.
7389
+ */
7390
+ withSolanaLegHint(peerId, error) {
7391
+ if (!this.unreadableSolanaLegs.has(peerId)) return error;
7392
+ const isFunding = error instanceof ChannelFundingError || isInsufficientGasError(error);
7393
+ if (!isFunding) return error;
7394
+ const detail = error instanceof Error ? error.message : String(error);
7395
+ return new ChannelFundingError(
7396
+ `${detail} NOTE: the route also offered a Solana settlement leg, but this client has no \`solanaChannel\` config (rpcUrl + tokenMint), so its Solana balance could not be read and the EVM leg was chosen by default. If the wallet is funded on Solana, configure \`solanaChannel\` and retry.`,
7397
+ error instanceof Error ? error : void 0
7398
+ );
7399
+ }
6860
7400
  resolvePeerId(destination) {
6861
7401
  const segments = destination.split(".");
6862
7402
  const lastSegment = segments[segments.length - 1] ?? "";
@@ -8951,7 +9491,7 @@ export {
8951
9491
  decodeEnvelopeRequest,
8952
9492
  decodeEnvelopeResponse,
8953
9493
  decodeEvmSettlementTx,
8954
- decodeVarOctetString,
9494
+ decodeVarOctetString2 as decodeVarOctetString,
8955
9495
  decodeVarUint,
8956
9496
  decryptMnemonic2 as decryptMnemonic,
8957
9497
  defaultFaucetTimeout,
@@ -8965,7 +9505,7 @@ export {
8965
9505
  encodeEnvelope,
8966
9506
  encodeEnvelopeRequest,
8967
9507
  encodeEnvelopeResponse,
8968
- encodeVarOctetString,
9508
+ encodeVarOctetString2 as encodeVarOctetString,
8969
9509
  encodeVarUint,
8970
9510
  encryptMnemonic2 as encryptMnemonic,
8971
9511
  ensureOwnedMinaZkApp,