@atumlabs/payment-gateway-client 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3125 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJS = (cb, mod) => function __require() {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+
29
+ // ../contracts/evm/escrow-encoding/typescript/dist/payment-id.js
30
+ var require_payment_id = __commonJS({
31
+ "../contracts/evm/escrow-encoding/typescript/dist/payment-id.js"(exports2) {
32
+ "use strict";
33
+ Object.defineProperty(exports2, "__esModule", { value: true });
34
+ exports2.computePaymentId = computePaymentId;
35
+ exports2.computePaymentIdV2 = computePaymentIdV2;
36
+ var ethers_1 = require("ethers");
37
+ function computePaymentId(depositor, signature) {
38
+ const abiCoder = ethers_1.ethers.AbiCoder.defaultAbiCoder();
39
+ const encoded = abiCoder.encode(["address", "bytes"], [depositor, signature]);
40
+ return ethers_1.ethers.keccak256(encoded);
41
+ }
42
+ function computePaymentIdV2(depositor, signature, nonce) {
43
+ const abiCoder = ethers_1.ethers.AbiCoder.defaultAbiCoder();
44
+ const encoded = abiCoder.encode(["address", "bytes", "uint256"], [depositor, signature, nonce]);
45
+ return ethers_1.ethers.keccak256(encoded);
46
+ }
47
+ }
48
+ });
49
+
50
+ // ../contracts/evm/escrow-encoding/typescript/dist/nonce-generator.js
51
+ var require_nonce_generator = __commonJS({
52
+ "../contracts/evm/escrow-encoding/typescript/dist/nonce-generator.js"(exports2) {
53
+ "use strict";
54
+ Object.defineProperty(exports2, "__esModule", { value: true });
55
+ exports2.generateNonce = generateNonce2;
56
+ var ethers_1 = require("ethers");
57
+ function generateNonce2() {
58
+ return ethers_1.ethers.hexlify(ethers_1.ethers.randomBytes(32));
59
+ }
60
+ }
61
+ });
62
+
63
+ // ../contracts/evm/escrow-encoding/typescript/dist/permit-types.js
64
+ var require_permit_types = __commonJS({
65
+ "../contracts/evm/escrow-encoding/typescript/dist/permit-types.js"(exports2) {
66
+ "use strict";
67
+ Object.defineProperty(exports2, "__esModule", { value: true });
68
+ exports2.REFUND_WITNESS_TYPES = exports2.RELEASE_WITNESS_TYPES = exports2.RESERVE_WITNESS_TYPES = exports2.PERMIT_WITNESS_TYPES_V2 = exports2.PERMIT_WITNESS_TYPES = void 0;
69
+ exports2.createPermit2Domain = createPermit2Domain;
70
+ exports2.createEscrowDomain = createEscrowDomain;
71
+ exports2.PERMIT_WITNESS_TYPES = {
72
+ PermitWitnessTransferFrom: [
73
+ { name: "permitted", type: "TokenPermissions" },
74
+ { name: "spender", type: "address" },
75
+ { name: "nonce", type: "uint256" },
76
+ { name: "deadline", type: "uint256" },
77
+ { name: "witness", type: "DepositWitness" }
78
+ ],
79
+ TokenPermissions: [
80
+ { name: "token", type: "address" },
81
+ { name: "amount", type: "uint256" }
82
+ ],
83
+ DepositWitness: [
84
+ { name: "requestId", type: "bytes32" },
85
+ { name: "reserver", type: "address" },
86
+ { name: "releaser", type: "address" }
87
+ ]
88
+ };
89
+ exports2.PERMIT_WITNESS_TYPES_V2 = {
90
+ PermitWitnessTransferFrom: [
91
+ { name: "permitted", type: "TokenPermissions" },
92
+ { name: "spender", type: "address" },
93
+ { name: "nonce", type: "uint256" },
94
+ { name: "deadline", type: "uint256" },
95
+ { name: "witness", type: "DepositWitness" }
96
+ ],
97
+ TokenPermissions: [
98
+ { name: "token", type: "address" },
99
+ { name: "amount", type: "uint256" }
100
+ ],
101
+ DepositWitness: [
102
+ { name: "reserver", type: "address" },
103
+ { name: "releaser", type: "address" }
104
+ ]
105
+ };
106
+ function createPermit2Domain(chainId, verifyingContract) {
107
+ return {
108
+ name: "Permit2",
109
+ chainId,
110
+ verifyingContract
111
+ };
112
+ }
113
+ function createEscrowDomain(chainId, verifyingContract) {
114
+ return {
115
+ name: "Escrow",
116
+ version: "3",
117
+ chainId,
118
+ verifyingContract
119
+ };
120
+ }
121
+ exports2.RESERVE_WITNESS_TYPES = {
122
+ ReserveWitness: [
123
+ { name: "paymentId", type: "bytes32" },
124
+ { name: "settler", type: "address" }
125
+ ]
126
+ };
127
+ exports2.RELEASE_WITNESS_TYPES = {
128
+ ReleaseWitness: [
129
+ { name: "paymentId", type: "bytes32" },
130
+ { name: "depositor", type: "address" },
131
+ { name: "token", type: "address" },
132
+ { name: "amount", type: "uint256" },
133
+ { name: "feeAmount", type: "uint256" },
134
+ { name: "reserver", type: "address" },
135
+ { name: "releaser", type: "address" },
136
+ { name: "settler", type: "address" }
137
+ ]
138
+ };
139
+ exports2.REFUND_WITNESS_TYPES = {
140
+ RefundWitness: [
141
+ { name: "paymentId", type: "bytes32" },
142
+ { name: "depositor", type: "address" },
143
+ { name: "token", type: "address" },
144
+ { name: "amount", type: "uint256" },
145
+ { name: "feeAmount", type: "uint256" },
146
+ { name: "reserver", type: "address" },
147
+ { name: "releaser", type: "address" },
148
+ { name: "settler", type: "address" }
149
+ ]
150
+ };
151
+ }
152
+ });
153
+
154
+ // ../contracts/evm/escrow-encoding/typescript/dist/escrow-abi.js
155
+ var require_escrow_abi = __commonJS({
156
+ "../contracts/evm/escrow-encoding/typescript/dist/escrow-abi.js"(exports2) {
157
+ "use strict";
158
+ Object.defineProperty(exports2, "__esModule", { value: true });
159
+ exports2.ESCROW_V2_ABI_JSON = exports2.ESCROW_V3_ABI_JSON = exports2.ESCROW_ABI_JSON = exports2.ESCROW_ABI = void 0;
160
+ exports2.ESCROW_ABI = [
161
+ "function deposit((( address token, uint256 amount) permitted, uint256 nonce, uint256 deadline) permit, address depositor, (bytes32 requestId, address reserver, address releaser) witness, bytes signature) returns (bytes32)",
162
+ "function refund((bytes32 depositId, uint256 deadline) witness, bytes signature)",
163
+ "function getDepositInfo(bytes32 depositId) view returns ((address depositor, address token, uint256 amount, address reserver, address releaser, address settler))",
164
+ "function i_permit2() view returns (address)"
165
+ ];
166
+ exports2.ESCROW_ABI_JSON = [
167
+ {
168
+ type: "function",
169
+ name: "deposit",
170
+ inputs: [
171
+ {
172
+ name: "permit",
173
+ type: "tuple",
174
+ components: [
175
+ {
176
+ name: "permitted",
177
+ type: "tuple",
178
+ components: [
179
+ { name: "token", type: "address" },
180
+ { name: "amount", type: "uint256" }
181
+ ]
182
+ },
183
+ { name: "nonce", type: "uint256" },
184
+ { name: "deadline", type: "uint256" }
185
+ ]
186
+ },
187
+ { name: "depositor", type: "address" },
188
+ {
189
+ name: "witness",
190
+ type: "tuple",
191
+ components: [
192
+ { name: "requestId", type: "bytes32" },
193
+ { name: "reserver", type: "address" },
194
+ { name: "releaser", type: "address" }
195
+ ]
196
+ },
197
+ { name: "signature", type: "bytes" }
198
+ ],
199
+ outputs: [{ name: "depositId", type: "bytes32" }],
200
+ stateMutability: "nonpayable"
201
+ },
202
+ {
203
+ type: "function",
204
+ name: "refund",
205
+ inputs: [
206
+ {
207
+ name: "witness",
208
+ type: "tuple",
209
+ components: [
210
+ { name: "depositId", type: "bytes32" },
211
+ { name: "deadline", type: "uint256" }
212
+ ]
213
+ },
214
+ { name: "signature", type: "bytes" }
215
+ ],
216
+ outputs: [],
217
+ stateMutability: "nonpayable"
218
+ },
219
+ {
220
+ type: "function",
221
+ name: "getDepositInfo",
222
+ inputs: [{ name: "depositId", type: "bytes32" }],
223
+ outputs: [
224
+ {
225
+ name: "",
226
+ type: "tuple",
227
+ components: [
228
+ { name: "depositor", type: "address" },
229
+ { name: "token", type: "address" },
230
+ { name: "amount", type: "uint256" },
231
+ { name: "reserver", type: "address" },
232
+ { name: "releaser", type: "address" },
233
+ { name: "settler", type: "address" }
234
+ ]
235
+ }
236
+ ],
237
+ stateMutability: "view"
238
+ },
239
+ {
240
+ type: "function",
241
+ name: "i_permit2",
242
+ inputs: [],
243
+ outputs: [{ name: "", type: "address" }],
244
+ stateMutability: "view"
245
+ }
246
+ ];
247
+ exports2.ESCROW_V3_ABI_JSON = [
248
+ {
249
+ type: "function",
250
+ name: "deposit",
251
+ inputs: [
252
+ {
253
+ name: "depositInput",
254
+ type: "tuple",
255
+ components: [
256
+ {
257
+ name: "permit",
258
+ type: "tuple",
259
+ components: [
260
+ {
261
+ name: "permitted",
262
+ type: "tuple",
263
+ components: [
264
+ { name: "token", type: "address" },
265
+ { name: "amount", type: "uint256" }
266
+ ]
267
+ },
268
+ { name: "nonce", type: "uint256" },
269
+ { name: "deadline", type: "uint256" }
270
+ ]
271
+ },
272
+ { name: "depositor", type: "address" },
273
+ {
274
+ name: "depositWitness",
275
+ type: "tuple",
276
+ components: [
277
+ { name: "reserver", type: "address" },
278
+ { name: "releaser", type: "address" }
279
+ ]
280
+ },
281
+ { name: "depositSignature", type: "bytes" },
282
+ {
283
+ name: "reserveWitness",
284
+ type: "tuple",
285
+ components: [
286
+ { name: "paymentId", type: "bytes32" },
287
+ { name: "settler", type: "address" }
288
+ ]
289
+ },
290
+ { name: "reserveSignature", type: "bytes" }
291
+ ]
292
+ }
293
+ ],
294
+ outputs: [{ name: "paymentId", type: "bytes32" }],
295
+ stateMutability: "nonpayable"
296
+ },
297
+ {
298
+ type: "function",
299
+ name: "refund",
300
+ inputs: [
301
+ {
302
+ name: "refundInput",
303
+ type: "tuple",
304
+ components: [
305
+ {
306
+ name: "refundWitness",
307
+ type: "tuple",
308
+ components: [
309
+ { name: "paymentId", type: "bytes32" },
310
+ { name: "depositor", type: "address" },
311
+ { name: "token", type: "address" },
312
+ { name: "amount", type: "uint256" },
313
+ { name: "feeAmount", type: "uint256" },
314
+ { name: "reserver", type: "address" },
315
+ { name: "releaser", type: "address" },
316
+ { name: "settler", type: "address" }
317
+ ]
318
+ },
319
+ { name: "refundSignature", type: "bytes" }
320
+ ]
321
+ }
322
+ ],
323
+ outputs: [],
324
+ stateMutability: "nonpayable"
325
+ },
326
+ {
327
+ type: "function",
328
+ name: "getDepositHash",
329
+ inputs: [{ name: "paymentId", type: "bytes32" }],
330
+ outputs: [{ name: "", type: "bytes32" }],
331
+ stateMutability: "view"
332
+ },
333
+ {
334
+ type: "function",
335
+ name: "i_permit2",
336
+ inputs: [],
337
+ outputs: [{ name: "", type: "address" }],
338
+ stateMutability: "view"
339
+ }
340
+ ];
341
+ exports2.ESCROW_V2_ABI_JSON = exports2.ESCROW_V3_ABI_JSON;
342
+ }
343
+ });
344
+
345
+ // ../contracts/evm/escrow-encoding/typescript/dist/reserve-encoder.js
346
+ var require_reserve_encoder = __commonJS({
347
+ "../contracts/evm/escrow-encoding/typescript/dist/reserve-encoder.js"(exports2) {
348
+ "use strict";
349
+ Object.defineProperty(exports2, "__esModule", { value: true });
350
+ exports2.computeReserveDigest = computeReserveDigest;
351
+ var ethers_1 = require("ethers");
352
+ var permit_types_1 = require_permit_types();
353
+ function computeReserveDigest(input) {
354
+ const domain = (0, permit_types_1.createEscrowDomain)(input.chainId, input.escrowContract);
355
+ return ethers_1.TypedDataEncoder.hash(domain, permit_types_1.RESERVE_WITNESS_TYPES, {
356
+ paymentId: input.paymentId,
357
+ settler: input.settler
358
+ });
359
+ }
360
+ }
361
+ });
362
+
363
+ // ../contracts/evm/escrow-encoding/typescript/dist/deposit-encoder.js
364
+ var require_deposit_encoder = __commonJS({
365
+ "../contracts/evm/escrow-encoding/typescript/dist/deposit-encoder.js"(exports2) {
366
+ "use strict";
367
+ Object.defineProperty(exports2, "__esModule", { value: true });
368
+ exports2.PERMIT2_CONTRACT_ADDRESS = void 0;
369
+ exports2.createPermitWitnessTransferFromPrehash = createPermitWitnessTransferFromPrehash2;
370
+ exports2.hashPermitWitnessTransferFrom = hashPermitWitnessTransferFrom2;
371
+ var ethers_1 = require("ethers");
372
+ var permit_types_1 = require_permit_types();
373
+ exports2.PERMIT2_CONTRACT_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
374
+ function createPermitWitnessTransferFromPrehash2(params) {
375
+ return {
376
+ types: permit_types_1.PERMIT_WITNESS_TYPES_V2,
377
+ primaryType: "PermitWitnessTransferFrom",
378
+ domain: {
379
+ name: "Permit2",
380
+ chainId: `0x${params.chainId.toString(16)}`,
381
+ verifyingContract: params.verifyingContract
382
+ },
383
+ message: {
384
+ permitted: {
385
+ token: params.token,
386
+ amount: params.amount
387
+ },
388
+ spender: params.spender,
389
+ nonce: params.nonce.toString(),
390
+ deadline: params.deadline.toString(),
391
+ witness: {
392
+ reserver: params.reserver,
393
+ releaser: params.releaser
394
+ }
395
+ }
396
+ };
397
+ }
398
+ function hashPermitWitnessTransferFrom2(prehash) {
399
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
400
+ }
401
+ }
402
+ });
403
+
404
+ // ../contracts/evm/escrow-encoding/typescript/dist/index.js
405
+ var require_dist = __commonJS({
406
+ "../contracts/evm/escrow-encoding/typescript/dist/index.js"(exports2) {
407
+ "use strict";
408
+ Object.defineProperty(exports2, "__esModule", { value: true });
409
+ exports2.PERMIT2_CONTRACT_ADDRESS = exports2.hashPermitWitnessTransferFrom = exports2.createPermitWitnessTransferFromPrehash = exports2.computeReserveDigest = exports2.ESCROW_V3_ABI_JSON = exports2.ESCROW_V2_ABI_JSON = exports2.ESCROW_ABI_JSON = exports2.ESCROW_ABI = exports2.REFUND_WITNESS_TYPES = exports2.RELEASE_WITNESS_TYPES = exports2.RESERVE_WITNESS_TYPES = exports2.createEscrowDomain = exports2.createPermit2Domain = exports2.PERMIT_WITNESS_TYPES_V2 = exports2.PERMIT_WITNESS_TYPES = exports2.generateNonce = exports2.computePaymentIdV2 = exports2.computePaymentId = void 0;
410
+ var payment_id_1 = require_payment_id();
411
+ Object.defineProperty(exports2, "computePaymentId", { enumerable: true, get: function() {
412
+ return payment_id_1.computePaymentId;
413
+ } });
414
+ Object.defineProperty(exports2, "computePaymentIdV2", { enumerable: true, get: function() {
415
+ return payment_id_1.computePaymentIdV2;
416
+ } });
417
+ var nonce_generator_1 = require_nonce_generator();
418
+ Object.defineProperty(exports2, "generateNonce", { enumerable: true, get: function() {
419
+ return nonce_generator_1.generateNonce;
420
+ } });
421
+ var permit_types_1 = require_permit_types();
422
+ Object.defineProperty(exports2, "PERMIT_WITNESS_TYPES", { enumerable: true, get: function() {
423
+ return permit_types_1.PERMIT_WITNESS_TYPES;
424
+ } });
425
+ Object.defineProperty(exports2, "PERMIT_WITNESS_TYPES_V2", { enumerable: true, get: function() {
426
+ return permit_types_1.PERMIT_WITNESS_TYPES_V2;
427
+ } });
428
+ Object.defineProperty(exports2, "createPermit2Domain", { enumerable: true, get: function() {
429
+ return permit_types_1.createPermit2Domain;
430
+ } });
431
+ Object.defineProperty(exports2, "createEscrowDomain", { enumerable: true, get: function() {
432
+ return permit_types_1.createEscrowDomain;
433
+ } });
434
+ Object.defineProperty(exports2, "RESERVE_WITNESS_TYPES", { enumerable: true, get: function() {
435
+ return permit_types_1.RESERVE_WITNESS_TYPES;
436
+ } });
437
+ Object.defineProperty(exports2, "RELEASE_WITNESS_TYPES", { enumerable: true, get: function() {
438
+ return permit_types_1.RELEASE_WITNESS_TYPES;
439
+ } });
440
+ Object.defineProperty(exports2, "REFUND_WITNESS_TYPES", { enumerable: true, get: function() {
441
+ return permit_types_1.REFUND_WITNESS_TYPES;
442
+ } });
443
+ var escrow_abi_1 = require_escrow_abi();
444
+ Object.defineProperty(exports2, "ESCROW_ABI", { enumerable: true, get: function() {
445
+ return escrow_abi_1.ESCROW_ABI;
446
+ } });
447
+ Object.defineProperty(exports2, "ESCROW_ABI_JSON", { enumerable: true, get: function() {
448
+ return escrow_abi_1.ESCROW_ABI_JSON;
449
+ } });
450
+ Object.defineProperty(exports2, "ESCROW_V2_ABI_JSON", { enumerable: true, get: function() {
451
+ return escrow_abi_1.ESCROW_V2_ABI_JSON;
452
+ } });
453
+ Object.defineProperty(exports2, "ESCROW_V3_ABI_JSON", { enumerable: true, get: function() {
454
+ return escrow_abi_1.ESCROW_V3_ABI_JSON;
455
+ } });
456
+ var reserve_encoder_1 = require_reserve_encoder();
457
+ Object.defineProperty(exports2, "computeReserveDigest", { enumerable: true, get: function() {
458
+ return reserve_encoder_1.computeReserveDigest;
459
+ } });
460
+ var deposit_encoder_1 = require_deposit_encoder();
461
+ Object.defineProperty(exports2, "createPermitWitnessTransferFromPrehash", { enumerable: true, get: function() {
462
+ return deposit_encoder_1.createPermitWitnessTransferFromPrehash;
463
+ } });
464
+ Object.defineProperty(exports2, "hashPermitWitnessTransferFrom", { enumerable: true, get: function() {
465
+ return deposit_encoder_1.hashPermitWitnessTransferFrom;
466
+ } });
467
+ Object.defineProperty(exports2, "PERMIT2_CONTRACT_ADDRESS", { enumerable: true, get: function() {
468
+ return deposit_encoder_1.PERMIT2_CONTRACT_ADDRESS;
469
+ } });
470
+ }
471
+ });
472
+
473
+ // ../contracts/tvm/escrow-encoding/typescript/dist/chain-id.js
474
+ var require_chain_id = __commonJS({
475
+ "../contracts/tvm/escrow-encoding/typescript/dist/chain-id.js"(exports2) {
476
+ "use strict";
477
+ Object.defineProperty(exports2, "__esModule", { value: true });
478
+ exports2.maskChainId = maskChainId2;
479
+ function maskChainId2(chainId) {
480
+ return (chainId & 4294967295) >>> 0;
481
+ }
482
+ }
483
+ });
484
+
485
+ // ../contracts/tvm/escrow-encoding/typescript/dist/tron-address.js
486
+ var require_tron_address = __commonJS({
487
+ "../contracts/tvm/escrow-encoding/typescript/dist/tron-address.js"(exports2) {
488
+ "use strict";
489
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
490
+ return mod && mod.__esModule ? mod : { "default": mod };
491
+ };
492
+ Object.defineProperty(exports2, "__esModule", { value: true });
493
+ exports2.base58ToHex = base58ToHex2;
494
+ exports2.normalizeAddress = normalizeAddress2;
495
+ var ethers_1 = require("ethers");
496
+ var bs58_1 = __importDefault(require("bs58"));
497
+ var TVM_MAINNET_PREFIX = "41";
498
+ function base58ToHex2(base58Address) {
499
+ if (!base58Address || !base58Address.startsWith("T")) {
500
+ throw new Error(`Invalid Tron base58 address: ${base58Address}`);
501
+ }
502
+ const decoded = bs58_1.default.decode(base58Address);
503
+ if (decoded.length !== 25) {
504
+ throw new Error(`Invalid Tron base58 length (expected 25 bytes): ${base58Address}`);
505
+ }
506
+ const payload = decoded.slice(0, 21);
507
+ const checksum = (0, ethers_1.hexlify)(decoded.slice(21)).slice(2);
508
+ const computed = (0, ethers_1.sha256)((0, ethers_1.sha256)(payload)).slice(2, 10);
509
+ if (checksum !== computed) {
510
+ throw new Error(`Invalid Tron base58 checksum: ${base58Address}`);
511
+ }
512
+ return (0, ethers_1.hexlify)(payload).slice(2);
513
+ }
514
+ function normalizeAddress2(address) {
515
+ if (!address) {
516
+ throw new Error("Empty address");
517
+ }
518
+ let hexAddress = address;
519
+ if (address.startsWith("T")) {
520
+ hexAddress = base58ToHex2(address);
521
+ }
522
+ hexAddress = hexAddress.replace(/^0x/, "");
523
+ if (hexAddress.startsWith(TVM_MAINNET_PREFIX)) {
524
+ hexAddress = hexAddress.substring(2);
525
+ }
526
+ if (hexAddress.length !== 40) {
527
+ throw new Error(`Invalid address length: expected 40 chars, got ${hexAddress.length}`);
528
+ }
529
+ if (!/^[0-9a-fA-F]{40}$/.test(hexAddress)) {
530
+ throw new Error("Invalid hex address format");
531
+ }
532
+ return "0x" + hexAddress.toLowerCase();
533
+ }
534
+ }
535
+ });
536
+
537
+ // ../contracts/tvm/escrow-encoding/typescript/dist/reserve-encoder.js
538
+ var require_reserve_encoder2 = __commonJS({
539
+ "../contracts/tvm/escrow-encoding/typescript/dist/reserve-encoder.js"(exports2) {
540
+ "use strict";
541
+ Object.defineProperty(exports2, "__esModule", { value: true });
542
+ exports2.computeReserveDigest = computeReserveDigest;
543
+ var ethers_1 = require("ethers");
544
+ var chain_id_1 = require_chain_id();
545
+ var RESERVE_WITNESS_TYPES = {
546
+ ReserveWitness: [
547
+ { name: "paymentId", type: "bytes32" },
548
+ { name: "settler", type: "address" }
549
+ ]
550
+ };
551
+ function computeReserveDigest(input) {
552
+ const domain = {
553
+ name: "Escrow",
554
+ version: "3",
555
+ chainId: (0, chain_id_1.maskChainId)(input.chainId),
556
+ verifyingContract: input.escrowContract
557
+ };
558
+ return ethers_1.TypedDataEncoder.hash(domain, RESERVE_WITNESS_TYPES, {
559
+ paymentId: input.paymentId,
560
+ settler: input.settler
561
+ });
562
+ }
563
+ }
564
+ });
565
+
566
+ // ../contracts/tvm/escrow-encoding/typescript/dist/payment-id.js
567
+ var require_payment_id2 = __commonJS({
568
+ "../contracts/tvm/escrow-encoding/typescript/dist/payment-id.js"(exports2) {
569
+ "use strict";
570
+ Object.defineProperty(exports2, "__esModule", { value: true });
571
+ exports2.computePaymentId = computePaymentId;
572
+ var ethers_1 = require("ethers");
573
+ var tron_address_1 = require_tron_address();
574
+ function computePaymentId(depositor, signature, nonce) {
575
+ if (!/^[0-9]+$/.test(nonce)) {
576
+ throw new Error(`invalid nonce (expected base-10 decimal): ${nonce}`);
577
+ }
578
+ const encoded = ethers_1.AbiCoder.defaultAbiCoder().encode(["address", "bytes", "uint256"], [(0, tron_address_1.normalizeAddress)(depositor), signature, nonce]);
579
+ return (0, ethers_1.keccak256)(encoded);
580
+ }
581
+ }
582
+ });
583
+
584
+ // ../contracts/tvm/escrow-encoding/typescript/dist/deposit-encoder.js
585
+ var require_deposit_encoder2 = __commonJS({
586
+ "../contracts/tvm/escrow-encoding/typescript/dist/deposit-encoder.js"(exports2) {
587
+ "use strict";
588
+ Object.defineProperty(exports2, "__esModule", { value: true });
589
+ exports2.createTvmPermitWitnessTransferFromPrehash = createTvmPermitWitnessTransferFromPrehash2;
590
+ exports2.hashTvmPermitWitnessTransferFrom = hashTvmPermitWitnessTransferFrom2;
591
+ var ethers_1 = require("ethers");
592
+ var chain_id_1 = require_chain_id();
593
+ var tron_address_1 = require_tron_address();
594
+ var PERMIT_WITNESS_TYPES_V2 = {
595
+ PermitWitnessTransferFrom: [
596
+ { name: "permitted", type: "TokenPermissions" },
597
+ { name: "spender", type: "address" },
598
+ { name: "nonce", type: "uint256" },
599
+ { name: "deadline", type: "uint256" },
600
+ { name: "witness", type: "DepositWitness" }
601
+ ],
602
+ TokenPermissions: [
603
+ { name: "token", type: "address" },
604
+ { name: "amount", type: "uint256" }
605
+ ],
606
+ DepositWitness: [
607
+ { name: "reserver", type: "address" },
608
+ { name: "releaser", type: "address" }
609
+ ]
610
+ };
611
+ function createTvmPermitWitnessTransferFromPrehash2(params) {
612
+ const maskedChainId = (0, chain_id_1.maskChainId)(params.chainId);
613
+ return {
614
+ types: PERMIT_WITNESS_TYPES_V2,
615
+ primaryType: "PermitWitnessTransferFrom",
616
+ domain: {
617
+ name: "Permit2",
618
+ chainId: `0x${maskedChainId.toString(16)}`,
619
+ verifyingContract: (0, tron_address_1.normalizeAddress)(params.permit2Address)
620
+ },
621
+ message: {
622
+ permitted: {
623
+ token: (0, tron_address_1.normalizeAddress)(params.tokenAddress),
624
+ amount: params.amount
625
+ },
626
+ spender: (0, tron_address_1.normalizeAddress)(params.spenderAddress),
627
+ nonce: params.nonce.toString(),
628
+ deadline: params.deadline.toString(),
629
+ witness: {
630
+ reserver: (0, tron_address_1.normalizeAddress)(params.reserverAddress),
631
+ releaser: (0, tron_address_1.normalizeAddress)(params.releaserAddress)
632
+ }
633
+ }
634
+ };
635
+ }
636
+ function hashTvmPermitWitnessTransferFrom2(prehash) {
637
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
638
+ }
639
+ }
640
+ });
641
+
642
+ // ../contracts/tvm/escrow-encoding/typescript/dist/index.js
643
+ var require_dist2 = __commonJS({
644
+ "../contracts/tvm/escrow-encoding/typescript/dist/index.js"(exports2) {
645
+ "use strict";
646
+ Object.defineProperty(exports2, "__esModule", { value: true });
647
+ exports2.hashTvmPermitWitnessTransferFrom = exports2.createTvmPermitWitnessTransferFromPrehash = exports2.computePaymentId = exports2.computeReserveDigest = exports2.normalizeAddress = exports2.base58ToHex = exports2.maskChainId = void 0;
648
+ var chain_id_1 = require_chain_id();
649
+ Object.defineProperty(exports2, "maskChainId", { enumerable: true, get: function() {
650
+ return chain_id_1.maskChainId;
651
+ } });
652
+ var tron_address_1 = require_tron_address();
653
+ Object.defineProperty(exports2, "base58ToHex", { enumerable: true, get: function() {
654
+ return tron_address_1.base58ToHex;
655
+ } });
656
+ Object.defineProperty(exports2, "normalizeAddress", { enumerable: true, get: function() {
657
+ return tron_address_1.normalizeAddress;
658
+ } });
659
+ var reserve_encoder_1 = require_reserve_encoder2();
660
+ Object.defineProperty(exports2, "computeReserveDigest", { enumerable: true, get: function() {
661
+ return reserve_encoder_1.computeReserveDigest;
662
+ } });
663
+ var payment_id_1 = require_payment_id2();
664
+ Object.defineProperty(exports2, "computePaymentId", { enumerable: true, get: function() {
665
+ return payment_id_1.computePaymentId;
666
+ } });
667
+ var deposit_encoder_1 = require_deposit_encoder2();
668
+ Object.defineProperty(exports2, "createTvmPermitWitnessTransferFromPrehash", { enumerable: true, get: function() {
669
+ return deposit_encoder_1.createTvmPermitWitnessTransferFromPrehash;
670
+ } });
671
+ Object.defineProperty(exports2, "hashTvmPermitWitnessTransferFrom", { enumerable: true, get: function() {
672
+ return deposit_encoder_1.hashTvmPermitWitnessTransferFrom;
673
+ } });
674
+ }
675
+ });
676
+
677
+ // ../contracts/svm/escrow-encoding/typescript/dist/errors.js
678
+ var require_errors = __commonJS({
679
+ "../contracts/svm/escrow-encoding/typescript/dist/errors.js"(exports2) {
680
+ "use strict";
681
+ Object.defineProperty(exports2, "__esModule", { value: true });
682
+ exports2.InvalidHexError = exports2.InvalidBase58Error = exports2.InvalidPubkeyLengthError = exports2.ZeroDepositHashError = exports2.ZeroRecipientError = exports2.ZeroReleaserError = exports2.ZeroReserverError = exports2.ZeroAmountError = exports2.ZeroMintError = exports2.ZeroDepositorError = exports2.ZeroPaymentIdError = exports2.EncodingError = void 0;
683
+ var EncodingError = class extends Error {
684
+ constructor(message) {
685
+ super(message);
686
+ this.name = "EncodingError";
687
+ }
688
+ };
689
+ exports2.EncodingError = EncodingError;
690
+ var ZeroPaymentIdError = class extends EncodingError {
691
+ constructor() {
692
+ super("payment ID cannot be zero");
693
+ this.name = "ZeroPaymentIdError";
694
+ }
695
+ };
696
+ exports2.ZeroPaymentIdError = ZeroPaymentIdError;
697
+ var ZeroDepositorError = class extends EncodingError {
698
+ constructor() {
699
+ super("depositor cannot be zero");
700
+ this.name = "ZeroDepositorError";
701
+ }
702
+ };
703
+ exports2.ZeroDepositorError = ZeroDepositorError;
704
+ var ZeroMintError = class extends EncodingError {
705
+ constructor() {
706
+ super("mint cannot be zero");
707
+ this.name = "ZeroMintError";
708
+ }
709
+ };
710
+ exports2.ZeroMintError = ZeroMintError;
711
+ var ZeroAmountError = class extends EncodingError {
712
+ constructor() {
713
+ super("amount cannot be zero");
714
+ this.name = "ZeroAmountError";
715
+ }
716
+ };
717
+ exports2.ZeroAmountError = ZeroAmountError;
718
+ var ZeroReserverError = class extends EncodingError {
719
+ constructor() {
720
+ super("reserver cannot be zero");
721
+ this.name = "ZeroReserverError";
722
+ }
723
+ };
724
+ exports2.ZeroReserverError = ZeroReserverError;
725
+ var ZeroReleaserError = class extends EncodingError {
726
+ constructor() {
727
+ super("releaser cannot be zero");
728
+ this.name = "ZeroReleaserError";
729
+ }
730
+ };
731
+ exports2.ZeroReleaserError = ZeroReleaserError;
732
+ var ZeroRecipientError = class extends EncodingError {
733
+ constructor() {
734
+ super("recipient cannot be zero");
735
+ this.name = "ZeroRecipientError";
736
+ }
737
+ };
738
+ exports2.ZeroRecipientError = ZeroRecipientError;
739
+ var ZeroDepositHashError = class extends EncodingError {
740
+ constructor() {
741
+ super("deposit hash cannot be zero");
742
+ this.name = "ZeroDepositHashError";
743
+ }
744
+ };
745
+ exports2.ZeroDepositHashError = ZeroDepositHashError;
746
+ var InvalidPubkeyLengthError = class extends EncodingError {
747
+ constructor() {
748
+ super("invalid pubkey length: expected 32 bytes");
749
+ this.name = "InvalidPubkeyLengthError";
750
+ }
751
+ };
752
+ exports2.InvalidPubkeyLengthError = InvalidPubkeyLengthError;
753
+ var InvalidBase58Error = class extends EncodingError {
754
+ constructor() {
755
+ super("invalid base58 encoding");
756
+ this.name = "InvalidBase58Error";
757
+ }
758
+ };
759
+ exports2.InvalidBase58Error = InvalidBase58Error;
760
+ var InvalidHexError = class extends EncodingError {
761
+ constructor() {
762
+ super("invalid hex encoding");
763
+ this.name = "InvalidHexError";
764
+ }
765
+ };
766
+ exports2.InvalidHexError = InvalidHexError;
767
+ }
768
+ });
769
+
770
+ // ../contracts/svm/escrow-encoding/typescript/dist/pubkey.js
771
+ var require_pubkey = __commonJS({
772
+ "../contracts/svm/escrow-encoding/typescript/dist/pubkey.js"(exports2) {
773
+ "use strict";
774
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
775
+ return mod && mod.__esModule ? mod : { "default": mod };
776
+ };
777
+ Object.defineProperty(exports2, "__esModule", { value: true });
778
+ exports2.Pubkey = void 0;
779
+ var bs58_1 = __importDefault(require("bs58"));
780
+ var errors_1 = require_errors();
781
+ var Pubkey3 = class _Pubkey {
782
+ constructor(data) {
783
+ if (data.length !== 32) {
784
+ throw new errors_1.InvalidPubkeyLengthError();
785
+ }
786
+ this.data = data;
787
+ }
788
+ /**
789
+ * Creates a Pubkey from a Base58-encoded string.
790
+ * This is the standard format for Solana public keys.
791
+ */
792
+ static fromBase58(s) {
793
+ try {
794
+ const decoded = bs58_1.default.decode(s);
795
+ if (decoded.length !== 32) {
796
+ throw new errors_1.InvalidPubkeyLengthError();
797
+ }
798
+ return new _Pubkey(decoded);
799
+ } catch (e) {
800
+ if (e instanceof errors_1.InvalidPubkeyLengthError) {
801
+ throw e;
802
+ }
803
+ throw new errors_1.InvalidBase58Error();
804
+ }
805
+ }
806
+ /**
807
+ * Creates a Pubkey from a hex-encoded string.
808
+ * Accepts with or without "0x" prefix.
809
+ */
810
+ static fromHex(s) {
811
+ let hex = s;
812
+ if (hex.startsWith("0x") || hex.startsWith("0X")) {
813
+ hex = hex.slice(2);
814
+ }
815
+ if (hex.length !== 64) {
816
+ throw new errors_1.InvalidPubkeyLengthError();
817
+ }
818
+ try {
819
+ const bytes = new Uint8Array(32);
820
+ for (let i = 0; i < 32; i++) {
821
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
822
+ if (isNaN(bytes[i])) {
823
+ throw new errors_1.InvalidHexError();
824
+ }
825
+ }
826
+ return new _Pubkey(bytes);
827
+ } catch (e) {
828
+ if (e instanceof errors_1.InvalidPubkeyLengthError || e instanceof errors_1.InvalidHexError) {
829
+ throw e;
830
+ }
831
+ throw new errors_1.InvalidHexError();
832
+ }
833
+ }
834
+ /**
835
+ * Creates a Pubkey from raw bytes.
836
+ */
837
+ static fromBytes(bytes) {
838
+ if (bytes.length !== 32) {
839
+ throw new errors_1.InvalidPubkeyLengthError();
840
+ }
841
+ return new _Pubkey(new Uint8Array(bytes));
842
+ }
843
+ /**
844
+ * Returns the pubkey as a byte array.
845
+ */
846
+ toBytes() {
847
+ return new Uint8Array(this.data);
848
+ }
849
+ /**
850
+ * Returns the Base58 encoding of the pubkey.
851
+ */
852
+ toString() {
853
+ return bs58_1.default.encode(this.data);
854
+ }
855
+ /**
856
+ * Returns the hex encoding of the pubkey (without 0x prefix).
857
+ */
858
+ toHex() {
859
+ return Array.from(this.data).map((b) => b.toString(16).padStart(2, "0")).join("");
860
+ }
861
+ /**
862
+ * Returns true if the pubkey is all zeros.
863
+ */
864
+ isZero() {
865
+ return this.data.every((b) => b === 0);
866
+ }
867
+ /**
868
+ * Returns true if this pubkey equals another.
869
+ */
870
+ equals(other) {
871
+ return this.data.every((b, i) => b === other.data[i]);
872
+ }
873
+ };
874
+ exports2.Pubkey = Pubkey3;
875
+ }
876
+ });
877
+
878
+ // ../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/_u64.js
879
+ var require_u64 = __commonJS({
880
+ "../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/_u64.js"(exports2) {
881
+ "use strict";
882
+ Object.defineProperty(exports2, "__esModule", { value: true });
883
+ exports2.toBig = exports2.shrSL = exports2.shrSH = exports2.rotrSL = exports2.rotrSH = exports2.rotrBL = exports2.rotrBH = exports2.rotr32L = exports2.rotr32H = exports2.rotlSL = exports2.rotlSH = exports2.rotlBL = exports2.rotlBH = exports2.add5L = exports2.add5H = exports2.add4L = exports2.add4H = exports2.add3L = exports2.add3H = void 0;
884
+ exports2.add = add;
885
+ exports2.fromBig = fromBig;
886
+ exports2.split = split;
887
+ var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
888
+ var _32n = /* @__PURE__ */ BigInt(32);
889
+ function fromBig(n, le = false) {
890
+ if (le)
891
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
892
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
893
+ }
894
+ function split(lst, le = false) {
895
+ const len = lst.length;
896
+ let Ah = new Uint32Array(len);
897
+ let Al = new Uint32Array(len);
898
+ for (let i = 0; i < len; i++) {
899
+ const { h, l } = fromBig(lst[i], le);
900
+ [Ah[i], Al[i]] = [h, l];
901
+ }
902
+ return [Ah, Al];
903
+ }
904
+ var toBig = (h, l) => BigInt(h >>> 0) << _32n | BigInt(l >>> 0);
905
+ exports2.toBig = toBig;
906
+ var shrSH = (h, _l, s) => h >>> s;
907
+ exports2.shrSH = shrSH;
908
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
909
+ exports2.shrSL = shrSL;
910
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
911
+ exports2.rotrSH = rotrSH;
912
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
913
+ exports2.rotrSL = rotrSL;
914
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
915
+ exports2.rotrBH = rotrBH;
916
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
917
+ exports2.rotrBL = rotrBL;
918
+ var rotr32H = (_h, l) => l;
919
+ exports2.rotr32H = rotr32H;
920
+ var rotr32L = (h, _l) => h;
921
+ exports2.rotr32L = rotr32L;
922
+ var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
923
+ exports2.rotlSH = rotlSH;
924
+ var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
925
+ exports2.rotlSL = rotlSL;
926
+ var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
927
+ exports2.rotlBH = rotlBH;
928
+ var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
929
+ exports2.rotlBL = rotlBL;
930
+ function add(Ah, Al, Bh, Bl) {
931
+ const l = (Al >>> 0) + (Bl >>> 0);
932
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
933
+ }
934
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
935
+ exports2.add3L = add3L;
936
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
937
+ exports2.add3H = add3H;
938
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
939
+ exports2.add4L = add4L;
940
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
941
+ exports2.add4H = add4H;
942
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
943
+ exports2.add5L = add5L;
944
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
945
+ exports2.add5H = add5H;
946
+ var u64 = {
947
+ fromBig,
948
+ split,
949
+ toBig,
950
+ shrSH,
951
+ shrSL,
952
+ rotrSH,
953
+ rotrSL,
954
+ rotrBH,
955
+ rotrBL,
956
+ rotr32H,
957
+ rotr32L,
958
+ rotlSH,
959
+ rotlSL,
960
+ rotlBH,
961
+ rotlBL,
962
+ add,
963
+ add3L,
964
+ add3H,
965
+ add4L,
966
+ add4H,
967
+ add5H,
968
+ add5L
969
+ };
970
+ exports2.default = u64;
971
+ }
972
+ });
973
+
974
+ // ../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/cryptoNode.js
975
+ var require_cryptoNode = __commonJS({
976
+ "../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/cryptoNode.js"(exports2) {
977
+ "use strict";
978
+ Object.defineProperty(exports2, "__esModule", { value: true });
979
+ exports2.crypto = void 0;
980
+ var nc = require("crypto");
981
+ exports2.crypto = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
982
+ }
983
+ });
984
+
985
+ // ../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/utils.js
986
+ var require_utils = __commonJS({
987
+ "../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/utils.js"(exports2) {
988
+ "use strict";
989
+ Object.defineProperty(exports2, "__esModule", { value: true });
990
+ exports2.wrapXOFConstructorWithOpts = exports2.wrapConstructorWithOpts = exports2.wrapConstructor = exports2.Hash = exports2.nextTick = exports2.swap32IfBE = exports2.byteSwapIfBE = exports2.swap8IfBE = exports2.isLE = void 0;
991
+ exports2.isBytes = isBytes;
992
+ exports2.anumber = anumber;
993
+ exports2.abytes = abytes;
994
+ exports2.ahash = ahash;
995
+ exports2.aexists = aexists;
996
+ exports2.aoutput = aoutput;
997
+ exports2.u8 = u8;
998
+ exports2.u32 = u32;
999
+ exports2.clean = clean;
1000
+ exports2.createView = createView;
1001
+ exports2.rotr = rotr;
1002
+ exports2.rotl = rotl;
1003
+ exports2.byteSwap = byteSwap;
1004
+ exports2.byteSwap32 = byteSwap32;
1005
+ exports2.bytesToHex = bytesToHex2;
1006
+ exports2.hexToBytes = hexToBytes2;
1007
+ exports2.asyncLoop = asyncLoop;
1008
+ exports2.utf8ToBytes = utf8ToBytes;
1009
+ exports2.bytesToUtf8 = bytesToUtf8;
1010
+ exports2.toBytes = toBytes;
1011
+ exports2.kdfInputToBytes = kdfInputToBytes;
1012
+ exports2.concatBytes = concatBytes;
1013
+ exports2.checkOpts = checkOpts;
1014
+ exports2.createHasher = createHasher;
1015
+ exports2.createOptHasher = createOptHasher;
1016
+ exports2.createXOFer = createXOFer;
1017
+ exports2.randomBytes = randomBytes;
1018
+ var crypto_1 = require_cryptoNode();
1019
+ function isBytes(a) {
1020
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
1021
+ }
1022
+ function anumber(n) {
1023
+ if (!Number.isSafeInteger(n) || n < 0)
1024
+ throw new Error("positive integer expected, got " + n);
1025
+ }
1026
+ function abytes(b, ...lengths) {
1027
+ if (!isBytes(b))
1028
+ throw new Error("Uint8Array expected");
1029
+ if (lengths.length > 0 && !lengths.includes(b.length))
1030
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
1031
+ }
1032
+ function ahash(h) {
1033
+ if (typeof h !== "function" || typeof h.create !== "function")
1034
+ throw new Error("Hash should be wrapped by utils.createHasher");
1035
+ anumber(h.outputLen);
1036
+ anumber(h.blockLen);
1037
+ }
1038
+ function aexists(instance, checkFinished = true) {
1039
+ if (instance.destroyed)
1040
+ throw new Error("Hash instance has been destroyed");
1041
+ if (checkFinished && instance.finished)
1042
+ throw new Error("Hash#digest() has already been called");
1043
+ }
1044
+ function aoutput(out, instance) {
1045
+ abytes(out);
1046
+ const min = instance.outputLen;
1047
+ if (out.length < min) {
1048
+ throw new Error("digestInto() expects output buffer of length at least " + min);
1049
+ }
1050
+ }
1051
+ function u8(arr) {
1052
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
1053
+ }
1054
+ function u32(arr) {
1055
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
1056
+ }
1057
+ function clean(...arrays) {
1058
+ for (let i = 0; i < arrays.length; i++) {
1059
+ arrays[i].fill(0);
1060
+ }
1061
+ }
1062
+ function createView(arr) {
1063
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
1064
+ }
1065
+ function rotr(word, shift) {
1066
+ return word << 32 - shift | word >>> shift;
1067
+ }
1068
+ function rotl(word, shift) {
1069
+ return word << shift | word >>> 32 - shift >>> 0;
1070
+ }
1071
+ exports2.isLE = (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
1072
+ function byteSwap(word) {
1073
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
1074
+ }
1075
+ exports2.swap8IfBE = exports2.isLE ? (n) => n : (n) => byteSwap(n);
1076
+ exports2.byteSwapIfBE = exports2.swap8IfBE;
1077
+ function byteSwap32(arr) {
1078
+ for (let i = 0; i < arr.length; i++) {
1079
+ arr[i] = byteSwap(arr[i]);
1080
+ }
1081
+ return arr;
1082
+ }
1083
+ exports2.swap32IfBE = exports2.isLE ? (u) => u : byteSwap32;
1084
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
1085
+ // @ts-ignore
1086
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
1087
+ ))();
1088
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
1089
+ function bytesToHex2(bytes) {
1090
+ abytes(bytes);
1091
+ if (hasHexBuiltin)
1092
+ return bytes.toHex();
1093
+ let hex = "";
1094
+ for (let i = 0; i < bytes.length; i++) {
1095
+ hex += hexes[bytes[i]];
1096
+ }
1097
+ return hex;
1098
+ }
1099
+ var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
1100
+ function asciiToBase16(ch) {
1101
+ if (ch >= asciis._0 && ch <= asciis._9)
1102
+ return ch - asciis._0;
1103
+ if (ch >= asciis.A && ch <= asciis.F)
1104
+ return ch - (asciis.A - 10);
1105
+ if (ch >= asciis.a && ch <= asciis.f)
1106
+ return ch - (asciis.a - 10);
1107
+ return;
1108
+ }
1109
+ function hexToBytes2(hex) {
1110
+ if (typeof hex !== "string")
1111
+ throw new Error("hex string expected, got " + typeof hex);
1112
+ if (hasHexBuiltin)
1113
+ return Uint8Array.fromHex(hex);
1114
+ const hl = hex.length;
1115
+ const al = hl / 2;
1116
+ if (hl % 2)
1117
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
1118
+ const array = new Uint8Array(al);
1119
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
1120
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
1121
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
1122
+ if (n1 === void 0 || n2 === void 0) {
1123
+ const char = hex[hi] + hex[hi + 1];
1124
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
1125
+ }
1126
+ array[ai] = n1 * 16 + n2;
1127
+ }
1128
+ return array;
1129
+ }
1130
+ var nextTick = async () => {
1131
+ };
1132
+ exports2.nextTick = nextTick;
1133
+ async function asyncLoop(iters, tick, cb) {
1134
+ let ts = Date.now();
1135
+ for (let i = 0; i < iters; i++) {
1136
+ cb(i);
1137
+ const diff = Date.now() - ts;
1138
+ if (diff >= 0 && diff < tick)
1139
+ continue;
1140
+ await (0, exports2.nextTick)();
1141
+ ts += diff;
1142
+ }
1143
+ }
1144
+ function utf8ToBytes(str) {
1145
+ if (typeof str !== "string")
1146
+ throw new Error("string expected");
1147
+ return new Uint8Array(new TextEncoder().encode(str));
1148
+ }
1149
+ function bytesToUtf8(bytes) {
1150
+ return new TextDecoder().decode(bytes);
1151
+ }
1152
+ function toBytes(data) {
1153
+ if (typeof data === "string")
1154
+ data = utf8ToBytes(data);
1155
+ abytes(data);
1156
+ return data;
1157
+ }
1158
+ function kdfInputToBytes(data) {
1159
+ if (typeof data === "string")
1160
+ data = utf8ToBytes(data);
1161
+ abytes(data);
1162
+ return data;
1163
+ }
1164
+ function concatBytes(...arrays) {
1165
+ let sum = 0;
1166
+ for (let i = 0; i < arrays.length; i++) {
1167
+ const a = arrays[i];
1168
+ abytes(a);
1169
+ sum += a.length;
1170
+ }
1171
+ const res = new Uint8Array(sum);
1172
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
1173
+ const a = arrays[i];
1174
+ res.set(a, pad);
1175
+ pad += a.length;
1176
+ }
1177
+ return res;
1178
+ }
1179
+ function checkOpts(defaults, opts) {
1180
+ if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]")
1181
+ throw new Error("options should be object or undefined");
1182
+ const merged = Object.assign(defaults, opts);
1183
+ return merged;
1184
+ }
1185
+ var Hash = class {
1186
+ };
1187
+ exports2.Hash = Hash;
1188
+ function createHasher(hashCons) {
1189
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
1190
+ const tmp = hashCons();
1191
+ hashC.outputLen = tmp.outputLen;
1192
+ hashC.blockLen = tmp.blockLen;
1193
+ hashC.create = () => hashCons();
1194
+ return hashC;
1195
+ }
1196
+ function createOptHasher(hashCons) {
1197
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
1198
+ const tmp = hashCons({});
1199
+ hashC.outputLen = tmp.outputLen;
1200
+ hashC.blockLen = tmp.blockLen;
1201
+ hashC.create = (opts) => hashCons(opts);
1202
+ return hashC;
1203
+ }
1204
+ function createXOFer(hashCons) {
1205
+ const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
1206
+ const tmp = hashCons({});
1207
+ hashC.outputLen = tmp.outputLen;
1208
+ hashC.blockLen = tmp.blockLen;
1209
+ hashC.create = (opts) => hashCons(opts);
1210
+ return hashC;
1211
+ }
1212
+ exports2.wrapConstructor = createHasher;
1213
+ exports2.wrapConstructorWithOpts = createOptHasher;
1214
+ exports2.wrapXOFConstructorWithOpts = createXOFer;
1215
+ function randomBytes(bytesLength = 32) {
1216
+ if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") {
1217
+ return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
1218
+ }
1219
+ if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === "function") {
1220
+ return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength));
1221
+ }
1222
+ throw new Error("crypto.getRandomValues must be defined");
1223
+ }
1224
+ }
1225
+ });
1226
+
1227
+ // ../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/sha3.js
1228
+ var require_sha3 = __commonJS({
1229
+ "../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/sha3.js"(exports2) {
1230
+ "use strict";
1231
+ Object.defineProperty(exports2, "__esModule", { value: true });
1232
+ exports2.shake256 = exports2.shake128 = exports2.keccak_512 = exports2.keccak_384 = exports2.keccak_256 = exports2.keccak_224 = exports2.sha3_512 = exports2.sha3_384 = exports2.sha3_256 = exports2.sha3_224 = exports2.Keccak = void 0;
1233
+ exports2.keccakP = keccakP;
1234
+ var _u64_ts_1 = require_u64();
1235
+ var utils_ts_1 = require_utils();
1236
+ var _0n = BigInt(0);
1237
+ var _1n = BigInt(1);
1238
+ var _2n = BigInt(2);
1239
+ var _7n = BigInt(7);
1240
+ var _256n = BigInt(256);
1241
+ var _0x71n = BigInt(113);
1242
+ var SHA3_PI = [];
1243
+ var SHA3_ROTL = [];
1244
+ var _SHA3_IOTA = [];
1245
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
1246
+ [x, y] = [y, (2 * x + 3 * y) % 5];
1247
+ SHA3_PI.push(2 * (5 * y + x));
1248
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
1249
+ let t = _0n;
1250
+ for (let j = 0; j < 7; j++) {
1251
+ R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
1252
+ if (R & _2n)
1253
+ t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n;
1254
+ }
1255
+ _SHA3_IOTA.push(t);
1256
+ }
1257
+ var IOTAS = (0, _u64_ts_1.split)(_SHA3_IOTA, true);
1258
+ var SHA3_IOTA_H = IOTAS[0];
1259
+ var SHA3_IOTA_L = IOTAS[1];
1260
+ var rotlH = (h, l, s) => s > 32 ? (0, _u64_ts_1.rotlBH)(h, l, s) : (0, _u64_ts_1.rotlSH)(h, l, s);
1261
+ var rotlL = (h, l, s) => s > 32 ? (0, _u64_ts_1.rotlBL)(h, l, s) : (0, _u64_ts_1.rotlSL)(h, l, s);
1262
+ function keccakP(s, rounds = 24) {
1263
+ const B = new Uint32Array(5 * 2);
1264
+ for (let round = 24 - rounds; round < 24; round++) {
1265
+ for (let x = 0; x < 10; x++)
1266
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
1267
+ for (let x = 0; x < 10; x += 2) {
1268
+ const idx1 = (x + 8) % 10;
1269
+ const idx0 = (x + 2) % 10;
1270
+ const B0 = B[idx0];
1271
+ const B1 = B[idx0 + 1];
1272
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
1273
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
1274
+ for (let y = 0; y < 50; y += 10) {
1275
+ s[x + y] ^= Th;
1276
+ s[x + y + 1] ^= Tl;
1277
+ }
1278
+ }
1279
+ let curH = s[2];
1280
+ let curL = s[3];
1281
+ for (let t = 0; t < 24; t++) {
1282
+ const shift = SHA3_ROTL[t];
1283
+ const Th = rotlH(curH, curL, shift);
1284
+ const Tl = rotlL(curH, curL, shift);
1285
+ const PI = SHA3_PI[t];
1286
+ curH = s[PI];
1287
+ curL = s[PI + 1];
1288
+ s[PI] = Th;
1289
+ s[PI + 1] = Tl;
1290
+ }
1291
+ for (let y = 0; y < 50; y += 10) {
1292
+ for (let x = 0; x < 10; x++)
1293
+ B[x] = s[y + x];
1294
+ for (let x = 0; x < 10; x++)
1295
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
1296
+ }
1297
+ s[0] ^= SHA3_IOTA_H[round];
1298
+ s[1] ^= SHA3_IOTA_L[round];
1299
+ }
1300
+ (0, utils_ts_1.clean)(B);
1301
+ }
1302
+ var Keccak = class _Keccak extends utils_ts_1.Hash {
1303
+ // NOTE: we accept arguments in bytes instead of bits here.
1304
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
1305
+ super();
1306
+ this.pos = 0;
1307
+ this.posOut = 0;
1308
+ this.finished = false;
1309
+ this.destroyed = false;
1310
+ this.enableXOF = false;
1311
+ this.blockLen = blockLen;
1312
+ this.suffix = suffix;
1313
+ this.outputLen = outputLen;
1314
+ this.enableXOF = enableXOF;
1315
+ this.rounds = rounds;
1316
+ (0, utils_ts_1.anumber)(outputLen);
1317
+ if (!(0 < blockLen && blockLen < 200))
1318
+ throw new Error("only keccak-f1600 function is supported");
1319
+ this.state = new Uint8Array(200);
1320
+ this.state32 = (0, utils_ts_1.u32)(this.state);
1321
+ }
1322
+ clone() {
1323
+ return this._cloneInto();
1324
+ }
1325
+ keccak() {
1326
+ (0, utils_ts_1.swap32IfBE)(this.state32);
1327
+ keccakP(this.state32, this.rounds);
1328
+ (0, utils_ts_1.swap32IfBE)(this.state32);
1329
+ this.posOut = 0;
1330
+ this.pos = 0;
1331
+ }
1332
+ update(data) {
1333
+ (0, utils_ts_1.aexists)(this);
1334
+ data = (0, utils_ts_1.toBytes)(data);
1335
+ (0, utils_ts_1.abytes)(data);
1336
+ const { blockLen, state } = this;
1337
+ const len = data.length;
1338
+ for (let pos = 0; pos < len; ) {
1339
+ const take = Math.min(blockLen - this.pos, len - pos);
1340
+ for (let i = 0; i < take; i++)
1341
+ state[this.pos++] ^= data[pos++];
1342
+ if (this.pos === blockLen)
1343
+ this.keccak();
1344
+ }
1345
+ return this;
1346
+ }
1347
+ finish() {
1348
+ if (this.finished)
1349
+ return;
1350
+ this.finished = true;
1351
+ const { state, suffix, pos, blockLen } = this;
1352
+ state[pos] ^= suffix;
1353
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
1354
+ this.keccak();
1355
+ state[blockLen - 1] ^= 128;
1356
+ this.keccak();
1357
+ }
1358
+ writeInto(out) {
1359
+ (0, utils_ts_1.aexists)(this, false);
1360
+ (0, utils_ts_1.abytes)(out);
1361
+ this.finish();
1362
+ const bufferOut = this.state;
1363
+ const { blockLen } = this;
1364
+ for (let pos = 0, len = out.length; pos < len; ) {
1365
+ if (this.posOut >= blockLen)
1366
+ this.keccak();
1367
+ const take = Math.min(blockLen - this.posOut, len - pos);
1368
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
1369
+ this.posOut += take;
1370
+ pos += take;
1371
+ }
1372
+ return out;
1373
+ }
1374
+ xofInto(out) {
1375
+ if (!this.enableXOF)
1376
+ throw new Error("XOF is not possible for this instance");
1377
+ return this.writeInto(out);
1378
+ }
1379
+ xof(bytes) {
1380
+ (0, utils_ts_1.anumber)(bytes);
1381
+ return this.xofInto(new Uint8Array(bytes));
1382
+ }
1383
+ digestInto(out) {
1384
+ (0, utils_ts_1.aoutput)(out, this);
1385
+ if (this.finished)
1386
+ throw new Error("digest() was already called");
1387
+ this.writeInto(out);
1388
+ this.destroy();
1389
+ return out;
1390
+ }
1391
+ digest() {
1392
+ return this.digestInto(new Uint8Array(this.outputLen));
1393
+ }
1394
+ destroy() {
1395
+ this.destroyed = true;
1396
+ (0, utils_ts_1.clean)(this.state);
1397
+ }
1398
+ _cloneInto(to) {
1399
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
1400
+ to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
1401
+ to.state32.set(this.state32);
1402
+ to.pos = this.pos;
1403
+ to.posOut = this.posOut;
1404
+ to.finished = this.finished;
1405
+ to.rounds = rounds;
1406
+ to.suffix = suffix;
1407
+ to.outputLen = outputLen;
1408
+ to.enableXOF = enableXOF;
1409
+ to.destroyed = this.destroyed;
1410
+ return to;
1411
+ }
1412
+ };
1413
+ exports2.Keccak = Keccak;
1414
+ var gen = (suffix, blockLen, outputLen) => (0, utils_ts_1.createHasher)(() => new Keccak(blockLen, suffix, outputLen));
1415
+ exports2.sha3_224 = (() => gen(6, 144, 224 / 8))();
1416
+ exports2.sha3_256 = (() => gen(6, 136, 256 / 8))();
1417
+ exports2.sha3_384 = (() => gen(6, 104, 384 / 8))();
1418
+ exports2.sha3_512 = (() => gen(6, 72, 512 / 8))();
1419
+ exports2.keccak_224 = (() => gen(1, 144, 224 / 8))();
1420
+ exports2.keccak_256 = (() => gen(1, 136, 256 / 8))();
1421
+ exports2.keccak_384 = (() => gen(1, 104, 384 / 8))();
1422
+ exports2.keccak_512 = (() => gen(1, 72, 512 / 8))();
1423
+ var genShake = (suffix, blockLen, outputLen) => (0, utils_ts_1.createXOFer)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true));
1424
+ exports2.shake128 = (() => genShake(31, 168, 128 / 8))();
1425
+ exports2.shake256 = (() => genShake(31, 136, 256 / 8))();
1426
+ }
1427
+ });
1428
+
1429
+ // ../contracts/svm/escrow-encoding/typescript/dist/encoding-utils.js
1430
+ var require_encoding_utils = __commonJS({
1431
+ "../contracts/svm/escrow-encoding/typescript/dist/encoding-utils.js"(exports2) {
1432
+ "use strict";
1433
+ Object.defineProperty(exports2, "__esModule", { value: true });
1434
+ exports2.encodeU64LE = encodeU64LE2;
1435
+ exports2.keccak256 = keccak2563;
1436
+ exports2.stringToBytes = stringToBytes;
1437
+ exports2.isZeroBytes32 = isZeroBytes32;
1438
+ var sha3_1 = require_sha3();
1439
+ function encodeU64LE2(value) {
1440
+ const buffer = new Uint8Array(8);
1441
+ let v = value;
1442
+ for (let i = 0; i < 8; i++) {
1443
+ buffer[i] = Number(v & 0xffn);
1444
+ v = v >> 8n;
1445
+ }
1446
+ return buffer;
1447
+ }
1448
+ function keccak2563(...data) {
1449
+ const totalLength = data.reduce((sum, arr) => sum + arr.length, 0);
1450
+ const combined = new Uint8Array(totalLength);
1451
+ let offset = 0;
1452
+ for (const arr of data) {
1453
+ combined.set(arr, offset);
1454
+ offset += arr.length;
1455
+ }
1456
+ return (0, sha3_1.keccak_256)(combined);
1457
+ }
1458
+ function stringToBytes(s) {
1459
+ return new TextEncoder().encode(s);
1460
+ }
1461
+ function isZeroBytes32(data) {
1462
+ if (data.length !== 32)
1463
+ return false;
1464
+ return data.every((b) => b === 0);
1465
+ }
1466
+ }
1467
+ });
1468
+
1469
+ // ../contracts/svm/escrow-encoding/typescript/dist/escrow-domain.js
1470
+ var require_escrow_domain = __commonJS({
1471
+ "../contracts/svm/escrow-encoding/typescript/dist/escrow-domain.js"(exports2) {
1472
+ "use strict";
1473
+ Object.defineProperty(exports2, "__esModule", { value: true });
1474
+ exports2.escrowDomainPrefixBytes = escrowDomainPrefixBytes;
1475
+ function escrowDomainPrefixBytes(domain) {
1476
+ if (domain.clusterId.length !== 32) {
1477
+ throw new Error(`EscrowDomain.clusterId must be 32 bytes, got ${domain.clusterId.length}`);
1478
+ }
1479
+ if (!Number.isInteger(domain.signatureDomainVersion) || domain.signatureDomainVersion < 1 || domain.signatureDomainVersion > 255) {
1480
+ throw new Error(`EscrowDomain.signatureDomainVersion must be an integer in 1..=255, got ${domain.signatureDomainVersion}`);
1481
+ }
1482
+ return [
1483
+ new TextEncoder().encode("escrow"),
1484
+ new Uint8Array([domain.signatureDomainVersion]),
1485
+ domain.clusterId,
1486
+ domain.programId.toBytes()
1487
+ ];
1488
+ }
1489
+ }
1490
+ });
1491
+
1492
+ // ../contracts/svm/escrow-encoding/typescript/dist/deposit-encoder.js
1493
+ var require_deposit_encoder3 = __commonJS({
1494
+ "../contracts/svm/escrow-encoding/typescript/dist/deposit-encoder.js"(exports2) {
1495
+ "use strict";
1496
+ Object.defineProperty(exports2, "__esModule", { value: true });
1497
+ exports2.computeDepositHash = computeDepositHash2;
1498
+ var encoding_utils_1 = require_encoding_utils();
1499
+ var escrow_domain_1 = require_escrow_domain();
1500
+ var errors_1 = require_errors();
1501
+ function computeDepositHash2(params, domain) {
1502
+ if (params.paymentId.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.paymentId)) {
1503
+ throw new errors_1.ZeroPaymentIdError();
1504
+ }
1505
+ if (params.depositor.isZero())
1506
+ throw new errors_1.ZeroDepositorError();
1507
+ if (params.mint.isZero())
1508
+ throw new errors_1.ZeroMintError();
1509
+ if (params.amount === 0n)
1510
+ throw new errors_1.ZeroAmountError();
1511
+ if (params.reserver.isZero())
1512
+ throw new errors_1.ZeroReserverError();
1513
+ if (params.releaser.isZero())
1514
+ throw new errors_1.ZeroReleaserError();
1515
+ return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("deposit"), params.paymentId, params.depositor.toBytes(), params.mint.toBytes(), (0, encoding_utils_1.encodeU64LE)(params.amount), params.reserver.toBytes(), params.releaser.toBytes(), (0, encoding_utils_1.encodeU64LE)(params.nonce), (0, encoding_utils_1.encodeU64LE)(params.issuedAt), (0, encoding_utils_1.encodeU64LE)(params.deadline));
1516
+ }
1517
+ }
1518
+ });
1519
+
1520
+ // ../contracts/svm/escrow-encoding/typescript/dist/reserve-encoder.js
1521
+ var require_reserve_encoder3 = __commonJS({
1522
+ "../contracts/svm/escrow-encoding/typescript/dist/reserve-encoder.js"(exports2) {
1523
+ "use strict";
1524
+ Object.defineProperty(exports2, "__esModule", { value: true });
1525
+ exports2.computeReserveHash = computeReserveHash;
1526
+ var encoding_utils_1 = require_encoding_utils();
1527
+ var escrow_domain_1 = require_escrow_domain();
1528
+ var errors_1 = require_errors();
1529
+ function computeReserveHash(params, domain) {
1530
+ if (params.depositHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositHash)) {
1531
+ throw new errors_1.ZeroDepositHashError();
1532
+ }
1533
+ if (params.recipient.isZero())
1534
+ throw new errors_1.ZeroRecipientError();
1535
+ return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("reserve"), params.recipient.toBytes(), params.depositHash);
1536
+ }
1537
+ }
1538
+ });
1539
+
1540
+ // ../contracts/svm/escrow-encoding/typescript/dist/release-encoder.js
1541
+ var require_release_encoder = __commonJS({
1542
+ "../contracts/svm/escrow-encoding/typescript/dist/release-encoder.js"(exports2) {
1543
+ "use strict";
1544
+ Object.defineProperty(exports2, "__esModule", { value: true });
1545
+ exports2.computeReleaseHash = computeReleaseHash;
1546
+ var encoding_utils_1 = require_encoding_utils();
1547
+ var escrow_domain_1 = require_escrow_domain();
1548
+ var errors_1 = require_errors();
1549
+ function computeReleaseHash(params, domain) {
1550
+ if (params.depositHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositHash)) {
1551
+ throw new errors_1.ZeroDepositHashError();
1552
+ }
1553
+ return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("release"), params.depositHash);
1554
+ }
1555
+ }
1556
+ });
1557
+
1558
+ // ../contracts/svm/escrow-encoding/typescript/dist/refund-encoder.js
1559
+ var require_refund_encoder = __commonJS({
1560
+ "../contracts/svm/escrow-encoding/typescript/dist/refund-encoder.js"(exports2) {
1561
+ "use strict";
1562
+ Object.defineProperty(exports2, "__esModule", { value: true });
1563
+ exports2.computeRefundHash = computeRefundHash;
1564
+ var encoding_utils_1 = require_encoding_utils();
1565
+ var escrow_domain_1 = require_escrow_domain();
1566
+ var errors_1 = require_errors();
1567
+ function computeRefundHash(params, domain) {
1568
+ if (params.depositHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositHash)) {
1569
+ throw new errors_1.ZeroDepositHashError();
1570
+ }
1571
+ return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("refund"), params.depositHash);
1572
+ }
1573
+ }
1574
+ });
1575
+
1576
+ // ../contracts/svm/escrow-encoding/typescript/dist/nonce-generator.js
1577
+ var require_nonce_generator2 = __commonJS({
1578
+ "../contracts/svm/escrow-encoding/typescript/dist/nonce-generator.js"(exports2) {
1579
+ "use strict";
1580
+ Object.defineProperty(exports2, "__esModule", { value: true });
1581
+ exports2.MAX_VALID_SLOT = exports2.REPLAY_SLOTS = void 0;
1582
+ exports2.generateNonce = generateNonce2;
1583
+ var crypto_1 = require("crypto");
1584
+ exports2.REPLAY_SLOTS = 235;
1585
+ exports2.MAX_VALID_SLOT = exports2.REPLAY_SLOTS - 1;
1586
+ var NONCE_BUCKET_MASK = 131071;
1587
+ var NONCE_BUCKET_SHIFT = 32n;
1588
+ function generateNonce2() {
1589
+ const bucketBytes = (0, crypto_1.randomBytes)(4);
1590
+ const bucketID = bucketBytes.readUInt32LE(0) & NONCE_BUCKET_MASK;
1591
+ let slot;
1592
+ do {
1593
+ slot = (0, crypto_1.randomBytes)(1)[0];
1594
+ } while (slot >= exports2.REPLAY_SLOTS);
1595
+ return BigInt(bucketID) << NONCE_BUCKET_SHIFT | BigInt(slot);
1596
+ }
1597
+ }
1598
+ });
1599
+
1600
+ // ../contracts/svm/escrow-encoding/typescript/dist/index.js
1601
+ var require_dist3 = __commonJS({
1602
+ "../contracts/svm/escrow-encoding/typescript/dist/index.js"(exports2) {
1603
+ "use strict";
1604
+ Object.defineProperty(exports2, "__esModule", { value: true });
1605
+ exports2.MAX_VALID_SLOT = exports2.REPLAY_SLOTS = exports2.generateNonce = exports2.computeRefundHash = exports2.computeReleaseHash = exports2.computeReserveHash = exports2.computeDepositHash = exports2.InvalidHexError = exports2.InvalidBase58Error = exports2.InvalidPubkeyLengthError = exports2.ZeroDepositHashError = exports2.ZeroRecipientError = exports2.ZeroReleaserError = exports2.ZeroReserverError = exports2.ZeroAmountError = exports2.ZeroMintError = exports2.ZeroDepositorError = exports2.ZeroPaymentIdError = exports2.EncodingError = exports2.escrowDomainPrefixBytes = exports2.isZeroBytes32 = exports2.stringToBytes = exports2.keccak256 = exports2.encodeU64LE = exports2.Pubkey = void 0;
1606
+ var pubkey_1 = require_pubkey();
1607
+ Object.defineProperty(exports2, "Pubkey", { enumerable: true, get: function() {
1608
+ return pubkey_1.Pubkey;
1609
+ } });
1610
+ var encoding_utils_1 = require_encoding_utils();
1611
+ Object.defineProperty(exports2, "encodeU64LE", { enumerable: true, get: function() {
1612
+ return encoding_utils_1.encodeU64LE;
1613
+ } });
1614
+ Object.defineProperty(exports2, "keccak256", { enumerable: true, get: function() {
1615
+ return encoding_utils_1.keccak256;
1616
+ } });
1617
+ Object.defineProperty(exports2, "stringToBytes", { enumerable: true, get: function() {
1618
+ return encoding_utils_1.stringToBytes;
1619
+ } });
1620
+ Object.defineProperty(exports2, "isZeroBytes32", { enumerable: true, get: function() {
1621
+ return encoding_utils_1.isZeroBytes32;
1622
+ } });
1623
+ var escrow_domain_1 = require_escrow_domain();
1624
+ Object.defineProperty(exports2, "escrowDomainPrefixBytes", { enumerable: true, get: function() {
1625
+ return escrow_domain_1.escrowDomainPrefixBytes;
1626
+ } });
1627
+ var errors_1 = require_errors();
1628
+ Object.defineProperty(exports2, "EncodingError", { enumerable: true, get: function() {
1629
+ return errors_1.EncodingError;
1630
+ } });
1631
+ Object.defineProperty(exports2, "ZeroPaymentIdError", { enumerable: true, get: function() {
1632
+ return errors_1.ZeroPaymentIdError;
1633
+ } });
1634
+ Object.defineProperty(exports2, "ZeroDepositorError", { enumerable: true, get: function() {
1635
+ return errors_1.ZeroDepositorError;
1636
+ } });
1637
+ Object.defineProperty(exports2, "ZeroMintError", { enumerable: true, get: function() {
1638
+ return errors_1.ZeroMintError;
1639
+ } });
1640
+ Object.defineProperty(exports2, "ZeroAmountError", { enumerable: true, get: function() {
1641
+ return errors_1.ZeroAmountError;
1642
+ } });
1643
+ Object.defineProperty(exports2, "ZeroReserverError", { enumerable: true, get: function() {
1644
+ return errors_1.ZeroReserverError;
1645
+ } });
1646
+ Object.defineProperty(exports2, "ZeroReleaserError", { enumerable: true, get: function() {
1647
+ return errors_1.ZeroReleaserError;
1648
+ } });
1649
+ Object.defineProperty(exports2, "ZeroRecipientError", { enumerable: true, get: function() {
1650
+ return errors_1.ZeroRecipientError;
1651
+ } });
1652
+ Object.defineProperty(exports2, "ZeroDepositHashError", { enumerable: true, get: function() {
1653
+ return errors_1.ZeroDepositHashError;
1654
+ } });
1655
+ Object.defineProperty(exports2, "InvalidPubkeyLengthError", { enumerable: true, get: function() {
1656
+ return errors_1.InvalidPubkeyLengthError;
1657
+ } });
1658
+ Object.defineProperty(exports2, "InvalidBase58Error", { enumerable: true, get: function() {
1659
+ return errors_1.InvalidBase58Error;
1660
+ } });
1661
+ Object.defineProperty(exports2, "InvalidHexError", { enumerable: true, get: function() {
1662
+ return errors_1.InvalidHexError;
1663
+ } });
1664
+ var deposit_encoder_1 = require_deposit_encoder3();
1665
+ Object.defineProperty(exports2, "computeDepositHash", { enumerable: true, get: function() {
1666
+ return deposit_encoder_1.computeDepositHash;
1667
+ } });
1668
+ var reserve_encoder_1 = require_reserve_encoder3();
1669
+ Object.defineProperty(exports2, "computeReserveHash", { enumerable: true, get: function() {
1670
+ return reserve_encoder_1.computeReserveHash;
1671
+ } });
1672
+ var release_encoder_1 = require_release_encoder();
1673
+ Object.defineProperty(exports2, "computeReleaseHash", { enumerable: true, get: function() {
1674
+ return release_encoder_1.computeReleaseHash;
1675
+ } });
1676
+ var refund_encoder_1 = require_refund_encoder();
1677
+ Object.defineProperty(exports2, "computeRefundHash", { enumerable: true, get: function() {
1678
+ return refund_encoder_1.computeRefundHash;
1679
+ } });
1680
+ var nonce_generator_1 = require_nonce_generator2();
1681
+ Object.defineProperty(exports2, "generateNonce", { enumerable: true, get: function() {
1682
+ return nonce_generator_1.generateNonce;
1683
+ } });
1684
+ Object.defineProperty(exports2, "REPLAY_SLOTS", { enumerable: true, get: function() {
1685
+ return nonce_generator_1.REPLAY_SLOTS;
1686
+ } });
1687
+ Object.defineProperty(exports2, "MAX_VALID_SLOT", { enumerable: true, get: function() {
1688
+ return nonce_generator_1.MAX_VALID_SLOT;
1689
+ } });
1690
+ }
1691
+ });
1692
+
1693
+ // src/cli/quote-status.ts
1694
+ var import_commander = require("commander");
1695
+
1696
+ // src/generated/core/OpenAPI.ts
1697
+ var Interceptors = class {
1698
+ constructor() {
1699
+ this._fns = [];
1700
+ }
1701
+ eject(fn) {
1702
+ const index = this._fns.indexOf(fn);
1703
+ if (index !== -1) {
1704
+ this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)];
1705
+ }
1706
+ }
1707
+ use(fn) {
1708
+ this._fns = [...this._fns, fn];
1709
+ }
1710
+ };
1711
+ var OpenAPI = {
1712
+ BASE: "https://api.atum.network",
1713
+ CREDENTIALS: "include",
1714
+ ENCODE_PATH: void 0,
1715
+ HEADERS: void 0,
1716
+ PASSWORD: void 0,
1717
+ TOKEN: void 0,
1718
+ USERNAME: void 0,
1719
+ VERSION: "1.0.0",
1720
+ WITH_CREDENTIALS: false,
1721
+ interceptors: {
1722
+ request: new Interceptors(),
1723
+ response: new Interceptors()
1724
+ }
1725
+ };
1726
+
1727
+ // src/generated/core/BaseHttpRequest.ts
1728
+ var BaseHttpRequest = class {
1729
+ constructor(config) {
1730
+ this.config = config;
1731
+ }
1732
+ };
1733
+
1734
+ // src/generated/core/request.ts
1735
+ var import_axios = __toESM(require("axios"));
1736
+
1737
+ // src/generated/core/ApiError.ts
1738
+ var ApiError = class extends Error {
1739
+ constructor(request2, response, message) {
1740
+ super(message);
1741
+ this.name = "ApiError";
1742
+ this.url = response.url;
1743
+ this.status = response.status;
1744
+ this.statusText = response.statusText;
1745
+ this.body = response.body;
1746
+ this.request = request2;
1747
+ }
1748
+ };
1749
+
1750
+ // src/generated/core/CancelablePromise.ts
1751
+ var CancelError = class extends Error {
1752
+ constructor(message) {
1753
+ super(message);
1754
+ this.name = "CancelError";
1755
+ }
1756
+ get isCancelled() {
1757
+ return true;
1758
+ }
1759
+ };
1760
+ var CancelablePromise = class {
1761
+ constructor(executor) {
1762
+ this._isResolved = false;
1763
+ this._isRejected = false;
1764
+ this._isCancelled = false;
1765
+ this.cancelHandlers = [];
1766
+ this.promise = new Promise((resolve2, reject) => {
1767
+ this._resolve = resolve2;
1768
+ this._reject = reject;
1769
+ const onResolve = (value) => {
1770
+ if (this._isResolved || this._isRejected || this._isCancelled) {
1771
+ return;
1772
+ }
1773
+ this._isResolved = true;
1774
+ if (this._resolve) this._resolve(value);
1775
+ };
1776
+ const onReject = (reason) => {
1777
+ if (this._isResolved || this._isRejected || this._isCancelled) {
1778
+ return;
1779
+ }
1780
+ this._isRejected = true;
1781
+ if (this._reject) this._reject(reason);
1782
+ };
1783
+ const onCancel = (cancelHandler) => {
1784
+ if (this._isResolved || this._isRejected || this._isCancelled) {
1785
+ return;
1786
+ }
1787
+ this.cancelHandlers.push(cancelHandler);
1788
+ };
1789
+ Object.defineProperty(onCancel, "isResolved", {
1790
+ get: () => this._isResolved
1791
+ });
1792
+ Object.defineProperty(onCancel, "isRejected", {
1793
+ get: () => this._isRejected
1794
+ });
1795
+ Object.defineProperty(onCancel, "isCancelled", {
1796
+ get: () => this._isCancelled
1797
+ });
1798
+ return executor(onResolve, onReject, onCancel);
1799
+ });
1800
+ }
1801
+ get [Symbol.toStringTag]() {
1802
+ return "Cancellable Promise";
1803
+ }
1804
+ then(onFulfilled, onRejected) {
1805
+ return this.promise.then(onFulfilled, onRejected);
1806
+ }
1807
+ catch(onRejected) {
1808
+ return this.promise.catch(onRejected);
1809
+ }
1810
+ finally(onFinally) {
1811
+ return this.promise.finally(onFinally);
1812
+ }
1813
+ cancel() {
1814
+ if (this._isResolved || this._isRejected || this._isCancelled) {
1815
+ return;
1816
+ }
1817
+ this._isCancelled = true;
1818
+ if (this.cancelHandlers.length) {
1819
+ try {
1820
+ for (const cancelHandler of this.cancelHandlers) {
1821
+ cancelHandler();
1822
+ }
1823
+ } catch (error) {
1824
+ console.warn("Cancellation threw an error", error);
1825
+ return;
1826
+ }
1827
+ }
1828
+ this.cancelHandlers.length = 0;
1829
+ if (this._reject) this._reject(new CancelError("Request aborted"));
1830
+ }
1831
+ get isCancelled() {
1832
+ return this._isCancelled;
1833
+ }
1834
+ };
1835
+
1836
+ // src/generated/core/request.ts
1837
+ var isString = (value) => {
1838
+ return typeof value === "string";
1839
+ };
1840
+ var isStringWithValue = (value) => {
1841
+ return isString(value) && value !== "";
1842
+ };
1843
+ var isBlob = (value) => {
1844
+ return value instanceof Blob;
1845
+ };
1846
+ var isFormData = (value) => {
1847
+ return value instanceof FormData;
1848
+ };
1849
+ var isSuccess = (status) => {
1850
+ return status >= 200 && status < 300;
1851
+ };
1852
+ var base64 = (str) => {
1853
+ try {
1854
+ return btoa(str);
1855
+ } catch (err) {
1856
+ return Buffer.from(str).toString("base64");
1857
+ }
1858
+ };
1859
+ var getQueryString = (params) => {
1860
+ const qs = [];
1861
+ const append = (key, value) => {
1862
+ qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
1863
+ };
1864
+ const encodePair = (key, value) => {
1865
+ if (value === void 0 || value === null) {
1866
+ return;
1867
+ }
1868
+ if (value instanceof Date) {
1869
+ append(key, value.toISOString());
1870
+ } else if (Array.isArray(value)) {
1871
+ value.forEach((v) => encodePair(key, v));
1872
+ } else if (typeof value === "object") {
1873
+ Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v));
1874
+ } else {
1875
+ append(key, value);
1876
+ }
1877
+ };
1878
+ Object.entries(params).forEach(([key, value]) => encodePair(key, value));
1879
+ return qs.length ? `?${qs.join("&")}` : "";
1880
+ };
1881
+ var getUrl = (config, options) => {
1882
+ const encoder = config.ENCODE_PATH || encodeURI;
1883
+ const path = options.url.replace("{api-version}", config.VERSION).replace(/{(.*?)}/g, (substring, group) => {
1884
+ if (options.path?.hasOwnProperty(group)) {
1885
+ return encoder(String(options.path[group]));
1886
+ }
1887
+ return substring;
1888
+ });
1889
+ const url = config.BASE + path;
1890
+ return options.query ? url + getQueryString(options.query) : url;
1891
+ };
1892
+ var getFormData = (options) => {
1893
+ if (options.formData) {
1894
+ const formData = new FormData();
1895
+ const process2 = (key, value) => {
1896
+ if (isString(value) || isBlob(value)) {
1897
+ formData.append(key, value);
1898
+ } else {
1899
+ formData.append(key, JSON.stringify(value));
1900
+ }
1901
+ };
1902
+ Object.entries(options.formData).filter(([, value]) => value !== void 0 && value !== null).forEach(([key, value]) => {
1903
+ if (Array.isArray(value)) {
1904
+ value.forEach((v) => process2(key, v));
1905
+ } else {
1906
+ process2(key, value);
1907
+ }
1908
+ });
1909
+ return formData;
1910
+ }
1911
+ return void 0;
1912
+ };
1913
+ var resolve = async (options, resolver) => {
1914
+ if (typeof resolver === "function") {
1915
+ return resolver(options);
1916
+ }
1917
+ return resolver;
1918
+ };
1919
+ var getHeaders = async (config, options) => {
1920
+ const [token, username, password, additionalHeaders] = await Promise.all([
1921
+ resolve(options, config.TOKEN),
1922
+ resolve(options, config.USERNAME),
1923
+ resolve(options, config.PASSWORD),
1924
+ resolve(options, config.HEADERS)
1925
+ ]);
1926
+ const headers = Object.entries({
1927
+ Accept: "application/json",
1928
+ ...additionalHeaders,
1929
+ ...options.headers
1930
+ }).filter(([, value]) => value !== void 0 && value !== null).reduce((headers2, [key, value]) => ({
1931
+ ...headers2,
1932
+ [key]: String(value)
1933
+ }), {});
1934
+ if (isStringWithValue(token)) {
1935
+ headers["Authorization"] = `Bearer ${token}`;
1936
+ }
1937
+ if (isStringWithValue(username) && isStringWithValue(password)) {
1938
+ const credentials = base64(`${username}:${password}`);
1939
+ headers["Authorization"] = `Basic ${credentials}`;
1940
+ }
1941
+ if (options.body !== void 0) {
1942
+ if (options.mediaType) {
1943
+ headers["Content-Type"] = options.mediaType;
1944
+ } else if (isBlob(options.body)) {
1945
+ headers["Content-Type"] = options.body.type || "application/octet-stream";
1946
+ } else if (isString(options.body)) {
1947
+ headers["Content-Type"] = "text/plain";
1948
+ } else if (!isFormData(options.body)) {
1949
+ headers["Content-Type"] = "application/json";
1950
+ }
1951
+ } else if (options.formData !== void 0) {
1952
+ if (options.mediaType) {
1953
+ headers["Content-Type"] = options.mediaType;
1954
+ }
1955
+ }
1956
+ return headers;
1957
+ };
1958
+ var getRequestBody = (options) => {
1959
+ if (options.body) {
1960
+ return options.body;
1961
+ }
1962
+ return void 0;
1963
+ };
1964
+ var sendRequest = async (config, options, url, body, formData, headers, onCancel, axiosClient) => {
1965
+ const controller = new AbortController();
1966
+ let requestConfig = {
1967
+ data: body ?? formData,
1968
+ headers,
1969
+ method: options.method,
1970
+ signal: controller.signal,
1971
+ url,
1972
+ withCredentials: config.WITH_CREDENTIALS
1973
+ };
1974
+ onCancel(() => controller.abort());
1975
+ for (const fn of config.interceptors.request._fns) {
1976
+ requestConfig = await fn(requestConfig);
1977
+ }
1978
+ try {
1979
+ return await axiosClient.request(requestConfig);
1980
+ } catch (error) {
1981
+ const axiosError = error;
1982
+ if (axiosError.response) {
1983
+ return axiosError.response;
1984
+ }
1985
+ throw error;
1986
+ }
1987
+ };
1988
+ var getResponseHeader = (response, responseHeader) => {
1989
+ if (responseHeader) {
1990
+ const content = response.headers[responseHeader];
1991
+ if (isString(content)) {
1992
+ return content;
1993
+ }
1994
+ }
1995
+ return void 0;
1996
+ };
1997
+ var getResponseBody = (response) => {
1998
+ if (response.status !== 204) {
1999
+ return response.data;
2000
+ }
2001
+ return void 0;
2002
+ };
2003
+ var catchErrorCodes = (options, result) => {
2004
+ const errors = {
2005
+ 400: "Bad Request",
2006
+ 401: "Unauthorized",
2007
+ 402: "Payment Required",
2008
+ 403: "Forbidden",
2009
+ 404: "Not Found",
2010
+ 405: "Method Not Allowed",
2011
+ 406: "Not Acceptable",
2012
+ 407: "Proxy Authentication Required",
2013
+ 408: "Request Timeout",
2014
+ 409: "Conflict",
2015
+ 410: "Gone",
2016
+ 411: "Length Required",
2017
+ 412: "Precondition Failed",
2018
+ 413: "Payload Too Large",
2019
+ 414: "URI Too Long",
2020
+ 415: "Unsupported Media Type",
2021
+ 416: "Range Not Satisfiable",
2022
+ 417: "Expectation Failed",
2023
+ 418: "Im a teapot",
2024
+ 421: "Misdirected Request",
2025
+ 422: "Unprocessable Content",
2026
+ 423: "Locked",
2027
+ 424: "Failed Dependency",
2028
+ 425: "Too Early",
2029
+ 426: "Upgrade Required",
2030
+ 428: "Precondition Required",
2031
+ 429: "Too Many Requests",
2032
+ 431: "Request Header Fields Too Large",
2033
+ 451: "Unavailable For Legal Reasons",
2034
+ 500: "Internal Server Error",
2035
+ 501: "Not Implemented",
2036
+ 502: "Bad Gateway",
2037
+ 503: "Service Unavailable",
2038
+ 504: "Gateway Timeout",
2039
+ 505: "HTTP Version Not Supported",
2040
+ 506: "Variant Also Negotiates",
2041
+ 507: "Insufficient Storage",
2042
+ 508: "Loop Detected",
2043
+ 510: "Not Extended",
2044
+ 511: "Network Authentication Required",
2045
+ ...options.errors
2046
+ };
2047
+ const error = errors[result.status];
2048
+ if (error) {
2049
+ throw new ApiError(options, result, error);
2050
+ }
2051
+ if (!result.ok) {
2052
+ const errorStatus = result.status ?? "unknown";
2053
+ const errorStatusText = result.statusText ?? "unknown";
2054
+ const errorBody = (() => {
2055
+ try {
2056
+ return JSON.stringify(result.body, null, 2);
2057
+ } catch (e) {
2058
+ return void 0;
2059
+ }
2060
+ })();
2061
+ throw new ApiError(
2062
+ options,
2063
+ result,
2064
+ `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}`
2065
+ );
2066
+ }
2067
+ };
2068
+ var request = (config, options, axiosClient = import_axios.default) => {
2069
+ return new CancelablePromise(async (resolve2, reject, onCancel) => {
2070
+ try {
2071
+ const url = getUrl(config, options);
2072
+ const formData = getFormData(options);
2073
+ const body = getRequestBody(options);
2074
+ const headers = await getHeaders(config, options);
2075
+ if (!onCancel.isCancelled) {
2076
+ let response = await sendRequest(config, options, url, body, formData, headers, onCancel, axiosClient);
2077
+ for (const fn of config.interceptors.response._fns) {
2078
+ response = await fn(response);
2079
+ }
2080
+ const responseBody = getResponseBody(response);
2081
+ const responseHeader = getResponseHeader(response, options.responseHeader);
2082
+ const result = {
2083
+ url,
2084
+ ok: isSuccess(response.status),
2085
+ status: response.status,
2086
+ statusText: response.statusText,
2087
+ body: responseHeader ?? responseBody
2088
+ };
2089
+ catchErrorCodes(options, result);
2090
+ resolve2(result.body);
2091
+ }
2092
+ } catch (error) {
2093
+ reject(error);
2094
+ }
2095
+ });
2096
+ };
2097
+
2098
+ // src/generated/core/AxiosHttpRequest.ts
2099
+ var AxiosHttpRequest = class extends BaseHttpRequest {
2100
+ constructor(config) {
2101
+ super(config);
2102
+ }
2103
+ /**
2104
+ * Request method
2105
+ * @param options The request options from the service
2106
+ * @returns CancelablePromise<T>
2107
+ * @throws ApiError
2108
+ */
2109
+ request(options) {
2110
+ return request(this.config, options);
2111
+ }
2112
+ };
2113
+
2114
+ // src/generated/services.gen.ts
2115
+ var PaymentsService = class {
2116
+ constructor(httpRequest) {
2117
+ this.httpRequest = httpRequest;
2118
+ }
2119
+ /**
2120
+ * Submit a payment request
2121
+ * Initiates a payment by submitting a cryptographically signed payment request.
2122
+ *
2123
+ * The payment gateway will:
2124
+ * 1. Validate the request and signatures
2125
+ * 2. Find optimal settlement routes across chains/assets
2126
+ * 3. Secure funds in escrow
2127
+ * 4. Coordinate with settlement agents for execution
2128
+ * 5. Return a real-time result if processing completes within 30 seconds,
2129
+ * otherwise return a payment ID for status polling
2130
+ *
2131
+ * @param data The data for the request.
2132
+ * @param data.requestBody
2133
+ * @returns PaymentResponse Payment request submitted successfully
2134
+ * @throws ApiError
2135
+ */
2136
+ submitPayment(data) {
2137
+ return this.httpRequest.request({
2138
+ method: "POST",
2139
+ url: "/v1/payments",
2140
+ body: data.requestBody,
2141
+ mediaType: "application/json",
2142
+ errors: {
2143
+ 400: "Invalid request",
2144
+ 500: "Internal server error"
2145
+ }
2146
+ });
2147
+ }
2148
+ /**
2149
+ * Get payment status
2150
+ * Retrieve the status of a payment by its ID
2151
+ * @param data The data for the request.
2152
+ * @param data.paymentId The ID of the payment to query
2153
+ * @returns GetPaymentStatusResponse Payment status retrieved successfully
2154
+ * @throws ApiError
2155
+ */
2156
+ getPaymentStatus(data) {
2157
+ return this.httpRequest.request({
2158
+ method: "GET",
2159
+ url: "/v1/payments/{paymentId}/status",
2160
+ path: {
2161
+ paymentId: data.paymentId
2162
+ },
2163
+ errors: {
2164
+ 404: "Payment not found",
2165
+ 500: "Internal server error"
2166
+ }
2167
+ });
2168
+ }
2169
+ /**
2170
+ * Resolve a request ID to a payment ID
2171
+ * Looks up the payment ID associated with a given client-supplied request ID.
2172
+ * Used by tooling like the payment explorer so callers can look a payment up
2173
+ * by the request ID they originally submitted.
2174
+ *
2175
+ * @param data The data for the request.
2176
+ * @param data.requestId The client-supplied request ID embedded in the payment request
2177
+ * @returns ResolvePaymentResponse Payment found
2178
+ * @throws ApiError
2179
+ */
2180
+ resolvePayment(data) {
2181
+ return this.httpRequest.request({
2182
+ method: "GET",
2183
+ url: "/v1/payments/resolve",
2184
+ query: {
2185
+ request_id: data.requestId
2186
+ },
2187
+ errors: {
2188
+ 400: "Missing request_id parameter",
2189
+ 404: "No payment found for the given request ID",
2190
+ 500: "Internal server error"
2191
+ }
2192
+ });
2193
+ }
2194
+ /**
2195
+ * Get step-by-step payment timeline
2196
+ * Returns the settlement timeline for a payment, including every step the
2197
+ * payment has passed through, per-step durations, chain IDs, transaction
2198
+ * hashes, and — if the payment has failed — a structured error describing
2199
+ * where and why it failed.
2200
+ *
2201
+ * @param data The data for the request.
2202
+ * @param data.paymentId The ID of the payment to query
2203
+ * @returns PaymentTimelineResponse Timeline retrieved successfully
2204
+ * @throws ApiError
2205
+ */
2206
+ getPaymentTimeline(data) {
2207
+ return this.httpRequest.request({
2208
+ method: "GET",
2209
+ url: "/v1/payments/{paymentId}/timeline",
2210
+ path: {
2211
+ paymentId: data.paymentId
2212
+ },
2213
+ errors: {
2214
+ 404: "Payment not found",
2215
+ 500: "Internal server error"
2216
+ }
2217
+ });
2218
+ }
2219
+ /**
2220
+ * Prepare an unsigned payment request
2221
+ * Generates an unsigned PaymentRequest object from human-readable inputs.
2222
+ * This endpoint allows clients to:
2223
+ * 1. Use friendly asset identifiers (e.g., "ethereum/usdc" instead of full CAIP-19)
2224
+ * 2. Specify amounts in decimal format
2225
+ * 3. Get back a complete PaymentRequest with typed data (eg EIP-712 for EVM-compatible chains) ready for signing
2226
+ *
2227
+ * The response includes everything needed to sign and submit a payment, except the signature itself.
2228
+ *
2229
+ * @param data The data for the request.
2230
+ * @param data.requestBody
2231
+ * @returns PreparePaymentResponse Payment request prepared successfully
2232
+ * @throws ApiError
2233
+ */
2234
+ preparePayment(data) {
2235
+ return this.httpRequest.request({
2236
+ method: "POST",
2237
+ url: "/v1/payments/prepare",
2238
+ body: data.requestBody,
2239
+ mediaType: "application/json",
2240
+ errors: {
2241
+ 400: "Invalid request parameters",
2242
+ 501: "Endpoint not yet implemented"
2243
+ }
2244
+ });
2245
+ }
2246
+ };
2247
+ var AuthorizationsService = class {
2248
+ constructor(httpRequest) {
2249
+ this.httpRequest = httpRequest;
2250
+ }
2251
+ /**
2252
+ * Request counterparty authorization
2253
+ * Submits a PaymentRequest for counterparty authorization before settlement.
2254
+ * The call blocks synchronously until the beneficiary PSP responds or the
2255
+ * timeout expires (default 30 seconds).
2256
+ *
2257
+ * If authorized, the response includes the counterparty's proof which can
2258
+ * be attached to the subsequent SubmitPayment call.
2259
+ *
2260
+ * Authorization and RFQ submission are separate steps. This endpoint does
2261
+ * NOT trigger an auction — the originator must call SubmitPayment separately.
2262
+ *
2263
+ * @param data The data for the request.
2264
+ * @param data.requestBody
2265
+ * @returns AuthorizationResult Authorization decision received (authorized or declined)
2266
+ * @throws ApiError
2267
+ */
2268
+ authorizePayment(data) {
2269
+ return this.httpRequest.request({
2270
+ method: "POST",
2271
+ url: "/v1/payments/authorizations",
2272
+ body: data.requestBody,
2273
+ mediaType: "application/json",
2274
+ errors: {
2275
+ 400: "Invalid payment request",
2276
+ 404: "Counterparty not found (no registration for the resolved DID)",
2277
+ 502: "Counterparty webhook error (HTTP error or connection failure)",
2278
+ 504: "Authorization timed out (counterparty did not respond)"
2279
+ }
2280
+ });
2281
+ }
2282
+ };
2283
+ var QuoteRequestsService = class {
2284
+ constructor(httpRequest) {
2285
+ this.httpRequest = httpRequest;
2286
+ }
2287
+ /**
2288
+ * Create a quote-request batch
2289
+ * Opens a quote-request batch: broadcasts the corridor to settlement agents and collects
2290
+ * their signed quotes. This is the first phase of the two-phase quote → award flow — the
2291
+ * originator later picks one quote and commits in a separate POST /v1/payments/awards call.
2292
+ * No spend authorization is supplied here; `sender_auth` is deferred to award time.
2293
+ *
2294
+ * Wait modes (the `wait` query parameter):
2295
+ * - `wait=false` (default): return 202 immediately with status `collecting`; poll
2296
+ * GET /v1/payments/quote-requests/{quoteRequestId} until status is `ready`.
2297
+ * - `wait=true`: hold the connection for up to
2298
+ * min(quote_deadline, quote_sync_wait_seconds) and return 200 with the collected quotes
2299
+ * (status `ready`). If the sync cap fires before the quote deadline, return 200 with
2300
+ * status `collecting` and poll the status endpoint.
2301
+ *
2302
+ * Collection continues server-side until the quote deadline regardless of the HTTP
2303
+ * connection, so quotes remain retrievable via the status endpoint in either mode.
2304
+ *
2305
+ * @param data The data for the request.
2306
+ * @param data.requestBody
2307
+ * @param data.wait Return a handle immediately (`false`, default) or hold the connection for collected quotes (`true`).
2308
+ * @returns QuoteRequestResponse Quote-request resolved synchronously. `status` is `ready` when quotes were collected,
2309
+ * or `collecting` when the sync wait cap fired before the quote deadline.
2310
+ *
2311
+ * @returns QuoteRequestAccepted Quote-request accepted; collection continues asynchronously.
2312
+ * @throws ApiError
2313
+ */
2314
+ createQuoteRequest(data) {
2315
+ return this.httpRequest.request({
2316
+ method: "POST",
2317
+ url: "/v1/payments/quote-requests",
2318
+ query: {
2319
+ wait: data.wait
2320
+ },
2321
+ body: data.requestBody,
2322
+ mediaType: "application/json",
2323
+ errors: {
2324
+ 400: "Invalid request",
2325
+ 500: "Internal server error"
2326
+ }
2327
+ });
2328
+ }
2329
+ /**
2330
+ * Get quote-request batch status
2331
+ * Returns the current state of a quote-request batch: a derived status, the collected
2332
+ * quotes (each with its settler-signed `award_deadline`), and the awarded
2333
+ * (quote_id, payment_id) pairs once a quote has been awarded. Used for async polling,
2334
+ * connection-drop recovery, and re-reading quotes before awarding.
2335
+ *
2336
+ * The `status` here describes the quote-request batch lifecycle
2337
+ * (`collecting`/`ready`/`awarded`/`expired`) and is disjoint from the payment-status enum
2338
+ * returned by the award and payment-status endpoints.
2339
+ *
2340
+ * @param data The data for the request.
2341
+ * @param data.quoteRequestId The ID of the quote-request batch to query
2342
+ * @returns QuoteRequestStatusResponse Quote-request status retrieved successfully
2343
+ * @throws ApiError
2344
+ */
2345
+ getQuoteRequestStatus(data) {
2346
+ return this.httpRequest.request({
2347
+ method: "GET",
2348
+ url: "/v1/payments/quote-requests/{quoteRequestId}",
2349
+ path: {
2350
+ quoteRequestId: data.quoteRequestId
2351
+ },
2352
+ errors: {
2353
+ 404: "Quote-request not found, or not owned by the caller.",
2354
+ 500: "Internal server error"
2355
+ }
2356
+ });
2357
+ }
2358
+ /**
2359
+ * Award a quote
2360
+ * Commits to a payment by awarding one quote from a previously-collected batch. The
2361
+ * originator submits two signatures from their wallet: `sender_auth` (the Permit2 deposit
2362
+ * authorization) and a fully-formed `bid_award` declaration whose `authorization` carries
2363
+ * the Escrow reserve-witness signature naming the chosen settler. The awarded quote is
2364
+ * identified server-side by content-hashing `bid_award.fulfillment_quote_json` — there is
2365
+ * no `quote_id` on the wire.
2366
+ *
2367
+ * From this call onward the `status` field describes the payment lifecycle (disjoint from the
2368
+ * quote-request batch status). Track the payment afterward via
2369
+ * GET /v1/payments/{paymentId}/status — a separate endpoint with its own status vocabulary
2370
+ * (an in-progress payment reads as `pending` there).
2371
+ *
2372
+ * Wait modes (the `wait` query parameter):
2373
+ * - `wait=false` (default): return 202 immediately with `payment_id` and status `awarding`;
2374
+ * poll GET /v1/payments/{paymentId}/status.
2375
+ * - `wait=true`: hold the connection for up to payment_sync_wait_seconds and
2376
+ * return 200 with the payment result. If the sync cap fires first, return 200 with a
2377
+ * non-terminal status (`awarding`); poll GET /v1/payments/{paymentId}/status.
2378
+ *
2379
+ * @param data The data for the request.
2380
+ * @param data.requestBody
2381
+ * @param data.wait Return a handle immediately (`false`, default) or hold the connection for the payment result (`true`).
2382
+ * @returns AwardResponse Award resolved synchronously. `status` is `completed` with a fulfillment_confirmation
2383
+ * when settlement finished within the sync wait, or a non-terminal payment status
2384
+ * (e.g. `awarding`) if the cap fired first.
2385
+ *
2386
+ * @returns AwardAccepted Award accepted; settlement continues asynchronously.
2387
+ * @throws ApiError
2388
+ */
2389
+ awardQuote(data) {
2390
+ return this.httpRequest.request({
2391
+ method: "POST",
2392
+ url: "/v1/payments/awards",
2393
+ query: {
2394
+ wait: data.wait
2395
+ },
2396
+ body: data.requestBody,
2397
+ mediaType: "application/json",
2398
+ errors: {
2399
+ 400: "Invalid request (bad signatures, expired quote, or ownership mismatch)",
2400
+ 409: `The quote, or another quote in the same batch, has already been awarded
2401
+ (single-award-per-batch, FR-09).
2402
+ `,
2403
+ 500: "Internal server error"
2404
+ }
2405
+ });
2406
+ }
2407
+ };
2408
+ var HealthService = class {
2409
+ constructor(httpRequest) {
2410
+ this.httpRequest = httpRequest;
2411
+ }
2412
+ /**
2413
+ * Health check
2414
+ * Returns the health status of the service
2415
+ * @returns unknown Service is healthy
2416
+ * @throws ApiError
2417
+ */
2418
+ healthCheck() {
2419
+ return this.httpRequest.request({
2420
+ method: "GET",
2421
+ url: "/health"
2422
+ });
2423
+ }
2424
+ };
2425
+
2426
+ // src/generated/PaymentGatewayClient.ts
2427
+ var PaymentGatewayClient = class {
2428
+ constructor(config, HttpRequest = AxiosHttpRequest) {
2429
+ this.request = new HttpRequest({
2430
+ BASE: config?.BASE ?? "https://api.atum.network",
2431
+ VERSION: config?.VERSION ?? "1.0.0",
2432
+ WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false,
2433
+ CREDENTIALS: config?.CREDENTIALS ?? "include",
2434
+ TOKEN: config?.TOKEN,
2435
+ USERNAME: config?.USERNAME,
2436
+ PASSWORD: config?.PASSWORD,
2437
+ HEADERS: config?.HEADERS,
2438
+ ENCODE_PATH: config?.ENCODE_PATH,
2439
+ interceptors: {
2440
+ request: config?.interceptors?.request ?? new Interceptors(),
2441
+ response: config?.interceptors?.response ?? new Interceptors()
2442
+ }
2443
+ });
2444
+ this.authorizations = new AuthorizationsService(this.request);
2445
+ this.health = new HealthService(this.request);
2446
+ this.payments = new PaymentsService(this.request);
2447
+ this.quoteRequests = new QuoteRequestsService(this.request);
2448
+ }
2449
+ };
2450
+
2451
+ // src/chain-adapters/evm.ts
2452
+ var import_ethers2 = require("ethers");
2453
+
2454
+ // src/chain-adapters/types.ts
2455
+ var PERMIT_DEADLINE = BigInt(1924991999);
2456
+ function resolvePermitDeadline(deadlineSeconds) {
2457
+ if (deadlineSeconds !== void 0) {
2458
+ return BigInt(Math.floor(Date.now() / 1e3) + deadlineSeconds);
2459
+ }
2460
+ return PERMIT_DEADLINE;
2461
+ }
2462
+ function generatePermitNonce() {
2463
+ const rand = new Uint32Array(1);
2464
+ globalThis.crypto.getRandomValues(rand);
2465
+ return (BigInt(Date.now()) << 32n) + BigInt(rand[0]);
2466
+ }
2467
+ function assertKeyMatchesSender(matches, sender, derived) {
2468
+ if (!matches) {
2469
+ throw new Error(`The private key derives ${derived}, which does not match the sender address ${sender}`);
2470
+ }
2471
+ }
2472
+
2473
+ // src/sender_auth_schemes/evm_permit2.ts
2474
+ var import_ethers = require("ethers");
2475
+ var import_evm_escrow_encoding = __toESM(require_dist());
2476
+
2477
+ // src/chain-adapters/evm.ts
2478
+ var evmAdapter = {
2479
+ turnkeyAddressFormat: "ADDRESS_FORMAT_ETHEREUM",
2480
+ async buildAuthMessage({ sourceAsset, fulfillmentAmount, sourceDefaults, deadlineSeconds }) {
2481
+ const sourceChainId = sourceAsset.split("/")[0];
2482
+ const chainIdNum = parseInt(sourceChainId.split(":")[1]);
2483
+ const tokenAddress = sourceAsset.split("/")[1].split(":")[1];
2484
+ const permitParams = {
2485
+ chainId: chainIdNum,
2486
+ verifyingContract: import_evm_escrow_encoding.PERMIT2_CONTRACT_ADDRESS,
2487
+ token: tokenAddress,
2488
+ amount: fulfillmentAmount,
2489
+ spender: sourceDefaults.escrowContract,
2490
+ nonce: generatePermitNonce(),
2491
+ deadline: resolvePermitDeadline(deadlineSeconds),
2492
+ reserver: sourceDefaults.quoteSelector,
2493
+ releaser: sourceDefaults.fulfillmentVerifierAccount
2494
+ };
2495
+ const messagePrehash = (0, import_evm_escrow_encoding.createPermitWitnessTransferFromPrehash)(permitParams);
2496
+ const messageHash = (0, import_evm_escrow_encoding.hashPermitWitnessTransferFrom)(messagePrehash);
2497
+ return {
2498
+ messageScheme: "EVM_PERMIT2",
2499
+ messageHash,
2500
+ messagePrehash: JSON.stringify(messagePrehash)
2501
+ };
2502
+ },
2503
+ formatPrivateKey(key) {
2504
+ return key.startsWith("0x") ? key : "0x" + key;
2505
+ },
2506
+ // Value-free: never interpolate the key. A malformed key would otherwise be
2507
+ // echoed by ethers.Wallet's "invalid BytesLike value" error.
2508
+ validatePrivateKey(key) {
2509
+ if (!/^(0x)?[0-9a-fA-F]{64}$/.test(key)) {
2510
+ throw new Error("Invalid private key");
2511
+ }
2512
+ },
2513
+ /**
2514
+ * Sign the Permit2 PermitWitnessTransferFrom typed data via standard
2515
+ * EIP-712 signing. The prehash is already shaped for direct consumption
2516
+ * by ethers' signTypedData (Permit2 domain has no version/salt; types
2517
+ * omits EIP712Domain since ethers generates that from the domain object).
2518
+ */
2519
+ async sign(signedMessage, privateKey) {
2520
+ if (!signedMessage.message_prehash) {
2521
+ throw new Error("EVM adapter sign(): signed_messages[i].message_prehash is required");
2522
+ }
2523
+ const prehash = JSON.parse(signedMessage.message_prehash);
2524
+ const wallet = new import_ethers2.ethers.Wallet(privateKey);
2525
+ return wallet.signTypedData(prehash.domain, prehash.types, prehash.message);
2526
+ },
2527
+ // Called after validatePrivateKey, so ethers.Wallet won't echo a malformed key.
2528
+ verifyAddressMatchesKey(privateKey, address) {
2529
+ const derived = new import_ethers2.ethers.Wallet(privateKey).address;
2530
+ assertKeyMatchesSender(derived.toLowerCase() === address.toLowerCase(), address, derived);
2531
+ }
2532
+ };
2533
+
2534
+ // src/chain-adapters/tron.ts
2535
+ var import_ethers3 = require("ethers");
2536
+
2537
+ // src/sender_auth_schemes/tron.ts
2538
+ var import_tvm_escrow_encoding = __toESM(require_dist2());
2539
+
2540
+ // src/chain-adapters/tron.ts
2541
+ var CHAIN_ID_MAP = {
2542
+ "shasta": 2494104990,
2543
+ "mainnet": 728126428
2544
+ };
2545
+ var PERMIT2_FALLBACKS = {
2546
+ "tron:shasta": "TPUqJPASUn1zLvbLBgRZ5pBYrx7WSe5ahp",
2547
+ "tron:mainnet": "TJhMXTHQHeQyMD7TcKQFqAePNgG4b31H9m"
2548
+ };
2549
+ var tronAdapter = {
2550
+ turnkeyAddressFormat: "ADDRESS_FORMAT_TRON",
2551
+ async buildAuthMessage({ sourceAsset, fulfillmentAmount, sourceDefaults, deadlineSeconds }) {
2552
+ const sourceChainId = sourceAsset.split("/")[0];
2553
+ const chainName = sourceChainId.split(":")[1];
2554
+ const chainIdNum = CHAIN_ID_MAP[chainName];
2555
+ if (!chainIdNum) {
2556
+ throw new Error(`Unsupported Tron chain: ${chainName}`);
2557
+ }
2558
+ const tokenAddress = sourceAsset.split("/")[1].split(":")[1];
2559
+ let permit2Address = sourceDefaults.permit2Contract;
2560
+ if (permit2Address === void 0) {
2561
+ permit2Address = PERMIT2_FALLBACKS[sourceChainId];
2562
+ if (!permit2Address) {
2563
+ throw new Error(`don't know Permit2 address for chain ${sourceChainId}`);
2564
+ }
2565
+ }
2566
+ const tvmParams = {
2567
+ chainId: chainIdNum,
2568
+ permit2Address,
2569
+ tokenAddress,
2570
+ amount: fulfillmentAmount,
2571
+ spenderAddress: sourceDefaults.escrowContract,
2572
+ nonce: generatePermitNonce(),
2573
+ deadline: resolvePermitDeadline(deadlineSeconds),
2574
+ reserverAddress: sourceDefaults.quoteSelector,
2575
+ releaserAddress: sourceDefaults.fulfillmentVerifierAccount
2576
+ };
2577
+ const messagePrehash = (0, import_tvm_escrow_encoding.createTvmPermitWitnessTransferFromPrehash)(tvmParams);
2578
+ const messageHash = (0, import_tvm_escrow_encoding.hashTvmPermitWitnessTransferFrom)(messagePrehash);
2579
+ return {
2580
+ messageScheme: "EVM_PERMIT2",
2581
+ messageHash,
2582
+ messagePrehash: JSON.stringify(messagePrehash)
2583
+ };
2584
+ },
2585
+ resolveContractOverrides(sourceDefaults) {
2586
+ return {
2587
+ quote_selector: (0, import_tvm_escrow_encoding.normalizeAddress)(sourceDefaults.quoteSelector),
2588
+ fulfillment_verifier: {
2589
+ account: (0, import_tvm_escrow_encoding.normalizeAddress)(sourceDefaults.fulfillmentVerifierAccount),
2590
+ endpoint: sourceDefaults.fulfillmentVerifierEndpoint
2591
+ }
2592
+ };
2593
+ },
2594
+ formatPrivateKey(key) {
2595
+ return key.startsWith("0x") ? key.slice(2) : key;
2596
+ },
2597
+ // Value-free: never interpolate the key. A malformed key would otherwise be
2598
+ // echoed by ethers.Wallet's "invalid BytesLike value" error.
2599
+ validatePrivateKey(key) {
2600
+ if (!/^(0x)?[0-9a-fA-F]{64}$/.test(key)) {
2601
+ throw new Error("Invalid private key");
2602
+ }
2603
+ },
2604
+ /**
2605
+ * Tron uses TIP-712 typed-data — same wire format as EIP-712. The prehash
2606
+ * built by createTvmPermitWitnessTransferFromPrehash is now directly
2607
+ * consumable by `wallet.signTypedData(prehash.domain, prehash.types,
2608
+ * prehash.message)`, but this adapter (an internal SDK helper) stays on the
2609
+ * raw-hash sign for parity with the EVM adapter — e2e tests use ethers
2610
+ * directly when they need the typed-data path.
2611
+ */
2612
+ async sign(signedMessage, privateKey) {
2613
+ const wallet = new import_ethers3.ethers.Wallet(privateKey.startsWith("0x") ? privateKey : "0x" + privateKey);
2614
+ return wallet.signingKey.sign(signedMessage.message).serialized;
2615
+ },
2616
+ // Tron addresses are the same secp256k1-derived 20 bytes as EVM. Compare the
2617
+ // derived hex directly against the canonical sender; do NOT run normalizeAddress
2618
+ // on the derived side — it strips a leading 41, which would corrupt an address
2619
+ // whose first byte is 0x41.
2620
+ verifyAddressMatchesKey(privateKey, address) {
2621
+ const key = privateKey.startsWith("0x") ? privateKey : "0x" + privateKey;
2622
+ const derived = new import_ethers3.ethers.Wallet(key).address;
2623
+ assertKeyMatchesSender(derived.toLowerCase() === (0, import_tvm_escrow_encoding.normalizeAddress)(address), address, derived);
2624
+ }
2625
+ };
2626
+
2627
+ // src/chain-adapters/solana.ts
2628
+ var import_tweetnacl = __toESM(require("tweetnacl"));
2629
+ var import_bs582 = __toESM(require("bs58"));
2630
+ var import_solana_escrow_encoding2 = __toESM(require_dist3());
2631
+
2632
+ // src/sender_auth_schemes/solana.ts
2633
+ var import_ethers4 = require("ethers");
2634
+ var import_bs58 = __toESM(require("bs58"));
2635
+ var import_solana_escrow_encoding = __toESM(require_dist3());
2636
+ var REPLAY_HORIZON_SECS = 128;
2637
+ function bytesToHex(bytes) {
2638
+ return (0, import_ethers4.hexlify)(bytes);
2639
+ }
2640
+ function hexToBytes(hex) {
2641
+ return (0, import_ethers4.getBytes)(hex.startsWith("0x") ? hex : "0x" + hex);
2642
+ }
2643
+ function createSolanaDepositPrehash(paymentId, params) {
2644
+ return {
2645
+ payment_id: paymentId,
2646
+ depositor: params.depositor,
2647
+ mint: params.mint,
2648
+ amount: params.amount.toString(),
2649
+ reserver: params.reserver,
2650
+ releaser: params.releaser,
2651
+ nonce: params.nonce.toString(),
2652
+ issued_at: params.issuedAt.toString(),
2653
+ deadline: params.deadline.toString()
2654
+ };
2655
+ }
2656
+ function generateSolanaNonce() {
2657
+ return (0, import_solana_escrow_encoding.generateNonce)();
2658
+ }
2659
+ function clusterIdFromName(name) {
2660
+ const encoded = new TextEncoder().encode(name);
2661
+ if (encoded.length > 32) {
2662
+ throw new Error(`cluster name too long for cluster_id: ${name} (${encoded.length} > 32 bytes)`);
2663
+ }
2664
+ const out = new Uint8Array(32);
2665
+ out.set(encoded);
2666
+ return out;
2667
+ }
2668
+ function generateSolanaPaymentIdV3(requestId) {
2669
+ return (0, import_ethers4.keccak256)((0, import_ethers4.toUtf8Bytes)(requestId));
2670
+ }
2671
+ function hashSolanaDepositV3(prehash, domain) {
2672
+ const hash = (0, import_solana_escrow_encoding.computeDepositHash)(
2673
+ {
2674
+ paymentId: hexToBytes(prehash.payment_id),
2675
+ depositor: import_solana_escrow_encoding.Pubkey.fromBase58(prehash.depositor),
2676
+ mint: import_solana_escrow_encoding.Pubkey.fromBase58(prehash.mint),
2677
+ amount: BigInt(prehash.amount),
2678
+ reserver: import_solana_escrow_encoding.Pubkey.fromBase58(prehash.reserver),
2679
+ releaser: import_solana_escrow_encoding.Pubkey.fromBase58(prehash.releaser),
2680
+ nonce: BigInt(prehash.nonce),
2681
+ issuedAt: BigInt(prehash.issued_at),
2682
+ deadline: BigInt(prehash.deadline)
2683
+ },
2684
+ domain
2685
+ );
2686
+ return bytesToHex(hash);
2687
+ }
2688
+
2689
+ // src/chain-adapters/solana-clock.ts
2690
+ var DEFAULT_SOLANA_RPC_URLS = {
2691
+ "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "https://api.mainnet-beta.solana.com",
2692
+ EtWTRABZaYq6iMfeYKouRu166VU2xqa1: "https://api.devnet.solana.com",
2693
+ "4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z": "https://api.testnet.solana.com"
2694
+ };
2695
+ var SYSVAR_CLOCK_ADDRESS = "SysvarC1ock11111111111111111111111111111111";
2696
+ var SOLANA_CLOCK_RPC_TIMEOUT_MS = 2e3;
2697
+ var SOLANA_ISSUED_AT_FALLBACK_SKEW_SECS = 45n;
2698
+ var SOLANA_CLOCK_READ_GUARD_SECS = 2n;
2699
+ function resolveSolanaRpcUrl(sourceChainId, override) {
2700
+ if (override) return override;
2701
+ const reference = sourceChainId.split(":")[1];
2702
+ return reference ? DEFAULT_SOLANA_RPC_URLS[reference] : void 0;
2703
+ }
2704
+ function readClockUnixTimeFromBase64(data) {
2705
+ const bytes = Buffer.from(data, "base64");
2706
+ if (bytes.length < 40) {
2707
+ throw new Error(`Solana Clock sysvar data too short: ${bytes.length} bytes`);
2708
+ }
2709
+ return bytes.readBigInt64LE(32);
2710
+ }
2711
+ var readClusterUnixTime = async (rpcUrl, timeoutMs) => {
2712
+ const controller = new AbortController();
2713
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
2714
+ try {
2715
+ const res = await fetch(rpcUrl, {
2716
+ method: "POST",
2717
+ headers: { "content-type": "application/json" },
2718
+ body: JSON.stringify({
2719
+ jsonrpc: "2.0",
2720
+ id: 1,
2721
+ method: "getAccountInfo",
2722
+ params: [SYSVAR_CLOCK_ADDRESS, { encoding: "base64" }]
2723
+ }),
2724
+ signal: controller.signal
2725
+ });
2726
+ if (!res.ok) {
2727
+ throw new Error(`Solana RPC ${rpcUrl} returned HTTP ${res.status}`);
2728
+ }
2729
+ const json = await res.json();
2730
+ const data = json?.result?.value?.data?.[0];
2731
+ if (typeof data !== "string") {
2732
+ throw new Error("Solana Clock sysvar account data missing from RPC response");
2733
+ }
2734
+ return readClockUnixTimeFromBase64(data);
2735
+ } finally {
2736
+ clearTimeout(timer);
2737
+ }
2738
+ };
2739
+ async function resolveSolanaIssuedAt(opts) {
2740
+ const rpcUrl = resolveSolanaRpcUrl(opts.sourceChainId, opts.rpcUrlOverride);
2741
+ if (rpcUrl) {
2742
+ try {
2743
+ const reader = opts.reader ?? readClusterUnixTime;
2744
+ const onChain = await reader(rpcUrl, opts.timeoutMs ?? SOLANA_CLOCK_RPC_TIMEOUT_MS);
2745
+ return onChain - SOLANA_CLOCK_READ_GUARD_SECS;
2746
+ } catch (err) {
2747
+ opts.logger?.warn(
2748
+ { err: err instanceof Error ? err.message : String(err), rpcUrl },
2749
+ "Solana cluster clock read failed; falling back to wall clock for issued_at"
2750
+ );
2751
+ }
2752
+ }
2753
+ return BigInt(Math.floor(Date.now() / 1e3)) - SOLANA_ISSUED_AT_FALLBACK_SKEW_SECS;
2754
+ }
2755
+
2756
+ // src/chain-adapters/solana.ts
2757
+ var solanaAdapter = {
2758
+ turnkeyAddressFormat: "ADDRESS_FORMAT_SOLANA",
2759
+ async buildAuthMessage({ sourceAsset, depositor, fulfillmentAmount, requestId, sourceDefaults, solanaRpcUrl, solanaClockReader, solanaLogger }) {
2760
+ const sourceChainId = sourceAsset.split("/")[0];
2761
+ const tokenMint = sourceAsset.split("/")[1].split(":")[1];
2762
+ const nonce = generateSolanaNonce();
2763
+ const issuedAt = await resolveSolanaIssuedAt({
2764
+ sourceChainId,
2765
+ rpcUrlOverride: solanaRpcUrl,
2766
+ reader: solanaClockReader,
2767
+ logger: solanaLogger
2768
+ });
2769
+ const deadline = issuedAt + BigInt(REPLAY_HORIZON_SECS - 8);
2770
+ const solanaParams = {
2771
+ depositor,
2772
+ mint: tokenMint,
2773
+ amount: BigInt(fulfillmentAmount),
2774
+ reserver: sourceDefaults.quoteSelector,
2775
+ releaser: sourceDefaults.fulfillmentVerifierAccount,
2776
+ nonce,
2777
+ issuedAt,
2778
+ deadline,
2779
+ requestId
2780
+ };
2781
+ const paymentId = generateSolanaPaymentIdV3(requestId);
2782
+ const prehash = createSolanaDepositPrehash(paymentId, solanaParams);
2783
+ if (!sourceDefaults.svmSignatureClusterId || sourceDefaults.svmSignatureDomainVersion == null) {
2784
+ throw new Error(
2785
+ "Solana source requires svm_signature_cluster_id and svm_signature_domain_version from payment-gw /defaults (V3 escrow domain separation). Is the gateway on V3?"
2786
+ );
2787
+ }
2788
+ const domain = {
2789
+ clusterId: clusterIdFromName(sourceDefaults.svmSignatureClusterId),
2790
+ signatureDomainVersion: sourceDefaults.svmSignatureDomainVersion,
2791
+ programId: import_solana_escrow_encoding2.Pubkey.fromBase58(sourceDefaults.escrowContract)
2792
+ };
2793
+ const depositHash = hashSolanaDepositV3(prehash, domain);
2794
+ return {
2795
+ messageScheme: "SOLANA",
2796
+ messageHash: depositHash,
2797
+ messagePrehash: JSON.stringify(prehash)
2798
+ };
2799
+ },
2800
+ formatPrivateKey(key) {
2801
+ return key.startsWith("0x") ? key.slice(2) : key;
2802
+ },
2803
+ /**
2804
+ * Solana has no EIP-712-style typed-data standard. The prehash structure
2805
+ * still describes what was hashed (for debugging / wallet UX), but the
2806
+ * canonical signing input is the chain-specific digest already in
2807
+ * signedMessage.message. We sign that with ed25519.
2808
+ */
2809
+ async sign(signedMessage, privateKey) {
2810
+ const messageBytes = new Uint8Array(Buffer.from(signedMessage.message.replace("0x", ""), "hex"));
2811
+ const secretKey = secretKeyFromPrivate(privateKey);
2812
+ const sig = import_tweetnacl.default.sign.detached(messageBytes, secretKey);
2813
+ return "0x" + Buffer.from(sig).toString("hex");
2814
+ },
2815
+ /**
2816
+ * Solana Ed25519 signatures are not public-key-recoverable (unlike EVM
2817
+ * secp256k1, where ecrecover derives the signer from the signature). The
2818
+ * on-chain Ed25519 verify instruction must therefore be given the signer's
2819
+ * public key explicitly, so we ship it as signed_messages[0].payload.delegate_signer.
2820
+ * In the self-custody CLI flow the signer is the depositor itself, so this
2821
+ * equals source.account.
2822
+ */
2823
+ deriveDelegateSigner(privateKey) {
2824
+ return deriveSolanaAddress(privateKey);
2825
+ },
2826
+ verifyAddressMatchesKey(privateKey, address) {
2827
+ const derived = deriveSolanaAddress(privateKey);
2828
+ assertKeyMatchesSender(derived === address, address, derived);
2829
+ }
2830
+ };
2831
+ function deriveSolanaAddress(privateKey) {
2832
+ return import_bs582.default.encode(import_tweetnacl.default.sign.keyPair.fromSecretKey(secretKeyFromPrivate(privateKey)).publicKey);
2833
+ }
2834
+ function secretKeyFromPrivate(privateKey) {
2835
+ if (/^[0-9a-fA-F]{64}$/.test(privateKey)) {
2836
+ const seed = new Uint8Array(32);
2837
+ for (let i = 0; i < 32; i++) {
2838
+ seed[i] = parseInt(privateKey.substring(i * 2, i * 2 + 2), 16);
2839
+ }
2840
+ return import_tweetnacl.default.sign.keyPair.fromSeed(seed).secretKey;
2841
+ }
2842
+ const decoded = import_bs582.default.decode(privateKey);
2843
+ if (decoded.length === 64) {
2844
+ return decoded;
2845
+ }
2846
+ if (decoded.length === 32) {
2847
+ return import_tweetnacl.default.sign.keyPair.fromSeed(decoded).secretKey;
2848
+ }
2849
+ throw new Error(`Invalid Solana private key length: expected 32 or 64 bytes, got ${decoded.length}`);
2850
+ }
2851
+
2852
+ // src/chain-adapters/index.ts
2853
+ var adapters = {
2854
+ "eip155": evmAdapter,
2855
+ "tron": tronAdapter,
2856
+ "solana": solanaAdapter
2857
+ };
2858
+ function getChainAdapter(sourceChainId) {
2859
+ const prefix = sourceChainId.split(":")[0];
2860
+ const adapter = adapters[prefix];
2861
+ if (!adapter) throw new Error(`Unsupported source chain: ${sourceChainId}`);
2862
+ return adapter;
2863
+ }
2864
+
2865
+ // src/index.ts
2866
+ var PAYMENT_REQUEST_VERSION = "1.0";
2867
+ var defaultGateway = "https://payment-gateway-testnet.atumlabs.xyz";
2868
+ var DEFAULT_QUOTE_DEADLINE_SECONDS = 5;
2869
+ var DEFAULT_FULFILLMENT_DEADLINE_SECONDS = 3600;
2870
+ var DEFAULT_PAYMENT_QUOTE_DEADLINE_SECONDS = 10;
2871
+ var PROTOCOL_FEE_BIPS = 2n;
2872
+ var BIPS_DENOMINATOR = 10000n;
2873
+ function defaultMaxSourceAmount(fulfillmentAmount) {
2874
+ const amount = BigInt(fulfillmentAmount);
2875
+ const protocolFee = (amount * PROTOCOL_FEE_BIPS + BIPS_DENOMINATOR - 1n) / BIPS_DENOMINATOR;
2876
+ return (amount + protocolFee).toString();
2877
+ }
2878
+ function resolveDeadlines(params, defaultQuoteSeconds) {
2879
+ const quoteDeadlineSeconds = params.quoteDeadlineSeconds ?? defaultQuoteSeconds;
2880
+ const fulfillmentDeadlineSeconds = params.fulfillmentDeadlineSeconds ?? DEFAULT_FULFILLMENT_DEADLINE_SECONDS;
2881
+ if (!Number.isFinite(quoteDeadlineSeconds) || !Number.isFinite(fulfillmentDeadlineSeconds)) {
2882
+ throw new Error("quoteDeadlineSeconds and fulfillmentDeadlineSeconds must be finite numbers of seconds.");
2883
+ }
2884
+ if (quoteDeadlineSeconds <= 0 || fulfillmentDeadlineSeconds <= 0) {
2885
+ throw new Error("quoteDeadlineSeconds and fulfillmentDeadlineSeconds must be positive numbers of seconds.");
2886
+ }
2887
+ if (quoteDeadlineSeconds >= fulfillmentDeadlineSeconds) {
2888
+ throw new Error(
2889
+ `quoteDeadlineSeconds (${quoteDeadlineSeconds}) must be strictly less than fulfillmentDeadlineSeconds (${fulfillmentDeadlineSeconds}). The gateway rejects a quote_deadline that is not before fulfillment_deadline.`
2890
+ );
2891
+ }
2892
+ const now = Date.now();
2893
+ return {
2894
+ quote_deadline: new Date(now + quoteDeadlineSeconds * 1e3).toISOString(),
2895
+ fulfillment_deadline: new Date(now + fulfillmentDeadlineSeconds * 1e3).toISOString()
2896
+ };
2897
+ }
2898
+ var PaymentGatewayClient2 = class extends PaymentGatewayClient {
2899
+ constructor(config, HttpRequest = AxiosHttpRequest) {
2900
+ super(config, HttpRequest);
2901
+ this.baseUrl = config?.BASE ?? defaultGateway;
2902
+ }
2903
+ /**
2904
+ * Fetches chain defaults from the payment gateway.
2905
+ *
2906
+ * @param chainId The CAIP-2 chain identifier (e.g., "eip155:42161")
2907
+ * @returns The chain defaults including escrow, quote selector, and fulfillment verifier
2908
+ */
2909
+ async fetchChainDefaults(chainId) {
2910
+ const response = await fetch(`${this.baseUrl}/defaults?chain_id=${chainId}`);
2911
+ if (!response.ok) {
2912
+ let availableDefaults = null;
2913
+ try {
2914
+ const allDefaultsResponse = await fetch(`${this.baseUrl}/defaults`);
2915
+ if (allDefaultsResponse.ok) {
2916
+ availableDefaults = await allDefaultsResponse.json();
2917
+ }
2918
+ } catch {
2919
+ }
2920
+ const error = new Error(`Failed to fetch defaults for chain ${chainId}: ${response.statusText}`);
2921
+ error.availableDefaults = availableDefaults;
2922
+ throw error;
2923
+ }
2924
+ const data = await response.json();
2925
+ if (!data.escrow_contract) {
2926
+ throw new Error("defaults missing escrow_contract");
2927
+ }
2928
+ if (!data.fulfillment_proxy) {
2929
+ throw new Error("defaults missing fulfillment_proxy");
2930
+ }
2931
+ if (!data.quote_selector) {
2932
+ throw new Error("defaults missing quote_selector");
2933
+ }
2934
+ if (!data.fulfillment_verifier) {
2935
+ throw new Error("defaults missing fulfillment_verifier");
2936
+ }
2937
+ if (!data.fulfillment_verifier.account) {
2938
+ throw new Error("defaults missing fulfillment_verifier.account");
2939
+ }
2940
+ if (!data.fulfillment_verifier.endpoint) {
2941
+ throw new Error("defaults missing fulfillment_verifier.endpoint");
2942
+ }
2943
+ return {
2944
+ escrowContract: data.escrow_contract,
2945
+ quoteSelector: data.quote_selector,
2946
+ fulfillmentVerifierAccount: data.fulfillment_verifier.account,
2947
+ fulfillmentVerifierEndpoint: data.fulfillment_verifier.endpoint,
2948
+ fulfillmentProxy: data.fulfillment_proxy,
2949
+ permit2Contract: data.permit2_contract,
2950
+ // V3 Solana escrow domain separation. Present only for Solana
2951
+ // source chains; the Solana adapter requires them to build the deposit hash.
2952
+ svmSignatureClusterId: data.svm_signature_cluster_id,
2953
+ svmSignatureDomainVersion: data.svm_signature_domain_version
2954
+ };
2955
+ }
2956
+ /**
2957
+ * Prepares a payment request with defaults, ready for signing.
2958
+ *
2959
+ * @param params Payment parameters
2960
+ * @returns A complete PaymentRequest object without the signature
2961
+ */
2962
+ async preparePaymentRequest(params) {
2963
+ const { quote_deadline, fulfillment_deadline } = resolveDeadlines(params, DEFAULT_PAYMENT_QUOTE_DEADLINE_SECONDS);
2964
+ const sourceChainId = params.sourceAsset.split("/")[0];
2965
+ const destChainId = params.destinationAsset.split("/")[0];
2966
+ const [sourceDefaults, destDefaults] = await Promise.all([
2967
+ this.fetchChainDefaults(sourceChainId),
2968
+ this.fetchChainDefaults(destChainId)
2969
+ ]);
2970
+ const requestId = params.requestId || `${params.requestIdPrefix || "pmt-gw-sdk"}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
2971
+ const adapter = getChainAdapter(sourceChainId);
2972
+ const auth = await adapter.buildAuthMessage({
2973
+ sourceAsset: params.sourceAsset,
2974
+ depositor: params.depositor,
2975
+ fulfillmentAmount: params.fulfillmentAmount,
2976
+ requestId,
2977
+ sourceDefaults,
2978
+ deadlineSeconds: params.deadlineSeconds,
2979
+ solanaRpcUrl: params.solanaRpcUrl
2980
+ });
2981
+ const contractOverrides = adapter.resolveContractOverrides?.(sourceDefaults);
2982
+ return {
2983
+ version: PAYMENT_REQUEST_VERSION,
2984
+ request_id: requestId,
2985
+ source: {
2986
+ asset_identifier: params.sourceAsset,
2987
+ account: params.depositor
2988
+ },
2989
+ destination: [{
2990
+ asset_identifier: params.destinationAsset,
2991
+ account: params.destinationAccount
2992
+ }],
2993
+ fulfillment_amount: params.fulfillmentAmount,
2994
+ max_source_amount: params.maxSourceAmount ?? defaultMaxSourceAmount(params.fulfillmentAmount),
2995
+ // REQUIRED (the gateway injects no defaults). Callers can widen the window via
2996
+ // quoteDeadlineSeconds / fulfillmentDeadlineSeconds, e.g. for slow Turnkey signing.
2997
+ quote_deadline,
2998
+ fulfillment_deadline,
2999
+ escrow_contract_address: sourceDefaults.escrowContract,
3000
+ quote_selector: contractOverrides?.quote_selector ?? sourceDefaults.quoteSelector,
3001
+ fulfillment_verifier: contractOverrides?.fulfillment_verifier ?? {
3002
+ account: sourceDefaults.fulfillmentVerifierAccount,
3003
+ endpoint: sourceDefaults.fulfillmentVerifierEndpoint
3004
+ },
3005
+ fulfillment_proxy: destDefaults.fulfillmentProxy,
3006
+ ...params.settlerRequirements ? { settler_requirements: params.settlerRequirements } : {},
3007
+ sender_auth: {
3008
+ message_scheme: auth.messageScheme,
3009
+ signed_messages: [{
3010
+ message: auth.messageHash,
3011
+ message_prehash: auth.messagePrehash,
3012
+ signature: ""
3013
+ }]
3014
+ }
3015
+ };
3016
+ }
3017
+ /**
3018
+ * Prepares a quote-request body (`CreateQuoteRequest`), ready to POST to
3019
+ * `/v1/payments/quote-requests`. This is the quote-phase counterpart to
3020
+ * `preparePaymentRequest`: it builds the same corridor shape but **without
3021
+ * `sender_auth`** — quote-time is the unauthenticated browse step, so no
3022
+ * signing (and no private key) is required. The spend authorization arrives
3023
+ * later, at the award call.
3024
+ *
3025
+ * Both deadlines are populated here because the gateway requires them and
3026
+ * injects no defaults — it never mutates the originator-supplied body.
3027
+ * `quote_deadline` bounds the collection window (default
3028
+ * `DEFAULT_QUOTE_DEADLINE_SECONDS`); `fulfillment_deadline` bounds settlement
3029
+ * (default `DEFAULT_FULFILLMENT_DEADLINE_SECONDS`). `quote_deadline` must be
3030
+ * strictly earlier than `fulfillment_deadline` (enforced server-side; guarded
3031
+ * here for a clear client-side error).
3032
+ *
3033
+ * `quote_deadline` is stamped client-side and the gateway rejects it unless it
3034
+ * is strictly in the gateway's future, so a caller whose clock may lag the
3035
+ * gateway should pass a larger `quoteDeadlineSeconds` (see
3036
+ * `DEFAULT_QUOTE_DEADLINE_SECONDS` for why the default is what it is).
3037
+ *
3038
+ * Like `preparePaymentRequest`, this fetches the source/destination chain
3039
+ * defaults and populates the SAME contract fields (`escrow_contract_address`,
3040
+ * `quote_selector`, `fulfillment_verifier`, `fulfillment_proxy`). These are not
3041
+ * optional in practice: the gateway requires `fulfillment_verifier` to build the
3042
+ * QuoteRequested event it broadcasts to settlers, so the quote-request body
3043
+ * must carry the identical contract fields the payment flow does. The ONLY
3044
+ * field this drops relative to `preparePaymentRequest` is `sender_auth`, which
3045
+ * is supplied at award time (quote-time is unauthenticated — no signing, no
3046
+ * private key).
3047
+ *
3048
+ * @param params Quote-request parameters
3049
+ * @returns A complete `CreateQuoteRequest` body (no signature step needed)
3050
+ */
3051
+ async prepareQuoteRequest(params) {
3052
+ const { quote_deadline, fulfillment_deadline } = resolveDeadlines(params, DEFAULT_QUOTE_DEADLINE_SECONDS);
3053
+ const sourceChainId = params.sourceAsset.split("/")[0];
3054
+ const destChainId = params.destinationAsset.split("/")[0];
3055
+ const [sourceDefaults, destDefaults] = await Promise.all([
3056
+ this.fetchChainDefaults(sourceChainId),
3057
+ this.fetchChainDefaults(destChainId)
3058
+ ]);
3059
+ const contractOverrides = getChainAdapter(sourceChainId).resolveContractOverrides?.(sourceDefaults);
3060
+ const requestId = params.requestId || `${params.requestIdPrefix || "quote-gw-sdk"}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
3061
+ return {
3062
+ version: PAYMENT_REQUEST_VERSION,
3063
+ request_id: requestId,
3064
+ source: {
3065
+ asset_identifier: params.sourceAsset,
3066
+ account: params.depositor
3067
+ },
3068
+ destination: [{
3069
+ asset_identifier: params.destinationAsset,
3070
+ account: params.destinationAccount
3071
+ }],
3072
+ fulfillment_amount: params.fulfillmentAmount,
3073
+ max_source_amount: params.maxSourceAmount ?? defaultMaxSourceAmount(params.fulfillmentAmount),
3074
+ // Required + originator-supplied: the gateway injects no default and never
3075
+ // mutates the body. Ordering (quote < fulfillment) is enforced in resolveDeadlines.
3076
+ quote_deadline,
3077
+ fulfillment_deadline,
3078
+ // Byte-identical contract fields to preparePaymentRequest (minus
3079
+ // sender_auth): the same adapter override resolution runs on both paths,
3080
+ // so a Tron base58 default becomes the identical canonical-hex value here
3081
+ // as in the signed payment flow.
3082
+ escrow_contract_address: sourceDefaults.escrowContract,
3083
+ quote_selector: contractOverrides?.quote_selector ?? sourceDefaults.quoteSelector,
3084
+ fulfillment_verifier: contractOverrides?.fulfillment_verifier ?? {
3085
+ account: sourceDefaults.fulfillmentVerifierAccount,
3086
+ endpoint: sourceDefaults.fulfillmentVerifierEndpoint
3087
+ },
3088
+ fulfillment_proxy: destDefaults.fulfillmentProxy,
3089
+ ...params.settlerRequirements ? { settler_requirements: params.settlerRequirements } : {}
3090
+ // No sender_auth — CreateQuoteRequest has no such field; it is supplied at
3091
+ // award time, not quote time.
3092
+ };
3093
+ }
3094
+ };
3095
+
3096
+ // src/cli/quote-status.ts
3097
+ var program = new import_commander.Command();
3098
+ program.name("quote-status").description("Fetch the status of a quote-request batch (no signing required)").version("1.0.0").argument("<quoteRequestId>", "The quote_request_id (qr_...) returned by request-quote").option("--gateway <url>", "Payment gateway URL", defaultGateway).addHelpText("after", `
3099
+ Example:
3100
+ quote-status --gateway http://localhost:8080 qr_019f27b9-420d-7353-8263-0cf310670a77
3101
+
3102
+ Status values: collecting | ready | awarded | expired
3103
+
3104
+ Output:
3105
+ Response JSON -> stdout (for parsing/automation, e.g. | jq)`).action(async (quoteRequestId, options) => {
3106
+ try {
3107
+ const client = new PaymentGatewayClient2({ BASE: options.gateway });
3108
+ const response = await client.quoteRequests.getQuoteRequestStatus({ quoteRequestId });
3109
+ console.log(JSON.stringify(response, null, 2));
3110
+ process.exit(0);
3111
+ } catch (error) {
3112
+ if (error instanceof ApiError && error.body) {
3113
+ console.log(JSON.stringify(error.body, null, 2));
3114
+ } else {
3115
+ console.error("\n\u274C Error:", error instanceof Error ? error.message : String(error));
3116
+ }
3117
+ process.exit(1);
3118
+ }
3119
+ });
3120
+ program.parse();
3121
+ /*! Bundled license information:
3122
+
3123
+ @noble/hashes/utils.js:
3124
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3125
+ */