@toon-protocol/client 0.25.1 → 0.26.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +113 -0
- package/dist/index.d.ts +2164 -1019
- package/dist/index.js +2183 -210
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -46,56 +46,99 @@ import {
|
|
|
46
46
|
|
|
47
47
|
// src/errors.ts
|
|
48
48
|
var ToonClientError = class extends Error {
|
|
49
|
-
constructor(
|
|
50
|
-
super(
|
|
49
|
+
constructor(message2, code, cause) {
|
|
50
|
+
super(message2, { cause });
|
|
51
51
|
this.code = code;
|
|
52
52
|
this.name = "ToonClientError";
|
|
53
53
|
}
|
|
54
54
|
code;
|
|
55
55
|
};
|
|
56
56
|
var NetworkError = class extends ToonClientError {
|
|
57
|
-
constructor(
|
|
58
|
-
super(
|
|
57
|
+
constructor(message2, cause) {
|
|
58
|
+
super(message2, "NETWORK_ERROR", cause);
|
|
59
59
|
this.name = "NetworkError";
|
|
60
60
|
}
|
|
61
61
|
};
|
|
62
62
|
var ConnectorError = class extends ToonClientError {
|
|
63
|
-
constructor(
|
|
64
|
-
super(
|
|
63
|
+
constructor(message2, cause) {
|
|
64
|
+
super(message2, "CONNECTOR_ERROR", cause);
|
|
65
65
|
this.name = "ConnectorError";
|
|
66
66
|
}
|
|
67
67
|
};
|
|
68
68
|
var ValidationError = class extends ToonClientError {
|
|
69
|
-
constructor(
|
|
70
|
-
super(
|
|
69
|
+
constructor(message2, cause) {
|
|
70
|
+
super(message2, "VALIDATION_ERROR", cause);
|
|
71
71
|
this.name = "ValidationError";
|
|
72
72
|
}
|
|
73
73
|
};
|
|
74
74
|
var UnauthorizedError = class extends ToonClientError {
|
|
75
|
-
constructor(
|
|
76
|
-
super(
|
|
75
|
+
constructor(message2, cause) {
|
|
76
|
+
super(message2, "UNAUTHORIZED", cause);
|
|
77
77
|
this.name = "UnauthorizedError";
|
|
78
78
|
}
|
|
79
79
|
};
|
|
80
80
|
var PeerNotFoundError = class extends ToonClientError {
|
|
81
|
-
constructor(
|
|
82
|
-
super(
|
|
81
|
+
constructor(message2, cause) {
|
|
82
|
+
super(message2, "PEER_NOT_FOUND", cause);
|
|
83
83
|
this.name = "PeerNotFoundError";
|
|
84
84
|
}
|
|
85
85
|
};
|
|
86
86
|
var PeerAlreadyExistsError = class extends ToonClientError {
|
|
87
|
-
constructor(
|
|
88
|
-
super(
|
|
87
|
+
constructor(message2, cause) {
|
|
88
|
+
super(message2, "PEER_ALREADY_EXISTS", cause);
|
|
89
89
|
this.name = "PeerAlreadyExistsError";
|
|
90
90
|
}
|
|
91
91
|
};
|
|
92
92
|
var ChannelFundingError = class extends ToonClientError {
|
|
93
93
|
retryable = true;
|
|
94
|
-
constructor(
|
|
95
|
-
super(
|
|
94
|
+
constructor(message2, cause) {
|
|
95
|
+
super(message2, "CHANNEL_FUNDING", cause);
|
|
96
96
|
this.name = "ChannelFundingError";
|
|
97
97
|
}
|
|
98
98
|
};
|
|
99
|
+
var ChannelResumeError = class extends ToonClientError {
|
|
100
|
+
constructor(message2, cause) {
|
|
101
|
+
super(message2, "CHANNEL_RESUME", cause);
|
|
102
|
+
this.name = "ChannelResumeError";
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
var InsufficientBalanceError = class extends ToonClientError {
|
|
106
|
+
constructor(message2, cause) {
|
|
107
|
+
super(message2, "INSUFFICIENT_BALANCE", cause);
|
|
108
|
+
this.name = "InsufficientBalanceError";
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
var StaleRpcReadError = class extends ToonClientError {
|
|
112
|
+
retryable = true;
|
|
113
|
+
constructor(message2, cause) {
|
|
114
|
+
super(message2, "STALE_RPC_READ", cause);
|
|
115
|
+
this.name = "StaleRpcReadError";
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
var UnknownChainError = class extends ToonClientError {
|
|
119
|
+
constructor(message2, cause) {
|
|
120
|
+
super(message2, "UNKNOWN_CHAIN", cause);
|
|
121
|
+
this.name = "UnknownChainError";
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
var InvalidAddressError = class extends ToonClientError {
|
|
125
|
+
constructor(message2, cause) {
|
|
126
|
+
super(message2, "INVALID_ADDRESS", cause);
|
|
127
|
+
this.name = "InvalidAddressError";
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
var TransferNotDeliveredError = class extends ToonClientError {
|
|
131
|
+
constructor(message2, cause) {
|
|
132
|
+
super(message2, "TRANSFER_NOT_DELIVERED", cause);
|
|
133
|
+
this.name = "TransferNotDeliveredError";
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
var TransferUnsupportedError = class extends ToonClientError {
|
|
137
|
+
constructor(message2, cause) {
|
|
138
|
+
super(message2, "TRANSFER_UNSUPPORTED", cause);
|
|
139
|
+
this.name = "TransferUnsupportedError";
|
|
140
|
+
}
|
|
141
|
+
};
|
|
99
142
|
var INSUFFICIENT_GAS_MARKERS = [
|
|
100
143
|
"exceeds the balance of the account",
|
|
101
144
|
"insufficient funds for gas",
|
|
@@ -159,7 +202,7 @@ function deriveEvmIdentity(secretKey) {
|
|
|
159
202
|
async function deriveSolanaKey(seed, accountIndex = 0) {
|
|
160
203
|
const { hmac } = await import("@noble/hashes/hmac");
|
|
161
204
|
const { sha512 } = await import("@noble/hashes/sha512");
|
|
162
|
-
const { ed25519:
|
|
205
|
+
const { ed25519: ed255195 } = await import("@noble/curves/ed25519.js");
|
|
163
206
|
const encoder = new TextEncoder();
|
|
164
207
|
let I = hmac(sha512, encoder.encode("ed25519 seed"), seed);
|
|
165
208
|
let key2 = I.slice(0, 32);
|
|
@@ -186,7 +229,7 @@ async function deriveSolanaKey(seed, accountIndex = 0) {
|
|
|
186
229
|
key2 = I.slice(0, 32);
|
|
187
230
|
chainCode = I.slice(32);
|
|
188
231
|
}
|
|
189
|
-
const publicKeyBytes =
|
|
232
|
+
const publicKeyBytes = ed255195.getPublicKey(key2);
|
|
190
233
|
const keypair = new Uint8Array(64);
|
|
191
234
|
keypair.set(key2, 0);
|
|
192
235
|
keypair.set(publicKeyBytes, 32);
|
|
@@ -486,6 +529,7 @@ function applyDefaults(rawConfig) {
|
|
|
486
529
|
queryTimeout: config.queryTimeout ?? 3e4,
|
|
487
530
|
maxRetries: config.maxRetries ?? 3,
|
|
488
531
|
retryDelay: config.retryDelay ?? 1e3,
|
|
532
|
+
preferBtpForPaidWrites: config.preferBtpForPaidWrites ?? false,
|
|
489
533
|
btpUrl,
|
|
490
534
|
destinationAddress
|
|
491
535
|
// Always set by logic above
|
|
@@ -534,6 +578,14 @@ function toHex2(bytes) {
|
|
|
534
578
|
}
|
|
535
579
|
return hex;
|
|
536
580
|
}
|
|
581
|
+
function fromHex(hex) {
|
|
582
|
+
const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
|
|
583
|
+
const bytes = new Uint8Array(clean.length / 2);
|
|
584
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
585
|
+
bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
|
|
586
|
+
}
|
|
587
|
+
return bytes;
|
|
588
|
+
}
|
|
537
589
|
function encodeUtf8(str) {
|
|
538
590
|
return new TextEncoder().encode(str);
|
|
539
591
|
}
|
|
@@ -550,7 +602,13 @@ var textDecoder = new TextDecoder();
|
|
|
550
602
|
var BTPMessageType = {
|
|
551
603
|
RESPONSE: 1,
|
|
552
604
|
ERROR: 2,
|
|
553
|
-
MESSAGE: 6
|
|
605
|
+
MESSAGE: 6,
|
|
606
|
+
/**
|
|
607
|
+
* RFC-0023's symmetric grammar (connector issue #697, toon-client#493):
|
|
608
|
+
* `Transfer ::= SEQUENCE { amount, protocolData }` — settlement value, no
|
|
609
|
+
* ILP-packet field. Byte-compatible with the connector's `btp.rs`.
|
|
610
|
+
*/
|
|
611
|
+
TRANSFER: 7
|
|
554
612
|
};
|
|
555
613
|
var ILPPacketType = {
|
|
556
614
|
PREPARE: 12,
|
|
@@ -581,6 +639,15 @@ function readUint32BE(buf, offset) {
|
|
|
581
639
|
throw new Error("Buffer underflow reading uint32");
|
|
582
640
|
return (buf[offset] << 24 | buf[offset + 1] << 16 | buf[offset + 2] << 8 | buf[offset + 3]) >>> 0;
|
|
583
641
|
}
|
|
642
|
+
function readUint64BE(buf, offset) {
|
|
643
|
+
if (offset + 8 > buf.length)
|
|
644
|
+
throw new Error("Buffer underflow reading uint64");
|
|
645
|
+
let value = 0n;
|
|
646
|
+
for (let i = 0; i < 8; i++) {
|
|
647
|
+
value = value << 8n | BigInt(buf[offset + i]);
|
|
648
|
+
}
|
|
649
|
+
return value;
|
|
650
|
+
}
|
|
584
651
|
function writeUint8(value) {
|
|
585
652
|
return new Uint8Array([value]);
|
|
586
653
|
}
|
|
@@ -595,6 +662,15 @@ function writeUint32BE(value) {
|
|
|
595
662
|
value & 255
|
|
596
663
|
]);
|
|
597
664
|
}
|
|
665
|
+
function writeUint64BE(value) {
|
|
666
|
+
const bytes = new Uint8Array(8);
|
|
667
|
+
let remaining = value;
|
|
668
|
+
for (let i = 7; i >= 0; i--) {
|
|
669
|
+
bytes[i] = Number(remaining & 0xffn);
|
|
670
|
+
remaining >>= 8n;
|
|
671
|
+
}
|
|
672
|
+
return bytes;
|
|
673
|
+
}
|
|
598
674
|
function sliceUtf8(buf, offset, length) {
|
|
599
675
|
return textDecoder.decode(buf.slice(offset, offset + length));
|
|
600
676
|
}
|
|
@@ -648,6 +724,30 @@ function encodeGeneralizedTime(date) {
|
|
|
648
724
|
const ms = date.getUTCMilliseconds().toString().padStart(3, "0");
|
|
649
725
|
return textEncoder.encode(`${y}${mo}${d}${h}${mi}${s}.${ms}Z`);
|
|
650
726
|
}
|
|
727
|
+
var GENERALIZED_TIME_LENGTH = 19;
|
|
728
|
+
function decodeGeneralizedTime(buf, offset) {
|
|
729
|
+
if (offset + GENERALIZED_TIME_LENGTH > buf.length) {
|
|
730
|
+
throw new Error("Buffer underflow reading GeneralizedTime");
|
|
731
|
+
}
|
|
732
|
+
const text = sliceUtf8(buf, offset, GENERALIZED_TIME_LENGTH);
|
|
733
|
+
const match = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{3})Z$/.exec(text);
|
|
734
|
+
if (!match) {
|
|
735
|
+
throw new Error(`Malformed GeneralizedTime: "${text}"`);
|
|
736
|
+
}
|
|
737
|
+
const [, y, mo, d, h, mi, s, ms] = match;
|
|
738
|
+
const value = new Date(
|
|
739
|
+
Date.UTC(
|
|
740
|
+
Number(y),
|
|
741
|
+
Number(mo) - 1,
|
|
742
|
+
Number(d),
|
|
743
|
+
Number(h),
|
|
744
|
+
Number(mi),
|
|
745
|
+
Number(s),
|
|
746
|
+
Number(ms)
|
|
747
|
+
)
|
|
748
|
+
);
|
|
749
|
+
return { value, bytesRead: GENERALIZED_TIME_LENGTH };
|
|
750
|
+
}
|
|
651
751
|
function serializeIlpPrepare(packet) {
|
|
652
752
|
const condition = packet.executionCondition.length === 32 ? packet.executionCondition : new Uint8Array(32);
|
|
653
753
|
return concat(
|
|
@@ -659,6 +759,38 @@ function serializeIlpPrepare(packet) {
|
|
|
659
759
|
encodeVarOctetString(packet.data)
|
|
660
760
|
);
|
|
661
761
|
}
|
|
762
|
+
function deserializeIlpPrepare(buf) {
|
|
763
|
+
if (buf.length === 0) throw new Error("Empty ILP packet");
|
|
764
|
+
const type = buf[0];
|
|
765
|
+
if (type !== ILPPacketType.PREPARE) {
|
|
766
|
+
throw new Error(`Expected PREPARE (type ${ILPPacketType.PREPARE}), got type ${type}`);
|
|
767
|
+
}
|
|
768
|
+
let offset = 1;
|
|
769
|
+
const { value: amount, bytesRead: amountBytes } = decodeVarUInt(buf, offset);
|
|
770
|
+
offset += amountBytes;
|
|
771
|
+
const { value: expiresAt, bytesRead: timeBytes } = decodeGeneralizedTime(
|
|
772
|
+
buf,
|
|
773
|
+
offset
|
|
774
|
+
);
|
|
775
|
+
offset += timeBytes;
|
|
776
|
+
if (offset + 32 > buf.length) {
|
|
777
|
+
throw new Error("Buffer underflow reading PREPARE executionCondition");
|
|
778
|
+
}
|
|
779
|
+
const executionCondition = buf.slice(offset, offset + 32);
|
|
780
|
+
offset += 32;
|
|
781
|
+
const { value: destinationBytes, bytesRead: destBytes } = decodeVarOctetString(buf, offset);
|
|
782
|
+
offset += destBytes;
|
|
783
|
+
const destination = textDecoder.decode(destinationBytes);
|
|
784
|
+
const { value: data } = decodeVarOctetString(buf, offset);
|
|
785
|
+
return {
|
|
786
|
+
type: ILPPacketType.PREPARE,
|
|
787
|
+
amount,
|
|
788
|
+
destination,
|
|
789
|
+
executionCondition,
|
|
790
|
+
expiresAt,
|
|
791
|
+
data
|
|
792
|
+
};
|
|
793
|
+
}
|
|
662
794
|
function deserializeIlpPacket(buf) {
|
|
663
795
|
if (buf.length === 0) throw new Error("Empty ILP packet");
|
|
664
796
|
const type = buf[0];
|
|
@@ -680,24 +812,46 @@ function deserializeIlpReject(buf) {
|
|
|
680
812
|
let offset = 1;
|
|
681
813
|
const code = sliceUtf8(buf, offset, 3);
|
|
682
814
|
offset += 3;
|
|
683
|
-
const { bytesRead: tbBytes } = decodeVarOctetString(
|
|
815
|
+
const { value: tbBuf, bytesRead: tbBytes } = decodeVarOctetString(
|
|
816
|
+
buf,
|
|
817
|
+
offset
|
|
818
|
+
);
|
|
684
819
|
offset += tbBytes;
|
|
820
|
+
const triggeredBy = textDecoder.decode(tbBuf);
|
|
685
821
|
const { value: msgBuf, bytesRead: msgBytes } = decodeVarOctetString(
|
|
686
822
|
buf,
|
|
687
823
|
offset
|
|
688
824
|
);
|
|
689
825
|
offset += msgBytes;
|
|
690
|
-
const
|
|
826
|
+
const message2 = textDecoder.decode(msgBuf);
|
|
691
827
|
const { value: data } = decodeVarOctetString(buf, offset);
|
|
692
|
-
return { type: ILPPacketType.REJECT, code, message, data };
|
|
828
|
+
return { type: ILPPacketType.REJECT, code, triggeredBy, message: message2, data };
|
|
693
829
|
}
|
|
694
|
-
function
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
830
|
+
function serializeIlpFulfill(packet) {
|
|
831
|
+
if (packet.fulfillment.length !== 32) {
|
|
832
|
+
throw new Error(
|
|
833
|
+
`FULFILL fulfillment must be exactly 32 bytes, got ${packet.fulfillment.length}`
|
|
834
|
+
);
|
|
835
|
+
}
|
|
836
|
+
return concat(
|
|
837
|
+
writeUint8(ILPPacketType.FULFILL),
|
|
838
|
+
packet.fulfillment,
|
|
839
|
+
encodeVarOctetString(packet.data)
|
|
840
|
+
);
|
|
841
|
+
}
|
|
842
|
+
function serializeIlpReject(packet) {
|
|
843
|
+
if (!/^[A-Za-z0-9]{3}$/.test(packet.code)) {
|
|
844
|
+
throw new Error(`REJECT code must be exactly 3 ASCII characters, got "${packet.code}"`);
|
|
845
|
+
}
|
|
846
|
+
return concat(
|
|
847
|
+
writeUint8(ILPPacketType.REJECT),
|
|
848
|
+
textEncoder.encode(packet.code),
|
|
849
|
+
encodeVarOctetString(textEncoder.encode(packet.triggeredBy ?? "")),
|
|
850
|
+
encodeVarOctetString(textEncoder.encode(packet.message)),
|
|
851
|
+
encodeVarOctetString(packet.data)
|
|
852
|
+
);
|
|
853
|
+
}
|
|
854
|
+
function pushProtocolData(parts, protocolData) {
|
|
701
855
|
parts.push(writeUint8(protocolData.length));
|
|
702
856
|
for (const pd of protocolData) {
|
|
703
857
|
const nameBytes = textEncoder.encode(pd.protocolName);
|
|
@@ -707,6 +861,51 @@ function serializeBtpMessage(message) {
|
|
|
707
861
|
parts.push(writeUint32BE(pd.data.length));
|
|
708
862
|
if (pd.data.length > 0) parts.push(pd.data);
|
|
709
863
|
}
|
|
864
|
+
}
|
|
865
|
+
function readProtocolData(buf, offset) {
|
|
866
|
+
const pdCount = readUint8(buf, offset);
|
|
867
|
+
offset += 1;
|
|
868
|
+
const protocolData = [];
|
|
869
|
+
for (let i = 0; i < pdCount; i++) {
|
|
870
|
+
const nameLen = readUint8(buf, offset);
|
|
871
|
+
offset += 1;
|
|
872
|
+
const protocolName = sliceUtf8(buf, offset, nameLen);
|
|
873
|
+
offset += nameLen;
|
|
874
|
+
const contentType = readUint16BE(buf, offset);
|
|
875
|
+
offset += 2;
|
|
876
|
+
const dataLen = readUint32BE(buf, offset);
|
|
877
|
+
offset += 4;
|
|
878
|
+
const data = buf.slice(offset, offset + dataLen);
|
|
879
|
+
offset += dataLen;
|
|
880
|
+
protocolData.push({ protocolName, contentType, data });
|
|
881
|
+
}
|
|
882
|
+
return { protocolData, offset };
|
|
883
|
+
}
|
|
884
|
+
function serializeBtpMessage(message2) {
|
|
885
|
+
const parts = [
|
|
886
|
+
writeUint8(message2.type),
|
|
887
|
+
writeUint32BE(message2.requestId)
|
|
888
|
+
];
|
|
889
|
+
if (message2.type === BTPMessageType.ERROR) {
|
|
890
|
+
const data2 = message2.data;
|
|
891
|
+
for (const field of [data2.code, data2.name, data2.triggeredAt ?? ""]) {
|
|
892
|
+
const bytes = textEncoder.encode(field);
|
|
893
|
+
parts.push(writeUint8(bytes.length));
|
|
894
|
+
parts.push(bytes);
|
|
895
|
+
}
|
|
896
|
+
const errorData = data2.data ?? textEncoder.encode(data2.message ?? "");
|
|
897
|
+
parts.push(writeUint32BE(errorData.length));
|
|
898
|
+
if (errorData.length > 0) parts.push(errorData);
|
|
899
|
+
return concat(...parts);
|
|
900
|
+
}
|
|
901
|
+
if (message2.type === BTPMessageType.TRANSFER) {
|
|
902
|
+
const data2 = message2.data;
|
|
903
|
+
parts.push(writeUint64BE(data2.amount));
|
|
904
|
+
pushProtocolData(parts, data2.protocolData ?? []);
|
|
905
|
+
return concat(...parts);
|
|
906
|
+
}
|
|
907
|
+
const data = message2.data;
|
|
908
|
+
pushProtocolData(parts, data.protocolData ?? []);
|
|
710
909
|
const ilpPacket = data.ilpPacket ?? new Uint8Array(0);
|
|
711
910
|
parts.push(writeUint32BE(ilpPacket.length));
|
|
712
911
|
if (ilpPacket.length > 0) parts.push(ilpPacket);
|
|
@@ -735,29 +934,24 @@ function parseBtpMessage(buf) {
|
|
|
735
934
|
const dataLen = readUint32BE(buf, offset);
|
|
736
935
|
offset += 4;
|
|
737
936
|
const data = buf.slice(offset, offset + dataLen);
|
|
738
|
-
const
|
|
937
|
+
const message2 = textDecoder.decode(data);
|
|
739
938
|
return {
|
|
740
939
|
type,
|
|
741
940
|
requestId,
|
|
742
|
-
data: { code, name, triggeredAt, message, data }
|
|
941
|
+
data: { code, name, triggeredAt, message: message2, data }
|
|
743
942
|
};
|
|
744
943
|
}
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
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 });
|
|
944
|
+
if (type === BTPMessageType.TRANSFER) {
|
|
945
|
+
const amount = readUint64BE(buf, offset);
|
|
946
|
+
offset += 8;
|
|
947
|
+
const { protocolData: protocolData2 } = readProtocolData(buf, offset);
|
|
948
|
+
return { type, requestId, data: { amount, protocolData: protocolData2 } };
|
|
760
949
|
}
|
|
950
|
+
const { protocolData, offset: afterProtocolData } = readProtocolData(
|
|
951
|
+
buf,
|
|
952
|
+
offset
|
|
953
|
+
);
|
|
954
|
+
offset = afterProtocolData;
|
|
761
955
|
let ilpPacket;
|
|
762
956
|
if (offset + 4 <= buf.length) {
|
|
763
957
|
const ilpLen = readUint32BE(buf, offset);
|
|
@@ -771,8 +965,8 @@ function parseBtpMessage(buf) {
|
|
|
771
965
|
|
|
772
966
|
// src/adapters/ConnectorEdgeClient.ts
|
|
773
967
|
var ConnectorEdgeError = class extends ToonClientError {
|
|
774
|
-
constructor(
|
|
775
|
-
super(
|
|
968
|
+
constructor(message2, code, cause) {
|
|
969
|
+
super(message2, code, cause);
|
|
776
970
|
this.name = "ConnectorEdgeError";
|
|
777
971
|
}
|
|
778
972
|
};
|
|
@@ -877,6 +1071,105 @@ function parseConnectorRoutePrice(body) {
|
|
|
877
1071
|
}
|
|
878
1072
|
return { destination, price: BigInt(price) };
|
|
879
1073
|
}
|
|
1074
|
+
function claimStr(e, key2, entryIndex) {
|
|
1075
|
+
const value = e[key2];
|
|
1076
|
+
if (typeof value !== "string") {
|
|
1077
|
+
throw new ConnectorEdgeError(
|
|
1078
|
+
`claim-state channel entry ${entryIndex} lacks a string '${key2}'`,
|
|
1079
|
+
"CLAIM_STATE_MALFORMED"
|
|
1080
|
+
);
|
|
1081
|
+
}
|
|
1082
|
+
return value;
|
|
1083
|
+
}
|
|
1084
|
+
function claimNullableStr(e, key2, entryIndex) {
|
|
1085
|
+
const value = e[key2];
|
|
1086
|
+
if (value === null) return null;
|
|
1087
|
+
if (typeof value !== "string") {
|
|
1088
|
+
throw new ConnectorEdgeError(
|
|
1089
|
+
`claim-state channel entry ${entryIndex}'s '${key2}' is neither a string nor null`,
|
|
1090
|
+
"CLAIM_STATE_MALFORMED"
|
|
1091
|
+
);
|
|
1092
|
+
}
|
|
1093
|
+
return value;
|
|
1094
|
+
}
|
|
1095
|
+
function parseClaimStateEntry(raw, entryIndex) {
|
|
1096
|
+
if (typeof raw !== "object" || raw === null) {
|
|
1097
|
+
throw new ConnectorEdgeError(
|
|
1098
|
+
`claim-state channel entry ${entryIndex} is not an object`,
|
|
1099
|
+
"CLAIM_STATE_MALFORMED"
|
|
1100
|
+
);
|
|
1101
|
+
}
|
|
1102
|
+
const e = raw;
|
|
1103
|
+
const blockchain = e["blockchain"];
|
|
1104
|
+
if (blockchain !== "evm" && blockchain !== "solana") {
|
|
1105
|
+
throw new ConnectorEdgeError(
|
|
1106
|
+
`claim-state channel entry ${entryIndex} names neither 'evm' nor 'solana'`,
|
|
1107
|
+
"CLAIM_STATE_MALFORMED"
|
|
1108
|
+
);
|
|
1109
|
+
}
|
|
1110
|
+
const channelId = typeof e["channelId"] === "string" ? e["channelId"] : void 0;
|
|
1111
|
+
const channelAccount = typeof e["channelAccount"] === "string" ? e["channelAccount"] : void 0;
|
|
1112
|
+
const identity = {
|
|
1113
|
+
...channelId !== void 0 ? { channelId } : {},
|
|
1114
|
+
...channelAccount !== void 0 ? { channelAccount } : {}
|
|
1115
|
+
};
|
|
1116
|
+
if (e["ok"] === false) {
|
|
1117
|
+
const error = e["error"];
|
|
1118
|
+
if (error !== "expired" && error !== "unverified") {
|
|
1119
|
+
throw new ConnectorEdgeError(
|
|
1120
|
+
`claim-state channel entry ${entryIndex} has an undocumented error: ${String(error)}`,
|
|
1121
|
+
"CLAIM_STATE_MALFORMED"
|
|
1122
|
+
);
|
|
1123
|
+
}
|
|
1124
|
+
return { blockchain, ...identity, ok: false, error };
|
|
1125
|
+
}
|
|
1126
|
+
if (e["ok"] !== true) {
|
|
1127
|
+
throw new ConnectorEdgeError(
|
|
1128
|
+
`claim-state channel entry ${entryIndex} lacks a boolean 'ok'`,
|
|
1129
|
+
"CLAIM_STATE_MALFORMED"
|
|
1130
|
+
);
|
|
1131
|
+
}
|
|
1132
|
+
const nonce = e["nonce"];
|
|
1133
|
+
if (typeof nonce !== "number" || !Number.isInteger(nonce) || nonce < 0) {
|
|
1134
|
+
throw new ConnectorEdgeError(
|
|
1135
|
+
`claim-state channel entry ${entryIndex} has a non-integer nonce`,
|
|
1136
|
+
"CLAIM_STATE_MALFORMED"
|
|
1137
|
+
);
|
|
1138
|
+
}
|
|
1139
|
+
const lastClaimTime = e["lastClaimTime"];
|
|
1140
|
+
if (lastClaimTime !== null && (typeof lastClaimTime !== "number" || !Number.isInteger(lastClaimTime))) {
|
|
1141
|
+
throw new ConnectorEdgeError(
|
|
1142
|
+
`claim-state channel entry ${entryIndex}'s lastClaimTime is neither an integer nor null`,
|
|
1143
|
+
"CLAIM_STATE_MALFORMED"
|
|
1144
|
+
);
|
|
1145
|
+
}
|
|
1146
|
+
return {
|
|
1147
|
+
blockchain,
|
|
1148
|
+
...identity,
|
|
1149
|
+
ok: true,
|
|
1150
|
+
depositTotal: claimNullableStr(e, "depositTotal", entryIndex),
|
|
1151
|
+
cumulativeClaimed: claimStr(e, "cumulativeClaimed", entryIndex),
|
|
1152
|
+
available: claimNullableStr(e, "available", entryIndex),
|
|
1153
|
+
nonce,
|
|
1154
|
+
lastClaimTime
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
function parseClaimStateResponse(body) {
|
|
1158
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
1159
|
+
throw new ConnectorEdgeError(
|
|
1160
|
+
"POST /ilp/claim-state did not answer a JSON object",
|
|
1161
|
+
"CLAIM_STATE_MALFORMED"
|
|
1162
|
+
);
|
|
1163
|
+
}
|
|
1164
|
+
const channels = body["channels"];
|
|
1165
|
+
if (!Array.isArray(channels)) {
|
|
1166
|
+
throw new ConnectorEdgeError(
|
|
1167
|
+
"POST /ilp/claim-state answered without a 'channels' array",
|
|
1168
|
+
"CLAIM_STATE_MALFORMED"
|
|
1169
|
+
);
|
|
1170
|
+
}
|
|
1171
|
+
return channels.map((entry, i) => parseClaimStateEntry(entry, i));
|
|
1172
|
+
}
|
|
880
1173
|
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
881
1174
|
var PRICE_KEY_SEPARATOR = "\0";
|
|
882
1175
|
function priceCacheKey(base, destination) {
|
|
@@ -1024,6 +1317,57 @@ var ConnectorEdgeClient = class {
|
|
|
1024
1317
|
}
|
|
1025
1318
|
return parseConnectorRouteTerms(body);
|
|
1026
1319
|
}
|
|
1320
|
+
/**
|
|
1321
|
+
* The credited/spendable position of one or more channels this client
|
|
1322
|
+
* controls (`POST /ilp/claim-state`, client-edge-spec.md §1.10) — the
|
|
1323
|
+
* runway source of truth (toon-meta#261/#262 decision 9): earnings net
|
|
1324
|
+
* off-chain on the same channel a client spends from, so this is also
|
|
1325
|
+
* where a credited balance is read. Never cached: unlike identity/price,
|
|
1326
|
+
* a claim watermark changes on every accepted claim, on EITHER side.
|
|
1327
|
+
*
|
|
1328
|
+
* Each entry is independently authenticated (own signature, own
|
|
1329
|
+
* blockchain) — a request MAY mix EVM and Solana channels. Returns `[]`
|
|
1330
|
+
* without a request when `channels` is empty.
|
|
1331
|
+
*
|
|
1332
|
+
* @throws {NetworkError} the connector could not be reached.
|
|
1333
|
+
* @throws {ConnectorEdgeError} a non-2xx status, or a body that is not the
|
|
1334
|
+
* documented shape.
|
|
1335
|
+
*/
|
|
1336
|
+
async getClaimState(endpoint, channels) {
|
|
1337
|
+
if (channels.length === 0) return [];
|
|
1338
|
+
const base = connectorEdgeBaseUrl(endpoint);
|
|
1339
|
+
const url = `${base}/ilp/claim-state`;
|
|
1340
|
+
const controller = new AbortController();
|
|
1341
|
+
const timer = setTimeout(() => controller.abort(), this.timeout);
|
|
1342
|
+
let response;
|
|
1343
|
+
try {
|
|
1344
|
+
response = await this.fetchImpl(url, {
|
|
1345
|
+
method: "POST",
|
|
1346
|
+
headers: {
|
|
1347
|
+
"content-type": "application/json",
|
|
1348
|
+
accept: "application/json"
|
|
1349
|
+
},
|
|
1350
|
+
body: JSON.stringify({ channels }),
|
|
1351
|
+
signal: controller.signal
|
|
1352
|
+
});
|
|
1353
|
+
} catch (error) {
|
|
1354
|
+
throw new NetworkError(
|
|
1355
|
+
`could not reach the connector client edge at ${url}`,
|
|
1356
|
+
error instanceof Error ? error : void 0
|
|
1357
|
+
);
|
|
1358
|
+
} finally {
|
|
1359
|
+
clearTimeout(timer);
|
|
1360
|
+
}
|
|
1361
|
+
if (!response.ok) {
|
|
1362
|
+
throw new ConnectorEdgeError(
|
|
1363
|
+
`POST /ilp/claim-state answered ${response.status}`,
|
|
1364
|
+
"CLAIM_STATE_HTTP_STATUS"
|
|
1365
|
+
);
|
|
1366
|
+
}
|
|
1367
|
+
return parseClaimStateResponse(
|
|
1368
|
+
await this.readJson(response, "CLAIM_STATE_MALFORMED")
|
|
1369
|
+
);
|
|
1370
|
+
}
|
|
1027
1371
|
/**
|
|
1028
1372
|
* Drop a cached route price — one (endpoint, destination)'s, every
|
|
1029
1373
|
* destination's at one endpoint when `destination` is omitted, or all of
|
|
@@ -1690,8 +2034,8 @@ function deriveCondition(fulfillment) {
|
|
|
1690
2034
|
|
|
1691
2035
|
// src/wire/sealed-exchange.ts
|
|
1692
2036
|
var SealedResponseError = class extends Error {
|
|
1693
|
-
constructor(kind,
|
|
1694
|
-
super(
|
|
2037
|
+
constructor(kind, message2, cause) {
|
|
2038
|
+
super(message2);
|
|
1695
2039
|
this.kind = kind;
|
|
1696
2040
|
this.cause = cause;
|
|
1697
2041
|
this.name = "SealedResponseError";
|
|
@@ -1717,20 +2061,20 @@ function readExchangeOutcome(result, data, sharedSecret) {
|
|
|
1717
2061
|
return { kind: "answered", response: openAnswer(data, sharedSecret) };
|
|
1718
2062
|
}
|
|
1719
2063
|
const code = result.code ?? "F00";
|
|
1720
|
-
const
|
|
2064
|
+
const message2 = result.message ?? "";
|
|
1721
2065
|
if (data !== void 0 && looksLikeSealedResponse(data)) {
|
|
1722
2066
|
try {
|
|
1723
2067
|
return {
|
|
1724
2068
|
kind: "destination-refused",
|
|
1725
2069
|
code,
|
|
1726
|
-
message,
|
|
2070
|
+
message: message2,
|
|
1727
2071
|
detail: openResponse(sharedSecret, data)
|
|
1728
2072
|
};
|
|
1729
2073
|
} catch (error) {
|
|
1730
2074
|
if (!(error instanceof GiftWrapError)) throw error;
|
|
1731
2075
|
}
|
|
1732
2076
|
}
|
|
1733
|
-
return { kind: "path-refused", code, message };
|
|
2077
|
+
return { kind: "path-refused", code, message: message2 };
|
|
1734
2078
|
}
|
|
1735
2079
|
function openAnswer(data, sharedSecret) {
|
|
1736
2080
|
if (data === void 0 || data.length === 0) {
|
|
@@ -1775,6 +2119,91 @@ function envelopeHeader(response, name) {
|
|
|
1775
2119
|
return void 0;
|
|
1776
2120
|
}
|
|
1777
2121
|
|
|
2122
|
+
// src/nip59.ts
|
|
2123
|
+
import { getConversationKey, decrypt as nip44Decrypt } from "nostr-tools/nip44";
|
|
2124
|
+
import { verifyEvent } from "nostr-tools/pure";
|
|
2125
|
+
var GIFT_WRAP_KIND = 1059;
|
|
2126
|
+
var SEAL_KIND = 13;
|
|
2127
|
+
var GiftWrapAddressError = class extends Error {
|
|
2128
|
+
constructor(message2) {
|
|
2129
|
+
super(message2);
|
|
2130
|
+
this.name = "GiftWrapAddressError";
|
|
2131
|
+
}
|
|
2132
|
+
};
|
|
2133
|
+
var GiftWrapDecryptError = class extends Error {
|
|
2134
|
+
constructor(message2) {
|
|
2135
|
+
super(message2);
|
|
2136
|
+
this.name = "GiftWrapDecryptError";
|
|
2137
|
+
}
|
|
2138
|
+
};
|
|
2139
|
+
function message(err) {
|
|
2140
|
+
return err instanceof Error ? err.message : String(err);
|
|
2141
|
+
}
|
|
2142
|
+
function isNostrEventShape(value) {
|
|
2143
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2144
|
+
const e = value;
|
|
2145
|
+
return typeof e["kind"] === "number" && typeof e["pubkey"] === "string" && typeof e["content"] === "string" && typeof e["created_at"] === "number" && Array.isArray(e["tags"]) && typeof e["id"] === "string" && typeof e["sig"] === "string";
|
|
2146
|
+
}
|
|
2147
|
+
function isUnsignedEventShape(value) {
|
|
2148
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2149
|
+
const e = value;
|
|
2150
|
+
return typeof e["kind"] === "number" && typeof e["pubkey"] === "string" && typeof e["content"] === "string" && typeof e["created_at"] === "number" && Array.isArray(e["tags"]);
|
|
2151
|
+
}
|
|
2152
|
+
function unwrapGiftWrapWithKey(recipientSecretKey, recipientPubkey, wrap) {
|
|
2153
|
+
if (!isNostrEventShape(wrap)) {
|
|
2154
|
+
throw new GiftWrapAddressError(
|
|
2155
|
+
"wrap is not a valid Nostr event (kind/pubkey/content/created_at/tags/id/sig required)."
|
|
2156
|
+
);
|
|
2157
|
+
}
|
|
2158
|
+
if (wrap.kind !== GIFT_WRAP_KIND) {
|
|
2159
|
+
throw new GiftWrapAddressError(
|
|
2160
|
+
`wrap.kind must be ${GIFT_WRAP_KIND} (gift wrap), got ${wrap.kind}.`
|
|
2161
|
+
);
|
|
2162
|
+
}
|
|
2163
|
+
const addressedToUs = wrap.tags.some(
|
|
2164
|
+
(tag) => tag[0] === "p" && tag[1] === recipientPubkey
|
|
2165
|
+
);
|
|
2166
|
+
if (!addressedToUs) {
|
|
2167
|
+
throw new GiftWrapAddressError(
|
|
2168
|
+
'gift wrap is not addressed to this identity (no matching "p" tag).'
|
|
2169
|
+
);
|
|
2170
|
+
}
|
|
2171
|
+
let seal;
|
|
2172
|
+
try {
|
|
2173
|
+
const wrapKey = getConversationKey(recipientSecretKey, wrap.pubkey);
|
|
2174
|
+
seal = JSON.parse(nip44Decrypt(wrap.content, wrapKey));
|
|
2175
|
+
} catch (err) {
|
|
2176
|
+
throw new GiftWrapDecryptError(
|
|
2177
|
+
`failed to decrypt gift wrap (layer 1): ${message(err)}`
|
|
2178
|
+
);
|
|
2179
|
+
}
|
|
2180
|
+
if (!isNostrEventShape(seal) || seal.kind !== SEAL_KIND) {
|
|
2181
|
+
throw new GiftWrapDecryptError(
|
|
2182
|
+
"decrypted wrap content is not a valid kind:13 seal event."
|
|
2183
|
+
);
|
|
2184
|
+
}
|
|
2185
|
+
if (!verifyEvent(seal)) {
|
|
2186
|
+
throw new GiftWrapDecryptError(
|
|
2187
|
+
"seal signature verification failed \u2014 the seal was not validly signed by its claimed pubkey."
|
|
2188
|
+
);
|
|
2189
|
+
}
|
|
2190
|
+
let rumor;
|
|
2191
|
+
try {
|
|
2192
|
+
const sealKey = getConversationKey(recipientSecretKey, seal.pubkey);
|
|
2193
|
+
rumor = JSON.parse(nip44Decrypt(seal.content, sealKey));
|
|
2194
|
+
} catch (err) {
|
|
2195
|
+
throw new GiftWrapDecryptError(
|
|
2196
|
+
`failed to decrypt seal (layer 2): ${message(err)}`
|
|
2197
|
+
);
|
|
2198
|
+
}
|
|
2199
|
+
if (!isUnsignedEventShape(rumor)) {
|
|
2200
|
+
throw new GiftWrapDecryptError(
|
|
2201
|
+
"decrypted seal content is not a valid unsigned event (rumor)."
|
|
2202
|
+
);
|
|
2203
|
+
}
|
|
2204
|
+
return { rumor, sealPubkey: seal.pubkey };
|
|
2205
|
+
}
|
|
2206
|
+
|
|
1778
2207
|
// src/modes/http.ts
|
|
1779
2208
|
import { BootstrapService, createDiscoveryTracker } from "@toon-protocol/core";
|
|
1780
2209
|
|
|
@@ -1969,14 +2398,14 @@ var HttpRuntimeClient = class {
|
|
|
1969
2398
|
// src/btp/IsomorphicBtpClient.ts
|
|
1970
2399
|
var textEncoder2 = new TextEncoder();
|
|
1971
2400
|
var BtpConnectionError = class extends Error {
|
|
1972
|
-
constructor(
|
|
1973
|
-
super(
|
|
2401
|
+
constructor(message2) {
|
|
2402
|
+
super(message2);
|
|
1974
2403
|
this.name = "BtpConnectionError";
|
|
1975
2404
|
}
|
|
1976
2405
|
};
|
|
1977
2406
|
var BtpAuthError = class extends Error {
|
|
1978
|
-
constructor(
|
|
1979
|
-
super(
|
|
2407
|
+
constructor(message2) {
|
|
2408
|
+
super(message2);
|
|
1980
2409
|
this.name = "BtpAuthError";
|
|
1981
2410
|
}
|
|
1982
2411
|
};
|
|
@@ -1985,6 +2414,17 @@ var IsomorphicBtpClient = class {
|
|
|
1985
2414
|
_isConnected = false;
|
|
1986
2415
|
requestIdCounter = 0;
|
|
1987
2416
|
pendingRequests = /* @__PURE__ */ new Map();
|
|
2417
|
+
/**
|
|
2418
|
+
* requestIds of server-originated MESSAGE/TRANSFER frames whose handler
|
|
2419
|
+
* has not yet replied. A wholly separate space from `pendingRequests`
|
|
2420
|
+
* (client-allocated ids awaiting a RESPONSE/ERROR): this client never
|
|
2421
|
+
* resolves a `pendingRequests` entry from an inbound MESSAGE/TRANSFER, and
|
|
2422
|
+
* never answers an inbound MESSAGE/TRANSFER as though it were one of its
|
|
2423
|
+
* own — the two are correlated purely by BTP frame type, not by whether an
|
|
2424
|
+
* id happens to collide (toon-client#493).
|
|
2425
|
+
*/
|
|
2426
|
+
inFlightInbound = /* @__PURE__ */ new Set();
|
|
2427
|
+
/** Config keys that stay optional after defaults are applied — everything else becomes required. */
|
|
1988
2428
|
config;
|
|
1989
2429
|
constructor(config) {
|
|
1990
2430
|
this.config = {
|
|
@@ -2040,6 +2480,7 @@ var IsomorphicBtpClient = class {
|
|
|
2040
2480
|
pending.reject(new BtpConnectionError("Connection closed"));
|
|
2041
2481
|
this.pendingRequests.delete(id);
|
|
2042
2482
|
}
|
|
2483
|
+
this.failInFlightInbound("Connection closed before inbound request could be answered");
|
|
2043
2484
|
};
|
|
2044
2485
|
});
|
|
2045
2486
|
}
|
|
@@ -2054,6 +2495,7 @@ var IsomorphicBtpClient = class {
|
|
|
2054
2495
|
pending.reject(new BtpConnectionError("Disconnected"));
|
|
2055
2496
|
this.pendingRequests.delete(id);
|
|
2056
2497
|
}
|
|
2498
|
+
this.failInFlightInbound("Disconnected before inbound request could be answered");
|
|
2057
2499
|
}
|
|
2058
2500
|
/**
|
|
2059
2501
|
* Send an ILP PREPARE packet, optionally with protocol data (e.g. payment channel claim).
|
|
@@ -2147,18 +2589,18 @@ var IsomorphicBtpClient = class {
|
|
|
2147
2589
|
}
|
|
2148
2590
|
} catch {
|
|
2149
2591
|
}
|
|
2150
|
-
const
|
|
2151
|
-
if (
|
|
2592
|
+
const message2 = parseBtpMessage(data);
|
|
2593
|
+
if (message2.requestId === requestId) {
|
|
2152
2594
|
clearTimeout(timeout);
|
|
2153
2595
|
this.ws.onmessage = originalHandler;
|
|
2154
|
-
if (
|
|
2155
|
-
const errData =
|
|
2596
|
+
if (message2.type === BTPMessageType.ERROR) {
|
|
2597
|
+
const errData = message2.data;
|
|
2156
2598
|
reject(
|
|
2157
2599
|
new BtpAuthError(
|
|
2158
2600
|
`Authentication failed: ${errData.code} msg=${errData.message ?? ""} trigger=${errData.triggeredAt ?? ""}`
|
|
2159
2601
|
)
|
|
2160
2602
|
);
|
|
2161
|
-
} else if (
|
|
2603
|
+
} else if (message2.type === BTPMessageType.RESPONSE) {
|
|
2162
2604
|
resolve();
|
|
2163
2605
|
}
|
|
2164
2606
|
}
|
|
@@ -2209,28 +2651,138 @@ var IsomorphicBtpClient = class {
|
|
|
2209
2651
|
}
|
|
2210
2652
|
try {
|
|
2211
2653
|
const data = this.toUint8Array(raw);
|
|
2212
|
-
const
|
|
2213
|
-
if (
|
|
2214
|
-
const pending = this.pendingRequests.get(
|
|
2654
|
+
const message2 = parseBtpMessage(data);
|
|
2655
|
+
if (message2.type === BTPMessageType.RESPONSE || message2.type === BTPMessageType.ERROR) {
|
|
2656
|
+
const pending = this.pendingRequests.get(message2.requestId);
|
|
2215
2657
|
if (!pending) return;
|
|
2216
2658
|
clearTimeout(pending.timeoutId);
|
|
2217
|
-
this.pendingRequests.delete(
|
|
2218
|
-
if (
|
|
2219
|
-
const errData =
|
|
2659
|
+
this.pendingRequests.delete(message2.requestId);
|
|
2660
|
+
if (message2.type === BTPMessageType.ERROR) {
|
|
2661
|
+
const errData = message2.data;
|
|
2220
2662
|
pending.reject(
|
|
2221
2663
|
new BtpConnectionError(`BTP error: ${errData.code} ${errData.name}`)
|
|
2222
2664
|
);
|
|
2223
2665
|
return;
|
|
2224
2666
|
}
|
|
2225
|
-
const msgData =
|
|
2667
|
+
const msgData = message2.data;
|
|
2226
2668
|
if (msgData.ilpPacket && msgData.ilpPacket.length > 0) {
|
|
2227
2669
|
const ilpResponse = deserializeIlpPacket(msgData.ilpPacket);
|
|
2228
2670
|
pending.resolve(ilpResponse);
|
|
2229
2671
|
}
|
|
2672
|
+
return;
|
|
2673
|
+
}
|
|
2674
|
+
if (message2.type === BTPMessageType.MESSAGE) {
|
|
2675
|
+
this.handleInboundMessage(message2.requestId, message2.data);
|
|
2676
|
+
return;
|
|
2677
|
+
}
|
|
2678
|
+
if (message2.type === BTPMessageType.TRANSFER) {
|
|
2679
|
+
this.handleInboundTransfer(message2.requestId, message2.data);
|
|
2680
|
+
return;
|
|
2230
2681
|
}
|
|
2231
2682
|
} catch {
|
|
2232
2683
|
}
|
|
2233
2684
|
}
|
|
2685
|
+
handleInboundMessage(requestId, data) {
|
|
2686
|
+
const handler = this.config.onMessage;
|
|
2687
|
+
if (!handler) return;
|
|
2688
|
+
this.dispatchInbound(
|
|
2689
|
+
requestId,
|
|
2690
|
+
() => handler({
|
|
2691
|
+
requestId,
|
|
2692
|
+
protocolData: data.protocolData ?? [],
|
|
2693
|
+
ilpPacket: data.ilpPacket
|
|
2694
|
+
})
|
|
2695
|
+
);
|
|
2696
|
+
}
|
|
2697
|
+
handleInboundTransfer(requestId, data) {
|
|
2698
|
+
const handler = this.config.onTransfer;
|
|
2699
|
+
this.dispatchInbound(
|
|
2700
|
+
requestId,
|
|
2701
|
+
() => handler ? handler({
|
|
2702
|
+
requestId,
|
|
2703
|
+
amount: data.amount,
|
|
2704
|
+
protocolData: data.protocolData ?? []
|
|
2705
|
+
}) : {}
|
|
2706
|
+
);
|
|
2707
|
+
}
|
|
2708
|
+
dispatchInbound(requestId, invoke) {
|
|
2709
|
+
this.inFlightInbound.add(requestId);
|
|
2710
|
+
Promise.resolve().then(invoke).then(
|
|
2711
|
+
(result) => this.replyToInbound(requestId, result ?? {}),
|
|
2712
|
+
(err) => this.replyToInboundError(requestId, err)
|
|
2713
|
+
);
|
|
2714
|
+
}
|
|
2715
|
+
/** True if the reply is still owed — false means a disconnect already failed it loudly. */
|
|
2716
|
+
takeInFlight(requestId) {
|
|
2717
|
+
return this.inFlightInbound.delete(requestId);
|
|
2718
|
+
}
|
|
2719
|
+
replyToInbound(requestId, result) {
|
|
2720
|
+
if (!this.takeInFlight(requestId)) return;
|
|
2721
|
+
this.sendInboundReply(
|
|
2722
|
+
requestId,
|
|
2723
|
+
"",
|
|
2724
|
+
() => serializeBtpMessage({
|
|
2725
|
+
type: BTPMessageType.RESPONSE,
|
|
2726
|
+
requestId,
|
|
2727
|
+
data: {
|
|
2728
|
+
protocolData: result.protocolData ?? [],
|
|
2729
|
+
ilpPacket: result.ilpPacket ?? new Uint8Array(0)
|
|
2730
|
+
}
|
|
2731
|
+
})
|
|
2732
|
+
);
|
|
2733
|
+
}
|
|
2734
|
+
replyToInboundError(requestId, error) {
|
|
2735
|
+
if (!this.takeInFlight(requestId)) return;
|
|
2736
|
+
const message2 = error instanceof Error ? error.message : String(error);
|
|
2737
|
+
this.sendInboundReply(
|
|
2738
|
+
requestId,
|
|
2739
|
+
` (handler error: ${message2})`,
|
|
2740
|
+
() => serializeBtpMessage({
|
|
2741
|
+
type: BTPMessageType.ERROR,
|
|
2742
|
+
requestId,
|
|
2743
|
+
data: {
|
|
2744
|
+
code: "F00",
|
|
2745
|
+
name: "NotAcceptedError",
|
|
2746
|
+
triggeredAt: "",
|
|
2747
|
+
message: message2,
|
|
2748
|
+
data: textEncoder2.encode(message2)
|
|
2749
|
+
}
|
|
2750
|
+
})
|
|
2751
|
+
);
|
|
2752
|
+
}
|
|
2753
|
+
/**
|
|
2754
|
+
* Sends a RESPONSE/ERROR frame answering an inbound request, reporting
|
|
2755
|
+
* through `onInboundError` (never throwing) if the socket is gone or
|
|
2756
|
+
* `send` itself fails. `notConnectedSuffix` lets the caller fold in extra
|
|
2757
|
+
* context (e.g. the handler error that `replyToInboundError` is reporting)
|
|
2758
|
+
* when the "not connected" case fires.
|
|
2759
|
+
*/
|
|
2760
|
+
sendInboundReply(requestId, notConnectedSuffix, build) {
|
|
2761
|
+
if (!this._isConnected || !this.ws) {
|
|
2762
|
+
this.config.onInboundError?.(
|
|
2763
|
+
new BtpConnectionError(
|
|
2764
|
+
`Cannot answer inbound request ${requestId}: not connected${notConnectedSuffix}`
|
|
2765
|
+
),
|
|
2766
|
+
requestId
|
|
2767
|
+
);
|
|
2768
|
+
return;
|
|
2769
|
+
}
|
|
2770
|
+
try {
|
|
2771
|
+
this.ws.send(build());
|
|
2772
|
+
} catch (err) {
|
|
2773
|
+
this.config.onInboundError?.(
|
|
2774
|
+
err instanceof Error ? err : new Error(String(err)),
|
|
2775
|
+
requestId
|
|
2776
|
+
);
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
/** Fail every inbound request still awaiting its handler, loudly rather than silently. */
|
|
2780
|
+
failInFlightInbound(reason) {
|
|
2781
|
+
for (const requestId of this.inFlightInbound) {
|
|
2782
|
+
this.config.onInboundError?.(new BtpConnectionError(reason), requestId);
|
|
2783
|
+
}
|
|
2784
|
+
this.inFlightInbound.clear();
|
|
2785
|
+
}
|
|
2234
2786
|
toUint8Array(data) {
|
|
2235
2787
|
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
2236
2788
|
if (data instanceof Uint8Array) return data;
|
|
@@ -2339,7 +2891,10 @@ var BtpRuntimeClient = class {
|
|
|
2339
2891
|
url: this.config.btpUrl,
|
|
2340
2892
|
peerId: this.config.peerId,
|
|
2341
2893
|
authToken: this.config.authToken,
|
|
2342
|
-
createWebSocket: this.config.createWebSocket
|
|
2894
|
+
createWebSocket: this.config.createWebSocket,
|
|
2895
|
+
onMessage: this.config.onMessage,
|
|
2896
|
+
onTransfer: this.config.onTransfer,
|
|
2897
|
+
onInboundError: this.config.onInboundError
|
|
2343
2898
|
});
|
|
2344
2899
|
await this.btpClient.connect();
|
|
2345
2900
|
this._isConnected = true;
|
|
@@ -2711,28 +3266,168 @@ async function makeBtpWebSocketFactory(headers) {
|
|
|
2711
3266
|
);
|
|
2712
3267
|
}
|
|
2713
3268
|
|
|
2714
|
-
// src/adapters/
|
|
2715
|
-
function
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
httpEndpoint: typeof p["httpEndpoint"] === "string" ? p["httpEndpoint"] : void 0,
|
|
2720
|
-
supportsUpgrade: typeof p["supportsUpgrade"] === "boolean" ? p["supportsUpgrade"] : void 0
|
|
2721
|
-
};
|
|
3269
|
+
// src/adapters/BtpPaidWriteTransport.ts
|
|
3270
|
+
function isConnectionError2(error) {
|
|
3271
|
+
if (!(error instanceof Error)) return false;
|
|
3272
|
+
const msg = error.message.toLowerCase();
|
|
3273
|
+
return msg.includes("not connected") || msg.includes("connection") || msg.includes("websocket") || msg.includes("econnrefused") || msg.includes("econnreset") || msg.includes("socket hang up") || msg.includes("timeout");
|
|
2722
3274
|
}
|
|
2723
|
-
function
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
3275
|
+
function sleep(ms) {
|
|
3276
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
3277
|
+
}
|
|
3278
|
+
var BtpPaidWriteTransport = class {
|
|
3279
|
+
session;
|
|
3280
|
+
fallback;
|
|
3281
|
+
maxReconnectAttempts;
|
|
3282
|
+
reconnectDelay;
|
|
3283
|
+
/**
|
|
3284
|
+
* Tail of the ordering queue. ALWAYS settles (never rejects) so one
|
|
3285
|
+
* failed write can never strand every write queued behind it — only the
|
|
3286
|
+
* write itself carries its own outcome, via the promise `sendIlpPacketWithClaim`
|
|
3287
|
+
* returns to its caller.
|
|
3288
|
+
*/
|
|
3289
|
+
queueTail = Promise.resolve();
|
|
3290
|
+
constructor(config) {
|
|
3291
|
+
this.session = config.session;
|
|
3292
|
+
this.fallback = config.fallback;
|
|
3293
|
+
this.maxReconnectAttempts = config.maxReconnectAttempts ?? 1;
|
|
3294
|
+
this.reconnectDelay = config.reconnectDelay ?? 250;
|
|
3295
|
+
}
|
|
3296
|
+
/** Whether the underlying session currently holds an open socket. */
|
|
3297
|
+
get isConnected() {
|
|
3298
|
+
return this.session.isConnected;
|
|
3299
|
+
}
|
|
3300
|
+
/** Explicitly closes the persistent session (e.g. `ToonClient.stop()`). */
|
|
3301
|
+
async disconnect() {
|
|
3302
|
+
await this.session.disconnect();
|
|
3303
|
+
}
|
|
3304
|
+
/**
|
|
3305
|
+
* Enqueue a claim-bearing write. The returned promise resolves/rejects
|
|
3306
|
+
* with THIS write's own outcome; its position in the queue only controls
|
|
3307
|
+
* WHEN it is dispatched onto the wire, never what it returns.
|
|
3308
|
+
*/
|
|
3309
|
+
sendIlpPacketWithClaim(params, claim) {
|
|
3310
|
+
const dispatched = this.queueTail.then(
|
|
3311
|
+
() => this.dispatchWithRetry(params, claim)
|
|
3312
|
+
);
|
|
3313
|
+
this.queueTail = dispatched.then(
|
|
3314
|
+
() => void 0,
|
|
3315
|
+
() => void 0
|
|
3316
|
+
);
|
|
3317
|
+
return dispatched;
|
|
3318
|
+
}
|
|
3319
|
+
/**
|
|
3320
|
+
* One write's worth of connect/send/reconnect/fallback policy. Runs
|
|
3321
|
+
* strictly after every write enqueued ahead of it has settled.
|
|
3322
|
+
*/
|
|
3323
|
+
async dispatchWithRetry(params, claim) {
|
|
3324
|
+
let attempt = 0;
|
|
3325
|
+
let lastError;
|
|
3326
|
+
while (attempt <= this.maxReconnectAttempts) {
|
|
3327
|
+
try {
|
|
3328
|
+
if (!this.session.isConnected) {
|
|
3329
|
+
if (attempt === 0) {
|
|
3330
|
+
await this.session.connect();
|
|
3331
|
+
} else {
|
|
3332
|
+
await sleep(this.reconnectDelay * attempt);
|
|
3333
|
+
await this.session.reconnect();
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
return await this.session.sendIlpPacketWithClaim(
|
|
3337
|
+
params,
|
|
3338
|
+
claim
|
|
3339
|
+
);
|
|
3340
|
+
} catch (error) {
|
|
3341
|
+
lastError = error;
|
|
3342
|
+
if (!isConnectionError2(error)) {
|
|
3343
|
+
throw error;
|
|
3344
|
+
}
|
|
3345
|
+
attempt += 1;
|
|
3346
|
+
}
|
|
3347
|
+
}
|
|
3348
|
+
if (this.fallback) {
|
|
3349
|
+
return this.fallback.sendIlpPacketWithClaim(params, claim);
|
|
3350
|
+
}
|
|
3351
|
+
throw lastError instanceof Error ? lastError : new NetworkError(
|
|
3352
|
+
"BTP paid-write transport exhausted its reconnect budget and no HTTP fallback is configured"
|
|
3353
|
+
);
|
|
3354
|
+
}
|
|
3355
|
+
};
|
|
3356
|
+
|
|
3357
|
+
// src/serve-job.ts
|
|
3358
|
+
var errText = (e) => e instanceof Error ? e.message : String(e);
|
|
3359
|
+
function rejectResponse(code, message2, triggeredBy) {
|
|
3360
|
+
return {
|
|
3361
|
+
ilpPacket: serializeIlpReject({
|
|
3362
|
+
code,
|
|
3363
|
+
...triggeredBy !== void 0 ? { triggeredBy } : {},
|
|
3364
|
+
message: message2,
|
|
3365
|
+
data: new Uint8Array(0)
|
|
3366
|
+
})
|
|
3367
|
+
};
|
|
3368
|
+
}
|
|
3369
|
+
function createJobMessageHandler(handler) {
|
|
3370
|
+
return async (message2) => {
|
|
3371
|
+
if (!message2.ilpPacket || message2.ilpPacket.length === 0) {
|
|
3372
|
+
return {};
|
|
3373
|
+
}
|
|
3374
|
+
let job;
|
|
3375
|
+
try {
|
|
3376
|
+
job = deserializeIlpPrepare(message2.ilpPacket);
|
|
3377
|
+
} catch (error) {
|
|
3378
|
+
return rejectResponse("F00", `undecodable PREPARE: ${errText(error)}`);
|
|
3379
|
+
}
|
|
3380
|
+
if (job.expiresAt.getTime() <= Date.now()) {
|
|
3381
|
+
return rejectResponse(
|
|
3382
|
+
"R00",
|
|
3383
|
+
"PREPARE already expired; the handler was never invoked",
|
|
3384
|
+
job.destination
|
|
3385
|
+
);
|
|
3386
|
+
}
|
|
3387
|
+
let answer;
|
|
3388
|
+
try {
|
|
3389
|
+
answer = await handler(job);
|
|
3390
|
+
} catch (error) {
|
|
3391
|
+
return rejectResponse("F99", errText(error), job.destination);
|
|
3392
|
+
}
|
|
3393
|
+
if (!fulfillmentMatchesCondition(answer.fulfillment, job.executionCondition)) {
|
|
3394
|
+
return rejectResponse(
|
|
3395
|
+
"F99",
|
|
3396
|
+
"handler fulfillment does not match the PREPARE execution condition",
|
|
3397
|
+
job.destination
|
|
3398
|
+
);
|
|
3399
|
+
}
|
|
3400
|
+
return {
|
|
3401
|
+
ilpPacket: serializeIlpFulfill({
|
|
3402
|
+
fulfillment: answer.fulfillment,
|
|
3403
|
+
data: answer.data ?? new Uint8Array(0)
|
|
3404
|
+
})
|
|
3405
|
+
};
|
|
3406
|
+
};
|
|
3407
|
+
}
|
|
3408
|
+
|
|
3409
|
+
// src/adapters/selectIlpTransport.ts
|
|
3410
|
+
function readDiscoveredIlpPeer(peer) {
|
|
3411
|
+
const p = peer ?? {};
|
|
3412
|
+
return {
|
|
3413
|
+
btpEndpoint: typeof p["btpEndpoint"] === "string" ? p["btpEndpoint"] : void 0,
|
|
3414
|
+
httpEndpoint: typeof p["httpEndpoint"] === "string" ? p["httpEndpoint"] : void 0,
|
|
3415
|
+
supportsUpgrade: typeof p["supportsUpgrade"] === "boolean" ? p["supportsUpgrade"] : void 0
|
|
3416
|
+
};
|
|
3417
|
+
}
|
|
3418
|
+
function selectIlpTransport(peer, options = {}) {
|
|
3419
|
+
const needsDuplex = options.needsDuplex ?? false;
|
|
3420
|
+
const http5 = peer.httpEndpoint?.trim() || void 0;
|
|
3421
|
+
const btp = peer.btpEndpoint?.trim() || void 0;
|
|
3422
|
+
const canUpgrade = peer.supportsUpgrade === true;
|
|
3423
|
+
if (needsDuplex) {
|
|
2729
3424
|
if (btp) return { kind: "btp", btpEndpoint: btp };
|
|
2730
|
-
if (
|
|
3425
|
+
if (http5 && canUpgrade) return { kind: "http-upgradable", httpEndpoint: http5 };
|
|
2731
3426
|
throw new Error(
|
|
2732
3427
|
"Duplex transport required but peer exposes neither a btpEndpoint nor an upgradable httpEndpoint"
|
|
2733
3428
|
);
|
|
2734
3429
|
}
|
|
2735
|
-
if (
|
|
3430
|
+
if (http5) return { kind: "http", httpEndpoint: http5, canUpgrade };
|
|
2736
3431
|
if (btp) return { kind: "btp", btpEndpoint: btp };
|
|
2737
3432
|
throw new Error("Peer exposes neither an httpEndpoint nor a btpEndpoint");
|
|
2738
3433
|
}
|
|
@@ -2877,11 +3572,11 @@ function deriveVaultPDA(channelPDA, programId) {
|
|
|
2877
3572
|
return { pda: base58Encode(pda), bump };
|
|
2878
3573
|
}
|
|
2879
3574
|
function buildBalanceProofMessage(channelPDA, nonce, transferredAmount) {
|
|
2880
|
-
const
|
|
2881
|
-
|
|
2882
|
-
writeU64LE(
|
|
2883
|
-
writeU64LE(
|
|
2884
|
-
return
|
|
3575
|
+
const message2 = new Uint8Array(48);
|
|
3576
|
+
message2.set(padTo32(base58Decode(channelPDA)), 0);
|
|
3577
|
+
writeU64LE(message2, 32, nonce);
|
|
3578
|
+
writeU64LE(message2, 40, transferredAmount);
|
|
3579
|
+
return message2;
|
|
2885
3580
|
}
|
|
2886
3581
|
var rpcIdCounter = 1;
|
|
2887
3582
|
var SolanaRpcError = class extends Error {
|
|
@@ -3075,28 +3770,28 @@ async function buildAndSendTransaction(rpcUrl, feePayer, instructions, additiona
|
|
|
3075
3770
|
instructionSize += compactU16Size(ix.data.length) + ix.data.length;
|
|
3076
3771
|
}
|
|
3077
3772
|
const messageSize = 3 + compactU16Size(accounts.length) + 32 * accounts.length + 32 + instructionSize;
|
|
3078
|
-
const
|
|
3773
|
+
const message2 = new Uint8Array(messageSize);
|
|
3079
3774
|
let offset = 0;
|
|
3080
|
-
|
|
3081
|
-
|
|
3082
|
-
|
|
3083
|
-
offset = writeCompactU16(
|
|
3775
|
+
message2[offset++] = numSigners;
|
|
3776
|
+
message2[offset++] = numReadonlySigners;
|
|
3777
|
+
message2[offset++] = numReadonlyNonSigners;
|
|
3778
|
+
offset = writeCompactU16(message2, offset, accounts.length);
|
|
3084
3779
|
for (const acct of accounts) {
|
|
3085
|
-
|
|
3780
|
+
message2.set(padTo32(base58Decode(acct.pubkey)), offset);
|
|
3086
3781
|
offset += 32;
|
|
3087
3782
|
}
|
|
3088
|
-
|
|
3783
|
+
message2.set(padTo32(blockhashBytes), offset);
|
|
3089
3784
|
offset += 32;
|
|
3090
|
-
offset = writeCompactU16(
|
|
3785
|
+
offset = writeCompactU16(message2, offset, compiled.length);
|
|
3091
3786
|
for (const ix of compiled) {
|
|
3092
|
-
|
|
3093
|
-
offset = writeCompactU16(
|
|
3094
|
-
for (const idx of ix.accountIndices)
|
|
3095
|
-
offset = writeCompactU16(
|
|
3096
|
-
|
|
3787
|
+
message2[offset++] = ix.programIdIndex;
|
|
3788
|
+
offset = writeCompactU16(message2, offset, ix.accountIndices.length);
|
|
3789
|
+
for (const idx of ix.accountIndices) message2[offset++] = idx;
|
|
3790
|
+
offset = writeCompactU16(message2, offset, ix.data.length);
|
|
3791
|
+
message2.set(ix.data, offset);
|
|
3097
3792
|
offset += ix.data.length;
|
|
3098
3793
|
}
|
|
3099
|
-
const finalMessage =
|
|
3794
|
+
const finalMessage = message2.slice(0, offset);
|
|
3100
3795
|
const allSigners = [feePayer, ...additionalSigners];
|
|
3101
3796
|
const signerPubkeys = accounts.filter((a) => a.isSigner).map((a) => a.pubkey);
|
|
3102
3797
|
const signatures = [];
|
|
@@ -3416,17 +4111,55 @@ var STATE_MAP2 = {
|
|
|
3416
4111
|
2: "closed",
|
|
3417
4112
|
3: "settled"
|
|
3418
4113
|
};
|
|
4114
|
+
var DEFAULT_READ_CONSISTENCY = {
|
|
4115
|
+
attempts: 12,
|
|
4116
|
+
delayMs: 1e3,
|
|
4117
|
+
depositRetries: 3
|
|
4118
|
+
};
|
|
4119
|
+
var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
4120
|
+
function isInvalidChannelStateRevert(err) {
|
|
4121
|
+
const parts = [];
|
|
4122
|
+
let cur = err;
|
|
4123
|
+
for (let i = 0; i < 10 && cur != null; i++) {
|
|
4124
|
+
parts.push(cur instanceof Error ? cur.message : String(cur));
|
|
4125
|
+
cur = cur instanceof Error ? cur.cause : void 0;
|
|
4126
|
+
}
|
|
4127
|
+
const text = parts.join(" | ").toLowerCase();
|
|
4128
|
+
return text.includes("0xf806e9d9") || text.includes("invalidchannelstate");
|
|
4129
|
+
}
|
|
4130
|
+
function sleep2(ms) {
|
|
4131
|
+
return ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
|
|
4132
|
+
}
|
|
3419
4133
|
var OnChainChannelClient = class {
|
|
3420
4134
|
evmSigner;
|
|
3421
4135
|
chainRpcUrls;
|
|
3422
4136
|
solanaConfig;
|
|
3423
4137
|
minaConfig;
|
|
3424
4138
|
channelContext = /* @__PURE__ */ new Map();
|
|
4139
|
+
readConsistency;
|
|
3425
4140
|
constructor(config) {
|
|
3426
4141
|
this.evmSigner = config.evmSigner;
|
|
3427
4142
|
this.chainRpcUrls = config.chainRpcUrls;
|
|
3428
4143
|
this.solanaConfig = config.solanaConfig;
|
|
3429
4144
|
this.minaConfig = config.minaConfig;
|
|
4145
|
+
this.readConsistency = {
|
|
4146
|
+
...DEFAULT_READ_CONSISTENCY,
|
|
4147
|
+
...config.readConsistency
|
|
4148
|
+
};
|
|
4149
|
+
}
|
|
4150
|
+
/**
|
|
4151
|
+
* Adopt a channel this process did NOT open — a RESUMED one (#489), whose
|
|
4152
|
+
* chain/token-network/token context came back from the channel store rather
|
|
4153
|
+
* than from an `openChannel` call. Without it a restarted client can track
|
|
4154
|
+
* and pay on a resumed channel but cannot deposit into, close, or read it,
|
|
4155
|
+
* because those all look up the in-memory `channelContext` this seeds.
|
|
4156
|
+
*/
|
|
4157
|
+
adoptChannel(channelId, ctx) {
|
|
4158
|
+
this.channelContext.set(channelId, {
|
|
4159
|
+
chain: ctx.chain,
|
|
4160
|
+
tokenNetworkAddress: ctx.tokenNetworkAddress,
|
|
4161
|
+
...ctx.tokenAddress ? { tokenAddress: ctx.tokenAddress } : {}
|
|
4162
|
+
});
|
|
3430
4163
|
}
|
|
3431
4164
|
/**
|
|
3432
4165
|
* Late-binds the Solana channel config.
|
|
@@ -4020,16 +4753,91 @@ var OnChainChannelClient = class {
|
|
|
4020
4753
|
...params.token ? { tokenAddress: params.token } : {}
|
|
4021
4754
|
});
|
|
4022
4755
|
if (deposit > 0n) {
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
|
|
4027
|
-
|
|
4756
|
+
await this.waitForEvmChannelVisible(
|
|
4757
|
+
publicClient,
|
|
4758
|
+
tokenNetworkAddr,
|
|
4759
|
+
channelId,
|
|
4760
|
+
chain
|
|
4761
|
+
);
|
|
4762
|
+
await this.setTotalDepositWithRetry({
|
|
4763
|
+
publicClient,
|
|
4764
|
+
walletClient,
|
|
4765
|
+
tokenNetworkAddr,
|
|
4766
|
+
channelId,
|
|
4767
|
+
total: deposit,
|
|
4768
|
+
chain
|
|
4028
4769
|
});
|
|
4029
|
-
await publicClient.waitForTransactionReceipt({ hash: depositHash });
|
|
4030
4770
|
}
|
|
4031
4771
|
return { channelId, status: "opening" };
|
|
4032
4772
|
}
|
|
4773
|
+
/**
|
|
4774
|
+
* Poll the TokenNetwork until it reports the just-opened channel (non-zero
|
|
4775
|
+
* `participant1`). Tolerates a read that throws or returns nothing — a stale
|
|
4776
|
+
* replica does both — and surfaces a {@link StaleRpcReadError} naming the RPC
|
|
4777
|
+
* when the endpoint never converges.
|
|
4778
|
+
*/
|
|
4779
|
+
async waitForEvmChannelVisible(publicClient, tokenNetworkAddr, channelId, chain) {
|
|
4780
|
+
const { attempts, delayMs } = this.readConsistency;
|
|
4781
|
+
let lastError;
|
|
4782
|
+
for (let i = 0; i < attempts; i++) {
|
|
4783
|
+
if (i > 0) await sleep2(delayMs);
|
|
4784
|
+
try {
|
|
4785
|
+
const res = await publicClient.readContract({
|
|
4786
|
+
address: tokenNetworkAddr,
|
|
4787
|
+
abi: TOKEN_NETWORK_ABI,
|
|
4788
|
+
functionName: "channels",
|
|
4789
|
+
args: [channelId]
|
|
4790
|
+
});
|
|
4791
|
+
const participant1 = res?.[4];
|
|
4792
|
+
if (typeof participant1 === "string" && participant1.toLowerCase() !== ZERO_ADDRESS) {
|
|
4793
|
+
return;
|
|
4794
|
+
}
|
|
4795
|
+
} catch (err) {
|
|
4796
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
4797
|
+
}
|
|
4798
|
+
}
|
|
4799
|
+
throw new StaleRpcReadError(
|
|
4800
|
+
`Channel ${channelId} was opened on ${chain} but ${this.chainRpcUrls[chain] ?? "the configured RPC"} still does not report it after ${attempts} reads. This is the stale-read failure of a load-balanced endpoint (e.g. \`https://sepolia.base.org\`) \u2014 point \`chainRpcUrls\` at a read-after-write consistent RPC such as \`https://base-sepolia-rpc.publicnode.com\` and retry. The channel IS open on-chain; it just has no collateral yet.`,
|
|
4801
|
+
lastError
|
|
4802
|
+
);
|
|
4803
|
+
}
|
|
4804
|
+
/**
|
|
4805
|
+
* `setTotalDeposit`, retried on `InvalidChannelState()` — the revert a stale
|
|
4806
|
+
* replica produces for a channel it hasn't observed. Every other revert
|
|
4807
|
+
* propagates immediately (an under-funded wallet must not be retried).
|
|
4808
|
+
*/
|
|
4809
|
+
async setTotalDepositWithRetry(args) {
|
|
4810
|
+
const { depositRetries, delayMs } = this.readConsistency;
|
|
4811
|
+
for (let attempt = 0; ; attempt++) {
|
|
4812
|
+
try {
|
|
4813
|
+
const depositHash = await args.walletClient.writeContract({
|
|
4814
|
+
address: args.tokenNetworkAddr,
|
|
4815
|
+
abi: TOKEN_NETWORK_ABI,
|
|
4816
|
+
functionName: "setTotalDeposit",
|
|
4817
|
+
args: [
|
|
4818
|
+
args.channelId,
|
|
4819
|
+
this.evmSigner.address,
|
|
4820
|
+
args.total
|
|
4821
|
+
]
|
|
4822
|
+
});
|
|
4823
|
+
await args.publicClient.waitForTransactionReceipt({
|
|
4824
|
+
hash: depositHash
|
|
4825
|
+
});
|
|
4826
|
+
return;
|
|
4827
|
+
} catch (err) {
|
|
4828
|
+
if (attempt >= depositRetries || !isInvalidChannelStateRevert(err)) {
|
|
4829
|
+
throw err;
|
|
4830
|
+
}
|
|
4831
|
+
await sleep2(delayMs);
|
|
4832
|
+
await this.waitForEvmChannelVisible(
|
|
4833
|
+
args.publicClient,
|
|
4834
|
+
args.tokenNetworkAddr,
|
|
4835
|
+
args.channelId,
|
|
4836
|
+
args.chain
|
|
4837
|
+
);
|
|
4838
|
+
}
|
|
4839
|
+
}
|
|
4840
|
+
}
|
|
4033
4841
|
/**
|
|
4034
4842
|
* Gets the current state of a payment channel from on-chain data.
|
|
4035
4843
|
*/
|
|
@@ -4088,6 +4896,12 @@ var BALANCE_PROOF_TYPES = {
|
|
|
4088
4896
|
{ name: "locksRoot", type: "bytes32" }
|
|
4089
4897
|
]
|
|
4090
4898
|
};
|
|
4899
|
+
var CLAIM_STATE_CHALLENGE_TYPES = {
|
|
4900
|
+
ClaimStateChallenge: [
|
|
4901
|
+
{ name: "channelId", type: "bytes32" },
|
|
4902
|
+
{ name: "expires", type: "uint256" }
|
|
4903
|
+
]
|
|
4904
|
+
};
|
|
4091
4905
|
var EvmSigner = class {
|
|
4092
4906
|
chainType = "evm";
|
|
4093
4907
|
_account;
|
|
@@ -4151,6 +4965,32 @@ var EvmSigner = class {
|
|
|
4151
4965
|
...params.tokenAddress && { tokenAddress: params.tokenAddress }
|
|
4152
4966
|
};
|
|
4153
4967
|
}
|
|
4968
|
+
/**
|
|
4969
|
+
* Signs a `POST /ilp/claim-state` claim-state challenge (client-edge-spec.md
|
|
4970
|
+
* §1.10): proves ownership of `channelId` without moving any value or
|
|
4971
|
+
* advancing the channel's nonce — this is a READ, not a claim. Read the
|
|
4972
|
+
* connector's answer for the actual credited/available balance (toon-meta#262
|
|
4973
|
+
* decision 9); this signature only unlocks the read.
|
|
4974
|
+
*
|
|
4975
|
+
* @param params.expires - Unix seconds the signature stops verifying.
|
|
4976
|
+
* Reissue with a fresh value whenever an outstanding one should stop
|
|
4977
|
+
* being trusted — the endpoint has no other replay bound.
|
|
4978
|
+
*/
|
|
4979
|
+
async signClaimStateChallenge(params) {
|
|
4980
|
+
const domain = getBalanceProofDomain(
|
|
4981
|
+
params.chainId,
|
|
4982
|
+
params.tokenNetworkAddress
|
|
4983
|
+
);
|
|
4984
|
+
return this._account.signTypedData({
|
|
4985
|
+
domain,
|
|
4986
|
+
types: CLAIM_STATE_CHALLENGE_TYPES,
|
|
4987
|
+
primaryType: "ClaimStateChallenge",
|
|
4988
|
+
message: {
|
|
4989
|
+
channelId: params.channelId,
|
|
4990
|
+
expires: BigInt(params.expires)
|
|
4991
|
+
}
|
|
4992
|
+
});
|
|
4993
|
+
}
|
|
4154
4994
|
/**
|
|
4155
4995
|
* Builds an EVMClaimMessage from a signed balance proof.
|
|
4156
4996
|
* Static so it can be called without an EvmSigner instance.
|
|
@@ -4196,7 +5036,12 @@ async function initializeHttpMode(config) {
|
|
|
4196
5036
|
btpClient = new BtpRuntimeClient({
|
|
4197
5037
|
btpUrl: effectiveBtpUrl,
|
|
4198
5038
|
peerId: config.btpPeerId ?? `client`,
|
|
4199
|
-
authToken: config.btpAuthToken ?? ""
|
|
5039
|
+
authToken: config.btpAuthToken ?? "",
|
|
5040
|
+
// Serve-side job registration (toon-client#494): a connector-originated
|
|
5041
|
+
// MESSAGE carrying a PREPARE is answered by the configured handler.
|
|
5042
|
+
// Unset `jobHandler` leaves `onMessage` unset too, so an inbound job
|
|
5043
|
+
// MESSAGE is dropped unanswered — unchanged from the pre-#494 default.
|
|
5044
|
+
...config.jobHandler ? { onMessage: createJobMessageHandler(config.jobHandler) } : {}
|
|
4200
5045
|
});
|
|
4201
5046
|
await btpClient.connect();
|
|
4202
5047
|
}
|
|
@@ -4217,6 +5062,10 @@ async function initializeHttpMode(config) {
|
|
|
4217
5062
|
maxRetries: config.maxRetries,
|
|
4218
5063
|
retryDelay: config.retryDelay
|
|
4219
5064
|
});
|
|
5065
|
+
const paidWriteBtpClient = btpClient && config.preferBtpForPaidWrites ? new BtpPaidWriteTransport({
|
|
5066
|
+
session: btpClient,
|
|
5067
|
+
...httpIlpClient ? { fallback: httpIlpClient } : {}
|
|
5068
|
+
}) : btpClient;
|
|
4220
5069
|
let onChainChannelClient = null;
|
|
4221
5070
|
if (config.chainRpcUrls) {
|
|
4222
5071
|
const evmSigner = new EvmSigner(config.evmPrivateKey);
|
|
@@ -4260,14 +5109,17 @@ async function initializeHttpMode(config) {
|
|
|
4260
5109
|
discoveryTracker,
|
|
4261
5110
|
runtimeClient,
|
|
4262
5111
|
adminClient: null,
|
|
4263
|
-
btpClient,
|
|
5112
|
+
btpClient: paidWriteBtpClient,
|
|
4264
5113
|
onChainChannelClient
|
|
4265
5114
|
};
|
|
4266
5115
|
}
|
|
4267
5116
|
|
|
4268
5117
|
// src/signing/solana-signer.ts
|
|
4269
5118
|
import { ed25519 as ed255193 } from "@noble/curves/ed25519.js";
|
|
4270
|
-
import { base58Encode as base58Encode3 } from "@toon-protocol/core";
|
|
5119
|
+
import { base58Encode as base58Encode3, base58Decode as base58Decode2 } from "@toon-protocol/core";
|
|
5120
|
+
var CLAIM_STATE_CHALLENGE_TAG = new TextEncoder().encode(
|
|
5121
|
+
"toon-claim-state-challenge-v1"
|
|
5122
|
+
);
|
|
4271
5123
|
var SolanaSigner = class {
|
|
4272
5124
|
chainType = "solana";
|
|
4273
5125
|
/** 32-byte Ed25519 seed. */
|
|
@@ -4303,12 +5155,12 @@ var SolanaSigner = class {
|
|
|
4303
5155
|
);
|
|
4304
5156
|
}
|
|
4305
5157
|
const base58 = this.ensurePublicKey();
|
|
4306
|
-
const
|
|
5158
|
+
const message2 = buildBalanceProofMessage(
|
|
4307
5159
|
params.channelId,
|
|
4308
5160
|
BigInt(params.nonce),
|
|
4309
5161
|
params.transferredAmount
|
|
4310
5162
|
);
|
|
4311
|
-
const signature = ed255193.sign(
|
|
5163
|
+
const signature = ed255193.sign(message2, this.privateKey);
|
|
4312
5164
|
const signatureHex = "0x" + toHex2(new Uint8Array(signature));
|
|
4313
5165
|
return {
|
|
4314
5166
|
channelId: params.channelId,
|
|
@@ -4323,6 +5175,37 @@ var SolanaSigner = class {
|
|
|
4323
5175
|
recipient: params.recipient
|
|
4324
5176
|
};
|
|
4325
5177
|
}
|
|
5178
|
+
/**
|
|
5179
|
+
* Signs a `POST /ilp/claim-state` claim-state challenge (client-edge-spec.md
|
|
5180
|
+
* §1.10): `"toon-claim-state-challenge-v1" || channelAccount(32) ||
|
|
5181
|
+
* expires(u64 LE)` — a tagged message distinct in both content and length
|
|
5182
|
+
* from a real 48-byte balance-proof message, so a captured challenge can
|
|
5183
|
+
* never be replayed as a payment or vice versa. Returns base64 (the
|
|
5184
|
+
* connector's documented wire encoding for this endpoint, unlike the
|
|
5185
|
+
* hex-encoded balance-proof signature elsewhere in this class).
|
|
5186
|
+
*
|
|
5187
|
+
* @param params.expires - Unix seconds the signature stops verifying.
|
|
5188
|
+
*/
|
|
5189
|
+
async signClaimStateChallenge(params) {
|
|
5190
|
+
const accountBytes = base58Decode2(params.channelAccount);
|
|
5191
|
+
if (accountBytes.length !== 32) {
|
|
5192
|
+
throw new Error(
|
|
5193
|
+
`channelAccount must decode to 32 bytes, got ${accountBytes.length}`
|
|
5194
|
+
);
|
|
5195
|
+
}
|
|
5196
|
+
const tag = CLAIM_STATE_CHALLENGE_TAG;
|
|
5197
|
+
const message2 = new Uint8Array(tag.length + 32 + 8);
|
|
5198
|
+
message2.set(tag, 0);
|
|
5199
|
+
message2.set(accountBytes, tag.length);
|
|
5200
|
+
new DataView(message2.buffer).setBigUint64(
|
|
5201
|
+
tag.length + 32,
|
|
5202
|
+
BigInt(params.expires),
|
|
5203
|
+
true
|
|
5204
|
+
// little-endian
|
|
5205
|
+
);
|
|
5206
|
+
const signature = ed255193.sign(message2, this.privateKey);
|
|
5207
|
+
return Buffer.from(signature).toString("base64");
|
|
5208
|
+
}
|
|
4326
5209
|
buildClaimMessage(proof, senderId) {
|
|
4327
5210
|
const sigHex = proof.signature.startsWith("0x") ? proof.signature.slice(2) : proof.signature;
|
|
4328
5211
|
const sigBytes = Uint8Array.from(
|
|
@@ -4428,8 +5311,8 @@ async function buildMinaPaymentChannelProof(params) {
|
|
|
4428
5311
|
params.participantB,
|
|
4429
5312
|
params.channelNonce ?? 0n
|
|
4430
5313
|
) : minaChannelHashField(Poseidon, PublicKey, params.zkAppAddress);
|
|
4431
|
-
const
|
|
4432
|
-
const signed = client.signFields(
|
|
5314
|
+
const message2 = [commitment, params.nonce, channelHashField];
|
|
5315
|
+
const signed = client.signFields(message2, params.minaPrivateKeyBase58);
|
|
4433
5316
|
const { r, s } = Signature.fromBase58(signed.signature);
|
|
4434
5317
|
const proofObject = {
|
|
4435
5318
|
commitment: commitment.toString(),
|
|
@@ -4682,7 +5565,7 @@ var MinaSigner = class {
|
|
|
4682
5565
|
};
|
|
4683
5566
|
|
|
4684
5567
|
// src/channel/ChannelManager.ts
|
|
4685
|
-
var ChannelManager = class {
|
|
5568
|
+
var ChannelManager = class _ChannelManager {
|
|
4686
5569
|
channels = /* @__PURE__ */ new Map();
|
|
4687
5570
|
chainSigners = /* @__PURE__ */ new Map();
|
|
4688
5571
|
peerChannels = /* @__PURE__ */ new Map();
|
|
@@ -4750,15 +5633,34 @@ var ChannelManager = class {
|
|
|
4750
5633
|
`No signer registered for chain type: ${tracking.chainType}`
|
|
4751
5634
|
);
|
|
4752
5635
|
}
|
|
5636
|
+
/**
|
|
5637
|
+
* The key a peer's channel binding is persisted under: the peer, the
|
|
5638
|
+
* negotiated chain, and the token network the channel lives on. All three
|
|
5639
|
+
* matter — the same peer on a second chain (or a redeployed token network) is
|
|
5640
|
+
* a DIFFERENT channel.
|
|
5641
|
+
*/
|
|
5642
|
+
static bindingKey(peerId, negotiation) {
|
|
5643
|
+
return `${peerId}|${negotiation.chain}|${negotiation.tokenNetwork ?? ""}`;
|
|
5644
|
+
}
|
|
4753
5645
|
/**
|
|
4754
5646
|
* Lazily open a channel for a peer. Idempotent — returns existing channel
|
|
4755
5647
|
* if already open. Deduplicates concurrent opens for the same peer.
|
|
5648
|
+
*
|
|
5649
|
+
* RESUME (#489): before opening anything on-chain, the persisted peer→channel
|
|
5650
|
+
* binding is consulted, so a restarted process re-attaches to the channel it
|
|
5651
|
+
* already holds instead of locking a second lot of collateral. Solana got this
|
|
5652
|
+
* for free (its channel id is a deterministic PDA, so a re-open re-derived the
|
|
5653
|
+
* same channel); EVM mints a fresh `bytes32` per `openChannel` call, so every
|
|
5654
|
+
* restart stranded a deposit until this binding existed.
|
|
4756
5655
|
*/
|
|
4757
5656
|
async ensureChannel(peerId, negotiation) {
|
|
4758
|
-
const
|
|
5657
|
+
const key2 = _ChannelManager.bindingKey(peerId, negotiation);
|
|
5658
|
+
const existing = this.peerChannels.get(key2);
|
|
4759
5659
|
if (existing) return existing;
|
|
4760
|
-
const pending = this.pendingOpens.get(
|
|
5660
|
+
const pending = this.pendingOpens.get(key2);
|
|
4761
5661
|
if (pending) return pending;
|
|
5662
|
+
const resumed = this.resumeChannel(peerId, negotiation);
|
|
5663
|
+
if (resumed) return resumed;
|
|
4762
5664
|
if (!this.channelClient) {
|
|
4763
5665
|
throw new Error(
|
|
4764
5666
|
"No channel client configured \u2014 cannot open payment channel"
|
|
@@ -4775,30 +5677,140 @@ var ChannelManager = class {
|
|
|
4775
5677
|
initialDeposit: negotiation.initialDeposit ?? this.defaultInitialDeposit,
|
|
4776
5678
|
settlementTimeout: negotiation.settlementTimeout ?? this.defaultSettlementTimeout
|
|
4777
5679
|
});
|
|
4778
|
-
|
|
5680
|
+
const context = {
|
|
4779
5681
|
chainType: negotiation.chainType,
|
|
4780
5682
|
chainId: typeof negotiation.chainId === "number" ? negotiation.chainId : 0,
|
|
4781
5683
|
tokenNetworkAddress: negotiation.tokenNetwork ?? "",
|
|
4782
5684
|
tokenAddress: negotiation.tokenAddress,
|
|
4783
|
-
recipient: negotiation.settlementAddress
|
|
5685
|
+
recipient: negotiation.settlementAddress
|
|
5686
|
+
};
|
|
5687
|
+
this.trackChannel(result.channelId, {
|
|
5688
|
+
...context,
|
|
4784
5689
|
// On-chain depositTotal (Mina only) — needed so the Mina signer binds
|
|
4785
5690
|
// balanceB = depositTotal − balanceA (connector#133).
|
|
4786
5691
|
depositTotal: result.depositTotal
|
|
4787
5692
|
});
|
|
4788
|
-
this.peerChannels.set(
|
|
5693
|
+
this.peerChannels.set(key2, result.channelId);
|
|
5694
|
+
this.bindChannel(key2, result.channelId, context, {
|
|
5695
|
+
...result.depositTotal !== void 0 ? { depositTotal: result.depositTotal } : {}
|
|
5696
|
+
});
|
|
4789
5697
|
return result.channelId;
|
|
4790
5698
|
} finally {
|
|
4791
|
-
this.pendingOpens.delete(
|
|
5699
|
+
this.pendingOpens.delete(key2);
|
|
4792
5700
|
}
|
|
4793
5701
|
})();
|
|
4794
|
-
this.pendingOpens.set(
|
|
5702
|
+
this.pendingOpens.set(key2, openPromise);
|
|
4795
5703
|
return openPromise;
|
|
4796
5704
|
}
|
|
4797
5705
|
/**
|
|
4798
|
-
*
|
|
5706
|
+
* Adopt an ALREADY-OPEN channel as this peer's channel: track it (rehydrating
|
|
5707
|
+
* its watermark from the store), bind it so later lazy opens RESUME it rather
|
|
5708
|
+
* than opening a second one, and hand the on-chain client its context back.
|
|
5709
|
+
*
|
|
5710
|
+
* For a host that persisted the channel id itself before the client could
|
|
5711
|
+
* (the MCP daemon's apex-channel store, rig's channel map): those hosts used
|
|
5712
|
+
* to `trackChannel` on restart, which left `ensureChannel` unaware — so the
|
|
5713
|
+
* first paid write opened a SECOND on-chain channel anyway (#489).
|
|
5714
|
+
*/
|
|
5715
|
+
adoptChannel(peerId, negotiation, channelId) {
|
|
5716
|
+
const key2 = _ChannelManager.bindingKey(peerId, negotiation);
|
|
5717
|
+
const context = {
|
|
5718
|
+
chainType: negotiation.chainType,
|
|
5719
|
+
chainId: typeof negotiation.chainId === "number" ? negotiation.chainId : 0,
|
|
5720
|
+
tokenNetworkAddress: negotiation.tokenNetwork ?? "",
|
|
5721
|
+
tokenAddress: negotiation.tokenAddress,
|
|
5722
|
+
recipient: negotiation.settlementAddress
|
|
5723
|
+
};
|
|
5724
|
+
this.trackChannel(channelId, context);
|
|
5725
|
+
this.peerChannels.set(key2, channelId);
|
|
5726
|
+
this.bindChannel(key2, channelId, context, {});
|
|
5727
|
+
this.adoptOnChainContext(channelId, negotiation);
|
|
5728
|
+
}
|
|
5729
|
+
/**
|
|
5730
|
+
* Re-attach to the channel this identity already holds with `peerId`, from the
|
|
5731
|
+
* store's peer→channel binding. Returns the resumed channel id, or undefined
|
|
5732
|
+
* when there is nothing to resume (no store, no binding, or a binding whose
|
|
5733
|
+
* channel is closing/settled — a spent channel must not be reused).
|
|
5734
|
+
*
|
|
5735
|
+
* `trackChannel` rehydrates the nonce/cumulative watermark from the store, so
|
|
5736
|
+
* the resumed channel keeps signing ABOVE the last claim the connector saw.
|
|
5737
|
+
*
|
|
5738
|
+
* @throws {ChannelResumeError} when the binding's watermark is missing —
|
|
5739
|
+
* resuming would silently reset the nonce and every later claim would be
|
|
5740
|
+
* rejected (F01), so the caller is told loudly instead.
|
|
5741
|
+
*/
|
|
5742
|
+
resumeChannel(peerId, negotiation) {
|
|
5743
|
+
const store = this.store;
|
|
5744
|
+
if (!store?.loadBinding) return void 0;
|
|
5745
|
+
const key2 = _ChannelManager.bindingKey(peerId, negotiation);
|
|
5746
|
+
const binding = store.loadBinding(key2);
|
|
5747
|
+
if (!binding) return void 0;
|
|
5748
|
+
const watermark = store.load(binding.channelId);
|
|
5749
|
+
if (!watermark) {
|
|
5750
|
+
throw new ChannelResumeError(
|
|
5751
|
+
`Payment channel "${binding.channelId}" is bound to peer "${peerId}" on ${negotiation.chain}, but its claim watermark is missing from the channel store. Resuming would restart the nonce at 0 and the connector would reject every claim; opening a new channel would strand the collateral already locked in this one. Restore the channel store file, or settle the channel on-chain and remove its binding (key "${key2}") before retrying.`
|
|
5752
|
+
);
|
|
5753
|
+
}
|
|
5754
|
+
if (watermark.closedAt !== void 0 || watermark.settledAt !== void 0) {
|
|
5755
|
+
store.deleteBinding?.(key2);
|
|
5756
|
+
return void 0;
|
|
5757
|
+
}
|
|
5758
|
+
this.trackChannel(binding.channelId, {
|
|
5759
|
+
...binding.context,
|
|
5760
|
+
...binding.depositTotal !== void 0 ? { depositTotal: binding.depositTotal } : {}
|
|
5761
|
+
});
|
|
5762
|
+
this.peerChannels.set(key2, binding.channelId);
|
|
5763
|
+
this.adoptOnChainContext(binding.channelId, negotiation);
|
|
5764
|
+
return binding.channelId;
|
|
5765
|
+
}
|
|
5766
|
+
/**
|
|
5767
|
+
* Persist a freshly opened channel as this peer's binding, and SEED its
|
|
5768
|
+
* watermark entry (`nonce 0`) so a later resume can tell "never claimed
|
|
5769
|
+
* against" apart from "watermark lost" (which is a hard
|
|
5770
|
+
* {@link ChannelResumeError}).
|
|
5771
|
+
*/
|
|
5772
|
+
bindChannel(key2, channelId, context, extra) {
|
|
5773
|
+
const store = this.store;
|
|
5774
|
+
if (!store?.saveBinding) return;
|
|
5775
|
+
if (!store.load(channelId)) {
|
|
5776
|
+
const tracking = this.channels.get(channelId);
|
|
5777
|
+
store.save(channelId, {
|
|
5778
|
+
nonce: tracking?.nonce ?? 0,
|
|
5779
|
+
cumulativeAmount: tracking?.cumulativeAmount ?? 0n
|
|
5780
|
+
});
|
|
5781
|
+
}
|
|
5782
|
+
store.saveBinding(key2, {
|
|
5783
|
+
channelId,
|
|
5784
|
+
context,
|
|
5785
|
+
...extra.depositTotal !== void 0 ? { depositTotal: extra.depositTotal } : {}
|
|
5786
|
+
});
|
|
5787
|
+
}
|
|
5788
|
+
/**
|
|
5789
|
+
* Re-seed the on-chain client's per-channel context for a RESUMED channel.
|
|
5790
|
+
* `OnChainChannelClient` caches `chain`/`tokenNetwork`/`token` only for
|
|
5791
|
+
* channels it opened in this process, so without this a resumed channel
|
|
5792
|
+
* cannot be deposited into or closed. Optional capability — a channel client
|
|
5793
|
+
* that doesn't implement `adoptChannel` is simply left alone.
|
|
5794
|
+
*/
|
|
5795
|
+
adoptOnChainContext(channelId, negotiation) {
|
|
5796
|
+
const client = this.channelClient;
|
|
5797
|
+
if (!client?.adoptChannel || !negotiation.tokenNetwork) return;
|
|
5798
|
+
client.adoptChannel(channelId, {
|
|
5799
|
+
chain: negotiation.chain,
|
|
5800
|
+
tokenNetworkAddress: negotiation.tokenNetwork,
|
|
5801
|
+
...negotiation.tokenAddress ? { tokenAddress: negotiation.tokenAddress } : {}
|
|
5802
|
+
});
|
|
5803
|
+
}
|
|
5804
|
+
/**
|
|
5805
|
+
* Get channel ID for a peer (if any). Channels are held per peer AND chain
|
|
5806
|
+
* AND token network, so a peer settled with on two chains has two — this
|
|
5807
|
+
* returns the first one tracked for the peer.
|
|
4799
5808
|
*/
|
|
4800
5809
|
getChannelForPeer(peerId) {
|
|
4801
|
-
|
|
5810
|
+
for (const [key2, channelId] of this.peerChannels) {
|
|
5811
|
+
if (key2 === peerId || key2.startsWith(`${peerId}|`)) return channelId;
|
|
5812
|
+
}
|
|
5813
|
+
return void 0;
|
|
4802
5814
|
}
|
|
4803
5815
|
/**
|
|
4804
5816
|
* Start tracking a channel.
|
|
@@ -5027,14 +6039,38 @@ var ChannelManager = class {
|
|
|
5027
6039
|
isTracking(channelId) {
|
|
5028
6040
|
return this.channels.has(channelId);
|
|
5029
6041
|
}
|
|
6042
|
+
/**
|
|
6043
|
+
* The chain context a tracked channel was opened/resumed with — the
|
|
6044
|
+
* chainType/chainId/tokenNetworkAddress a caller needs to build a
|
|
6045
|
+
* `POST /ilp/claim-state` request (toon-client#494) without re-deriving
|
|
6046
|
+
* them from the peer negotiation. `undefined` when `channelId` is not
|
|
6047
|
+
* tracked.
|
|
6048
|
+
*/
|
|
6049
|
+
getChannelContext(channelId) {
|
|
6050
|
+
const tracking = this.channels.get(channelId);
|
|
6051
|
+
if (!tracking) return void 0;
|
|
6052
|
+
return {
|
|
6053
|
+
chainType: tracking.chainType,
|
|
6054
|
+
chainId: tracking.chainId,
|
|
6055
|
+
tokenNetworkAddress: tracking.tokenNetworkAddress,
|
|
6056
|
+
...tracking.tokenAddress !== void 0 ? { tokenAddress: tracking.tokenAddress } : {},
|
|
6057
|
+
...tracking.recipient !== void 0 ? { recipient: tracking.recipient } : {}
|
|
6058
|
+
};
|
|
6059
|
+
}
|
|
5030
6060
|
};
|
|
5031
6061
|
|
|
5032
6062
|
// src/channel/ChannelStore.ts
|
|
5033
|
-
import { readFileSync, writeFileSync, existsSync } from "fs";
|
|
6063
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
|
|
6064
|
+
import { dirname } from "path";
|
|
6065
|
+
function defaultBindingsPath(filePath) {
|
|
6066
|
+
return filePath.replace(/\.json$/i, "") + ".peers.json";
|
|
6067
|
+
}
|
|
5034
6068
|
var JsonFileChannelStore = class {
|
|
5035
6069
|
filePath;
|
|
5036
|
-
|
|
6070
|
+
bindingsPath;
|
|
6071
|
+
constructor(filePath, options) {
|
|
5037
6072
|
this.filePath = filePath;
|
|
6073
|
+
this.bindingsPath = options?.bindingsPath ?? defaultBindingsPath(filePath);
|
|
5038
6074
|
}
|
|
5039
6075
|
save(channelId, tracking) {
|
|
5040
6076
|
const data = this.readFile();
|
|
@@ -5067,6 +6103,33 @@ var JsonFileChannelStore = class {
|
|
|
5067
6103
|
const { [channelId]: _, ...rest } = data;
|
|
5068
6104
|
this.writeFile(rest);
|
|
5069
6105
|
}
|
|
6106
|
+
saveBinding(key2, binding) {
|
|
6107
|
+
const data = this.readBindings();
|
|
6108
|
+
data[key2] = {
|
|
6109
|
+
channelId: binding.channelId,
|
|
6110
|
+
context: binding.context,
|
|
6111
|
+
...binding.depositTotal !== void 0 ? { depositTotal: binding.depositTotal.toString() } : {},
|
|
6112
|
+
openedAt: binding.openedAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
6113
|
+
};
|
|
6114
|
+
this.writeBindings(data);
|
|
6115
|
+
}
|
|
6116
|
+
loadBinding(key2) {
|
|
6117
|
+
const entry = this.readBindings()[key2];
|
|
6118
|
+
if (!entry) return void 0;
|
|
6119
|
+
return toBinding(entry);
|
|
6120
|
+
}
|
|
6121
|
+
listBindings() {
|
|
6122
|
+
return Object.entries(this.readBindings()).map(([key2, entry]) => ({
|
|
6123
|
+
key: key2,
|
|
6124
|
+
binding: toBinding(entry)
|
|
6125
|
+
}));
|
|
6126
|
+
}
|
|
6127
|
+
deleteBinding(key2) {
|
|
6128
|
+
const data = this.readBindings();
|
|
6129
|
+
if (!(key2 in data)) return;
|
|
6130
|
+
const { [key2]: _removed, ...rest } = data;
|
|
6131
|
+
this.writeBindings(rest);
|
|
6132
|
+
}
|
|
5070
6133
|
readFile() {
|
|
5071
6134
|
if (!existsSync(this.filePath)) {
|
|
5072
6135
|
return {};
|
|
@@ -5075,8 +6138,65 @@ var JsonFileChannelStore = class {
|
|
|
5075
6138
|
return JSON.parse(raw);
|
|
5076
6139
|
}
|
|
5077
6140
|
writeFile(data) {
|
|
6141
|
+
mkdirSync(dirname(this.filePath), { recursive: true });
|
|
5078
6142
|
writeFileSync(this.filePath, JSON.stringify(data, null, 2), "utf-8");
|
|
5079
6143
|
}
|
|
6144
|
+
readBindings() {
|
|
6145
|
+
if (!existsSync(this.bindingsPath)) return {};
|
|
6146
|
+
const raw = readFileSync(this.bindingsPath, "utf-8");
|
|
6147
|
+
return JSON.parse(raw);
|
|
6148
|
+
}
|
|
6149
|
+
writeBindings(data) {
|
|
6150
|
+
mkdirSync(dirname(this.bindingsPath), { recursive: true });
|
|
6151
|
+
writeFileSync(this.bindingsPath, JSON.stringify(data, null, 2), {
|
|
6152
|
+
encoding: "utf-8",
|
|
6153
|
+
mode: 384
|
|
6154
|
+
});
|
|
6155
|
+
}
|
|
6156
|
+
};
|
|
6157
|
+
function toBinding(entry) {
|
|
6158
|
+
return {
|
|
6159
|
+
channelId: entry.channelId,
|
|
6160
|
+
context: entry.context,
|
|
6161
|
+
...entry.depositTotal !== void 0 ? { depositTotal: BigInt(entry.depositTotal) } : {},
|
|
6162
|
+
...entry.openedAt !== void 0 ? { openedAt: entry.openedAt } : {}
|
|
6163
|
+
};
|
|
6164
|
+
}
|
|
6165
|
+
var InMemoryChannelStore = class {
|
|
6166
|
+
entries = /* @__PURE__ */ new Map();
|
|
6167
|
+
bindings = /* @__PURE__ */ new Map();
|
|
6168
|
+
save(channelId, tracking) {
|
|
6169
|
+
this.entries.set(channelId, { ...tracking });
|
|
6170
|
+
}
|
|
6171
|
+
load(channelId) {
|
|
6172
|
+
const entry = this.entries.get(channelId);
|
|
6173
|
+
return entry ? { ...entry } : void 0;
|
|
6174
|
+
}
|
|
6175
|
+
list() {
|
|
6176
|
+
return [...this.entries.keys()];
|
|
6177
|
+
}
|
|
6178
|
+
delete(channelId) {
|
|
6179
|
+
this.entries.delete(channelId);
|
|
6180
|
+
}
|
|
6181
|
+
saveBinding(key2, binding) {
|
|
6182
|
+
this.bindings.set(key2, {
|
|
6183
|
+
...binding,
|
|
6184
|
+
openedAt: binding.openedAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
6185
|
+
});
|
|
6186
|
+
}
|
|
6187
|
+
loadBinding(key2) {
|
|
6188
|
+
const binding = this.bindings.get(key2);
|
|
6189
|
+
return binding ? { ...binding } : void 0;
|
|
6190
|
+
}
|
|
6191
|
+
listBindings() {
|
|
6192
|
+
return [...this.bindings.entries()].map(([key2, binding]) => ({
|
|
6193
|
+
key: key2,
|
|
6194
|
+
binding: { ...binding }
|
|
6195
|
+
}));
|
|
6196
|
+
}
|
|
6197
|
+
deleteBinding(key2) {
|
|
6198
|
+
this.bindings.delete(key2);
|
|
6199
|
+
}
|
|
5080
6200
|
};
|
|
5081
6201
|
|
|
5082
6202
|
// src/balance/WalletBalanceReader.ts
|
|
@@ -5270,14 +6390,14 @@ async function readMinaTokenBalance(opts) {
|
|
|
5270
6390
|
assetScale: 6
|
|
5271
6391
|
};
|
|
5272
6392
|
}
|
|
5273
|
-
var
|
|
6393
|
+
var errText2 = (e) => e instanceof Error ? e.message : String(e);
|
|
5274
6394
|
function foldNative(out, settled, errors) {
|
|
5275
6395
|
if (settled.status === "fulfilled") out.native = settled.value;
|
|
5276
|
-
else errors.push(
|
|
6396
|
+
else errors.push(errText2(settled.reason));
|
|
5277
6397
|
}
|
|
5278
6398
|
function foldToken(out, settled, tokenAddress, errors) {
|
|
5279
6399
|
if (settled.status === "rejected") {
|
|
5280
|
-
errors.push(
|
|
6400
|
+
errors.push(errText2(settled.reason));
|
|
5281
6401
|
return;
|
|
5282
6402
|
}
|
|
5283
6403
|
const bal = settled.value;
|
|
@@ -5469,6 +6589,481 @@ function extractArweaveTxId(response) {
|
|
|
5469
6589
|
);
|
|
5470
6590
|
}
|
|
5471
6591
|
|
|
6592
|
+
// src/transfer.ts
|
|
6593
|
+
import {
|
|
6594
|
+
createPublicClient as createPublicClient3,
|
|
6595
|
+
createWalletClient as createWalletClient2,
|
|
6596
|
+
http as http3,
|
|
6597
|
+
defineChain as defineChain3
|
|
6598
|
+
} from "viem";
|
|
6599
|
+
import { ed25519 as ed255194 } from "@noble/curves/ed25519.js";
|
|
6600
|
+
import {
|
|
6601
|
+
base58Decode as base58Decode3,
|
|
6602
|
+
base58Encode as base58Encode4,
|
|
6603
|
+
hexToMinaBase58PrivateKey as hexToMinaBase58PrivateKey3
|
|
6604
|
+
} from "@toon-protocol/core";
|
|
6605
|
+
function assertValidEvmAddress(address) {
|
|
6606
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
|
|
6607
|
+
throw new InvalidAddressError(
|
|
6608
|
+
`"${address}" is not a valid EVM address (expected 0x + 40 hex chars).`
|
|
6609
|
+
);
|
|
6610
|
+
}
|
|
6611
|
+
}
|
|
6612
|
+
function assertValidSolanaAddress(address) {
|
|
6613
|
+
let decoded;
|
|
6614
|
+
try {
|
|
6615
|
+
decoded = base58Decode3(address);
|
|
6616
|
+
} catch (err) {
|
|
6617
|
+
throw new InvalidAddressError(
|
|
6618
|
+
`"${address}" is not valid base58 for a Solana address.`,
|
|
6619
|
+
err instanceof Error ? err : void 0
|
|
6620
|
+
);
|
|
6621
|
+
}
|
|
6622
|
+
if (decoded.length !== 32) {
|
|
6623
|
+
throw new InvalidAddressError(
|
|
6624
|
+
`"${address}" decodes to ${decoded.length} bytes, not the 32 a Solana address requires.`
|
|
6625
|
+
);
|
|
6626
|
+
}
|
|
6627
|
+
}
|
|
6628
|
+
function assertValidMinaAddress(address) {
|
|
6629
|
+
if (!/^B62[a-zA-Z0-9]{40,60}$/.test(address)) {
|
|
6630
|
+
throw new InvalidAddressError(
|
|
6631
|
+
`"${address}" is not a valid Mina (B62) address.`
|
|
6632
|
+
);
|
|
6633
|
+
}
|
|
6634
|
+
}
|
|
6635
|
+
var DEFAULT_POLL_INTERVAL_MS = 2e3;
|
|
6636
|
+
async function waitForBalanceDelta(opts) {
|
|
6637
|
+
const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
6638
|
+
const deadline = Date.now() + opts.timeoutMs;
|
|
6639
|
+
for (; ; ) {
|
|
6640
|
+
const current = await opts.readBalance();
|
|
6641
|
+
if (current - opts.before >= opts.minDelta) return current;
|
|
6642
|
+
if (Date.now() >= deadline) return current;
|
|
6643
|
+
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
|
6644
|
+
}
|
|
6645
|
+
}
|
|
6646
|
+
async function confirmDelivered(opts) {
|
|
6647
|
+
const after = await waitForBalanceDelta({
|
|
6648
|
+
readBalance: opts.readBalance,
|
|
6649
|
+
before: opts.before,
|
|
6650
|
+
minDelta: opts.amount,
|
|
6651
|
+
timeoutMs: opts.timeoutMs,
|
|
6652
|
+
pollIntervalMs: opts.pollIntervalMs
|
|
6653
|
+
});
|
|
6654
|
+
if (after - opts.before < opts.amount) {
|
|
6655
|
+
throw new TransferNotDeliveredError(
|
|
6656
|
+
opts.notDeliveredMessage(after - opts.before)
|
|
6657
|
+
);
|
|
6658
|
+
}
|
|
6659
|
+
return after;
|
|
6660
|
+
}
|
|
6661
|
+
function buildResult(chain, asset, to, amount, txHash, before, after) {
|
|
6662
|
+
return {
|
|
6663
|
+
chain,
|
|
6664
|
+
asset,
|
|
6665
|
+
to,
|
|
6666
|
+
amount: amount.toString(),
|
|
6667
|
+
txHash,
|
|
6668
|
+
balanceBefore: before.toString(),
|
|
6669
|
+
balanceAfter: after.toString()
|
|
6670
|
+
};
|
|
6671
|
+
}
|
|
6672
|
+
var DEFAULT_EVM_CONFIRM_TIMEOUT_MS = 3e4;
|
|
6673
|
+
var ERC20_TRANSFER_ABI = [
|
|
6674
|
+
{
|
|
6675
|
+
name: "balanceOf",
|
|
6676
|
+
type: "function",
|
|
6677
|
+
stateMutability: "view",
|
|
6678
|
+
inputs: [{ name: "account", type: "address" }],
|
|
6679
|
+
outputs: [{ type: "uint256" }]
|
|
6680
|
+
},
|
|
6681
|
+
{
|
|
6682
|
+
name: "transfer",
|
|
6683
|
+
type: "function",
|
|
6684
|
+
stateMutability: "nonpayable",
|
|
6685
|
+
inputs: [
|
|
6686
|
+
{ name: "to", type: "address" },
|
|
6687
|
+
{ name: "amount", type: "uint256" }
|
|
6688
|
+
],
|
|
6689
|
+
outputs: [{ type: "bool" }]
|
|
6690
|
+
}
|
|
6691
|
+
];
|
|
6692
|
+
function evmClients(cfg) {
|
|
6693
|
+
const chainId = parseEvmChainId(cfg.chainKey);
|
|
6694
|
+
const viemChain = defineChain3({
|
|
6695
|
+
id: chainId,
|
|
6696
|
+
name: cfg.chainKey,
|
|
6697
|
+
nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 },
|
|
6698
|
+
rpcUrls: { default: { http: [cfg.rpcUrl] } }
|
|
6699
|
+
});
|
|
6700
|
+
const publicClient = createPublicClient3({
|
|
6701
|
+
transport: http3(cfg.rpcUrl),
|
|
6702
|
+
chain: viemChain
|
|
6703
|
+
});
|
|
6704
|
+
const walletClient = createWalletClient2({
|
|
6705
|
+
account: cfg.signer.account,
|
|
6706
|
+
transport: http3(cfg.rpcUrl),
|
|
6707
|
+
chain: viemChain
|
|
6708
|
+
});
|
|
6709
|
+
return { publicClient, walletClient };
|
|
6710
|
+
}
|
|
6711
|
+
async function sendEvmTransfer(cfg, params, amount) {
|
|
6712
|
+
const { publicClient, walletClient } = evmClients(cfg);
|
|
6713
|
+
const from = cfg.signer.address;
|
|
6714
|
+
const to = params.to;
|
|
6715
|
+
const timeoutMs = params.confirmTimeoutMs ?? DEFAULT_EVM_CONFIRM_TIMEOUT_MS;
|
|
6716
|
+
if (params.asset === "native") {
|
|
6717
|
+
const senderBalance2 = await publicClient.getBalance({ address: from });
|
|
6718
|
+
if (senderBalance2 < amount) {
|
|
6719
|
+
throw new InsufficientBalanceError(
|
|
6720
|
+
`EVM wallet ${from} holds ${senderBalance2} wei, short of the ${amount} wei transfer (before gas).`
|
|
6721
|
+
);
|
|
6722
|
+
}
|
|
6723
|
+
const readDest2 = () => publicClient.getBalance({ address: to });
|
|
6724
|
+
const before2 = await readDest2();
|
|
6725
|
+
const txHash2 = await walletClient.sendTransaction({ to, value: amount });
|
|
6726
|
+
const receipt2 = await publicClient.waitForTransactionReceipt({
|
|
6727
|
+
hash: txHash2
|
|
6728
|
+
});
|
|
6729
|
+
if (receipt2.status === "reverted") {
|
|
6730
|
+
throw new TransferNotDeliveredError(
|
|
6731
|
+
`EVM native transfer ${txHash2} reverted on-chain \u2014 no funds reached ${to}.`
|
|
6732
|
+
);
|
|
6733
|
+
}
|
|
6734
|
+
const after2 = await confirmDelivered({
|
|
6735
|
+
readBalance: readDest2,
|
|
6736
|
+
before: before2,
|
|
6737
|
+
amount,
|
|
6738
|
+
timeoutMs,
|
|
6739
|
+
pollIntervalMs: params.confirmPollIntervalMs,
|
|
6740
|
+
notDeliveredMessage: (delta) => `EVM native transfer ${txHash2} confirmed on-chain, but ${to}'s balance only rose by ${delta} wei (expected ${amount}) within the wait window.`
|
|
6741
|
+
});
|
|
6742
|
+
return buildResult("evm", "native", params.to, amount, txHash2, before2, after2);
|
|
6743
|
+
}
|
|
6744
|
+
if (!cfg.tokenAddress) {
|
|
6745
|
+
throw new TransferUnsupportedError(
|
|
6746
|
+
`No settlement-token address configured for EVM chain "${cfg.chainKey}" \u2014 cannot send the token leg.`
|
|
6747
|
+
);
|
|
6748
|
+
}
|
|
6749
|
+
const tokenAddr = cfg.tokenAddress;
|
|
6750
|
+
const readSenderBalance = () => publicClient.readContract({
|
|
6751
|
+
address: tokenAddr,
|
|
6752
|
+
abi: ERC20_TRANSFER_ABI,
|
|
6753
|
+
functionName: "balanceOf",
|
|
6754
|
+
args: [from]
|
|
6755
|
+
});
|
|
6756
|
+
const readDest = () => publicClient.readContract({
|
|
6757
|
+
address: tokenAddr,
|
|
6758
|
+
abi: ERC20_TRANSFER_ABI,
|
|
6759
|
+
functionName: "balanceOf",
|
|
6760
|
+
args: [to]
|
|
6761
|
+
});
|
|
6762
|
+
const senderBalance = await readSenderBalance();
|
|
6763
|
+
if (senderBalance < amount) {
|
|
6764
|
+
throw new InsufficientBalanceError(
|
|
6765
|
+
`EVM wallet ${from} holds ${senderBalance} base units of ${tokenAddr}, short of the ${amount} transfer.`
|
|
6766
|
+
);
|
|
6767
|
+
}
|
|
6768
|
+
const before = await readDest();
|
|
6769
|
+
const txHash = await walletClient.writeContract({
|
|
6770
|
+
address: tokenAddr,
|
|
6771
|
+
abi: ERC20_TRANSFER_ABI,
|
|
6772
|
+
functionName: "transfer",
|
|
6773
|
+
args: [to, amount]
|
|
6774
|
+
});
|
|
6775
|
+
const receipt = await publicClient.waitForTransactionReceipt({
|
|
6776
|
+
hash: txHash
|
|
6777
|
+
});
|
|
6778
|
+
if (receipt.status === "reverted") {
|
|
6779
|
+
throw new TransferNotDeliveredError(
|
|
6780
|
+
`EVM token transfer ${txHash} reverted on-chain \u2014 no funds reached ${to}.`
|
|
6781
|
+
);
|
|
6782
|
+
}
|
|
6783
|
+
const after = await confirmDelivered({
|
|
6784
|
+
readBalance: readDest,
|
|
6785
|
+
before,
|
|
6786
|
+
amount,
|
|
6787
|
+
timeoutMs,
|
|
6788
|
+
pollIntervalMs: params.confirmPollIntervalMs,
|
|
6789
|
+
notDeliveredMessage: (delta) => `EVM token transfer ${txHash} confirmed on-chain, but ${to}'s balance only rose by ${delta} base units (expected ${amount}) within the wait window.`
|
|
6790
|
+
});
|
|
6791
|
+
return buildResult("evm", "token", params.to, amount, txHash, before, after);
|
|
6792
|
+
}
|
|
6793
|
+
var DEFAULT_SOLANA_CONFIRM_TIMEOUT_MS = 3e4;
|
|
6794
|
+
var SOLANA_SYSTEM_PROGRAM_ID = "11111111111111111111111111111111";
|
|
6795
|
+
var SOLANA_TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
|
|
6796
|
+
var SOLANA_ASSOCIATED_TOKEN_PROGRAM_ID = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
|
|
6797
|
+
var SOLANA_LAMPORTS_PER_SIGNATURE = 5000n;
|
|
6798
|
+
function writeU64LE2(buf, offset, value) {
|
|
6799
|
+
for (let i = 0; i < 8; i++) {
|
|
6800
|
+
buf[offset + i] = Number(value >> BigInt(i * 8) & 0xffn);
|
|
6801
|
+
}
|
|
6802
|
+
}
|
|
6803
|
+
async function sendSolanaTransfer(cfg, params, amount) {
|
|
6804
|
+
const payerSeed = cfg.keypair.slice(0, 32);
|
|
6805
|
+
const payerPubkey = base58Encode4(
|
|
6806
|
+
new Uint8Array(ed255194.getPublicKey(payerSeed))
|
|
6807
|
+
);
|
|
6808
|
+
const payer = { publicKey: base58Decode3(payerPubkey), privateKey: payerSeed };
|
|
6809
|
+
const timeoutMs = params.confirmTimeoutMs ?? DEFAULT_SOLANA_CONFIRM_TIMEOUT_MS;
|
|
6810
|
+
if (params.asset === "native") {
|
|
6811
|
+
const lamports2 = await getLamports(cfg.rpcUrl, payerPubkey);
|
|
6812
|
+
const need = amount + SOLANA_LAMPORTS_PER_SIGNATURE;
|
|
6813
|
+
if (lamports2 < need) {
|
|
6814
|
+
throw new InsufficientBalanceError(
|
|
6815
|
+
`Solana wallet ${payerPubkey} holds ${lamports2} lamports, short of the ${amount}-lamport transfer plus the ${SOLANA_LAMPORTS_PER_SIGNATURE}-lamport signature fee.`
|
|
6816
|
+
);
|
|
6817
|
+
}
|
|
6818
|
+
const readDest2 = () => getLamports(cfg.rpcUrl, params.to);
|
|
6819
|
+
const before2 = await readDest2();
|
|
6820
|
+
const data = new Uint8Array(12);
|
|
6821
|
+
new DataView(data.buffer).setUint32(0, 2, true);
|
|
6822
|
+
writeU64LE2(data, 4, amount);
|
|
6823
|
+
const txHash2 = await buildAndSendTransaction(cfg.rpcUrl, payer, [
|
|
6824
|
+
{
|
|
6825
|
+
programId: SOLANA_SYSTEM_PROGRAM_ID,
|
|
6826
|
+
keys: [
|
|
6827
|
+
{ pubkey: payerPubkey, isSigner: true, isWritable: true },
|
|
6828
|
+
{ pubkey: params.to, isSigner: false, isWritable: true }
|
|
6829
|
+
],
|
|
6830
|
+
data
|
|
6831
|
+
}
|
|
6832
|
+
]);
|
|
6833
|
+
const after2 = await confirmDelivered({
|
|
6834
|
+
readBalance: readDest2,
|
|
6835
|
+
before: before2,
|
|
6836
|
+
amount,
|
|
6837
|
+
timeoutMs,
|
|
6838
|
+
pollIntervalMs: params.confirmPollIntervalMs,
|
|
6839
|
+
notDeliveredMessage: (delta) => `Solana native transfer ${txHash2} confirmed on-chain, but ${params.to}'s balance only rose by ${delta} lamports (expected ${amount}) within the wait window \u2014 the devnet faucet's Solana leg has shown exactly this shape (connector#691): a real transaction signature with 0 lamports delivered.`
|
|
6840
|
+
});
|
|
6841
|
+
return buildResult(
|
|
6842
|
+
"solana",
|
|
6843
|
+
"native",
|
|
6844
|
+
params.to,
|
|
6845
|
+
amount,
|
|
6846
|
+
txHash2,
|
|
6847
|
+
before2,
|
|
6848
|
+
after2
|
|
6849
|
+
);
|
|
6850
|
+
}
|
|
6851
|
+
if (!cfg.tokenMint) {
|
|
6852
|
+
throw new TransferUnsupportedError(
|
|
6853
|
+
"No settlement-token mint configured for Solana \u2014 cannot send the token leg."
|
|
6854
|
+
);
|
|
6855
|
+
}
|
|
6856
|
+
const senderAta = deriveAssociatedTokenAccount(payerPubkey, cfg.tokenMint);
|
|
6857
|
+
const senderBalance = await getTokenAccountBalance(cfg.rpcUrl, senderAta);
|
|
6858
|
+
if (senderBalance === null || senderBalance < amount) {
|
|
6859
|
+
throw new InsufficientBalanceError(
|
|
6860
|
+
`Solana token account ${senderAta} holds ${senderBalance ?? 0n} base units of ${cfg.tokenMint}, short of the ${amount} transfer.`
|
|
6861
|
+
);
|
|
6862
|
+
}
|
|
6863
|
+
const lamports = await getLamports(cfg.rpcUrl, payerPubkey);
|
|
6864
|
+
if (lamports < SOLANA_LAMPORTS_PER_SIGNATURE) {
|
|
6865
|
+
throw new InsufficientBalanceError(
|
|
6866
|
+
`Solana wallet ${payerPubkey} holds ${lamports} lamports, below the ${SOLANA_LAMPORTS_PER_SIGNATURE}-lamport fee this token transfer needs.`
|
|
6867
|
+
);
|
|
6868
|
+
}
|
|
6869
|
+
const destAta = deriveAssociatedTokenAccount(params.to, cfg.tokenMint);
|
|
6870
|
+
const readDest = async () => await getTokenAccountBalance(cfg.rpcUrl, destAta) ?? 0n;
|
|
6871
|
+
const before = await readDest();
|
|
6872
|
+
const createAtaIx = {
|
|
6873
|
+
programId: SOLANA_ASSOCIATED_TOKEN_PROGRAM_ID,
|
|
6874
|
+
keys: [
|
|
6875
|
+
{ pubkey: payerPubkey, isSigner: true, isWritable: true },
|
|
6876
|
+
{ pubkey: destAta, isSigner: false, isWritable: true },
|
|
6877
|
+
{ pubkey: params.to, isSigner: false, isWritable: false },
|
|
6878
|
+
{ pubkey: cfg.tokenMint, isSigner: false, isWritable: false },
|
|
6879
|
+
{ pubkey: SOLANA_SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },
|
|
6880
|
+
{ pubkey: SOLANA_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false }
|
|
6881
|
+
],
|
|
6882
|
+
data: new Uint8Array([1])
|
|
6883
|
+
};
|
|
6884
|
+
const transferData = new Uint8Array(9);
|
|
6885
|
+
transferData[0] = 3;
|
|
6886
|
+
writeU64LE2(transferData, 1, amount);
|
|
6887
|
+
const transferIx = {
|
|
6888
|
+
programId: SOLANA_TOKEN_PROGRAM_ID,
|
|
6889
|
+
keys: [
|
|
6890
|
+
{ pubkey: senderAta, isSigner: false, isWritable: true },
|
|
6891
|
+
{ pubkey: destAta, isSigner: false, isWritable: true },
|
|
6892
|
+
{ pubkey: payerPubkey, isSigner: true, isWritable: false }
|
|
6893
|
+
],
|
|
6894
|
+
data: transferData
|
|
6895
|
+
};
|
|
6896
|
+
const txHash = await buildAndSendTransaction(cfg.rpcUrl, payer, [
|
|
6897
|
+
createAtaIx,
|
|
6898
|
+
transferIx
|
|
6899
|
+
]);
|
|
6900
|
+
const after = await confirmDelivered({
|
|
6901
|
+
readBalance: readDest,
|
|
6902
|
+
before,
|
|
6903
|
+
amount,
|
|
6904
|
+
timeoutMs,
|
|
6905
|
+
pollIntervalMs: params.confirmPollIntervalMs,
|
|
6906
|
+
notDeliveredMessage: (delta) => `Solana token transfer ${txHash} confirmed on-chain, but ${destAta}'s balance only rose by ${delta} base units (expected ${amount}) within the wait window (connector#691 shape).`
|
|
6907
|
+
});
|
|
6908
|
+
return buildResult("solana", "token", params.to, amount, txHash, before, after);
|
|
6909
|
+
}
|
|
6910
|
+
var DEFAULT_MINA_FEE_NANOMINA = 1000000n;
|
|
6911
|
+
var DEFAULT_MINA_CONFIRM_TIMEOUT_MS = 3e5;
|
|
6912
|
+
async function loadMinaSignerClient() {
|
|
6913
|
+
try {
|
|
6914
|
+
const lib = await import(
|
|
6915
|
+
/* @vite-ignore */
|
|
6916
|
+
"mina-signer"
|
|
6917
|
+
);
|
|
6918
|
+
return "default" in lib ? lib.default : lib;
|
|
6919
|
+
} catch {
|
|
6920
|
+
throw new Error(
|
|
6921
|
+
"mina-signer is required for a Mina transfer. Install it as an optional dependency."
|
|
6922
|
+
);
|
|
6923
|
+
}
|
|
6924
|
+
}
|
|
6925
|
+
async function fetchMinaSenderState(graphqlUrl, publicKey, fetchImpl) {
|
|
6926
|
+
const query = "query($pk:String!){account(publicKey:$pk){balance{total} nonce inferredNonce}}";
|
|
6927
|
+
const res = await fetchImpl(graphqlUrl, {
|
|
6928
|
+
method: "POST",
|
|
6929
|
+
headers: { "content-type": "application/json" },
|
|
6930
|
+
body: JSON.stringify({ query, variables: { pk: publicKey } })
|
|
6931
|
+
});
|
|
6932
|
+
if (!res.ok) {
|
|
6933
|
+
throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);
|
|
6934
|
+
}
|
|
6935
|
+
const json = await res.json();
|
|
6936
|
+
if (json.errors && json.errors.length > 0) {
|
|
6937
|
+
throw new Error(`Mina GraphQL error: ${json.errors[0]?.message ?? "unknown"}`);
|
|
6938
|
+
}
|
|
6939
|
+
const account = json.data?.account;
|
|
6940
|
+
const nonce = Number(account?.inferredNonce ?? account?.nonce ?? "0");
|
|
6941
|
+
const balance = BigInt(account?.balance?.total ?? "0");
|
|
6942
|
+
return { balance, nonce };
|
|
6943
|
+
}
|
|
6944
|
+
async function submitMinaPayment(graphqlUrl, input, signature, fetchImpl) {
|
|
6945
|
+
const mutation = "mutation($input: SendPaymentInput!, $signature: SignatureInput){sendPayment(input:$input, signature:$signature){ payment { hash } } }";
|
|
6946
|
+
const res = await fetchImpl(graphqlUrl, {
|
|
6947
|
+
method: "POST",
|
|
6948
|
+
headers: { "content-type": "application/json" },
|
|
6949
|
+
body: JSON.stringify({ query: mutation, variables: { input, signature } })
|
|
6950
|
+
});
|
|
6951
|
+
if (!res.ok) {
|
|
6952
|
+
throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);
|
|
6953
|
+
}
|
|
6954
|
+
const json = await res.json();
|
|
6955
|
+
if (json.errors && json.errors.length > 0) {
|
|
6956
|
+
throw new Error(`Mina GraphQL error: ${json.errors[0]?.message ?? "unknown"}`);
|
|
6957
|
+
}
|
|
6958
|
+
const hash = json.data?.sendPayment?.payment?.hash;
|
|
6959
|
+
if (!hash) {
|
|
6960
|
+
throw new Error("Mina sendPayment returned no transaction hash.");
|
|
6961
|
+
}
|
|
6962
|
+
return hash;
|
|
6963
|
+
}
|
|
6964
|
+
async function sendMinaTransfer(cfg, params, amount) {
|
|
6965
|
+
if (params.asset === "token") {
|
|
6966
|
+
throw new TransferUnsupportedError(
|
|
6967
|
+
"Mina settlement-token transfer is not yet supported (native MINA only today \u2014 a custom-token send needs an o1js zkApp-approval path this client does not build yet; mirrors the Mina deposit/close/settle gaps in OnChainChannelClient)."
|
|
6968
|
+
);
|
|
6969
|
+
}
|
|
6970
|
+
const fetchImpl = cfg.fetchImpl ?? fetch;
|
|
6971
|
+
const timeoutMs = params.confirmTimeoutMs ?? DEFAULT_MINA_CONFIRM_TIMEOUT_MS;
|
|
6972
|
+
const fee = cfg.fee !== void 0 ? BigInt(cfg.fee) : DEFAULT_MINA_FEE_NANOMINA;
|
|
6973
|
+
const minaPrivateKey = hexToMinaBase58PrivateKey3(cfg.privateKey);
|
|
6974
|
+
const Client = await loadMinaSignerClient();
|
|
6975
|
+
const client = new Client({ network: cfg.networkId ?? "devnet" });
|
|
6976
|
+
const fromPublicKey = client.derivePublicKey(minaPrivateKey);
|
|
6977
|
+
const { balance, nonce } = await fetchMinaSenderState(
|
|
6978
|
+
cfg.graphqlUrl,
|
|
6979
|
+
fromPublicKey,
|
|
6980
|
+
fetchImpl
|
|
6981
|
+
);
|
|
6982
|
+
if (balance < amount + fee) {
|
|
6983
|
+
throw new InsufficientBalanceError(
|
|
6984
|
+
`Mina wallet ${fromPublicKey} holds ${balance} nanomina, short of the ${amount}-nanomina transfer plus the ${fee}-nanomina fee.`
|
|
6985
|
+
);
|
|
6986
|
+
}
|
|
6987
|
+
const readDest = async () => BigInt(
|
|
6988
|
+
(await readMinaBalance({
|
|
6989
|
+
graphqlUrl: cfg.graphqlUrl,
|
|
6990
|
+
owner: params.to,
|
|
6991
|
+
fetchImpl
|
|
6992
|
+
})).amount
|
|
6993
|
+
);
|
|
6994
|
+
const before = await readDest();
|
|
6995
|
+
const signed = client.signPayment(
|
|
6996
|
+
{
|
|
6997
|
+
to: params.to,
|
|
6998
|
+
from: fromPublicKey,
|
|
6999
|
+
fee: fee.toString(),
|
|
7000
|
+
amount: amount.toString(),
|
|
7001
|
+
nonce
|
|
7002
|
+
},
|
|
7003
|
+
minaPrivateKey
|
|
7004
|
+
);
|
|
7005
|
+
const txHash = await submitMinaPayment(
|
|
7006
|
+
cfg.graphqlUrl,
|
|
7007
|
+
{
|
|
7008
|
+
from: fromPublicKey,
|
|
7009
|
+
to: params.to,
|
|
7010
|
+
amount: amount.toString(),
|
|
7011
|
+
fee: fee.toString(),
|
|
7012
|
+
nonce: String(nonce)
|
|
7013
|
+
},
|
|
7014
|
+
signed.signature,
|
|
7015
|
+
fetchImpl
|
|
7016
|
+
);
|
|
7017
|
+
const after = await confirmDelivered({
|
|
7018
|
+
readBalance: readDest,
|
|
7019
|
+
before,
|
|
7020
|
+
amount,
|
|
7021
|
+
timeoutMs,
|
|
7022
|
+
pollIntervalMs: params.confirmPollIntervalMs,
|
|
7023
|
+
notDeliveredMessage: (delta) => `Mina native transfer ${txHash} was accepted by the node, but ${params.to}'s balance only rose by ${delta} nanomina (expected ${amount}) within the wait window.`
|
|
7024
|
+
});
|
|
7025
|
+
return buildResult("mina", "native", params.to, amount, txHash, before, after);
|
|
7026
|
+
}
|
|
7027
|
+
async function sendTransfer(config, params) {
|
|
7028
|
+
const amount = typeof params.amount === "string" ? BigInt(params.amount) : params.amount;
|
|
7029
|
+
if (amount <= 0n) {
|
|
7030
|
+
throw new ValidationError("sendTransfer: amount must be positive.");
|
|
7031
|
+
}
|
|
7032
|
+
switch (params.chain) {
|
|
7033
|
+
case "evm": {
|
|
7034
|
+
if (!config.evm) {
|
|
7035
|
+
throw new UnknownChainError(
|
|
7036
|
+
"sendTransfer: no EVM chain configured on this client (chainRpcUrls/evmPrivateKey missing)."
|
|
7037
|
+
);
|
|
7038
|
+
}
|
|
7039
|
+
assertValidEvmAddress(params.to);
|
|
7040
|
+
return sendEvmTransfer(config.evm, params, amount);
|
|
7041
|
+
}
|
|
7042
|
+
case "solana": {
|
|
7043
|
+
if (!config.solana) {
|
|
7044
|
+
throw new UnknownChainError(
|
|
7045
|
+
"sendTransfer: no Solana chain configured on this client (solanaChannel missing, or the Solana key has not been derived \u2014 call start() first, or construct from a mnemonic)."
|
|
7046
|
+
);
|
|
7047
|
+
}
|
|
7048
|
+
assertValidSolanaAddress(params.to);
|
|
7049
|
+
return sendSolanaTransfer(config.solana, params, amount);
|
|
7050
|
+
}
|
|
7051
|
+
case "mina": {
|
|
7052
|
+
if (!config.mina) {
|
|
7053
|
+
throw new UnknownChainError(
|
|
7054
|
+
"sendTransfer: no Mina chain configured on this client (minaChannel missing, or the Mina key has not been derived \u2014 call start() first, or construct from a mnemonic)."
|
|
7055
|
+
);
|
|
7056
|
+
}
|
|
7057
|
+
assertValidMinaAddress(params.to);
|
|
7058
|
+
return sendMinaTransfer(config.mina, params, amount);
|
|
7059
|
+
}
|
|
7060
|
+
default:
|
|
7061
|
+
throw new UnknownChainError(
|
|
7062
|
+
`sendTransfer: unknown chain "${String(params.chain)}". Supported: evm, solana, mina.`
|
|
7063
|
+
);
|
|
7064
|
+
}
|
|
7065
|
+
}
|
|
7066
|
+
|
|
5472
7067
|
// src/adapters/Http402Client.ts
|
|
5473
7068
|
var Http402Client = class {
|
|
5474
7069
|
fetchImpl;
|
|
@@ -5699,10 +7294,10 @@ import {
|
|
|
5699
7294
|
SettlementTxError
|
|
5700
7295
|
} from "@toon-protocol/sdk";
|
|
5701
7296
|
import {
|
|
5702
|
-
createPublicClient as
|
|
5703
|
-
defineChain as
|
|
7297
|
+
createPublicClient as createPublicClient4,
|
|
7298
|
+
defineChain as defineChain4,
|
|
5704
7299
|
fromRlp,
|
|
5705
|
-
http as
|
|
7300
|
+
http as http4
|
|
5706
7301
|
} from "viem";
|
|
5707
7302
|
function entryToAccumulatedClaim(entry) {
|
|
5708
7303
|
return {
|
|
@@ -5823,15 +7418,15 @@ async function submitEvmSettlement(bundle, params) {
|
|
|
5823
7418
|
);
|
|
5824
7419
|
}
|
|
5825
7420
|
const { to, data, chainId } = decodeEvmSettlementTx(bundle);
|
|
5826
|
-
const chain =
|
|
7421
|
+
const chain = defineChain4({
|
|
5827
7422
|
id: chainId,
|
|
5828
7423
|
name: bundle.chain,
|
|
5829
7424
|
nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 },
|
|
5830
7425
|
rpcUrls: { default: { http: [params.rpcUrl] } }
|
|
5831
7426
|
});
|
|
5832
|
-
const publicClient =
|
|
7427
|
+
const publicClient = createPublicClient4({
|
|
5833
7428
|
chain,
|
|
5834
|
-
transport:
|
|
7429
|
+
transport: http4(params.rpcUrl)
|
|
5835
7430
|
});
|
|
5836
7431
|
const [nonce, gasPrice, gas] = await Promise.all([
|
|
5837
7432
|
publicClient.getTransactionCount({
|
|
@@ -5866,11 +7461,11 @@ async function submitEvmSettlement(bundle, params) {
|
|
|
5866
7461
|
}
|
|
5867
7462
|
|
|
5868
7463
|
// src/swap/mina-settlement.ts
|
|
5869
|
-
import { hexToMinaBase58PrivateKey as
|
|
7464
|
+
import { hexToMinaBase58PrivateKey as hexToMinaBase58PrivateKey4 } from "@toon-protocol/core";
|
|
5870
7465
|
var MinaSettlementError = class extends Error {
|
|
5871
7466
|
code;
|
|
5872
|
-
constructor(code,
|
|
5873
|
-
super(`${code}: ${
|
|
7467
|
+
constructor(code, message2) {
|
|
7468
|
+
super(`${code}: ${message2}`);
|
|
5874
7469
|
this.name = "MinaSettlementError";
|
|
5875
7470
|
this.code = code;
|
|
5876
7471
|
}
|
|
@@ -5935,7 +7530,7 @@ async function buildMinaCoSignedClaim(inputs) {
|
|
|
5935
7530
|
balanceB,
|
|
5936
7531
|
salt
|
|
5937
7532
|
).toString();
|
|
5938
|
-
const recipientPrivateKeyBase58 =
|
|
7533
|
+
const recipientPrivateKeyBase58 = hexToMinaBase58PrivateKey4(
|
|
5939
7534
|
inputs.recipientPrivateKey
|
|
5940
7535
|
);
|
|
5941
7536
|
const built = await buildMinaPaymentChannelProof({
|
|
@@ -6062,7 +7657,7 @@ function createO1jsMinaClaimSubmitter() {
|
|
|
6062
7657
|
const PaymentChannel = zkAppMod.PaymentChannel;
|
|
6063
7658
|
Mina.setActiveInstance(Mina.Network(args.graphqlUrl));
|
|
6064
7659
|
const feePayerKey = PrivateKey.fromBase58(
|
|
6065
|
-
|
|
7660
|
+
hexToMinaBase58PrivateKey4(args.feePayerPrivateKey)
|
|
6066
7661
|
);
|
|
6067
7662
|
const feePayerPub = feePayerKey.toPublicKey();
|
|
6068
7663
|
await PaymentChannel.compile();
|
|
@@ -6124,6 +7719,19 @@ function parseMakerMinaSignature(raw) {
|
|
|
6124
7719
|
}
|
|
6125
7720
|
return void 0;
|
|
6126
7721
|
}
|
|
7722
|
+
function canonicalChainId(chain) {
|
|
7723
|
+
const parts = chain.split(":");
|
|
7724
|
+
return parts[0] === "evm" && parts.length >= 3 ? `evm:${parts[2]}` : chain;
|
|
7725
|
+
}
|
|
7726
|
+
function lookupByCanonicalChain(map, chain) {
|
|
7727
|
+
if (!map) return void 0;
|
|
7728
|
+
if (map[chain] !== void 0) return map[chain];
|
|
7729
|
+
const canonical = canonicalChainId(chain);
|
|
7730
|
+
for (const [key2, value] of Object.entries(map)) {
|
|
7731
|
+
if (canonicalChainId(key2) === canonical) return value;
|
|
7732
|
+
}
|
|
7733
|
+
return void 0;
|
|
7734
|
+
}
|
|
6127
7735
|
var ToonClient = class {
|
|
6128
7736
|
config;
|
|
6129
7737
|
state = null;
|
|
@@ -6206,6 +7814,30 @@ var ToonClient = class {
|
|
|
6206
7814
|
signEvent(template) {
|
|
6207
7815
|
return finalizeEvent(template, this.config.secretKey);
|
|
6208
7816
|
}
|
|
7817
|
+
/**
|
|
7818
|
+
* Unwrap a NIP-59 gift wrap (kind:1059) addressed to this client's own
|
|
7819
|
+
* Nostr identity, decrypting both NIP-44 layers with the identity's secret
|
|
7820
|
+
* key. The secret key never leaves this call — only the decrypted rumor
|
|
7821
|
+
* and the seal's (signature-verified) signer pubkey come back out.
|
|
7822
|
+
*
|
|
7823
|
+
* Backs the daemon's `POST /nip59-unwrap` control-API endpoint (buzz#19
|
|
7824
|
+
* agent-members receiving gift-wrapped channel keys addressed to the
|
|
7825
|
+
* daemon's identity). Callers MUST validate authorship from the returned
|
|
7826
|
+
* `sealPubkey` — never from `wrap.pubkey`, which NIP-59 mints fresh and
|
|
7827
|
+
* throws away per wrap.
|
|
7828
|
+
*
|
|
7829
|
+
* @throws {GiftWrapAddressError} malformed input, wrong kind, or not
|
|
7830
|
+
* addressed to this identity.
|
|
7831
|
+
* @throws {GiftWrapDecryptError} a NIP-44 layer failed to decrypt, or the
|
|
7832
|
+
* seal's signature didn't verify.
|
|
7833
|
+
*/
|
|
7834
|
+
unwrapGiftWrap(wrap) {
|
|
7835
|
+
return unwrapGiftWrapWithKey(
|
|
7836
|
+
this.config.secretKey,
|
|
7837
|
+
this.getPublicKey(),
|
|
7838
|
+
wrap
|
|
7839
|
+
);
|
|
7840
|
+
}
|
|
6209
7841
|
/**
|
|
6210
7842
|
* Upload bytes to Arweave via the kind:5094 blob-storage DVM (single-packet),
|
|
6211
7843
|
* signing the request with this client's Nostr key and paying through its
|
|
@@ -6337,21 +7969,29 @@ var ToonClient = class {
|
|
|
6337
7969
|
const peerInfo = result.peerInfo;
|
|
6338
7970
|
const peerChains = peerInfo.supportedChains ?? [];
|
|
6339
7971
|
const ourChains = this.config.supportedChains ?? [];
|
|
6340
|
-
const matchedChain =
|
|
6341
|
-
|
|
6342
|
-
|
|
6343
|
-
|
|
6344
|
-
|
|
6345
|
-
|
|
6346
|
-
|
|
6347
|
-
|
|
6348
|
-
|
|
6349
|
-
|
|
6350
|
-
|
|
6351
|
-
|
|
6352
|
-
|
|
6353
|
-
|
|
6354
|
-
|
|
7972
|
+
const matchedChain = this.matchNegotiatedChain(
|
|
7973
|
+
ourChains,
|
|
7974
|
+
peerChains,
|
|
7975
|
+
result.registeredPeerId
|
|
7976
|
+
);
|
|
7977
|
+
const peerAddr = peerInfo.settlementAddresses?.[matchedChain];
|
|
7978
|
+
const parts = matchedChain.split(":");
|
|
7979
|
+
const chainId = parts.length >= 3 ? parseInt(parts[2] ?? "0", 10) : parts.length >= 2 ? parseInt(parts[1] ?? "0", 10) : 0;
|
|
7980
|
+
if (peerAddr) {
|
|
7981
|
+
this.peerNegotiations.set(result.registeredPeerId, {
|
|
7982
|
+
chain: matchedChain,
|
|
7983
|
+
chainType: parts[0] ?? "evm",
|
|
7984
|
+
chainId: isNaN(chainId) ? 0 : chainId,
|
|
7985
|
+
settlementAddress: peerAddr,
|
|
7986
|
+
tokenAddress: peerInfo.preferredTokens?.[matchedChain] ?? lookupByCanonicalChain(
|
|
7987
|
+
this.config.preferredTokens,
|
|
7988
|
+
matchedChain
|
|
7989
|
+
),
|
|
7990
|
+
tokenNetwork: peerInfo.tokenNetworks?.[matchedChain] ?? lookupByCanonicalChain(
|
|
7991
|
+
this.config.tokenNetworks,
|
|
7992
|
+
matchedChain
|
|
7993
|
+
)
|
|
7994
|
+
});
|
|
6355
7995
|
}
|
|
6356
7996
|
}
|
|
6357
7997
|
if (this.channelManager && result.channelId && !this.channelManager.isTracking(result.channelId)) {
|
|
@@ -6745,6 +8385,13 @@ var ToonClient = class {
|
|
|
6745
8385
|
* `connectorHttpEndpoint` is configured, else the BtpRuntimeClient.
|
|
6746
8386
|
* 2. `btpClient` as an explicit fallback (always present when `btpUrl` is set).
|
|
6747
8387
|
*
|
|
8388
|
+
* `config.preferBtpForPaidWrites` (toon-client#482) SWAPS that order: when
|
|
8389
|
+
* set, `btpClient` — which `modes/http.ts` wraps in a
|
|
8390
|
+
* {@link BtpPaidWriteTransport} for this case, giving persistent,
|
|
8391
|
+
* strictly-ordered claim dispatch with its own fallback to `runtimeClient`
|
|
8392
|
+
* — is tried first, and `runtimeClient` remains as a second candidate.
|
|
8393
|
+
* Default `false` reproduces the exact precedence above, unchanged.
|
|
8394
|
+
*
|
|
6748
8395
|
* The level-3 `HttpRuntimeClient` (connector-admin HTTP, no `btpUrl` AND no
|
|
6749
8396
|
* proxy) does NOT implement `sendIlpPacketWithClaim`; in that case there is no
|
|
6750
8397
|
* paid-write transport and we throw a clear, actionable error.
|
|
@@ -6760,10 +8407,7 @@ var ToonClient = class {
|
|
|
6760
8407
|
"INVALID_STATE"
|
|
6761
8408
|
);
|
|
6762
8409
|
}
|
|
6763
|
-
const candidates = [
|
|
6764
|
-
state.runtimeClient,
|
|
6765
|
-
state.btpClient
|
|
6766
|
-
];
|
|
8410
|
+
const candidates = this.config.preferBtpForPaidWrites ? [state.btpClient, state.runtimeClient] : [state.runtimeClient, state.btpClient];
|
|
6767
8411
|
for (const candidate of candidates) {
|
|
6768
8412
|
if (candidate && typeof candidate.sendIlpPacketWithClaim === "function") {
|
|
6769
8413
|
return candidate;
|
|
@@ -6878,6 +8522,33 @@ var ToonClient = class {
|
|
|
6878
8522
|
throw this.withSolanaLegHint(peerId, error);
|
|
6879
8523
|
}
|
|
6880
8524
|
}
|
|
8525
|
+
/**
|
|
8526
|
+
* Adopt an ALREADY-OPEN payment channel for `destination` — the restart path
|
|
8527
|
+
* for a host that persisted the channel id itself (#489).
|
|
8528
|
+
*
|
|
8529
|
+
* Tracking a channel is not enough: the lazy-open path keys off the peer, so
|
|
8530
|
+
* a host that only re-tracked its saved channel still opened (and funded) a
|
|
8531
|
+
* SECOND one on the first paid write. This binds it, so every later write
|
|
8532
|
+
* resumes it, with its claim watermark, and the on-chain client can deposit
|
|
8533
|
+
* into and close it too. Idempotent.
|
|
8534
|
+
*/
|
|
8535
|
+
async adoptChannel(destination, channelId) {
|
|
8536
|
+
if (!this.channelManager) {
|
|
8537
|
+
throw new ToonClientError(
|
|
8538
|
+
"No channel manager configured. Provide evmPrivateKey in config.",
|
|
8539
|
+
"NO_EVM_SIGNER"
|
|
8540
|
+
);
|
|
8541
|
+
}
|
|
8542
|
+
const peerId = this.peerIdForClaim(destination);
|
|
8543
|
+
const negotiation = this.peerNegotiations.get(peerId) ?? await this.negotiateFromGreeting(destination, peerId);
|
|
8544
|
+
if (!negotiation) {
|
|
8545
|
+
throw new ToonClientError(
|
|
8546
|
+
`No negotiation metadata for peer "${peerId}" \u2014 cannot adopt channel "${channelId}" without knowing its chain and token network.`,
|
|
8547
|
+
"PEER_NOT_NEGOTIATED"
|
|
8548
|
+
);
|
|
8549
|
+
}
|
|
8550
|
+
this.channelManager.adoptChannel(peerId, negotiation, channelId);
|
|
8551
|
+
}
|
|
6881
8552
|
/**
|
|
6882
8553
|
* Gets list of tracked payment channel IDs.
|
|
6883
8554
|
*/
|
|
@@ -6898,6 +8569,70 @@ var ToonClient = class {
|
|
|
6898
8569
|
if (!this.channelManager) throw new Error("ChannelManager not initialized");
|
|
6899
8570
|
return this.channelManager.getCumulativeAmount(channelId);
|
|
6900
8571
|
}
|
|
8572
|
+
/**
|
|
8573
|
+
* The credited balance — earning's read surface (toon-client#494,
|
|
8574
|
+
* toon-meta#262 decision 9). Asks the connector's `POST /ilp/claim-state`
|
|
8575
|
+
* (client-edge-spec.md §1.10) for the netted off-chain position of one or
|
|
8576
|
+
* more tracked channels: deposit, cumulative claimed, available, nonce and
|
|
8577
|
+
* last-claim time — the SAME place `getBalances`'s on-chain reads and a
|
|
8578
|
+
* paid write's claim gate both already treat as this channel's runway
|
|
8579
|
+
* source of truth, rather than a parallel figure this client derives
|
|
8580
|
+
* itself (#262 decision 4 forbids self-reported money).
|
|
8581
|
+
*
|
|
8582
|
+
* `channelIds` defaults to every tracked channel. A channel this client has
|
|
8583
|
+
* no signer for (e.g. Mina — unsupported by this endpoint) or no recorded
|
|
8584
|
+
* chain context for is silently skipped, matching `getBalances`'s
|
|
8585
|
+
* best-effort-per-chain posture.
|
|
8586
|
+
*
|
|
8587
|
+
* @param opts.expiresInSeconds - How long the signed challenge stays valid
|
|
8588
|
+
* (default 300s). This is a READ signature, distinct from a real claim —
|
|
8589
|
+
* it moves no value and advances no nonce.
|
|
8590
|
+
*/
|
|
8591
|
+
async getClaimState(channelIds, opts) {
|
|
8592
|
+
if (!this.channelManager) {
|
|
8593
|
+
throw new ToonClientError(
|
|
8594
|
+
"No channel manager configured. Provide evmPrivateKey in config.",
|
|
8595
|
+
"NO_EVM_SIGNER"
|
|
8596
|
+
);
|
|
8597
|
+
}
|
|
8598
|
+
const channelManager = this.channelManager;
|
|
8599
|
+
const ids = channelIds ?? channelManager.getTrackedChannels();
|
|
8600
|
+
if (ids.length === 0) return [];
|
|
8601
|
+
const expires = Math.floor(Date.now() / 1e3) + (opts?.expiresInSeconds ?? 300);
|
|
8602
|
+
const entries = await Promise.all(
|
|
8603
|
+
ids.map(async (channelId) => {
|
|
8604
|
+
const context = channelManager.getChannelContext(channelId);
|
|
8605
|
+
if (!context) return null;
|
|
8606
|
+
if (context.chainType === "evm") {
|
|
8607
|
+
if (!this.evmSigner) return null;
|
|
8608
|
+
const signature = await this.evmSigner.signClaimStateChallenge({
|
|
8609
|
+
chainId: context.chainId,
|
|
8610
|
+
tokenNetworkAddress: context.tokenNetworkAddress,
|
|
8611
|
+
channelId,
|
|
8612
|
+
expires
|
|
8613
|
+
});
|
|
8614
|
+
return { blockchain: "evm", channelId, expires, signature };
|
|
8615
|
+
}
|
|
8616
|
+
if (context.chainType === "solana") {
|
|
8617
|
+
if (!this.solanaSigner) return null;
|
|
8618
|
+
const signature = await this.solanaSigner.signClaimStateChallenge({
|
|
8619
|
+
channelAccount: channelId,
|
|
8620
|
+
expires
|
|
8621
|
+
});
|
|
8622
|
+
return { blockchain: "solana", channelAccount: channelId, expires, signature };
|
|
8623
|
+
}
|
|
8624
|
+
return null;
|
|
8625
|
+
})
|
|
8626
|
+
);
|
|
8627
|
+
const requests = entries.filter(
|
|
8628
|
+
(e) => e !== null
|
|
8629
|
+
);
|
|
8630
|
+
if (requests.length === 0) return [];
|
|
8631
|
+
return this.connectorEdge.getClaimState(
|
|
8632
|
+
this.resolveClientEdgeEndpoint(),
|
|
8633
|
+
requests
|
|
8634
|
+
);
|
|
8635
|
+
}
|
|
6901
8636
|
/**
|
|
6902
8637
|
* Gets the on-chain deposit total (locked collateral) for a tracked channel.
|
|
6903
8638
|
* The available (spendable) balance is this minus the cumulative spent amount.
|
|
@@ -7141,6 +8876,44 @@ var ToonClient = class {
|
|
|
7141
8876
|
}
|
|
7142
8877
|
return out;
|
|
7143
8878
|
}
|
|
8879
|
+
/**
|
|
8880
|
+
* Lazily derive the mnemonic's full multi-chain identity, at most once per
|
|
8881
|
+
* call to the returned function. Solana/Mina keys are only registered as
|
|
8882
|
+
* signers during `start()`; this lets an UNSTARTED client (e.g. `rig
|
|
8883
|
+
* balance`, or `sendTransfer` before `start()`) derive them on demand
|
|
8884
|
+
* instead. Shared by {@link getWalletBalances} and {@link sendTransfer}.
|
|
8885
|
+
*/
|
|
8886
|
+
createIdentityDeriver() {
|
|
8887
|
+
let derived;
|
|
8888
|
+
let derivedTried = false;
|
|
8889
|
+
return async () => {
|
|
8890
|
+
if (derivedTried) return derived;
|
|
8891
|
+
derivedTried = true;
|
|
8892
|
+
if (this.config.mnemonic) {
|
|
8893
|
+
derived = await deriveFullIdentity(
|
|
8894
|
+
this.config.mnemonic,
|
|
8895
|
+
this.config.mnemonicAccountIndex ?? 0
|
|
8896
|
+
);
|
|
8897
|
+
}
|
|
8898
|
+
return derived;
|
|
8899
|
+
};
|
|
8900
|
+
}
|
|
8901
|
+
/**
|
|
8902
|
+
* The EVM chain key + RPC URL to use for a settlement-token/native-gas
|
|
8903
|
+
* operation: the settlement chain wins over the preset-first chain, mirroring
|
|
8904
|
+
* {@link getBalances}. Shared by {@link getWalletBalances} and
|
|
8905
|
+
* {@link sendTransfer}.
|
|
8906
|
+
*/
|
|
8907
|
+
resolveSettlementEvmChain() {
|
|
8908
|
+
const rpcUrls = this.config.chainRpcUrls;
|
|
8909
|
+
if (!rpcUrls) return void 0;
|
|
8910
|
+
const usableEvm = (c) => c.startsWith("evm") && Boolean(rpcUrls[c]);
|
|
8911
|
+
const settlementKeys = Object.keys(this.config.settlementAddresses ?? {});
|
|
8912
|
+
const chainKeys = this.config.supportedChains ?? Object.keys(rpcUrls);
|
|
8913
|
+
const chainKey = settlementKeys.find(usableEvm) ?? chainKeys.find(usableEvm);
|
|
8914
|
+
const rpcUrl = chainKey ? rpcUrls[chainKey] : void 0;
|
|
8915
|
+
return chainKey && rpcUrl ? { chainKey, rpcUrl } : void 0;
|
|
8916
|
+
}
|
|
7144
8917
|
/**
|
|
7145
8918
|
* The FULL multi-chain wallet view (#299): for every chain the identity is
|
|
7146
8919
|
* configured for, the native coin (ETH / SOL / MINA) AND every configured
|
|
@@ -7165,35 +8938,17 @@ var ToonClient = class {
|
|
|
7165
8938
|
*/
|
|
7166
8939
|
async getWalletBalances(fallback) {
|
|
7167
8940
|
const sources = {};
|
|
7168
|
-
|
|
7169
|
-
let derivedTried = false;
|
|
7170
|
-
const ensureDerived = async () => {
|
|
7171
|
-
if (derivedTried) return derived;
|
|
7172
|
-
derivedTried = true;
|
|
7173
|
-
if (this.config.mnemonic) {
|
|
7174
|
-
derived = await deriveFullIdentity(
|
|
7175
|
-
this.config.mnemonic,
|
|
7176
|
-
this.config.mnemonicAccountIndex ?? 0
|
|
7177
|
-
);
|
|
7178
|
-
}
|
|
7179
|
-
return derived;
|
|
7180
|
-
};
|
|
8941
|
+
const ensureDerived = this.createIdentityDeriver();
|
|
7181
8942
|
const evmAddress = this.getEvmAddress();
|
|
7182
|
-
const
|
|
8943
|
+
const evmChain = this.resolveSettlementEvmChain();
|
|
7183
8944
|
const tokens = this.config.preferredTokens;
|
|
7184
|
-
if (evmAddress &&
|
|
7185
|
-
|
|
7186
|
-
|
|
7187
|
-
|
|
7188
|
-
|
|
7189
|
-
|
|
7190
|
-
|
|
7191
|
-
chainKey,
|
|
7192
|
-
rpcUrl: rpcUrls[chainKey],
|
|
7193
|
-
owner: evmAddress,
|
|
7194
|
-
...tokens?.[chainKey] ? { tokenAddress: tokens[chainKey] } : {}
|
|
7195
|
-
};
|
|
7196
|
-
}
|
|
8945
|
+
if (evmAddress && evmChain) {
|
|
8946
|
+
sources.evm = {
|
|
8947
|
+
chainKey: evmChain.chainKey,
|
|
8948
|
+
rpcUrl: evmChain.rpcUrl,
|
|
8949
|
+
owner: evmAddress,
|
|
8950
|
+
...tokens?.[evmChain.chainKey] ? { tokenAddress: tokens[evmChain.chainKey] } : {}
|
|
8951
|
+
};
|
|
7197
8952
|
}
|
|
7198
8953
|
const sol = this.config.solanaChannel ?? fallback?.solanaChannel;
|
|
7199
8954
|
if (sol?.rpcUrl) {
|
|
@@ -7221,6 +8976,68 @@ var ToonClient = class {
|
|
|
7221
8976
|
}
|
|
7222
8977
|
return readWalletBalances(sources);
|
|
7223
8978
|
}
|
|
8979
|
+
/**
|
|
8980
|
+
* Send the settlement token or native gas from THIS client's own wallet to
|
|
8981
|
+
* an arbitrary address, on any chain this client is configured for.
|
|
8982
|
+
* Non-custodial plain send (issue #491) — distinct from the payment-channel
|
|
8983
|
+
* machinery, and the missing primitive underneath provisioning a buzz agent
|
|
8984
|
+
* (toon-protocol/buzz#74): the owner's treasury funds a freshly-derived
|
|
8985
|
+
* agent address with USDC + gas before that address can open a channel.
|
|
8986
|
+
*
|
|
8987
|
+
* Confirmed by an OBSERVED balance delta at the destination, never by the
|
|
8988
|
+
* send call/transaction merely landing — see `transfer.ts` module docs
|
|
8989
|
+
* (the devnet faucet's Solana leg has returned a real tx signature while
|
|
8990
|
+
* delivering 0 lamports, connector#691).
|
|
8991
|
+
*
|
|
8992
|
+
* Chain resolution mirrors {@link getWalletBalances}: EVM picks the
|
|
8993
|
+
* settlement chain key (falling back to the first usable EVM chain) from
|
|
8994
|
+
* `chainRpcUrls`/`settlementAddresses`; Solana/Mina need `solanaChannel`/
|
|
8995
|
+
* `minaChannel` configured, and their signing keys are either already
|
|
8996
|
+
* derived (client was `start()`-ed) or derived on demand from `mnemonic`.
|
|
8997
|
+
*
|
|
8998
|
+
* @throws {UnknownChainError} `params.chain` isn't configured on this client.
|
|
8999
|
+
* @throws {InvalidAddressError} `params.to` is malformed for the chain.
|
|
9000
|
+
* @throws {InsufficientBalanceError} the sender can't cover amount (+ fees).
|
|
9001
|
+
* @throws {TransferNotDeliveredError} accepted on-chain/by-node, but the
|
|
9002
|
+
* destination balance never reflected it within the wait window.
|
|
9003
|
+
* @throws {TransferUnsupportedError} chain/asset combination not implemented
|
|
9004
|
+
* yet (currently: the Mina settlement token).
|
|
9005
|
+
*/
|
|
9006
|
+
async sendTransfer(params) {
|
|
9007
|
+
const config = {};
|
|
9008
|
+
if (this.evmSigner) {
|
|
9009
|
+
const evmChain = this.resolveSettlementEvmChain();
|
|
9010
|
+
if (evmChain) {
|
|
9011
|
+
const tokens = this.config.preferredTokens;
|
|
9012
|
+
config.evm = {
|
|
9013
|
+
chainKey: evmChain.chainKey,
|
|
9014
|
+
rpcUrl: evmChain.rpcUrl,
|
|
9015
|
+
signer: this.evmSigner,
|
|
9016
|
+
...tokens?.[evmChain.chainKey] ? { tokenAddress: tokens[evmChain.chainKey] } : {}
|
|
9017
|
+
};
|
|
9018
|
+
}
|
|
9019
|
+
}
|
|
9020
|
+
const ensureDerived = this.createIdentityDeriver();
|
|
9021
|
+
const sol = this.config.solanaChannel;
|
|
9022
|
+
if (sol?.rpcUrl) {
|
|
9023
|
+
const seed = this.solanaSeed ?? (await ensureDerived())?.solana.secretKey.slice(0, 32);
|
|
9024
|
+
if (seed) {
|
|
9025
|
+
config.solana = {
|
|
9026
|
+
rpcUrl: sol.rpcUrl,
|
|
9027
|
+
keypair: seed,
|
|
9028
|
+
...sol.tokenMint ? { tokenMint: sol.tokenMint } : {}
|
|
9029
|
+
};
|
|
9030
|
+
}
|
|
9031
|
+
}
|
|
9032
|
+
const mina = this.config.minaChannel;
|
|
9033
|
+
if (mina?.graphqlUrl) {
|
|
9034
|
+
const privateKey = this.minaPrivateKey ?? (await ensureDerived())?.mina.privateKey;
|
|
9035
|
+
if (privateKey) {
|
|
9036
|
+
config.mina = { graphqlUrl: mina.graphqlUrl, privateKey };
|
|
9037
|
+
}
|
|
9038
|
+
}
|
|
9039
|
+
return sendTransfer(config, params);
|
|
9040
|
+
}
|
|
7224
9041
|
/**
|
|
7225
9042
|
* Resolves an ILP destination address to a peer ID.
|
|
7226
9043
|
* Convention: destination "g.toon.peer1" → peerId "peer1" (last segment).
|
|
@@ -7431,11 +9248,72 @@ var ToonClient = class {
|
|
|
7431
9248
|
return { chainId: numericChainId, tokenNetworkAddress, tokenAddress };
|
|
7432
9249
|
}
|
|
7433
9250
|
/**
|
|
7434
|
-
*
|
|
9251
|
+
* Picks the settlement chain both `ourChains` and `peerChains` support,
|
|
9252
|
+
* used by the lightweight bootstrap-fallback negotiation (peer discovered
|
|
9253
|
+
* but no connector admin registered a chain). Prefers
|
|
9254
|
+
* `this.config.preferredChain`'s family (#485) over array order; picks the
|
|
9255
|
+
* first mutually-supported chain (legacy behavior) when unconfigured.
|
|
9256
|
+
*
|
|
9257
|
+
* Chains are matched by {@link canonicalChainId} rather than exact string
|
|
9258
|
+
* equality (#500): the devnet preset's family-qualified `evm:base:84532`
|
|
9259
|
+
* and the live apex's unqualified `evm:84532` name the same chain, and
|
|
9260
|
+
* exact matching skipped straight past it to the next mutually-supported
|
|
9261
|
+
* chain (`solana:devnet`) — negotiating a chain nobody asked for instead
|
|
9262
|
+
* of failing loudly. The PEER's own chain string is returned (not ours),
|
|
9263
|
+
* since callers index the peer's own `settlementAddresses` /
|
|
9264
|
+
* `preferredTokens` / `tokenNetworks` maps with it.
|
|
9265
|
+
*
|
|
9266
|
+
* @throws {ToonClientError} `CHAIN_NOT_SUPPORTED` naming both chain sets
|
|
9267
|
+
* when no common chain exists — a caller explicitly configured this
|
|
9268
|
+
* peer as a counterparty, so silently negotiating a different chain (or
|
|
9269
|
+
* returning nothing) would hide a real incompatibility behind an
|
|
9270
|
+
* unrelated failure several layers downstream (#500).
|
|
9271
|
+
*/
|
|
9272
|
+
matchNegotiatedChain(ourChains, peerChains, peerId) {
|
|
9273
|
+
const peerByCanonical = new Map(
|
|
9274
|
+
peerChains.map((c) => [canonicalChainId(c), c])
|
|
9275
|
+
);
|
|
9276
|
+
const preferred = this.config.preferredChain;
|
|
9277
|
+
const candidates = preferred ? ourChains.filter((c) => c.split(":")[0] === preferred) : ourChains;
|
|
9278
|
+
for (const c of candidates) {
|
|
9279
|
+
const peerMatch = peerByCanonical.get(canonicalChainId(c));
|
|
9280
|
+
if (peerMatch) return peerMatch;
|
|
9281
|
+
}
|
|
9282
|
+
if (preferred) {
|
|
9283
|
+
throw new ToonClientError(
|
|
9284
|
+
`Configured chain "${preferred}" is not supported by peer "${peerId}" (peer supportedChains: ${peerChains.join(", ") || "(none)"}).`,
|
|
9285
|
+
"CHAIN_NOT_SUPPORTED"
|
|
9286
|
+
);
|
|
9287
|
+
}
|
|
9288
|
+
throw new ToonClientError(
|
|
9289
|
+
`No common settlement chain with peer "${peerId}" (our supportedChains: ${ourChains.join(", ") || "(none)"}; peer supportedChains: ${peerChains.join(", ") || "(none)"}).`,
|
|
9290
|
+
"CHAIN_NOT_SUPPORTED"
|
|
9291
|
+
);
|
|
9292
|
+
}
|
|
9293
|
+
/**
|
|
9294
|
+
* Gets the default chain context: the explicitly-configured
|
|
9295
|
+
* `preferredChain` family when set (#485 — e.g. `TOON_CLIENT_CHAIN=evm`
|
|
9296
|
+
* must not silently pin to `supportedChains[0]` when that happens to be a
|
|
9297
|
+
* different chain, such as Solana), else the first supported chain.
|
|
9298
|
+
*
|
|
9299
|
+
* @throws {ToonClientError} `CHAIN_NOT_SUPPORTED` if `preferredChain` is
|
|
9300
|
+
* set but none of `supportedChains` belong to that family — this must
|
|
9301
|
+
* fail loudly rather than fall back to a chain the caller didn't choose.
|
|
7435
9302
|
*/
|
|
7436
9303
|
getDefaultChainContext() {
|
|
7437
9304
|
const chains = this.config.supportedChains;
|
|
7438
9305
|
if (!chains?.length) return void 0;
|
|
9306
|
+
const preferred = this.config.preferredChain;
|
|
9307
|
+
if (preferred) {
|
|
9308
|
+
const match = chains.find((c) => c.split(":")[0] === preferred);
|
|
9309
|
+
if (!match) {
|
|
9310
|
+
throw new ToonClientError(
|
|
9311
|
+
`Configured chain "${preferred}" is not supported by this peer (supportedChains: ${chains.join(", ")}). Set a matching TOON_CLIENT_CHAIN / preferredChain, or fund a supported chain.`,
|
|
9312
|
+
"CHAIN_NOT_SUPPORTED"
|
|
9313
|
+
);
|
|
9314
|
+
}
|
|
9315
|
+
return this.getChainContext(match);
|
|
9316
|
+
}
|
|
7439
9317
|
return this.getChainContext(chains[0]);
|
|
7440
9318
|
}
|
|
7441
9319
|
/**
|
|
@@ -7534,6 +9412,77 @@ var ToonClient = class {
|
|
|
7534
9412
|
}
|
|
7535
9413
|
};
|
|
7536
9414
|
|
|
9415
|
+
// src/hashlock-delivery.ts
|
|
9416
|
+
import { chacha20poly1305 as chacha20poly13052 } from "@noble/ciphers/chacha.js";
|
|
9417
|
+
import { sha256 as sha2566 } from "@noble/hashes/sha2.js";
|
|
9418
|
+
import { randomBytes as randomBytes3 } from "@noble/hashes/utils.js";
|
|
9419
|
+
var NONCE_LENGTH = 12;
|
|
9420
|
+
var TAG_LENGTH2 = 16;
|
|
9421
|
+
function encryptArtifact(artifact) {
|
|
9422
|
+
const key2 = randomBytes3(CONDITION_LENGTH);
|
|
9423
|
+
const nonce = randomBytes3(NONCE_LENGTH);
|
|
9424
|
+
const sealed = chacha20poly13052(key2, nonce).encrypt(artifact);
|
|
9425
|
+
const ciphertext = new Uint8Array(NONCE_LENGTH + sealed.length);
|
|
9426
|
+
ciphertext.set(nonce, 0);
|
|
9427
|
+
ciphertext.set(sealed, NONCE_LENGTH);
|
|
9428
|
+
return { ciphertext, key: key2, condition: sha2566(key2) };
|
|
9429
|
+
}
|
|
9430
|
+
function fulfillIncrement(key2) {
|
|
9431
|
+
assertValidCondition(key2);
|
|
9432
|
+
return key2;
|
|
9433
|
+
}
|
|
9434
|
+
var HashlockConditionMismatchError = class extends Error {
|
|
9435
|
+
constructor(message2) {
|
|
9436
|
+
super(message2);
|
|
9437
|
+
this.name = "HashlockConditionMismatchError";
|
|
9438
|
+
}
|
|
9439
|
+
};
|
|
9440
|
+
var HashlockDecryptError = class extends Error {
|
|
9441
|
+
constructor(message2, cause) {
|
|
9442
|
+
super(message2);
|
|
9443
|
+
this.cause = cause;
|
|
9444
|
+
this.name = "HashlockDecryptError";
|
|
9445
|
+
}
|
|
9446
|
+
cause;
|
|
9447
|
+
};
|
|
9448
|
+
function decryptArtifact(ciphertext, key2, paidCondition) {
|
|
9449
|
+
assertValidCondition(paidCondition);
|
|
9450
|
+
if (!fulfillmentMatchesCondition(key2, paidCondition)) {
|
|
9451
|
+
throw new HashlockConditionMismatchError(
|
|
9452
|
+
"sha256(key) does not match the condition that was paid \u2014 refusing to decrypt"
|
|
9453
|
+
);
|
|
9454
|
+
}
|
|
9455
|
+
if (ciphertext.length < NONCE_LENGTH + TAG_LENGTH2) {
|
|
9456
|
+
throw new HashlockDecryptError(
|
|
9457
|
+
`ciphertext is too short to be a sealed artifact (${ciphertext.length} bytes)`
|
|
9458
|
+
);
|
|
9459
|
+
}
|
|
9460
|
+
const nonce = ciphertext.subarray(0, NONCE_LENGTH);
|
|
9461
|
+
const sealed = ciphertext.subarray(NONCE_LENGTH);
|
|
9462
|
+
try {
|
|
9463
|
+
return chacha20poly13052(key2, nonce).decrypt(sealed);
|
|
9464
|
+
} catch (error) {
|
|
9465
|
+
throw new HashlockDecryptError(
|
|
9466
|
+
"artifact ciphertext failed to decrypt (tampered or corrupted fetch)",
|
|
9467
|
+
error instanceof Error ? error : void 0
|
|
9468
|
+
);
|
|
9469
|
+
}
|
|
9470
|
+
}
|
|
9471
|
+
function buildIncrementPrepare(offer) {
|
|
9472
|
+
const executionCondition = fromHex(offer.conditionHex);
|
|
9473
|
+
assertValidCondition(executionCondition);
|
|
9474
|
+
let amount;
|
|
9475
|
+
try {
|
|
9476
|
+
amount = BigInt(offer.amountUsdc);
|
|
9477
|
+
} catch {
|
|
9478
|
+
throw new Error(`amount tag is not a valid integer: "${offer.amountUsdc}"`);
|
|
9479
|
+
}
|
|
9480
|
+
if (amount <= 0n) {
|
|
9481
|
+
throw new Error(`amount tag must be positive, got "${offer.amountUsdc}"`);
|
|
9482
|
+
}
|
|
9483
|
+
return { executionCondition, amount };
|
|
9484
|
+
}
|
|
9485
|
+
|
|
7537
9486
|
// src/adapters/HttpConnectorAdmin.ts
|
|
7538
9487
|
var HttpConnectorAdmin = class {
|
|
7539
9488
|
adminUrl;
|
|
@@ -7844,8 +9793,8 @@ var HttpConnectorAdmin = class {
|
|
|
7844
9793
|
};
|
|
7845
9794
|
|
|
7846
9795
|
// src/channel/ReceivedClaimStore.ts
|
|
7847
|
-
import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync2, mkdirSync } from "fs";
|
|
7848
|
-
import { dirname } from "path";
|
|
9796
|
+
import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync2, mkdirSync as mkdirSync2 } from "fs";
|
|
9797
|
+
import { dirname as dirname2 } from "path";
|
|
7849
9798
|
function key(chain, channelId) {
|
|
7850
9799
|
return `${chain}|${channelId}`;
|
|
7851
9800
|
}
|
|
@@ -7894,7 +9843,7 @@ var JsonFileReceivedClaimStore = class {
|
|
|
7894
9843
|
return JSON.parse(raw);
|
|
7895
9844
|
}
|
|
7896
9845
|
writeFile(data) {
|
|
7897
|
-
|
|
9846
|
+
mkdirSync2(dirname2(this.filePath), { recursive: true });
|
|
7898
9847
|
writeFileSync2(this.filePath, JSON.stringify(data, null, 2), "utf-8");
|
|
7899
9848
|
}
|
|
7900
9849
|
};
|
|
@@ -7975,28 +9924,28 @@ function domainOf(ctx) {
|
|
|
7975
9924
|
verifyingContract: normalizeAddress(ctx.verifyingContract)
|
|
7976
9925
|
};
|
|
7977
9926
|
}
|
|
7978
|
-
function evmClaimDigest(ctx,
|
|
9927
|
+
function evmClaimDigest(ctx, message2) {
|
|
7979
9928
|
return hashTypedData({
|
|
7980
9929
|
domain: domainOf(ctx),
|
|
7981
9930
|
types: CLAIM_TYPES,
|
|
7982
9931
|
primaryType: "ClaimBalanceProof",
|
|
7983
9932
|
message: {
|
|
7984
|
-
channelId:
|
|
7985
|
-
cumulativeAmount:
|
|
7986
|
-
nonce:
|
|
7987
|
-
recipient: normalizeAddress(
|
|
9933
|
+
channelId: message2.channelId,
|
|
9934
|
+
cumulativeAmount: message2.cumulativeAmount,
|
|
9935
|
+
nonce: message2.nonce,
|
|
9936
|
+
recipient: normalizeAddress(message2.recipient)
|
|
7988
9937
|
}
|
|
7989
9938
|
});
|
|
7990
9939
|
}
|
|
7991
|
-
function evmCooperativeCloseDigest(ctx,
|
|
9940
|
+
function evmCooperativeCloseDigest(ctx, message2) {
|
|
7992
9941
|
return hashTypedData({
|
|
7993
9942
|
domain: domainOf(ctx),
|
|
7994
9943
|
types: COOP_CLOSE_TYPES,
|
|
7995
9944
|
primaryType: "CooperativeClose",
|
|
7996
9945
|
message: {
|
|
7997
|
-
channelId:
|
|
7998
|
-
cumulativeAmount:
|
|
7999
|
-
nonce:
|
|
9946
|
+
channelId: message2.channelId,
|
|
9947
|
+
cumulativeAmount: message2.cumulativeAmount,
|
|
9948
|
+
nonce: message2.nonce
|
|
8000
9949
|
}
|
|
8001
9950
|
});
|
|
8002
9951
|
}
|
|
@@ -8006,7 +9955,7 @@ function signatureToBytes(sig) {
|
|
|
8006
9955
|
const hex = sig.startsWith("0x") ? sig.slice(2) : sig;
|
|
8007
9956
|
return hexToBytes(hex);
|
|
8008
9957
|
}
|
|
8009
|
-
function recoverEvmClaimSigner(ctx,
|
|
9958
|
+
function recoverEvmClaimSigner(ctx, message2, signature) {
|
|
8010
9959
|
const bytes = signatureToBytes(signature);
|
|
8011
9960
|
if (bytes.length !== SIG_BYTES) {
|
|
8012
9961
|
throw new Error(
|
|
@@ -8017,7 +9966,7 @@ function recoverEvmClaimSigner(ctx, message, signature) {
|
|
|
8017
9966
|
if (v !== 27 && v !== 28) {
|
|
8018
9967
|
throw new Error(`EVM signature v must be 27 or 28, got ${v}`);
|
|
8019
9968
|
}
|
|
8020
|
-
const digest = evmClaimDigest(ctx,
|
|
9969
|
+
const digest = evmClaimDigest(ctx, message2).slice(2);
|
|
8021
9970
|
const recovered = secp256k12.Signature.fromBytes(bytes.slice(0, 64), "compact").addRecoveryBit(v - 27).recoverPublicKey(hexToBytes(digest));
|
|
8022
9971
|
const uncompressed = recovered.toBytes(false);
|
|
8023
9972
|
const addrHash = keccak_256(uncompressed.slice(1));
|
|
@@ -8067,8 +10016,8 @@ function ingestReceivedClaims(params) {
|
|
|
8067
10016
|
const legacy = [];
|
|
8068
10017
|
let valueReceived = 0n;
|
|
8069
10018
|
const watermarks = /* @__PURE__ */ new Map();
|
|
8070
|
-
const reject = (claim, code,
|
|
8071
|
-
rejected.push({ claim, code, message });
|
|
10019
|
+
const reject = (claim, code, message2) => {
|
|
10020
|
+
rejected.push({ claim, code, message: message2 });
|
|
8072
10021
|
};
|
|
8073
10022
|
for (const claim of params.claims) {
|
|
8074
10023
|
if (!hasSettlementMetadata(claim)) {
|
|
@@ -9290,7 +11239,7 @@ import {
|
|
|
9290
11239
|
scryptSync,
|
|
9291
11240
|
createCipheriv,
|
|
9292
11241
|
createDecipheriv,
|
|
9293
|
-
randomBytes as
|
|
11242
|
+
randomBytes as randomBytes4
|
|
9294
11243
|
} from "crypto";
|
|
9295
11244
|
import { writeFileSync as writeFileSync3, readFileSync as readFileSync3 } from "fs";
|
|
9296
11245
|
var SCRYPT_N = 2 ** 17;
|
|
@@ -9317,8 +11266,8 @@ function encryptMnemonic2(mnemonic, password) {
|
|
|
9317
11266
|
if (typeof password !== "string" || password.length === 0) {
|
|
9318
11267
|
throw new Error("encryptMnemonic: password must be a non-empty string");
|
|
9319
11268
|
}
|
|
9320
|
-
const salt =
|
|
9321
|
-
const iv =
|
|
11269
|
+
const salt = randomBytes4(SALT_LEN);
|
|
11270
|
+
const iv = randomBytes4(IV_LEN);
|
|
9322
11271
|
const key2 = scryptSync(password, salt, SCRYPT_KEY_LEN, {
|
|
9323
11272
|
N: SCRYPT_N,
|
|
9324
11273
|
r: SCRYPT_R,
|
|
@@ -9420,12 +11369,14 @@ function writeKeystoreFile(path, keystore) {
|
|
|
9420
11369
|
});
|
|
9421
11370
|
}
|
|
9422
11371
|
export {
|
|
11372
|
+
BtpPaidWriteTransport,
|
|
9423
11373
|
BtpRuntimeClient,
|
|
9424
11374
|
CLAIM_TYPEHASH,
|
|
9425
11375
|
CONDITION_LENGTH,
|
|
9426
11376
|
COOP_CLOSE_TYPEHASH,
|
|
9427
11377
|
ChannelFundingError,
|
|
9428
11378
|
ChannelManager,
|
|
11379
|
+
ChannelResumeError,
|
|
9429
11380
|
ConnectorEdgeClient,
|
|
9430
11381
|
ConnectorEdgeError,
|
|
9431
11382
|
ConnectorError,
|
|
@@ -9439,17 +11390,26 @@ export {
|
|
|
9439
11390
|
GIFTWRAP_SECRET_LENGTH,
|
|
9440
11391
|
GIFTWRAP_TYPE_REQUEST,
|
|
9441
11392
|
GIFTWRAP_TYPE_RESPONSE,
|
|
11393
|
+
GIFT_WRAP_KIND,
|
|
9442
11394
|
GenerativeFallbackRenderer,
|
|
11395
|
+
GiftWrapAddressError,
|
|
11396
|
+
GiftWrapDecryptError,
|
|
9443
11397
|
GiftWrapError,
|
|
9444
11398
|
GiftWrapErrorKind,
|
|
11399
|
+
HashlockConditionMismatchError,
|
|
11400
|
+
HashlockDecryptError,
|
|
9445
11401
|
Http402Client,
|
|
9446
11402
|
HttpConnectorAdmin,
|
|
9447
11403
|
HttpIlpClient,
|
|
9448
11404
|
HttpRuntimeClient,
|
|
9449
11405
|
ILP_CLAIM_HEADER,
|
|
9450
11406
|
ILP_PEER_ID_HEADER,
|
|
11407
|
+
InMemoryChannelStore,
|
|
9451
11408
|
InMemoryPreimageRetentionStore,
|
|
9452
11409
|
InMemoryReceivedClaimStore,
|
|
11410
|
+
InsufficientBalanceError,
|
|
11411
|
+
InvalidAddressError,
|
|
11412
|
+
JsonFileChannelStore,
|
|
9453
11413
|
JsonFileReceivedClaimStore,
|
|
9454
11414
|
KeyManager,
|
|
9455
11415
|
KindRegistry,
|
|
@@ -9465,12 +11425,17 @@ export {
|
|
|
9465
11425
|
ROLLING_SWAP_DOMAIN_NAME,
|
|
9466
11426
|
ROLLING_SWAP_DOMAIN_VERSION,
|
|
9467
11427
|
RendererPinStore,
|
|
11428
|
+
SEAL_KIND,
|
|
9468
11429
|
SealedResponseError,
|
|
9469
11430
|
SolanaSigner,
|
|
11431
|
+
StaleRpcReadError,
|
|
9470
11432
|
ToonClient,
|
|
9471
11433
|
ToonClientError,
|
|
11434
|
+
TransferNotDeliveredError,
|
|
11435
|
+
TransferUnsupportedError,
|
|
9472
11436
|
UI_RENDERER_KIND,
|
|
9473
11437
|
UI_TAG,
|
|
11438
|
+
UnknownChainError,
|
|
9474
11439
|
ValidationError,
|
|
9475
11440
|
applyDefaults,
|
|
9476
11441
|
applyNetworkPresets,
|
|
@@ -9478,6 +11443,7 @@ export {
|
|
|
9478
11443
|
buildBackupEvent,
|
|
9479
11444
|
buildBackupFilter,
|
|
9480
11445
|
buildConsentRequest,
|
|
11446
|
+
buildIncrementPrepare,
|
|
9481
11447
|
buildMinaCoSignedClaim,
|
|
9482
11448
|
buildRendererEventTemplate,
|
|
9483
11449
|
buildSettlementInfo,
|
|
@@ -9485,6 +11451,7 @@ export {
|
|
|
9485
11451
|
buildUiCoordinate,
|
|
9486
11452
|
classifyIntent,
|
|
9487
11453
|
connectorEdgeBaseUrl,
|
|
11454
|
+
createJobMessageHandler,
|
|
9488
11455
|
createO1jsMinaClaimSubmitter,
|
|
9489
11456
|
decodeConnectorPublicKey,
|
|
9490
11457
|
decodeEnvelope,
|
|
@@ -9493,6 +11460,7 @@ export {
|
|
|
9493
11460
|
decodeEvmSettlementTx,
|
|
9494
11461
|
decodeVarOctetString2 as decodeVarOctetString,
|
|
9495
11462
|
decodeVarUint,
|
|
11463
|
+
decryptArtifact,
|
|
9496
11464
|
decryptMnemonic2 as decryptMnemonic,
|
|
9497
11465
|
defaultFaucetTimeout,
|
|
9498
11466
|
deployMinaChannelZkApp,
|
|
@@ -9507,6 +11475,7 @@ export {
|
|
|
9507
11475
|
encodeEnvelopeResponse,
|
|
9508
11476
|
encodeVarOctetString2 as encodeVarOctetString,
|
|
9509
11477
|
encodeVarUint,
|
|
11478
|
+
encryptArtifact,
|
|
9510
11479
|
encryptMnemonic2 as encryptMnemonic,
|
|
9511
11480
|
ensureOwnedMinaZkApp,
|
|
9512
11481
|
entryToAccumulatedClaim,
|
|
@@ -9515,6 +11484,7 @@ export {
|
|
|
9515
11484
|
evmCooperativeCloseDigest,
|
|
9516
11485
|
extractArweaveTxId,
|
|
9517
11486
|
extractUiResource,
|
|
11487
|
+
fulfillIncrement,
|
|
9518
11488
|
fulfillmentMatchesCondition,
|
|
9519
11489
|
fundWallet,
|
|
9520
11490
|
generateKeystore,
|
|
@@ -9539,6 +11509,7 @@ export {
|
|
|
9539
11509
|
openRequest,
|
|
9540
11510
|
openResponse,
|
|
9541
11511
|
parseBackupPayload,
|
|
11512
|
+
parseClaimStateResponse,
|
|
9542
11513
|
parseConnectorIdentity,
|
|
9543
11514
|
parseConnectorRoutePrice,
|
|
9544
11515
|
parseEvmChainId2 as parseEvmChainId,
|
|
@@ -9571,8 +11542,10 @@ export {
|
|
|
9571
11542
|
sealResponseWithRandomness,
|
|
9572
11543
|
selectIlpTransport,
|
|
9573
11544
|
selectLatestAddressable,
|
|
11545
|
+
sendTransfer,
|
|
9574
11546
|
submitEvmSettlement,
|
|
9575
11547
|
submitMinaSettlement,
|
|
11548
|
+
unwrapGiftWrapWithKey,
|
|
9576
11549
|
validateConfig,
|
|
9577
11550
|
validateMnemonic,
|
|
9578
11551
|
verifyEvmClaimSignature,
|