@toon-protocol/client 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +113 -0
- package/dist/index.d.ts +2153 -1018
- package/dist/index.js +2137 -196
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
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();
|
|
@@ -6206,6 +7801,30 @@ var ToonClient = class {
|
|
|
6206
7801
|
signEvent(template) {
|
|
6207
7802
|
return finalizeEvent(template, this.config.secretKey);
|
|
6208
7803
|
}
|
|
7804
|
+
/**
|
|
7805
|
+
* Unwrap a NIP-59 gift wrap (kind:1059) addressed to this client's own
|
|
7806
|
+
* Nostr identity, decrypting both NIP-44 layers with the identity's secret
|
|
7807
|
+
* key. The secret key never leaves this call — only the decrypted rumor
|
|
7808
|
+
* and the seal's (signature-verified) signer pubkey come back out.
|
|
7809
|
+
*
|
|
7810
|
+
* Backs the daemon's `POST /nip59-unwrap` control-API endpoint (buzz#19
|
|
7811
|
+
* agent-members receiving gift-wrapped channel keys addressed to the
|
|
7812
|
+
* daemon's identity). Callers MUST validate authorship from the returned
|
|
7813
|
+
* `sealPubkey` — never from `wrap.pubkey`, which NIP-59 mints fresh and
|
|
7814
|
+
* throws away per wrap.
|
|
7815
|
+
*
|
|
7816
|
+
* @throws {GiftWrapAddressError} malformed input, wrong kind, or not
|
|
7817
|
+
* addressed to this identity.
|
|
7818
|
+
* @throws {GiftWrapDecryptError} a NIP-44 layer failed to decrypt, or the
|
|
7819
|
+
* seal's signature didn't verify.
|
|
7820
|
+
*/
|
|
7821
|
+
unwrapGiftWrap(wrap) {
|
|
7822
|
+
return unwrapGiftWrapWithKey(
|
|
7823
|
+
this.config.secretKey,
|
|
7824
|
+
this.getPublicKey(),
|
|
7825
|
+
wrap
|
|
7826
|
+
);
|
|
7827
|
+
}
|
|
6209
7828
|
/**
|
|
6210
7829
|
* Upload bytes to Arweave via the kind:5094 blob-storage DVM (single-packet),
|
|
6211
7830
|
* signing the request with this client's Nostr key and paying through its
|
|
@@ -6337,7 +7956,11 @@ var ToonClient = class {
|
|
|
6337
7956
|
const peerInfo = result.peerInfo;
|
|
6338
7957
|
const peerChains = peerInfo.supportedChains ?? [];
|
|
6339
7958
|
const ourChains = this.config.supportedChains ?? [];
|
|
6340
|
-
const matchedChain =
|
|
7959
|
+
const matchedChain = this.matchNegotiatedChain(
|
|
7960
|
+
ourChains,
|
|
7961
|
+
peerChains,
|
|
7962
|
+
result.registeredPeerId
|
|
7963
|
+
);
|
|
6341
7964
|
if (matchedChain) {
|
|
6342
7965
|
const peerAddr = peerInfo.settlementAddresses?.[matchedChain];
|
|
6343
7966
|
const parts = matchedChain.split(":");
|
|
@@ -6745,6 +8368,13 @@ var ToonClient = class {
|
|
|
6745
8368
|
* `connectorHttpEndpoint` is configured, else the BtpRuntimeClient.
|
|
6746
8369
|
* 2. `btpClient` as an explicit fallback (always present when `btpUrl` is set).
|
|
6747
8370
|
*
|
|
8371
|
+
* `config.preferBtpForPaidWrites` (toon-client#482) SWAPS that order: when
|
|
8372
|
+
* set, `btpClient` — which `modes/http.ts` wraps in a
|
|
8373
|
+
* {@link BtpPaidWriteTransport} for this case, giving persistent,
|
|
8374
|
+
* strictly-ordered claim dispatch with its own fallback to `runtimeClient`
|
|
8375
|
+
* — is tried first, and `runtimeClient` remains as a second candidate.
|
|
8376
|
+
* Default `false` reproduces the exact precedence above, unchanged.
|
|
8377
|
+
*
|
|
6748
8378
|
* The level-3 `HttpRuntimeClient` (connector-admin HTTP, no `btpUrl` AND no
|
|
6749
8379
|
* proxy) does NOT implement `sendIlpPacketWithClaim`; in that case there is no
|
|
6750
8380
|
* paid-write transport and we throw a clear, actionable error.
|
|
@@ -6760,10 +8390,7 @@ var ToonClient = class {
|
|
|
6760
8390
|
"INVALID_STATE"
|
|
6761
8391
|
);
|
|
6762
8392
|
}
|
|
6763
|
-
const candidates = [
|
|
6764
|
-
state.runtimeClient,
|
|
6765
|
-
state.btpClient
|
|
6766
|
-
];
|
|
8393
|
+
const candidates = this.config.preferBtpForPaidWrites ? [state.btpClient, state.runtimeClient] : [state.runtimeClient, state.btpClient];
|
|
6767
8394
|
for (const candidate of candidates) {
|
|
6768
8395
|
if (candidate && typeof candidate.sendIlpPacketWithClaim === "function") {
|
|
6769
8396
|
return candidate;
|
|
@@ -6878,6 +8505,33 @@ var ToonClient = class {
|
|
|
6878
8505
|
throw this.withSolanaLegHint(peerId, error);
|
|
6879
8506
|
}
|
|
6880
8507
|
}
|
|
8508
|
+
/**
|
|
8509
|
+
* Adopt an ALREADY-OPEN payment channel for `destination` — the restart path
|
|
8510
|
+
* for a host that persisted the channel id itself (#489).
|
|
8511
|
+
*
|
|
8512
|
+
* Tracking a channel is not enough: the lazy-open path keys off the peer, so
|
|
8513
|
+
* a host that only re-tracked its saved channel still opened (and funded) a
|
|
8514
|
+
* SECOND one on the first paid write. This binds it, so every later write
|
|
8515
|
+
* resumes it, with its claim watermark, and the on-chain client can deposit
|
|
8516
|
+
* into and close it too. Idempotent.
|
|
8517
|
+
*/
|
|
8518
|
+
async adoptChannel(destination, channelId) {
|
|
8519
|
+
if (!this.channelManager) {
|
|
8520
|
+
throw new ToonClientError(
|
|
8521
|
+
"No channel manager configured. Provide evmPrivateKey in config.",
|
|
8522
|
+
"NO_EVM_SIGNER"
|
|
8523
|
+
);
|
|
8524
|
+
}
|
|
8525
|
+
const peerId = this.peerIdForClaim(destination);
|
|
8526
|
+
const negotiation = this.peerNegotiations.get(peerId) ?? await this.negotiateFromGreeting(destination, peerId);
|
|
8527
|
+
if (!negotiation) {
|
|
8528
|
+
throw new ToonClientError(
|
|
8529
|
+
`No negotiation metadata for peer "${peerId}" \u2014 cannot adopt channel "${channelId}" without knowing its chain and token network.`,
|
|
8530
|
+
"PEER_NOT_NEGOTIATED"
|
|
8531
|
+
);
|
|
8532
|
+
}
|
|
8533
|
+
this.channelManager.adoptChannel(peerId, negotiation, channelId);
|
|
8534
|
+
}
|
|
6881
8535
|
/**
|
|
6882
8536
|
* Gets list of tracked payment channel IDs.
|
|
6883
8537
|
*/
|
|
@@ -6898,6 +8552,70 @@ var ToonClient = class {
|
|
|
6898
8552
|
if (!this.channelManager) throw new Error("ChannelManager not initialized");
|
|
6899
8553
|
return this.channelManager.getCumulativeAmount(channelId);
|
|
6900
8554
|
}
|
|
8555
|
+
/**
|
|
8556
|
+
* The credited balance — earning's read surface (toon-client#494,
|
|
8557
|
+
* toon-meta#262 decision 9). Asks the connector's `POST /ilp/claim-state`
|
|
8558
|
+
* (client-edge-spec.md §1.10) for the netted off-chain position of one or
|
|
8559
|
+
* more tracked channels: deposit, cumulative claimed, available, nonce and
|
|
8560
|
+
* last-claim time — the SAME place `getBalances`'s on-chain reads and a
|
|
8561
|
+
* paid write's claim gate both already treat as this channel's runway
|
|
8562
|
+
* source of truth, rather than a parallel figure this client derives
|
|
8563
|
+
* itself (#262 decision 4 forbids self-reported money).
|
|
8564
|
+
*
|
|
8565
|
+
* `channelIds` defaults to every tracked channel. A channel this client has
|
|
8566
|
+
* no signer for (e.g. Mina — unsupported by this endpoint) or no recorded
|
|
8567
|
+
* chain context for is silently skipped, matching `getBalances`'s
|
|
8568
|
+
* best-effort-per-chain posture.
|
|
8569
|
+
*
|
|
8570
|
+
* @param opts.expiresInSeconds - How long the signed challenge stays valid
|
|
8571
|
+
* (default 300s). This is a READ signature, distinct from a real claim —
|
|
8572
|
+
* it moves no value and advances no nonce.
|
|
8573
|
+
*/
|
|
8574
|
+
async getClaimState(channelIds, opts) {
|
|
8575
|
+
if (!this.channelManager) {
|
|
8576
|
+
throw new ToonClientError(
|
|
8577
|
+
"No channel manager configured. Provide evmPrivateKey in config.",
|
|
8578
|
+
"NO_EVM_SIGNER"
|
|
8579
|
+
);
|
|
8580
|
+
}
|
|
8581
|
+
const channelManager = this.channelManager;
|
|
8582
|
+
const ids = channelIds ?? channelManager.getTrackedChannels();
|
|
8583
|
+
if (ids.length === 0) return [];
|
|
8584
|
+
const expires = Math.floor(Date.now() / 1e3) + (opts?.expiresInSeconds ?? 300);
|
|
8585
|
+
const entries = await Promise.all(
|
|
8586
|
+
ids.map(async (channelId) => {
|
|
8587
|
+
const context = channelManager.getChannelContext(channelId);
|
|
8588
|
+
if (!context) return null;
|
|
8589
|
+
if (context.chainType === "evm") {
|
|
8590
|
+
if (!this.evmSigner) return null;
|
|
8591
|
+
const signature = await this.evmSigner.signClaimStateChallenge({
|
|
8592
|
+
chainId: context.chainId,
|
|
8593
|
+
tokenNetworkAddress: context.tokenNetworkAddress,
|
|
8594
|
+
channelId,
|
|
8595
|
+
expires
|
|
8596
|
+
});
|
|
8597
|
+
return { blockchain: "evm", channelId, expires, signature };
|
|
8598
|
+
}
|
|
8599
|
+
if (context.chainType === "solana") {
|
|
8600
|
+
if (!this.solanaSigner) return null;
|
|
8601
|
+
const signature = await this.solanaSigner.signClaimStateChallenge({
|
|
8602
|
+
channelAccount: channelId,
|
|
8603
|
+
expires
|
|
8604
|
+
});
|
|
8605
|
+
return { blockchain: "solana", channelAccount: channelId, expires, signature };
|
|
8606
|
+
}
|
|
8607
|
+
return null;
|
|
8608
|
+
})
|
|
8609
|
+
);
|
|
8610
|
+
const requests = entries.filter(
|
|
8611
|
+
(e) => e !== null
|
|
8612
|
+
);
|
|
8613
|
+
if (requests.length === 0) return [];
|
|
8614
|
+
return this.connectorEdge.getClaimState(
|
|
8615
|
+
this.resolveClientEdgeEndpoint(),
|
|
8616
|
+
requests
|
|
8617
|
+
);
|
|
8618
|
+
}
|
|
6901
8619
|
/**
|
|
6902
8620
|
* Gets the on-chain deposit total (locked collateral) for a tracked channel.
|
|
6903
8621
|
* The available (spendable) balance is this minus the cumulative spent amount.
|
|
@@ -7141,6 +8859,44 @@ var ToonClient = class {
|
|
|
7141
8859
|
}
|
|
7142
8860
|
return out;
|
|
7143
8861
|
}
|
|
8862
|
+
/**
|
|
8863
|
+
* Lazily derive the mnemonic's full multi-chain identity, at most once per
|
|
8864
|
+
* call to the returned function. Solana/Mina keys are only registered as
|
|
8865
|
+
* signers during `start()`; this lets an UNSTARTED client (e.g. `rig
|
|
8866
|
+
* balance`, or `sendTransfer` before `start()`) derive them on demand
|
|
8867
|
+
* instead. Shared by {@link getWalletBalances} and {@link sendTransfer}.
|
|
8868
|
+
*/
|
|
8869
|
+
createIdentityDeriver() {
|
|
8870
|
+
let derived;
|
|
8871
|
+
let derivedTried = false;
|
|
8872
|
+
return async () => {
|
|
8873
|
+
if (derivedTried) return derived;
|
|
8874
|
+
derivedTried = true;
|
|
8875
|
+
if (this.config.mnemonic) {
|
|
8876
|
+
derived = await deriveFullIdentity(
|
|
8877
|
+
this.config.mnemonic,
|
|
8878
|
+
this.config.mnemonicAccountIndex ?? 0
|
|
8879
|
+
);
|
|
8880
|
+
}
|
|
8881
|
+
return derived;
|
|
8882
|
+
};
|
|
8883
|
+
}
|
|
8884
|
+
/**
|
|
8885
|
+
* The EVM chain key + RPC URL to use for a settlement-token/native-gas
|
|
8886
|
+
* operation: the settlement chain wins over the preset-first chain, mirroring
|
|
8887
|
+
* {@link getBalances}. Shared by {@link getWalletBalances} and
|
|
8888
|
+
* {@link sendTransfer}.
|
|
8889
|
+
*/
|
|
8890
|
+
resolveSettlementEvmChain() {
|
|
8891
|
+
const rpcUrls = this.config.chainRpcUrls;
|
|
8892
|
+
if (!rpcUrls) return void 0;
|
|
8893
|
+
const usableEvm = (c) => c.startsWith("evm") && Boolean(rpcUrls[c]);
|
|
8894
|
+
const settlementKeys = Object.keys(this.config.settlementAddresses ?? {});
|
|
8895
|
+
const chainKeys = this.config.supportedChains ?? Object.keys(rpcUrls);
|
|
8896
|
+
const chainKey = settlementKeys.find(usableEvm) ?? chainKeys.find(usableEvm);
|
|
8897
|
+
const rpcUrl = chainKey ? rpcUrls[chainKey] : void 0;
|
|
8898
|
+
return chainKey && rpcUrl ? { chainKey, rpcUrl } : void 0;
|
|
8899
|
+
}
|
|
7144
8900
|
/**
|
|
7145
8901
|
* The FULL multi-chain wallet view (#299): for every chain the identity is
|
|
7146
8902
|
* configured for, the native coin (ETH / SOL / MINA) AND every configured
|
|
@@ -7165,35 +8921,17 @@ var ToonClient = class {
|
|
|
7165
8921
|
*/
|
|
7166
8922
|
async getWalletBalances(fallback) {
|
|
7167
8923
|
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
|
-
};
|
|
8924
|
+
const ensureDerived = this.createIdentityDeriver();
|
|
7181
8925
|
const evmAddress = this.getEvmAddress();
|
|
7182
|
-
const
|
|
8926
|
+
const evmChain = this.resolveSettlementEvmChain();
|
|
7183
8927
|
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
|
-
}
|
|
8928
|
+
if (evmAddress && evmChain) {
|
|
8929
|
+
sources.evm = {
|
|
8930
|
+
chainKey: evmChain.chainKey,
|
|
8931
|
+
rpcUrl: evmChain.rpcUrl,
|
|
8932
|
+
owner: evmAddress,
|
|
8933
|
+
...tokens?.[evmChain.chainKey] ? { tokenAddress: tokens[evmChain.chainKey] } : {}
|
|
8934
|
+
};
|
|
7197
8935
|
}
|
|
7198
8936
|
const sol = this.config.solanaChannel ?? fallback?.solanaChannel;
|
|
7199
8937
|
if (sol?.rpcUrl) {
|
|
@@ -7221,6 +8959,68 @@ var ToonClient = class {
|
|
|
7221
8959
|
}
|
|
7222
8960
|
return readWalletBalances(sources);
|
|
7223
8961
|
}
|
|
8962
|
+
/**
|
|
8963
|
+
* Send the settlement token or native gas from THIS client's own wallet to
|
|
8964
|
+
* an arbitrary address, on any chain this client is configured for.
|
|
8965
|
+
* Non-custodial plain send (issue #491) — distinct from the payment-channel
|
|
8966
|
+
* machinery, and the missing primitive underneath provisioning a buzz agent
|
|
8967
|
+
* (toon-protocol/buzz#74): the owner's treasury funds a freshly-derived
|
|
8968
|
+
* agent address with USDC + gas before that address can open a channel.
|
|
8969
|
+
*
|
|
8970
|
+
* Confirmed by an OBSERVED balance delta at the destination, never by the
|
|
8971
|
+
* send call/transaction merely landing — see `transfer.ts` module docs
|
|
8972
|
+
* (the devnet faucet's Solana leg has returned a real tx signature while
|
|
8973
|
+
* delivering 0 lamports, connector#691).
|
|
8974
|
+
*
|
|
8975
|
+
* Chain resolution mirrors {@link getWalletBalances}: EVM picks the
|
|
8976
|
+
* settlement chain key (falling back to the first usable EVM chain) from
|
|
8977
|
+
* `chainRpcUrls`/`settlementAddresses`; Solana/Mina need `solanaChannel`/
|
|
8978
|
+
* `minaChannel` configured, and their signing keys are either already
|
|
8979
|
+
* derived (client was `start()`-ed) or derived on demand from `mnemonic`.
|
|
8980
|
+
*
|
|
8981
|
+
* @throws {UnknownChainError} `params.chain` isn't configured on this client.
|
|
8982
|
+
* @throws {InvalidAddressError} `params.to` is malformed for the chain.
|
|
8983
|
+
* @throws {InsufficientBalanceError} the sender can't cover amount (+ fees).
|
|
8984
|
+
* @throws {TransferNotDeliveredError} accepted on-chain/by-node, but the
|
|
8985
|
+
* destination balance never reflected it within the wait window.
|
|
8986
|
+
* @throws {TransferUnsupportedError} chain/asset combination not implemented
|
|
8987
|
+
* yet (currently: the Mina settlement token).
|
|
8988
|
+
*/
|
|
8989
|
+
async sendTransfer(params) {
|
|
8990
|
+
const config = {};
|
|
8991
|
+
if (this.evmSigner) {
|
|
8992
|
+
const evmChain = this.resolveSettlementEvmChain();
|
|
8993
|
+
if (evmChain) {
|
|
8994
|
+
const tokens = this.config.preferredTokens;
|
|
8995
|
+
config.evm = {
|
|
8996
|
+
chainKey: evmChain.chainKey,
|
|
8997
|
+
rpcUrl: evmChain.rpcUrl,
|
|
8998
|
+
signer: this.evmSigner,
|
|
8999
|
+
...tokens?.[evmChain.chainKey] ? { tokenAddress: tokens[evmChain.chainKey] } : {}
|
|
9000
|
+
};
|
|
9001
|
+
}
|
|
9002
|
+
}
|
|
9003
|
+
const ensureDerived = this.createIdentityDeriver();
|
|
9004
|
+
const sol = this.config.solanaChannel;
|
|
9005
|
+
if (sol?.rpcUrl) {
|
|
9006
|
+
const seed = this.solanaSeed ?? (await ensureDerived())?.solana.secretKey.slice(0, 32);
|
|
9007
|
+
if (seed) {
|
|
9008
|
+
config.solana = {
|
|
9009
|
+
rpcUrl: sol.rpcUrl,
|
|
9010
|
+
keypair: seed,
|
|
9011
|
+
...sol.tokenMint ? { tokenMint: sol.tokenMint } : {}
|
|
9012
|
+
};
|
|
9013
|
+
}
|
|
9014
|
+
}
|
|
9015
|
+
const mina = this.config.minaChannel;
|
|
9016
|
+
if (mina?.graphqlUrl) {
|
|
9017
|
+
const privateKey = this.minaPrivateKey ?? (await ensureDerived())?.mina.privateKey;
|
|
9018
|
+
if (privateKey) {
|
|
9019
|
+
config.mina = { graphqlUrl: mina.graphqlUrl, privateKey };
|
|
9020
|
+
}
|
|
9021
|
+
}
|
|
9022
|
+
return sendTransfer(config, params);
|
|
9023
|
+
}
|
|
7224
9024
|
/**
|
|
7225
9025
|
* Resolves an ILP destination address to a peer ID.
|
|
7226
9026
|
* Convention: destination "g.toon.peer1" → peerId "peer1" (last segment).
|
|
@@ -7431,11 +9231,57 @@ var ToonClient = class {
|
|
|
7431
9231
|
return { chainId: numericChainId, tokenNetworkAddress, tokenAddress };
|
|
7432
9232
|
}
|
|
7433
9233
|
/**
|
|
7434
|
-
*
|
|
9234
|
+
* Picks the settlement chain both `ourChains` and `peerChains` support,
|
|
9235
|
+
* used by the lightweight bootstrap-fallback negotiation (peer discovered
|
|
9236
|
+
* but no connector admin registered a chain). Prefers
|
|
9237
|
+
* `this.config.preferredChain`'s family (#485) over array order; falls
|
|
9238
|
+
* back to the first mutually-supported chain (legacy behavior) when
|
|
9239
|
+
* unconfigured.
|
|
9240
|
+
*
|
|
9241
|
+
* @throws {ToonClientError} `CHAIN_NOT_SUPPORTED` if a chain is explicitly
|
|
9242
|
+
* configured but the peer doesn't support any chain in that family —
|
|
9243
|
+
* this must fail loudly rather than silently negotiate a different chain.
|
|
9244
|
+
*/
|
|
9245
|
+
matchNegotiatedChain(ourChains, peerChains, peerId) {
|
|
9246
|
+
const preferred = this.config.preferredChain;
|
|
9247
|
+
if (preferred) {
|
|
9248
|
+
const matched = ourChains.find(
|
|
9249
|
+
(c) => c.split(":")[0] === preferred && peerChains.includes(c)
|
|
9250
|
+
);
|
|
9251
|
+
if (!matched) {
|
|
9252
|
+
throw new ToonClientError(
|
|
9253
|
+
`Configured chain "${preferred}" is not supported by peer "${peerId}" (peer supportedChains: ${peerChains.join(", ") || "(none)"}).`,
|
|
9254
|
+
"CHAIN_NOT_SUPPORTED"
|
|
9255
|
+
);
|
|
9256
|
+
}
|
|
9257
|
+
return matched;
|
|
9258
|
+
}
|
|
9259
|
+
return ourChains.find((c) => peerChains.includes(c)) ?? ourChains[0];
|
|
9260
|
+
}
|
|
9261
|
+
/**
|
|
9262
|
+
* Gets the default chain context: the explicitly-configured
|
|
9263
|
+
* `preferredChain` family when set (#485 — e.g. `TOON_CLIENT_CHAIN=evm`
|
|
9264
|
+
* must not silently pin to `supportedChains[0]` when that happens to be a
|
|
9265
|
+
* different chain, such as Solana), else the first supported chain.
|
|
9266
|
+
*
|
|
9267
|
+
* @throws {ToonClientError} `CHAIN_NOT_SUPPORTED` if `preferredChain` is
|
|
9268
|
+
* set but none of `supportedChains` belong to that family — this must
|
|
9269
|
+
* fail loudly rather than fall back to a chain the caller didn't choose.
|
|
7435
9270
|
*/
|
|
7436
9271
|
getDefaultChainContext() {
|
|
7437
9272
|
const chains = this.config.supportedChains;
|
|
7438
9273
|
if (!chains?.length) return void 0;
|
|
9274
|
+
const preferred = this.config.preferredChain;
|
|
9275
|
+
if (preferred) {
|
|
9276
|
+
const match = chains.find((c) => c.split(":")[0] === preferred);
|
|
9277
|
+
if (!match) {
|
|
9278
|
+
throw new ToonClientError(
|
|
9279
|
+
`Configured chain "${preferred}" is not supported by this peer (supportedChains: ${chains.join(", ")}). Set a matching TOON_CLIENT_CHAIN / preferredChain, or fund a supported chain.`,
|
|
9280
|
+
"CHAIN_NOT_SUPPORTED"
|
|
9281
|
+
);
|
|
9282
|
+
}
|
|
9283
|
+
return this.getChainContext(match);
|
|
9284
|
+
}
|
|
7439
9285
|
return this.getChainContext(chains[0]);
|
|
7440
9286
|
}
|
|
7441
9287
|
/**
|
|
@@ -7534,6 +9380,77 @@ var ToonClient = class {
|
|
|
7534
9380
|
}
|
|
7535
9381
|
};
|
|
7536
9382
|
|
|
9383
|
+
// src/hashlock-delivery.ts
|
|
9384
|
+
import { chacha20poly1305 as chacha20poly13052 } from "@noble/ciphers/chacha.js";
|
|
9385
|
+
import { sha256 as sha2566 } from "@noble/hashes/sha2.js";
|
|
9386
|
+
import { randomBytes as randomBytes3 } from "@noble/hashes/utils.js";
|
|
9387
|
+
var NONCE_LENGTH = 12;
|
|
9388
|
+
var TAG_LENGTH2 = 16;
|
|
9389
|
+
function encryptArtifact(artifact) {
|
|
9390
|
+
const key2 = randomBytes3(CONDITION_LENGTH);
|
|
9391
|
+
const nonce = randomBytes3(NONCE_LENGTH);
|
|
9392
|
+
const sealed = chacha20poly13052(key2, nonce).encrypt(artifact);
|
|
9393
|
+
const ciphertext = new Uint8Array(NONCE_LENGTH + sealed.length);
|
|
9394
|
+
ciphertext.set(nonce, 0);
|
|
9395
|
+
ciphertext.set(sealed, NONCE_LENGTH);
|
|
9396
|
+
return { ciphertext, key: key2, condition: sha2566(key2) };
|
|
9397
|
+
}
|
|
9398
|
+
function fulfillIncrement(key2) {
|
|
9399
|
+
assertValidCondition(key2);
|
|
9400
|
+
return key2;
|
|
9401
|
+
}
|
|
9402
|
+
var HashlockConditionMismatchError = class extends Error {
|
|
9403
|
+
constructor(message2) {
|
|
9404
|
+
super(message2);
|
|
9405
|
+
this.name = "HashlockConditionMismatchError";
|
|
9406
|
+
}
|
|
9407
|
+
};
|
|
9408
|
+
var HashlockDecryptError = class extends Error {
|
|
9409
|
+
constructor(message2, cause) {
|
|
9410
|
+
super(message2);
|
|
9411
|
+
this.cause = cause;
|
|
9412
|
+
this.name = "HashlockDecryptError";
|
|
9413
|
+
}
|
|
9414
|
+
cause;
|
|
9415
|
+
};
|
|
9416
|
+
function decryptArtifact(ciphertext, key2, paidCondition) {
|
|
9417
|
+
assertValidCondition(paidCondition);
|
|
9418
|
+
if (!fulfillmentMatchesCondition(key2, paidCondition)) {
|
|
9419
|
+
throw new HashlockConditionMismatchError(
|
|
9420
|
+
"sha256(key) does not match the condition that was paid \u2014 refusing to decrypt"
|
|
9421
|
+
);
|
|
9422
|
+
}
|
|
9423
|
+
if (ciphertext.length < NONCE_LENGTH + TAG_LENGTH2) {
|
|
9424
|
+
throw new HashlockDecryptError(
|
|
9425
|
+
`ciphertext is too short to be a sealed artifact (${ciphertext.length} bytes)`
|
|
9426
|
+
);
|
|
9427
|
+
}
|
|
9428
|
+
const nonce = ciphertext.subarray(0, NONCE_LENGTH);
|
|
9429
|
+
const sealed = ciphertext.subarray(NONCE_LENGTH);
|
|
9430
|
+
try {
|
|
9431
|
+
return chacha20poly13052(key2, nonce).decrypt(sealed);
|
|
9432
|
+
} catch (error) {
|
|
9433
|
+
throw new HashlockDecryptError(
|
|
9434
|
+
"artifact ciphertext failed to decrypt (tampered or corrupted fetch)",
|
|
9435
|
+
error instanceof Error ? error : void 0
|
|
9436
|
+
);
|
|
9437
|
+
}
|
|
9438
|
+
}
|
|
9439
|
+
function buildIncrementPrepare(offer) {
|
|
9440
|
+
const executionCondition = fromHex(offer.conditionHex);
|
|
9441
|
+
assertValidCondition(executionCondition);
|
|
9442
|
+
let amount;
|
|
9443
|
+
try {
|
|
9444
|
+
amount = BigInt(offer.amountUsdc);
|
|
9445
|
+
} catch {
|
|
9446
|
+
throw new Error(`amount tag is not a valid integer: "${offer.amountUsdc}"`);
|
|
9447
|
+
}
|
|
9448
|
+
if (amount <= 0n) {
|
|
9449
|
+
throw new Error(`amount tag must be positive, got "${offer.amountUsdc}"`);
|
|
9450
|
+
}
|
|
9451
|
+
return { executionCondition, amount };
|
|
9452
|
+
}
|
|
9453
|
+
|
|
7537
9454
|
// src/adapters/HttpConnectorAdmin.ts
|
|
7538
9455
|
var HttpConnectorAdmin = class {
|
|
7539
9456
|
adminUrl;
|
|
@@ -7844,8 +9761,8 @@ var HttpConnectorAdmin = class {
|
|
|
7844
9761
|
};
|
|
7845
9762
|
|
|
7846
9763
|
// src/channel/ReceivedClaimStore.ts
|
|
7847
|
-
import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync2, mkdirSync } from "fs";
|
|
7848
|
-
import { dirname } from "path";
|
|
9764
|
+
import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync2, mkdirSync as mkdirSync2 } from "fs";
|
|
9765
|
+
import { dirname as dirname2 } from "path";
|
|
7849
9766
|
function key(chain, channelId) {
|
|
7850
9767
|
return `${chain}|${channelId}`;
|
|
7851
9768
|
}
|
|
@@ -7894,7 +9811,7 @@ var JsonFileReceivedClaimStore = class {
|
|
|
7894
9811
|
return JSON.parse(raw);
|
|
7895
9812
|
}
|
|
7896
9813
|
writeFile(data) {
|
|
7897
|
-
|
|
9814
|
+
mkdirSync2(dirname2(this.filePath), { recursive: true });
|
|
7898
9815
|
writeFileSync2(this.filePath, JSON.stringify(data, null, 2), "utf-8");
|
|
7899
9816
|
}
|
|
7900
9817
|
};
|
|
@@ -7975,28 +9892,28 @@ function domainOf(ctx) {
|
|
|
7975
9892
|
verifyingContract: normalizeAddress(ctx.verifyingContract)
|
|
7976
9893
|
};
|
|
7977
9894
|
}
|
|
7978
|
-
function evmClaimDigest(ctx,
|
|
9895
|
+
function evmClaimDigest(ctx, message2) {
|
|
7979
9896
|
return hashTypedData({
|
|
7980
9897
|
domain: domainOf(ctx),
|
|
7981
9898
|
types: CLAIM_TYPES,
|
|
7982
9899
|
primaryType: "ClaimBalanceProof",
|
|
7983
9900
|
message: {
|
|
7984
|
-
channelId:
|
|
7985
|
-
cumulativeAmount:
|
|
7986
|
-
nonce:
|
|
7987
|
-
recipient: normalizeAddress(
|
|
9901
|
+
channelId: message2.channelId,
|
|
9902
|
+
cumulativeAmount: message2.cumulativeAmount,
|
|
9903
|
+
nonce: message2.nonce,
|
|
9904
|
+
recipient: normalizeAddress(message2.recipient)
|
|
7988
9905
|
}
|
|
7989
9906
|
});
|
|
7990
9907
|
}
|
|
7991
|
-
function evmCooperativeCloseDigest(ctx,
|
|
9908
|
+
function evmCooperativeCloseDigest(ctx, message2) {
|
|
7992
9909
|
return hashTypedData({
|
|
7993
9910
|
domain: domainOf(ctx),
|
|
7994
9911
|
types: COOP_CLOSE_TYPES,
|
|
7995
9912
|
primaryType: "CooperativeClose",
|
|
7996
9913
|
message: {
|
|
7997
|
-
channelId:
|
|
7998
|
-
cumulativeAmount:
|
|
7999
|
-
nonce:
|
|
9914
|
+
channelId: message2.channelId,
|
|
9915
|
+
cumulativeAmount: message2.cumulativeAmount,
|
|
9916
|
+
nonce: message2.nonce
|
|
8000
9917
|
}
|
|
8001
9918
|
});
|
|
8002
9919
|
}
|
|
@@ -8006,7 +9923,7 @@ function signatureToBytes(sig) {
|
|
|
8006
9923
|
const hex = sig.startsWith("0x") ? sig.slice(2) : sig;
|
|
8007
9924
|
return hexToBytes(hex);
|
|
8008
9925
|
}
|
|
8009
|
-
function recoverEvmClaimSigner(ctx,
|
|
9926
|
+
function recoverEvmClaimSigner(ctx, message2, signature) {
|
|
8010
9927
|
const bytes = signatureToBytes(signature);
|
|
8011
9928
|
if (bytes.length !== SIG_BYTES) {
|
|
8012
9929
|
throw new Error(
|
|
@@ -8017,7 +9934,7 @@ function recoverEvmClaimSigner(ctx, message, signature) {
|
|
|
8017
9934
|
if (v !== 27 && v !== 28) {
|
|
8018
9935
|
throw new Error(`EVM signature v must be 27 or 28, got ${v}`);
|
|
8019
9936
|
}
|
|
8020
|
-
const digest = evmClaimDigest(ctx,
|
|
9937
|
+
const digest = evmClaimDigest(ctx, message2).slice(2);
|
|
8021
9938
|
const recovered = secp256k12.Signature.fromBytes(bytes.slice(0, 64), "compact").addRecoveryBit(v - 27).recoverPublicKey(hexToBytes(digest));
|
|
8022
9939
|
const uncompressed = recovered.toBytes(false);
|
|
8023
9940
|
const addrHash = keccak_256(uncompressed.slice(1));
|
|
@@ -8067,8 +9984,8 @@ function ingestReceivedClaims(params) {
|
|
|
8067
9984
|
const legacy = [];
|
|
8068
9985
|
let valueReceived = 0n;
|
|
8069
9986
|
const watermarks = /* @__PURE__ */ new Map();
|
|
8070
|
-
const reject = (claim, code,
|
|
8071
|
-
rejected.push({ claim, code, message });
|
|
9987
|
+
const reject = (claim, code, message2) => {
|
|
9988
|
+
rejected.push({ claim, code, message: message2 });
|
|
8072
9989
|
};
|
|
8073
9990
|
for (const claim of params.claims) {
|
|
8074
9991
|
if (!hasSettlementMetadata(claim)) {
|
|
@@ -9290,7 +11207,7 @@ import {
|
|
|
9290
11207
|
scryptSync,
|
|
9291
11208
|
createCipheriv,
|
|
9292
11209
|
createDecipheriv,
|
|
9293
|
-
randomBytes as
|
|
11210
|
+
randomBytes as randomBytes4
|
|
9294
11211
|
} from "crypto";
|
|
9295
11212
|
import { writeFileSync as writeFileSync3, readFileSync as readFileSync3 } from "fs";
|
|
9296
11213
|
var SCRYPT_N = 2 ** 17;
|
|
@@ -9317,8 +11234,8 @@ function encryptMnemonic2(mnemonic, password) {
|
|
|
9317
11234
|
if (typeof password !== "string" || password.length === 0) {
|
|
9318
11235
|
throw new Error("encryptMnemonic: password must be a non-empty string");
|
|
9319
11236
|
}
|
|
9320
|
-
const salt =
|
|
9321
|
-
const iv =
|
|
11237
|
+
const salt = randomBytes4(SALT_LEN);
|
|
11238
|
+
const iv = randomBytes4(IV_LEN);
|
|
9322
11239
|
const key2 = scryptSync(password, salt, SCRYPT_KEY_LEN, {
|
|
9323
11240
|
N: SCRYPT_N,
|
|
9324
11241
|
r: SCRYPT_R,
|
|
@@ -9420,12 +11337,14 @@ function writeKeystoreFile(path, keystore) {
|
|
|
9420
11337
|
});
|
|
9421
11338
|
}
|
|
9422
11339
|
export {
|
|
11340
|
+
BtpPaidWriteTransport,
|
|
9423
11341
|
BtpRuntimeClient,
|
|
9424
11342
|
CLAIM_TYPEHASH,
|
|
9425
11343
|
CONDITION_LENGTH,
|
|
9426
11344
|
COOP_CLOSE_TYPEHASH,
|
|
9427
11345
|
ChannelFundingError,
|
|
9428
11346
|
ChannelManager,
|
|
11347
|
+
ChannelResumeError,
|
|
9429
11348
|
ConnectorEdgeClient,
|
|
9430
11349
|
ConnectorEdgeError,
|
|
9431
11350
|
ConnectorError,
|
|
@@ -9439,17 +11358,26 @@ export {
|
|
|
9439
11358
|
GIFTWRAP_SECRET_LENGTH,
|
|
9440
11359
|
GIFTWRAP_TYPE_REQUEST,
|
|
9441
11360
|
GIFTWRAP_TYPE_RESPONSE,
|
|
11361
|
+
GIFT_WRAP_KIND,
|
|
9442
11362
|
GenerativeFallbackRenderer,
|
|
11363
|
+
GiftWrapAddressError,
|
|
11364
|
+
GiftWrapDecryptError,
|
|
9443
11365
|
GiftWrapError,
|
|
9444
11366
|
GiftWrapErrorKind,
|
|
11367
|
+
HashlockConditionMismatchError,
|
|
11368
|
+
HashlockDecryptError,
|
|
9445
11369
|
Http402Client,
|
|
9446
11370
|
HttpConnectorAdmin,
|
|
9447
11371
|
HttpIlpClient,
|
|
9448
11372
|
HttpRuntimeClient,
|
|
9449
11373
|
ILP_CLAIM_HEADER,
|
|
9450
11374
|
ILP_PEER_ID_HEADER,
|
|
11375
|
+
InMemoryChannelStore,
|
|
9451
11376
|
InMemoryPreimageRetentionStore,
|
|
9452
11377
|
InMemoryReceivedClaimStore,
|
|
11378
|
+
InsufficientBalanceError,
|
|
11379
|
+
InvalidAddressError,
|
|
11380
|
+
JsonFileChannelStore,
|
|
9453
11381
|
JsonFileReceivedClaimStore,
|
|
9454
11382
|
KeyManager,
|
|
9455
11383
|
KindRegistry,
|
|
@@ -9465,12 +11393,17 @@ export {
|
|
|
9465
11393
|
ROLLING_SWAP_DOMAIN_NAME,
|
|
9466
11394
|
ROLLING_SWAP_DOMAIN_VERSION,
|
|
9467
11395
|
RendererPinStore,
|
|
11396
|
+
SEAL_KIND,
|
|
9468
11397
|
SealedResponseError,
|
|
9469
11398
|
SolanaSigner,
|
|
11399
|
+
StaleRpcReadError,
|
|
9470
11400
|
ToonClient,
|
|
9471
11401
|
ToonClientError,
|
|
11402
|
+
TransferNotDeliveredError,
|
|
11403
|
+
TransferUnsupportedError,
|
|
9472
11404
|
UI_RENDERER_KIND,
|
|
9473
11405
|
UI_TAG,
|
|
11406
|
+
UnknownChainError,
|
|
9474
11407
|
ValidationError,
|
|
9475
11408
|
applyDefaults,
|
|
9476
11409
|
applyNetworkPresets,
|
|
@@ -9478,6 +11411,7 @@ export {
|
|
|
9478
11411
|
buildBackupEvent,
|
|
9479
11412
|
buildBackupFilter,
|
|
9480
11413
|
buildConsentRequest,
|
|
11414
|
+
buildIncrementPrepare,
|
|
9481
11415
|
buildMinaCoSignedClaim,
|
|
9482
11416
|
buildRendererEventTemplate,
|
|
9483
11417
|
buildSettlementInfo,
|
|
@@ -9485,6 +11419,7 @@ export {
|
|
|
9485
11419
|
buildUiCoordinate,
|
|
9486
11420
|
classifyIntent,
|
|
9487
11421
|
connectorEdgeBaseUrl,
|
|
11422
|
+
createJobMessageHandler,
|
|
9488
11423
|
createO1jsMinaClaimSubmitter,
|
|
9489
11424
|
decodeConnectorPublicKey,
|
|
9490
11425
|
decodeEnvelope,
|
|
@@ -9493,6 +11428,7 @@ export {
|
|
|
9493
11428
|
decodeEvmSettlementTx,
|
|
9494
11429
|
decodeVarOctetString2 as decodeVarOctetString,
|
|
9495
11430
|
decodeVarUint,
|
|
11431
|
+
decryptArtifact,
|
|
9496
11432
|
decryptMnemonic2 as decryptMnemonic,
|
|
9497
11433
|
defaultFaucetTimeout,
|
|
9498
11434
|
deployMinaChannelZkApp,
|
|
@@ -9507,6 +11443,7 @@ export {
|
|
|
9507
11443
|
encodeEnvelopeResponse,
|
|
9508
11444
|
encodeVarOctetString2 as encodeVarOctetString,
|
|
9509
11445
|
encodeVarUint,
|
|
11446
|
+
encryptArtifact,
|
|
9510
11447
|
encryptMnemonic2 as encryptMnemonic,
|
|
9511
11448
|
ensureOwnedMinaZkApp,
|
|
9512
11449
|
entryToAccumulatedClaim,
|
|
@@ -9515,6 +11452,7 @@ export {
|
|
|
9515
11452
|
evmCooperativeCloseDigest,
|
|
9516
11453
|
extractArweaveTxId,
|
|
9517
11454
|
extractUiResource,
|
|
11455
|
+
fulfillIncrement,
|
|
9518
11456
|
fulfillmentMatchesCondition,
|
|
9519
11457
|
fundWallet,
|
|
9520
11458
|
generateKeystore,
|
|
@@ -9539,6 +11477,7 @@ export {
|
|
|
9539
11477
|
openRequest,
|
|
9540
11478
|
openResponse,
|
|
9541
11479
|
parseBackupPayload,
|
|
11480
|
+
parseClaimStateResponse,
|
|
9542
11481
|
parseConnectorIdentity,
|
|
9543
11482
|
parseConnectorRoutePrice,
|
|
9544
11483
|
parseEvmChainId2 as parseEvmChainId,
|
|
@@ -9571,8 +11510,10 @@ export {
|
|
|
9571
11510
|
sealResponseWithRandomness,
|
|
9572
11511
|
selectIlpTransport,
|
|
9573
11512
|
selectLatestAddressable,
|
|
11513
|
+
sendTransfer,
|
|
9574
11514
|
submitEvmSettlement,
|
|
9575
11515
|
submitMinaSettlement,
|
|
11516
|
+
unwrapGiftWrapWithKey,
|
|
9576
11517
|
validateConfig,
|
|
9577
11518
|
validateMnemonic,
|
|
9578
11519
|
verifyEvmClaimSignature,
|