@atumlabs/payment-gateway-client 2.2.0 → 3.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.
@@ -1,9 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  /*
3
- * Copyright (c) 2026 Atum Labs, Inc. All rights reserved.
4
- * Proprietary and confidential.
5
- * Access and use are governed by the LICENSE file distributed with this package.
6
- * Do not remove, alter, or obscure this notice.
3
+ * Copyright 2026 Atum Labs, Inc.
4
+ * SPDX-License-Identifier: Apache-2.0
7
5
  */
8
6
  "use strict";
9
7
  var __create = Object.create;
@@ -12,8 +10,20 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
10
  var __getOwnPropNames = Object.getOwnPropertyNames;
13
11
  var __getProtoOf = Object.getPrototypeOf;
14
12
  var __hasOwnProp = Object.prototype.hasOwnProperty;
13
+ var __esm = (fn, res, err) => function __init() {
14
+ if (err) throw err[0];
15
+ try {
16
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
17
+ } catch (e) {
18
+ throw err = [e], e;
19
+ }
20
+ };
15
21
  var __commonJS = (cb, mod) => function __require() {
16
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
22
+ try {
23
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
24
+ } catch (e) {
25
+ throw mod = 0, e;
26
+ }
17
27
  };
18
28
  var __copyProps = (to, from, except, desc) => {
19
29
  if (from && typeof from === "object" || typeof from === "function") {
@@ -82,7 +92,7 @@ var require_tron_address = __commonJS({
82
92
  hexAddress = base58ToHex2(address);
83
93
  }
84
94
  hexAddress = hexAddress.replace(/^0x/, "");
85
- if (hexAddress.startsWith(TVM_MAINNET_PREFIX)) {
95
+ if (hexAddress.length === 42 && hexAddress.startsWith(TVM_MAINNET_PREFIX)) {
86
96
  hexAddress = hexAddress.substring(2);
87
97
  }
88
98
  if (hexAddress.length !== 40) {
@@ -96,14 +106,62 @@ var require_tron_address = __commonJS({
96
106
  }
97
107
  });
98
108
 
109
+ // ../contracts/tvm/escrow-encoding/typescript/dist/witness-values.js
110
+ var require_witness_values = __commonJS({
111
+ "../contracts/tvm/escrow-encoding/typescript/dist/witness-values.js"(exports2) {
112
+ "use strict";
113
+ Object.defineProperty(exports2, "__esModule", { value: true });
114
+ exports2.normalizeBytes32 = normalizeBytes32;
115
+ exports2.normalizeUint256 = normalizeUint256;
116
+ exports2.maskedChainIdToHex = maskedChainIdToHex;
117
+ var ethers_1 = require("ethers");
118
+ var chain_id_1 = require_chain_id();
119
+ function normalizeBytes32(label, value) {
120
+ let bytes;
121
+ try {
122
+ bytes = (0, ethers_1.getBytes)(value);
123
+ } catch {
124
+ throw new Error(`${label} must be 0x-prefixed hex (32 bytes), got ${JSON.stringify(value)}`);
125
+ }
126
+ if (bytes.length !== 32) {
127
+ throw new Error(`${label} must be exactly 32 bytes, got ${bytes.length}`);
128
+ }
129
+ return (0, ethers_1.hexlify)(bytes);
130
+ }
131
+ function normalizeUint256(label, value) {
132
+ let n;
133
+ try {
134
+ n = BigInt(value);
135
+ } catch {
136
+ throw new Error(`${label} must be an integer (bigint or decimal string), got ${JSON.stringify(value)}`);
137
+ }
138
+ if (n < 0n) {
139
+ throw new Error(`${label} must be non-negative (uint256), got ${n.toString()}`);
140
+ }
141
+ return n.toString();
142
+ }
143
+ function maskedChainIdToHex(chainId) {
144
+ if (!Number.isSafeInteger(chainId) || chainId < 0) {
145
+ throw new Error(`chainId must be a non-negative safe integer, got ${chainId}`);
146
+ }
147
+ return `0x${(0, chain_id_1.maskChainId)(chainId).toString(16)}`;
148
+ }
149
+ }
150
+ });
151
+
99
152
  // ../contracts/tvm/escrow-encoding/typescript/dist/reserve-encoder.js
100
153
  var require_reserve_encoder = __commonJS({
101
154
  "../contracts/tvm/escrow-encoding/typescript/dist/reserve-encoder.js"(exports2) {
102
155
  "use strict";
103
156
  Object.defineProperty(exports2, "__esModule", { value: true });
157
+ exports2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE = void 0;
104
158
  exports2.computeReserveDigest = computeReserveDigest;
159
+ exports2.buildTvmReserveTypedDataWithQuoteSource = buildTvmReserveTypedDataWithQuoteSource;
160
+ exports2.computeTvmReserveDigestWithQuoteSource = computeTvmReserveDigestWithQuoteSource;
105
161
  var ethers_1 = require("ethers");
106
162
  var chain_id_1 = require_chain_id();
163
+ var tron_address_1 = require_tron_address();
164
+ var witness_values_1 = require_witness_values();
107
165
  var RESERVE_WITNESS_TYPES = {
108
166
  ReserveWitness: [
109
167
  { name: "paymentId", type: "bytes32" },
@@ -122,6 +180,36 @@ var require_reserve_encoder = __commonJS({
122
180
  settler: input.settler
123
181
  });
124
182
  }
183
+ exports2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE = {
184
+ ReserveWitness: [
185
+ { name: "depositId", type: "bytes32" },
186
+ { name: "quoteHash", type: "bytes32" },
187
+ { name: "settler", type: "address" },
188
+ { name: "sourceAmount", type: "uint256" }
189
+ ]
190
+ };
191
+ function buildTvmReserveTypedDataWithQuoteSource(input) {
192
+ return {
193
+ types: exports2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE,
194
+ primaryType: "ReserveWitness",
195
+ domain: {
196
+ name: "Escrow",
197
+ version: "3",
198
+ chainId: (0, witness_values_1.maskedChainIdToHex)(input.chainId),
199
+ verifyingContract: (0, tron_address_1.normalizeAddress)(input.escrowContract)
200
+ },
201
+ message: {
202
+ depositId: (0, witness_values_1.normalizeBytes32)("depositId", input.depositId),
203
+ quoteHash: (0, witness_values_1.normalizeBytes32)("quoteHash", input.quoteHash),
204
+ settler: (0, tron_address_1.normalizeAddress)(input.settler),
205
+ sourceAmount: (0, witness_values_1.normalizeUint256)("sourceAmount", input.sourceAmount)
206
+ }
207
+ };
208
+ }
209
+ function computeTvmReserveDigestWithQuoteSource(input) {
210
+ const prehash = buildTvmReserveTypedDataWithQuoteSource(input);
211
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
212
+ }
125
213
  }
126
214
  });
127
215
 
@@ -148,11 +236,14 @@ var require_deposit_encoder = __commonJS({
148
236
  "../contracts/tvm/escrow-encoding/typescript/dist/deposit-encoder.js"(exports2) {
149
237
  "use strict";
150
238
  Object.defineProperty(exports2, "__esModule", { value: true });
239
+ exports2.MAX_DESTINATION_BYTES = exports2.PERMIT_WITNESS_TYPES_WITH_DESTINATION = void 0;
151
240
  exports2.createTvmPermitWitnessTransferFromPrehash = createTvmPermitWitnessTransferFromPrehash2;
152
241
  exports2.hashTvmPermitWitnessTransferFrom = hashTvmPermitWitnessTransferFrom2;
242
+ exports2.createTvmPermitWitnessTransferFromPrehashWithDestination = createTvmPermitWitnessTransferFromPrehashWithDestination;
153
243
  var ethers_1 = require("ethers");
154
244
  var chain_id_1 = require_chain_id();
155
245
  var tron_address_1 = require_tron_address();
246
+ var witness_values_1 = require_witness_values();
156
247
  var PERMIT_WITNESS_TYPES_V2 = {
157
248
  PermitWitnessTransferFrom: [
158
249
  { name: "permitted", type: "TokenPermissions" },
@@ -198,6 +289,180 @@ var require_deposit_encoder = __commonJS({
198
289
  function hashTvmPermitWitnessTransferFrom2(prehash) {
199
290
  return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
200
291
  }
292
+ exports2.PERMIT_WITNESS_TYPES_WITH_DESTINATION = {
293
+ PermitWitnessTransferFrom: [
294
+ { name: "permitted", type: "TokenPermissions" },
295
+ { name: "spender", type: "address" },
296
+ { name: "nonce", type: "uint256" },
297
+ { name: "deadline", type: "uint256" },
298
+ { name: "witness", type: "DepositWitness" }
299
+ ],
300
+ TokenPermissions: [
301
+ { name: "token", type: "address" },
302
+ { name: "amount", type: "uint256" }
303
+ ],
304
+ DepositWitness: [
305
+ { name: "depositRequestHash", type: "bytes32" },
306
+ { name: "destination", type: "string" },
307
+ { name: "reserver", type: "address" },
308
+ { name: "releaser", type: "address" }
309
+ ]
310
+ };
311
+ exports2.MAX_DESTINATION_BYTES = 256;
312
+ function assertDestinationWithinBounds(destination) {
313
+ if (destination === "") {
314
+ throw new Error('destination is empty: the escrow reverts DestinationCannotBeEmpty, and because keccak256("") is a valid bytes32 this would otherwise sign a commitment to no destination at all');
315
+ }
316
+ const byteLength = (0, ethers_1.toUtf8Bytes)(destination).length;
317
+ if (byteLength > exports2.MAX_DESTINATION_BYTES) {
318
+ throw new Error(`destination is ${byteLength} bytes, over the escrow's MAX_DESTINATION_BYTES of ${exports2.MAX_DESTINATION_BYTES}: the contract reverts DestinationTooLong, so this digest could never be redeemed`);
319
+ }
320
+ }
321
+ function createTvmPermitWitnessTransferFromPrehashWithDestination(params) {
322
+ assertDestinationWithinBounds(params.destination);
323
+ return {
324
+ types: exports2.PERMIT_WITNESS_TYPES_WITH_DESTINATION,
325
+ primaryType: "PermitWitnessTransferFrom",
326
+ domain: {
327
+ name: "Permit2",
328
+ chainId: (0, witness_values_1.maskedChainIdToHex)(params.chainId),
329
+ verifyingContract: (0, tron_address_1.normalizeAddress)(params.permit2Address)
330
+ },
331
+ message: {
332
+ permitted: {
333
+ token: (0, tron_address_1.normalizeAddress)(params.tokenAddress),
334
+ amount: (0, witness_values_1.normalizeUint256)("amount", params.amount)
335
+ },
336
+ spender: (0, tron_address_1.normalizeAddress)(params.spenderAddress),
337
+ nonce: (0, witness_values_1.normalizeUint256)("nonce", params.nonce),
338
+ deadline: (0, witness_values_1.normalizeUint256)("deadline", params.deadline),
339
+ witness: {
340
+ depositRequestHash: (0, witness_values_1.normalizeBytes32)("depositRequestHash", params.depositRequestHash),
341
+ destination: params.destination,
342
+ reserver: (0, tron_address_1.normalizeAddress)(params.reserverAddress),
343
+ releaser: (0, tron_address_1.normalizeAddress)(params.releaserAddress)
344
+ }
345
+ }
346
+ };
347
+ }
348
+ }
349
+ });
350
+
351
+ // ../contracts/tvm/escrow-encoding/typescript/dist/release-encoder.js
352
+ var require_release_encoder = __commonJS({
353
+ "../contracts/tvm/escrow-encoding/typescript/dist/release-encoder.js"(exports2) {
354
+ "use strict";
355
+ Object.defineProperty(exports2, "__esModule", { value: true });
356
+ exports2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH = void 0;
357
+ exports2.buildTvmReleaseTypedDataWithQuoteHash = buildTvmReleaseTypedDataWithQuoteHash;
358
+ exports2.computeTvmReleaseDigestWithQuoteHash = computeTvmReleaseDigestWithQuoteHash;
359
+ var ethers_1 = require("ethers");
360
+ var tron_address_1 = require_tron_address();
361
+ var witness_values_1 = require_witness_values();
362
+ exports2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH = {
363
+ ReleaseWitness: [
364
+ { name: "depositId", type: "bytes32" },
365
+ { name: "quoteHash", type: "bytes32" },
366
+ { name: "depositRequestHash", type: "bytes32" },
367
+ { name: "destinationHash", type: "bytes32" },
368
+ { name: "depositor", type: "address" },
369
+ { name: "token", type: "address" },
370
+ { name: "amount", type: "uint256" },
371
+ { name: "feeAmount", type: "uint256" },
372
+ { name: "reserver", type: "address" },
373
+ { name: "releaser", type: "address" },
374
+ { name: "settler", type: "address" }
375
+ ]
376
+ };
377
+ function buildTvmReleaseTypedDataWithQuoteHash(input) {
378
+ const w = input.witness;
379
+ return {
380
+ types: exports2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH,
381
+ primaryType: "ReleaseWitness",
382
+ domain: {
383
+ name: "Escrow",
384
+ version: "3",
385
+ chainId: (0, witness_values_1.maskedChainIdToHex)(input.chainId),
386
+ verifyingContract: (0, tron_address_1.normalizeAddress)(input.escrowContract)
387
+ },
388
+ message: {
389
+ depositId: (0, witness_values_1.normalizeBytes32)("depositId", w.depositId),
390
+ quoteHash: (0, witness_values_1.normalizeBytes32)("quoteHash", w.quoteHash),
391
+ depositRequestHash: (0, witness_values_1.normalizeBytes32)("depositRequestHash", w.depositRequestHash),
392
+ destinationHash: (0, witness_values_1.normalizeBytes32)("destinationHash", w.destinationHash),
393
+ depositor: (0, tron_address_1.normalizeAddress)(w.depositor),
394
+ token: (0, tron_address_1.normalizeAddress)(w.token),
395
+ amount: (0, witness_values_1.normalizeUint256)("amount", w.amount),
396
+ feeAmount: (0, witness_values_1.normalizeUint256)("feeAmount", w.feeAmount),
397
+ reserver: (0, tron_address_1.normalizeAddress)(w.reserver),
398
+ releaser: (0, tron_address_1.normalizeAddress)(w.releaser),
399
+ settler: (0, tron_address_1.normalizeAddress)(w.settler)
400
+ }
401
+ };
402
+ }
403
+ function computeTvmReleaseDigestWithQuoteHash(input) {
404
+ const prehash = buildTvmReleaseTypedDataWithQuoteHash(input);
405
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
406
+ }
407
+ }
408
+ });
409
+
410
+ // ../contracts/tvm/escrow-encoding/typescript/dist/refund-encoder.js
411
+ var require_refund_encoder = __commonJS({
412
+ "../contracts/tvm/escrow-encoding/typescript/dist/refund-encoder.js"(exports2) {
413
+ "use strict";
414
+ Object.defineProperty(exports2, "__esModule", { value: true });
415
+ exports2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH = void 0;
416
+ exports2.buildTvmRefundTypedDataWithQuoteHash = buildTvmRefundTypedDataWithQuoteHash;
417
+ exports2.computeTvmRefundDigestWithQuoteHash = computeTvmRefundDigestWithQuoteHash;
418
+ var ethers_1 = require("ethers");
419
+ var tron_address_1 = require_tron_address();
420
+ var witness_values_1 = require_witness_values();
421
+ exports2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH = {
422
+ RefundWitness: [
423
+ { name: "depositId", type: "bytes32" },
424
+ { name: "quoteHash", type: "bytes32" },
425
+ { name: "depositRequestHash", type: "bytes32" },
426
+ { name: "destinationHash", type: "bytes32" },
427
+ { name: "depositor", type: "address" },
428
+ { name: "token", type: "address" },
429
+ { name: "amount", type: "uint256" },
430
+ { name: "feeAmount", type: "uint256" },
431
+ { name: "reserver", type: "address" },
432
+ { name: "releaser", type: "address" },
433
+ { name: "settler", type: "address" }
434
+ ]
435
+ };
436
+ function buildTvmRefundTypedDataWithQuoteHash(input) {
437
+ const w = input.witness;
438
+ return {
439
+ types: exports2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH,
440
+ primaryType: "RefundWitness",
441
+ domain: {
442
+ name: "Escrow",
443
+ version: "3",
444
+ chainId: (0, witness_values_1.maskedChainIdToHex)(input.chainId),
445
+ verifyingContract: (0, tron_address_1.normalizeAddress)(input.escrowContract)
446
+ },
447
+ message: {
448
+ depositId: (0, witness_values_1.normalizeBytes32)("depositId", w.depositId),
449
+ quoteHash: (0, witness_values_1.normalizeBytes32)("quoteHash", w.quoteHash),
450
+ depositRequestHash: (0, witness_values_1.normalizeBytes32)("depositRequestHash", w.depositRequestHash),
451
+ destinationHash: (0, witness_values_1.normalizeBytes32)("destinationHash", w.destinationHash),
452
+ depositor: (0, tron_address_1.normalizeAddress)(w.depositor),
453
+ token: (0, tron_address_1.normalizeAddress)(w.token),
454
+ amount: (0, witness_values_1.normalizeUint256)("amount", w.amount),
455
+ feeAmount: (0, witness_values_1.normalizeUint256)("feeAmount", w.feeAmount),
456
+ reserver: (0, tron_address_1.normalizeAddress)(w.reserver),
457
+ releaser: (0, tron_address_1.normalizeAddress)(w.releaser),
458
+ settler: (0, tron_address_1.normalizeAddress)(w.settler)
459
+ }
460
+ };
461
+ }
462
+ function computeTvmRefundDigestWithQuoteHash(input) {
463
+ const prehash = buildTvmRefundTypedDataWithQuoteHash(input);
464
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
465
+ }
201
466
  }
202
467
  });
203
468
 
@@ -206,7 +471,7 @@ var require_dist = __commonJS({
206
471
  "../contracts/tvm/escrow-encoding/typescript/dist/index.js"(exports2) {
207
472
  "use strict";
208
473
  Object.defineProperty(exports2, "__esModule", { value: true });
209
- exports2.hashTvmPermitWitnessTransferFrom = exports2.createTvmPermitWitnessTransferFromPrehash = exports2.computePaymentId = exports2.computeReserveDigest = exports2.normalizeAddress = exports2.base58ToHex = exports2.maskChainId = void 0;
474
+ exports2.MAX_DESTINATION_BYTES = exports2.createTvmPermitWitnessTransferFromPrehashWithDestination = exports2.PERMIT_WITNESS_TYPES_WITH_DESTINATION = exports2.computeTvmRefundDigestWithQuoteHash = exports2.buildTvmRefundTypedDataWithQuoteHash = exports2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH = exports2.computeTvmReleaseDigestWithQuoteHash = exports2.buildTvmReleaseTypedDataWithQuoteHash = exports2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH = exports2.computeTvmReserveDigestWithQuoteSource = exports2.buildTvmReserveTypedDataWithQuoteSource = exports2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE = exports2.hashTvmPermitWitnessTransferFrom = exports2.createTvmPermitWitnessTransferFromPrehash = exports2.computePaymentId = exports2.computeReserveDigest = exports2.normalizeAddress = exports2.base58ToHex = exports2.maskChainId = void 0;
210
475
  var chain_id_1 = require_chain_id();
211
476
  Object.defineProperty(exports2, "maskChainId", { enumerable: true, get: function() {
212
477
  return chain_id_1.maskChainId;
@@ -233,6 +498,222 @@ var require_dist = __commonJS({
233
498
  Object.defineProperty(exports2, "hashTvmPermitWitnessTransferFrom", { enumerable: true, get: function() {
234
499
  return deposit_encoder_1.hashTvmPermitWitnessTransferFrom;
235
500
  } });
501
+ var reserve_encoder_2 = require_reserve_encoder();
502
+ Object.defineProperty(exports2, "RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE", { enumerable: true, get: function() {
503
+ return reserve_encoder_2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE;
504
+ } });
505
+ Object.defineProperty(exports2, "buildTvmReserveTypedDataWithQuoteSource", { enumerable: true, get: function() {
506
+ return reserve_encoder_2.buildTvmReserveTypedDataWithQuoteSource;
507
+ } });
508
+ Object.defineProperty(exports2, "computeTvmReserveDigestWithQuoteSource", { enumerable: true, get: function() {
509
+ return reserve_encoder_2.computeTvmReserveDigestWithQuoteSource;
510
+ } });
511
+ var release_encoder_1 = require_release_encoder();
512
+ Object.defineProperty(exports2, "RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH", { enumerable: true, get: function() {
513
+ return release_encoder_1.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH;
514
+ } });
515
+ Object.defineProperty(exports2, "buildTvmReleaseTypedDataWithQuoteHash", { enumerable: true, get: function() {
516
+ return release_encoder_1.buildTvmReleaseTypedDataWithQuoteHash;
517
+ } });
518
+ Object.defineProperty(exports2, "computeTvmReleaseDigestWithQuoteHash", { enumerable: true, get: function() {
519
+ return release_encoder_1.computeTvmReleaseDigestWithQuoteHash;
520
+ } });
521
+ var refund_encoder_1 = require_refund_encoder();
522
+ Object.defineProperty(exports2, "REFUND_WITNESS_TYPES_WITH_QUOTE_HASH", { enumerable: true, get: function() {
523
+ return refund_encoder_1.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH;
524
+ } });
525
+ Object.defineProperty(exports2, "buildTvmRefundTypedDataWithQuoteHash", { enumerable: true, get: function() {
526
+ return refund_encoder_1.buildTvmRefundTypedDataWithQuoteHash;
527
+ } });
528
+ Object.defineProperty(exports2, "computeTvmRefundDigestWithQuoteHash", { enumerable: true, get: function() {
529
+ return refund_encoder_1.computeTvmRefundDigestWithQuoteHash;
530
+ } });
531
+ var deposit_encoder_2 = require_deposit_encoder();
532
+ Object.defineProperty(exports2, "PERMIT_WITNESS_TYPES_WITH_DESTINATION", { enumerable: true, get: function() {
533
+ return deposit_encoder_2.PERMIT_WITNESS_TYPES_WITH_DESTINATION;
534
+ } });
535
+ Object.defineProperty(exports2, "createTvmPermitWitnessTransferFromPrehashWithDestination", { enumerable: true, get: function() {
536
+ return deposit_encoder_2.createTvmPermitWitnessTransferFromPrehashWithDestination;
537
+ } });
538
+ Object.defineProperty(exports2, "MAX_DESTINATION_BYTES", { enumerable: true, get: function() {
539
+ return deposit_encoder_2.MAX_DESTINATION_BYTES;
540
+ } });
541
+ }
542
+ });
543
+
544
+ // ../schemas/declarations/common/chain-address/typescript/dist/index.js
545
+ var require_dist2 = __commonJS({
546
+ "../schemas/declarations/common/chain-address/typescript/dist/index.js"(exports2) {
547
+ "use strict";
548
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
549
+ return mod && mod.__esModule ? mod : { "default": mod };
550
+ };
551
+ Object.defineProperty(exports2, "__esModule", { value: true });
552
+ exports2.InvalidAccountError = exports2.REASONS = exports2.NAMESPACE_SOLANA = exports2.NAMESPACE_TRON = exports2.NAMESPACE_EIP155 = void 0;
553
+ exports2.supportedNamespaces = supportedNamespaces;
554
+ exports2.parse = parse;
555
+ exports2.validate = validate;
556
+ exports2.checkAccount = checkAccount;
557
+ var bs58_1 = __importDefault(require("bs58"));
558
+ var ethers_1 = require("ethers");
559
+ var tvm_escrow_encoding_1 = require_dist();
560
+ exports2.NAMESPACE_EIP155 = "eip155";
561
+ exports2.NAMESPACE_TRON = "tron";
562
+ exports2.NAMESPACE_SOLANA = "solana";
563
+ exports2.REASONS = [
564
+ "EMPTY",
565
+ "SURROUNDING_WHITESPACE",
566
+ "UNSUPPORTED_NAMESPACE",
567
+ "UNPARSEABLE",
568
+ "ZERO"
569
+ ];
570
+ var InvalidAccountError2 = class extends Error {
571
+ reason;
572
+ network;
573
+ account;
574
+ detail;
575
+ constructor(reason, network, account, detail = "") {
576
+ super(messageFor(reason, network, detail));
577
+ this.name = "InvalidAccountError";
578
+ this.reason = reason;
579
+ this.network = network;
580
+ this.account = account;
581
+ this.detail = detail;
582
+ }
583
+ };
584
+ exports2.InvalidAccountError = InvalidAccountError2;
585
+ function messageFor(reason, network, detail) {
586
+ switch (reason) {
587
+ case "EMPTY":
588
+ return "account is required and cannot be empty";
589
+ case "SURROUNDING_WHITESPACE":
590
+ return "account must not contain leading or trailing whitespace";
591
+ case "UNSUPPORTED_NAMESPACE":
592
+ return `no address rules are known for chain ${network}`;
593
+ case "ZERO":
594
+ return `account is the zero address on ${network}, which cannot receive a payout`;
595
+ default:
596
+ return `account is not a valid address for ${network}`;
597
+ }
598
+ }
599
+ function supportedNamespaces() {
600
+ return [exports2.NAMESPACE_EIP155, exports2.NAMESPACE_SOLANA, exports2.NAMESPACE_TRON];
601
+ }
602
+ function trimSurrounding(value) {
603
+ return value.replace(/^[\s\u0085]+|[\s\u0085]+$/gu, "");
604
+ }
605
+ function parse(network, account) {
606
+ if (trimSurrounding(account) === "") {
607
+ throw new InvalidAccountError2("EMPTY", network, account);
608
+ }
609
+ if (account !== trimSurrounding(account)) {
610
+ throw new InvalidAccountError2("SURROUNDING_WHITESPACE", network, account);
611
+ }
612
+ const separator = network.indexOf(":");
613
+ if (separator <= 0) {
614
+ throw new InvalidAccountError2("UNSUPPORTED_NAMESPACE", network, account);
615
+ }
616
+ const namespace = network.slice(0, separator);
617
+ let bytes;
618
+ try {
619
+ switch (namespace) {
620
+ case exports2.NAMESPACE_EIP155:
621
+ bytes = parseEvm(account);
622
+ break;
623
+ case exports2.NAMESPACE_TRON:
624
+ bytes = parseTron(account);
625
+ break;
626
+ case exports2.NAMESPACE_SOLANA:
627
+ bytes = parseSolana(account);
628
+ break;
629
+ default:
630
+ throw new InvalidAccountError2("UNSUPPORTED_NAMESPACE", network, account);
631
+ }
632
+ } catch (error) {
633
+ if (error instanceof InvalidAccountError2)
634
+ throw error;
635
+ throw new InvalidAccountError2("UNPARSEABLE", network, account, error.message);
636
+ }
637
+ return { namespace, bytes };
638
+ }
639
+ function validate(network, account) {
640
+ const parsed = parse(network, account);
641
+ if (isZero(parsed.bytes)) {
642
+ throw new InvalidAccountError2("ZERO", network, account);
643
+ }
644
+ return parsed;
645
+ }
646
+ function checkAccount(network, account) {
647
+ try {
648
+ validate(network, account);
649
+ return null;
650
+ } catch (error) {
651
+ if (error instanceof InvalidAccountError2)
652
+ return error;
653
+ throw error;
654
+ }
655
+ }
656
+ function isZero(bytes) {
657
+ return bytes.length > 0 && bytes.every((one) => one === 0);
658
+ }
659
+ var HEX_40 = /^(0[xX])?[0-9a-fA-F]{40}$/;
660
+ function parseEvm(account) {
661
+ if (!HEX_40.test(account)) {
662
+ throw new Error("expected 40 hex characters, optionally 0x-prefixed");
663
+ }
664
+ const body = account.replace(/^0[xX]/, "");
665
+ const lower = body.toLowerCase();
666
+ if (body !== lower && body !== body.toUpperCase()) {
667
+ if ((0, ethers_1.getAddress)(`0x${lower}`) !== account) {
668
+ throw new Error("mixed-case address fails its EIP-55 checksum");
669
+ }
670
+ }
671
+ return hexToBytes2(lower);
672
+ }
673
+ function parseTron(account) {
674
+ let hexBody;
675
+ if (account.startsWith("T") && account.length === 34) {
676
+ try {
677
+ hexBody = (0, tvm_escrow_encoding_1.base58ToHex)(account);
678
+ } catch (error) {
679
+ throw new Error(`base58 address failed its checksum: ${error.message}`);
680
+ }
681
+ } else if (account.toLowerCase().startsWith("0x41") && account.length === 44) {
682
+ hexBody = account.slice(2);
683
+ } else if (HEX_40.test(account)) {
684
+ return parseEvm(account);
685
+ } else {
686
+ throw new Error("expected a T-prefixed base58 address or 40 hex characters");
687
+ }
688
+ hexBody = hexBody.startsWith("41") ? hexBody.slice(2) : hexBody;
689
+ if (hexBody.length !== 40) {
690
+ throw new Error(`expected 40 hex characters after conversion, got ${hexBody.length}`);
691
+ }
692
+ return hexToBytes2(hexBody);
693
+ }
694
+ function parseSolana(account) {
695
+ let decoded;
696
+ try {
697
+ decoded = bs58_1.default.decode(account);
698
+ } catch {
699
+ throw new Error("expected a 32-byte base58 public key");
700
+ }
701
+ if (decoded.length !== 32) {
702
+ throw new Error(`expected a 32-byte base58 public key, got ${decoded.length} bytes`);
703
+ }
704
+ return decoded;
705
+ }
706
+ var HEX_BODY = /^[0-9a-fA-F]*$/;
707
+ function hexToBytes2(hex) {
708
+ if (hex.length % 2 !== 0 || !HEX_BODY.test(hex)) {
709
+ throw new Error("expected hex characters");
710
+ }
711
+ const out = new Uint8Array(hex.length / 2);
712
+ for (let i = 0; i < out.length; i += 1) {
713
+ out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
714
+ }
715
+ return out;
716
+ }
236
717
  }
237
718
  });
238
719
 
@@ -244,12 +725,96 @@ var require_types = __commonJS({
244
725
  }
245
726
  });
246
727
 
728
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/destination.js
729
+ var require_destination = __commonJS({
730
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/destination.js"(exports2) {
731
+ "use strict";
732
+ Object.defineProperty(exports2, "__esModule", { value: true });
733
+ exports2.DESTINATION_COMMITMENT_WITNESS_VERSION = exports2.MAX_DESTINATION_BYTES = void 0;
734
+ exports2.usesDestinationCommitment = usesDestinationCommitment;
735
+ exports2.deriveDepositRequestHash = deriveDepositRequestHash;
736
+ exports2.buildEscrowDestination = buildEscrowDestination;
737
+ var ethers_1 = require("ethers");
738
+ exports2.MAX_DESTINATION_BYTES = 256;
739
+ var NAMESPACE_EIP155 = "eip155";
740
+ exports2.DESTINATION_COMMITMENT_WITNESS_VERSION = 4;
741
+ function usesDestinationCommitment(depositWitnessVersion) {
742
+ return depositWitnessVersion === void 0 || depositWitnessVersion >= exports2.DESTINATION_COMMITMENT_WITNESS_VERSION;
743
+ }
744
+ function deriveDepositRequestHash(requestId) {
745
+ if (requestId === "") {
746
+ throw new Error('sender_auth: cannot derive deposit_request_hash: request_id is empty, and keccak256("") is a perfectly valid non-zero bytes32, so this would silently commit every empty-id deposit to the same hash instead of failing');
747
+ }
748
+ return (0, ethers_1.keccak256)((0, ethers_1.toUtf8Bytes)(requestId));
749
+ }
750
+ function buildEscrowDestination(assetIdentifier, account) {
751
+ if (assetIdentifier === "") {
752
+ throw new Error("sender_auth: destination asset_identifier is empty");
753
+ }
754
+ if (account === "") {
755
+ throw new Error("sender_auth: destination account is empty");
756
+ }
757
+ if (assetIdentifier.includes("@") || account.includes("@")) {
758
+ throw new Error(`sender_auth: destination asset_identifier (${JSON.stringify(assetIdentifier)}) and account (${JSON.stringify(account)}) must not contain '@': it is the separator between them in the committed destination grammar`);
759
+ }
760
+ const namespace = caip2Namespace(assetIdentifier);
761
+ let asset = assetIdentifier;
762
+ let acct = account;
763
+ if (namespace === NAMESPACE_EIP155) {
764
+ asset = asset.toLowerCase();
765
+ acct = acct.toLowerCase();
766
+ }
767
+ const destination = `${asset}@${acct}`;
768
+ const byteLength = (0, ethers_1.toUtf8Bytes)(destination).length;
769
+ if (byteLength > exports2.MAX_DESTINATION_BYTES) {
770
+ throw new Error(`sender_auth: composed destination is ${byteLength} bytes, over the escrow's MAX_DESTINATION_BYTES of ${exports2.MAX_DESTINATION_BYTES}: the contract reverts DestinationTooLong, so this deposit could never be redeemed`);
771
+ }
772
+ return destination;
773
+ }
774
+ function caip2Namespace(assetIdentifier) {
775
+ const slash = assetIdentifier.indexOf("/");
776
+ const chainPart = slash === -1 ? "" : assetIdentifier.slice(0, slash);
777
+ const assetPart = slash === -1 ? "" : assetIdentifier.slice(slash + 1);
778
+ if (slash === -1 || chainPart === "" || assetPart === "") {
779
+ const looksLegacy = !assetIdentifier.includes("/") && countChar(assetIdentifier, ":") === 2;
780
+ const hint = looksLegacy ? " (this looks like the deprecated `<chain>:<ref>:<asset>` form; migrate it to `<chain>:<ref>/<asset-namespace>:<asset-reference>`)" : "";
781
+ throw new Error(`sender_auth: destination asset_identifier ${JSON.stringify(assetIdentifier)} is not CAIP-19: expected <caip2-chain-id>/<asset-namespace>:<asset-reference>${hint}`);
782
+ }
783
+ const assetColon = assetPart.indexOf(":");
784
+ if (assetColon <= 0 || assetColon === assetPart.length - 1) {
785
+ throw new Error(`sender_auth: destination asset_identifier ${JSON.stringify(assetIdentifier)} has a malformed asset part ${JSON.stringify(assetPart)}: expected <asset-namespace>:<asset-reference>`);
786
+ }
787
+ const assetNamespace = assetPart.slice(0, assetColon);
788
+ if (assetNamespace !== assetNamespace.toLowerCase()) {
789
+ throw new Error(`sender_auth: destination asset_identifier ${JSON.stringify(assetIdentifier)} has a non-canonical asset namespace ${JSON.stringify(assetNamespace)}: the ratified grammar requires it lowercase (${JSON.stringify(assetNamespace.toLowerCase())}). It is rejected rather than normalised because the destination commitment is over these exact bytes`);
790
+ }
791
+ const chainColon = chainPart.indexOf(":");
792
+ if (chainColon <= 0 || chainColon === chainPart.length - 1) {
793
+ throw new Error(`sender_auth: destination asset_identifier ${JSON.stringify(assetIdentifier)} has a malformed chain part ${JSON.stringify(chainPart)}: expected <namespace>:<reference>`);
794
+ }
795
+ const namespace = chainPart.slice(0, chainColon);
796
+ if (namespace !== namespace.toLowerCase()) {
797
+ throw new Error(`sender_auth: destination asset_identifier ${JSON.stringify(assetIdentifier)} has a non-canonical chain namespace ${JSON.stringify(namespace)}: the ratified grammar requires it lowercase (${JSON.stringify(namespace.toLowerCase())}). It is rejected rather than normalised because the destination commitment is over these exact bytes`);
798
+ }
799
+ return namespace;
800
+ }
801
+ function countChar(s, c) {
802
+ let n = 0;
803
+ for (const ch of s) {
804
+ if (ch === c)
805
+ n++;
806
+ }
807
+ return n;
808
+ }
809
+ }
810
+ });
811
+
247
812
  // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/utils.js
248
813
  var require_utils = __commonJS({
249
814
  "../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/utils.js"(exports2) {
250
815
  "use strict";
251
816
  Object.defineProperty(exports2, "__esModule", { value: true });
252
- exports2.REQUEST_ID_DOMAIN = exports2.SOLANA_REPLAY_SLOTS = exports2.PERMIT_NONCE_DOMAIN = exports2.REPLAY_HORIZON_SECS = void 0;
817
+ exports2.REQUEST_ID_DOMAIN = exports2.SOLANA_REPLAY_BUCKETS = exports2.SOLANA_REPLAY_SLOTS = exports2.PERMIT_NONCE_DOMAIN = exports2.REPLAY_HORIZON_SECS = void 0;
253
818
  exports2.resolvePermitDeadline = resolvePermitDeadline;
254
819
  exports2.generatePermitNonce = generatePermitNonce;
255
820
  exports2.resolvePermitNonce = resolvePermitNonce;
@@ -257,6 +822,7 @@ var require_utils = __commonJS({
257
822
  exports2.deterministicPermitNonce = deterministicPermitNonce2;
258
823
  exports2.deterministicSolanaNonce = deterministicSolanaNonce2;
259
824
  exports2.deterministicRequestId = deterministicRequestId;
825
+ exports2.parseSourceAsset = parseSourceAsset;
260
826
  exports2.sameAddress = sameAddress;
261
827
  exports2.assertKeyMatchesSender = assertKeyMatchesSender2;
262
828
  exports2.assertToken = assertToken;
@@ -265,8 +831,11 @@ var require_utils = __commonJS({
265
831
  exports2.assertSpender = assertSpender;
266
832
  exports2.assertWitnessRoles = assertWitnessRoles;
267
833
  exports2.assertRolePairComplete = assertRolePairComplete;
834
+ exports2.assertDestination = assertDestination;
835
+ exports2.assertDepositRequestHash = assertDepositRequestHash;
268
836
  exports2.nowSec = nowSec;
269
837
  var ethers_1 = require("ethers");
838
+ var destination_js_1 = require_destination();
270
839
  exports2.REPLAY_HORIZON_SECS = 128;
271
840
  function resolvePermitDeadline(deadline) {
272
841
  return BigInt(deadline);
@@ -281,7 +850,7 @@ var require_utils = __commonJS({
281
850
  }
282
851
  exports2.PERMIT_NONCE_DOMAIN = "atum-permit:v1:";
283
852
  exports2.SOLANA_REPLAY_SLOTS = 235n;
284
- var SOLANA_BUCKET_BITS = 17n;
853
+ exports2.SOLANA_REPLAY_BUCKETS = 256n;
285
854
  function canonicalDepositor(depositor) {
286
855
  const lower = depositor.toLowerCase();
287
856
  return lower.startsWith("0x") ? lower : depositor;
@@ -298,7 +867,7 @@ var require_utils = __commonJS({
298
867
  function deterministicSolanaNonce2(params) {
299
868
  const seed = permitNonceSeed(params.requestId, params.depositor);
300
869
  const slot = seed % exports2.SOLANA_REPLAY_SLOTS;
301
- const bucket = (seed >> 8n) % (1n << SOLANA_BUCKET_BITS);
870
+ const bucket = (seed >> 8n) % exports2.SOLANA_REPLAY_BUCKETS;
302
871
  return bucket << 32n | slot;
303
872
  }
304
873
  exports2.REQUEST_ID_DOMAIN = "atum-request:v1:";
@@ -315,6 +884,17 @@ var require_utils = __commonJS({
315
884
  const digest = (0, ethers_1.keccak256)((0, ethers_1.toUtf8Bytes)(`${exports2.REQUEST_ID_DOMAIN}${params.anchor}:${canonicalDepositor(params.account)}`));
316
885
  return `${params.prefix}${digest.slice(2, 26)}`;
317
886
  }
887
+ function parseSourceAsset(assetIdentifier) {
888
+ const parts = typeof assetIdentifier === "string" ? assetIdentifier.split("/") : [];
889
+ const nsParts = parts[1]?.split(":");
890
+ if (parts.length === 3 && parts[0] && parts[1] && parts[2]) {
891
+ throw new Error(`sender_auth: source asset ${JSON.stringify(assetIdentifier)} names a token id, which a deposit cannot bind`);
892
+ }
893
+ if (parts.length !== 2 || !parts[0] || !nsParts || nsParts.length !== 2 || !nsParts[0] || !nsParts[1]) {
894
+ throw new Error(`sender_auth: invalid source asset ${JSON.stringify(assetIdentifier)}`);
895
+ }
896
+ return { network: parts[0], asset: nsParts[1] };
897
+ }
318
898
  function sameAddress(a, b) {
319
899
  if (a.startsWith("0x") && b.startsWith("0x")) {
320
900
  return a.toLowerCase() === b.toLowerCase();
@@ -356,6 +936,17 @@ var require_utils = __commonJS({
356
936
  throw new Error("sender_auth: reserver and releaser must be supplied together");
357
937
  }
358
938
  }
939
+ function assertDestination(signed, expected) {
940
+ if (signed !== expected) {
941
+ throw new Error(`sender_auth: signed deposit destination ${JSON.stringify(signed)} does not match the expected destination ${JSON.stringify(expected)} \u2014 the escrow stores only keccak256(bytes(destination)) and cannot tell a formatting disagreement from a wrong payee, so a deposit signed against this destination could be neither released nor refunded`);
942
+ }
943
+ }
944
+ function assertDepositRequestHash(signedHex, expectedRequestId) {
945
+ const expected = (0, destination_js_1.deriveDepositRequestHash)(expectedRequestId);
946
+ if (signedHex.toLowerCase() !== expected.toLowerCase()) {
947
+ throw new Error(`sender_auth: signed deposit_request_hash ${signedHex} is not keccak256(request_id) for request_id ${JSON.stringify(expectedRequestId)} (expected ${expected}): the deposit authorizes a different payment request`);
948
+ }
949
+ }
359
950
  function nowSec() {
360
951
  return Math.floor(Date.now() / 1e3);
361
952
  }
@@ -367,7 +958,7 @@ var require_chain_id2 = __commonJS({
367
958
  "../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/chain-id.js"(exports2) {
368
959
  "use strict";
369
960
  Object.defineProperty(exports2, "__esModule", { value: true });
370
- exports2.TRON_PERMIT2_FALLBACKS = exports2.TRON_CHAIN_IDS = void 0;
961
+ exports2.TRON_PERMIT2_FALLBACKS = exports2.TRON_CHAIN_IDS = exports2.MAX_EVM_CHAIN_ID = void 0;
371
962
  exports2.namespaceOf = namespaceOf;
372
963
  exports2.evmChainId = evmChainId;
373
964
  exports2.tronNumericChainId = tronNumericChainId;
@@ -376,21 +967,30 @@ var require_chain_id2 = __commonJS({
376
967
  function namespaceOf(network) {
377
968
  return network.split(":")[0];
378
969
  }
970
+ exports2.MAX_EVM_CHAIN_ID = Number.MAX_SAFE_INTEGER;
379
971
  function evmChainId(network) {
380
972
  const match = /^eip155:([0-9]+)$/.exec(network);
381
973
  if (!match) {
382
974
  throw new Error(`sender_auth: expected an eip155 network, got ${network}`);
383
975
  }
384
- return Number(match[1]);
976
+ const chainId = Number(match[1]);
977
+ if (chainId > exports2.MAX_EVM_CHAIN_ID) {
978
+ throw new Error(`sender_auth: eip155 chain id ${match[1]} exceeds the EIP-2294 maximum (${exports2.MAX_EVM_CHAIN_ID})`);
979
+ }
980
+ return chainId;
385
981
  }
386
982
  exports2.TRON_CHAIN_IDS = {
387
983
  mainnet: 728126428,
388
984
  shasta: 2494104990
389
985
  };
390
986
  function tronNumericChainId(network) {
391
- const cluster = network.split(":")[1];
392
- const id = exports2.TRON_CHAIN_IDS[cluster ?? ""];
393
- if (id === void 0) {
987
+ if (namespaceOf(network) !== "tron") {
988
+ throw new Error(`sender_auth: expected a tron network, got ${network}`);
989
+ }
990
+ const segments = network.split(":");
991
+ const cluster = segments.length === 2 ? segments[1] : void 0;
992
+ const id = cluster !== void 0 && Object.hasOwn(exports2.TRON_CHAIN_IDS, cluster) ? exports2.TRON_CHAIN_IDS[cluster] : void 0;
993
+ if (typeof id !== "number") {
394
994
  throw new Error(`sender_auth: unsupported Tron network '${network}'`);
395
995
  }
396
996
  return id;
@@ -400,8 +1000,8 @@ var require_chain_id2 = __commonJS({
400
1000
  "tron:shasta": "TPUqJPASUn1zLvbLBgRZ5pBYrx7WSe5ahp"
401
1001
  };
402
1002
  function resolveTronPermit2(network) {
403
- const resolved = exports2.TRON_PERMIT2_FALLBACKS[network];
404
- if (!resolved) {
1003
+ const resolved = Object.hasOwn(exports2.TRON_PERMIT2_FALLBACKS, network) ? exports2.TRON_PERMIT2_FALLBACKS[network] : void 0;
1004
+ if (typeof resolved !== "string" || resolved === "") {
405
1005
  throw new Error(`sender_auth: no Permit2 address known for Tron network '${network}'`);
406
1006
  }
407
1007
  return resolved;
@@ -457,7 +1057,7 @@ var require_permit_types = __commonJS({
457
1057
  "../contracts/evm/escrow-encoding/typescript/dist/permit-types.js"(exports2) {
458
1058
  "use strict";
459
1059
  Object.defineProperty(exports2, "__esModule", { value: true });
460
- exports2.REFUND_WITNESS_TYPES = exports2.RELEASE_WITNESS_TYPES = exports2.RESERVE_WITNESS_TYPES = exports2.PERMIT_WITNESS_TYPES_V2 = exports2.PERMIT_WITNESS_TYPES = void 0;
1060
+ exports2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH = exports2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH = exports2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE = exports2.PERMIT_WITNESS_TYPES_WITH_DESTINATION = exports2.REFUND_WITNESS_TYPES = exports2.RELEASE_WITNESS_TYPES = exports2.RESERVE_WITNESS_TYPES = exports2.PERMIT_WITNESS_TYPES_V2 = exports2.PERMIT_WITNESS_TYPES = void 0;
461
1061
  exports2.createPermit2Domain = createPermit2Domain;
462
1062
  exports2.createEscrowDomain = createEscrowDomain;
463
1063
  exports2.PERMIT_WITNESS_TYPES = {
@@ -540,30 +1140,87 @@ var require_permit_types = __commonJS({
540
1140
  { name: "settler", type: "address" }
541
1141
  ]
542
1142
  };
543
- }
544
- });
545
-
546
- // ../contracts/evm/escrow-encoding/typescript/dist/escrow-abi.js
547
- var require_escrow_abi = __commonJS({
548
- "../contracts/evm/escrow-encoding/typescript/dist/escrow-abi.js"(exports2) {
549
- "use strict";
550
- Object.defineProperty(exports2, "__esModule", { value: true });
551
- exports2.ESCROW_V2_ABI_JSON = exports2.ESCROW_V3_ABI_JSON = exports2.ESCROW_ABI_JSON = exports2.ESCROW_ABI = void 0;
552
- exports2.ESCROW_ABI = [
553
- "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)",
554
- "function refund((bytes32 depositId, uint256 deadline) witness, bytes signature)",
555
- "function getDepositInfo(bytes32 depositId) view returns ((address depositor, address token, uint256 amount, address reserver, address releaser, address settler))",
556
- "function i_permit2() view returns (address)"
557
- ];
558
- exports2.ESCROW_ABI_JSON = [
559
- {
560
- type: "function",
561
- name: "deposit",
562
- inputs: [
563
- {
564
- name: "permit",
565
- type: "tuple",
566
- components: [
1143
+ exports2.PERMIT_WITNESS_TYPES_WITH_DESTINATION = {
1144
+ PermitWitnessTransferFrom: [
1145
+ { name: "permitted", type: "TokenPermissions" },
1146
+ { name: "spender", type: "address" },
1147
+ { name: "nonce", type: "uint256" },
1148
+ { name: "deadline", type: "uint256" },
1149
+ { name: "witness", type: "DepositWitness" }
1150
+ ],
1151
+ TokenPermissions: [
1152
+ { name: "token", type: "address" },
1153
+ { name: "amount", type: "uint256" }
1154
+ ],
1155
+ DepositWitness: [
1156
+ { name: "depositRequestHash", type: "bytes32" },
1157
+ { name: "destination", type: "string" },
1158
+ { name: "reserver", type: "address" },
1159
+ { name: "releaser", type: "address" }
1160
+ ]
1161
+ };
1162
+ exports2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE = {
1163
+ ReserveWitness: [
1164
+ { name: "depositId", type: "bytes32" },
1165
+ { name: "quoteHash", type: "bytes32" },
1166
+ { name: "settler", type: "address" },
1167
+ { name: "sourceAmount", type: "uint256" }
1168
+ ]
1169
+ };
1170
+ exports2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH = {
1171
+ ReleaseWitness: [
1172
+ { name: "depositId", type: "bytes32" },
1173
+ { name: "quoteHash", type: "bytes32" },
1174
+ { name: "depositRequestHash", type: "bytes32" },
1175
+ { name: "destinationHash", type: "bytes32" },
1176
+ { name: "depositor", type: "address" },
1177
+ { name: "token", type: "address" },
1178
+ { name: "amount", type: "uint256" },
1179
+ { name: "feeAmount", type: "uint256" },
1180
+ { name: "reserver", type: "address" },
1181
+ { name: "releaser", type: "address" },
1182
+ { name: "settler", type: "address" }
1183
+ ]
1184
+ };
1185
+ exports2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH = {
1186
+ RefundWitness: [
1187
+ { name: "depositId", type: "bytes32" },
1188
+ { name: "quoteHash", type: "bytes32" },
1189
+ { name: "depositRequestHash", type: "bytes32" },
1190
+ { name: "destinationHash", type: "bytes32" },
1191
+ { name: "depositor", type: "address" },
1192
+ { name: "token", type: "address" },
1193
+ { name: "amount", type: "uint256" },
1194
+ { name: "feeAmount", type: "uint256" },
1195
+ { name: "reserver", type: "address" },
1196
+ { name: "releaser", type: "address" },
1197
+ { name: "settler", type: "address" }
1198
+ ]
1199
+ };
1200
+ }
1201
+ });
1202
+
1203
+ // ../contracts/evm/escrow-encoding/typescript/dist/escrow-abi.js
1204
+ var require_escrow_abi = __commonJS({
1205
+ "../contracts/evm/escrow-encoding/typescript/dist/escrow-abi.js"(exports2) {
1206
+ "use strict";
1207
+ Object.defineProperty(exports2, "__esModule", { value: true });
1208
+ exports2.ESCROW_V2_ABI_JSON = exports2.ESCROW_V3_ABI_JSON = exports2.ESCROW_ABI_JSON = exports2.ESCROW_ABI = void 0;
1209
+ exports2.ESCROW_ABI = [
1210
+ "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)",
1211
+ "function refund((bytes32 depositId, uint256 deadline) witness, bytes signature)",
1212
+ "function getDepositInfo(bytes32 depositId) view returns ((address depositor, address token, uint256 amount, address reserver, address releaser, address settler))",
1213
+ "function i_permit2() view returns (address)"
1214
+ ];
1215
+ exports2.ESCROW_ABI_JSON = [
1216
+ {
1217
+ type: "function",
1218
+ name: "deposit",
1219
+ inputs: [
1220
+ {
1221
+ name: "permit",
1222
+ type: "tuple",
1223
+ components: [
567
1224
  {
568
1225
  name: "permitted",
569
1226
  type: "tuple",
@@ -666,6 +1323,8 @@ var require_escrow_abi = __commonJS({
666
1323
  name: "depositWitness",
667
1324
  type: "tuple",
668
1325
  components: [
1326
+ { name: "depositRequestHash", type: "bytes32" },
1327
+ { name: "destination", type: "string" },
669
1328
  { name: "reserver", type: "address" },
670
1329
  { name: "releaser", type: "address" }
671
1330
  ]
@@ -675,15 +1334,17 @@ var require_escrow_abi = __commonJS({
675
1334
  name: "reserveWitness",
676
1335
  type: "tuple",
677
1336
  components: [
678
- { name: "paymentId", type: "bytes32" },
679
- { name: "settler", type: "address" }
1337
+ { name: "depositId", type: "bytes32" },
1338
+ { name: "quoteHash", type: "bytes32" },
1339
+ { name: "settler", type: "address" },
1340
+ { name: "sourceAmount", type: "uint256" }
680
1341
  ]
681
1342
  },
682
1343
  { name: "reserveSignature", type: "bytes" }
683
1344
  ]
684
1345
  }
685
1346
  ],
686
- outputs: [{ name: "paymentId", type: "bytes32" }],
1347
+ outputs: [{ name: "depositId", type: "bytes32" }],
687
1348
  stateMutability: "nonpayable"
688
1349
  },
689
1350
  {
@@ -698,7 +1359,10 @@ var require_escrow_abi = __commonJS({
698
1359
  name: "refundWitness",
699
1360
  type: "tuple",
700
1361
  components: [
701
- { name: "paymentId", type: "bytes32" },
1362
+ { name: "depositId", type: "bytes32" },
1363
+ { name: "quoteHash", type: "bytes32" },
1364
+ { name: "depositRequestHash", type: "bytes32" },
1365
+ { name: "destinationHash", type: "bytes32" },
702
1366
  { name: "depositor", type: "address" },
703
1367
  { name: "token", type: "address" },
704
1368
  { name: "amount", type: "uint256" },
@@ -718,7 +1382,7 @@ var require_escrow_abi = __commonJS({
718
1382
  {
719
1383
  type: "function",
720
1384
  name: "getDepositHash",
721
- inputs: [{ name: "paymentId", type: "bytes32" }],
1385
+ inputs: [{ name: "depositId", type: "bytes32" }],
722
1386
  outputs: [{ name: "", type: "bytes32" }],
723
1387
  stateMutability: "view"
724
1388
  },
@@ -734,14 +1398,67 @@ var require_escrow_abi = __commonJS({
734
1398
  }
735
1399
  });
736
1400
 
1401
+ // ../contracts/evm/escrow-encoding/typescript/dist/witness-values.js
1402
+ var require_witness_values2 = __commonJS({
1403
+ "../contracts/evm/escrow-encoding/typescript/dist/witness-values.js"(exports2) {
1404
+ "use strict";
1405
+ Object.defineProperty(exports2, "__esModule", { value: true });
1406
+ exports2.normalizeBytes32 = normalizeBytes32;
1407
+ exports2.normalizeAddressField = normalizeAddressField;
1408
+ exports2.normalizeUint256 = normalizeUint256;
1409
+ exports2.chainIdToHex = chainIdToHex;
1410
+ var ethers_1 = require("ethers");
1411
+ function normalizeBytes32(label, value) {
1412
+ let bytes;
1413
+ try {
1414
+ bytes = (0, ethers_1.getBytes)(value);
1415
+ } catch {
1416
+ throw new Error(`${label} must be 0x-prefixed hex (32 bytes), got ${JSON.stringify(value)}`);
1417
+ }
1418
+ if (bytes.length !== 32) {
1419
+ throw new Error(`${label} must be exactly 32 bytes, got ${bytes.length}`);
1420
+ }
1421
+ return (0, ethers_1.hexlify)(bytes);
1422
+ }
1423
+ function normalizeAddressField(label, value) {
1424
+ try {
1425
+ return (0, ethers_1.getAddress)(value);
1426
+ } catch {
1427
+ throw new Error(`${label} must be a 20-byte hex address, got ${JSON.stringify(value)}`);
1428
+ }
1429
+ }
1430
+ function normalizeUint256(label, value) {
1431
+ let n;
1432
+ try {
1433
+ n = BigInt(value);
1434
+ } catch {
1435
+ throw new Error(`${label} must be an integer (bigint or decimal string), got ${JSON.stringify(value)}`);
1436
+ }
1437
+ if (n < 0n) {
1438
+ throw new Error(`${label} must be non-negative (uint256), got ${n.toString()}`);
1439
+ }
1440
+ return n.toString();
1441
+ }
1442
+ function chainIdToHex(chainId) {
1443
+ if (!Number.isSafeInteger(chainId) || chainId < 0) {
1444
+ throw new Error(`chainId must be a non-negative safe integer, got ${chainId}`);
1445
+ }
1446
+ return `0x${chainId.toString(16)}`;
1447
+ }
1448
+ }
1449
+ });
1450
+
737
1451
  // ../contracts/evm/escrow-encoding/typescript/dist/reserve-encoder.js
738
1452
  var require_reserve_encoder2 = __commonJS({
739
1453
  "../contracts/evm/escrow-encoding/typescript/dist/reserve-encoder.js"(exports2) {
740
1454
  "use strict";
741
1455
  Object.defineProperty(exports2, "__esModule", { value: true });
742
1456
  exports2.computeReserveDigest = computeReserveDigest;
1457
+ exports2.buildReserveTypedDataWithQuoteSource = buildReserveTypedDataWithQuoteSource;
1458
+ exports2.computeReserveDigestWithQuoteSource = computeReserveDigestWithQuoteSource;
743
1459
  var ethers_1 = require("ethers");
744
1460
  var permit_types_1 = require_permit_types();
1461
+ var witness_values_1 = require_witness_values2();
745
1462
  function computeReserveDigest(input) {
746
1463
  const domain = (0, permit_types_1.createEscrowDomain)(input.chainId, input.escrowContract);
747
1464
  return ethers_1.TypedDataEncoder.hash(domain, permit_types_1.RESERVE_WITNESS_TYPES, {
@@ -749,6 +1466,114 @@ var require_reserve_encoder2 = __commonJS({
749
1466
  settler: input.settler
750
1467
  });
751
1468
  }
1469
+ function buildReserveTypedDataWithQuoteSource(input) {
1470
+ return {
1471
+ types: permit_types_1.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE,
1472
+ primaryType: "ReserveWitness",
1473
+ domain: {
1474
+ name: "Escrow",
1475
+ version: "3",
1476
+ chainId: (0, witness_values_1.chainIdToHex)(input.chainId),
1477
+ verifyingContract: (0, witness_values_1.normalizeAddressField)("escrowContract", input.escrowContract)
1478
+ },
1479
+ message: {
1480
+ depositId: (0, witness_values_1.normalizeBytes32)("depositId", input.depositId),
1481
+ quoteHash: (0, witness_values_1.normalizeBytes32)("quoteHash", input.quoteHash),
1482
+ settler: (0, witness_values_1.normalizeAddressField)("settler", input.settler),
1483
+ sourceAmount: (0, witness_values_1.normalizeUint256)("sourceAmount", input.sourceAmount)
1484
+ }
1485
+ };
1486
+ }
1487
+ function computeReserveDigestWithQuoteSource(input) {
1488
+ const prehash = buildReserveTypedDataWithQuoteSource(input);
1489
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
1490
+ }
1491
+ }
1492
+ });
1493
+
1494
+ // ../contracts/evm/escrow-encoding/typescript/dist/release-encoder.js
1495
+ var require_release_encoder2 = __commonJS({
1496
+ "../contracts/evm/escrow-encoding/typescript/dist/release-encoder.js"(exports2) {
1497
+ "use strict";
1498
+ Object.defineProperty(exports2, "__esModule", { value: true });
1499
+ exports2.buildReleaseTypedDataWithQuoteHash = buildReleaseTypedDataWithQuoteHash;
1500
+ exports2.computeReleaseDigestWithQuoteHash = computeReleaseDigestWithQuoteHash;
1501
+ var ethers_1 = require("ethers");
1502
+ var permit_types_1 = require_permit_types();
1503
+ var witness_values_1 = require_witness_values2();
1504
+ function buildReleaseTypedDataWithQuoteHash(input) {
1505
+ const w = input.witness;
1506
+ return {
1507
+ types: permit_types_1.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH,
1508
+ primaryType: "ReleaseWitness",
1509
+ domain: {
1510
+ name: "Escrow",
1511
+ version: "3",
1512
+ chainId: (0, witness_values_1.chainIdToHex)(input.chainId),
1513
+ verifyingContract: (0, witness_values_1.normalizeAddressField)("escrowContract", input.escrowContract)
1514
+ },
1515
+ message: {
1516
+ depositId: (0, witness_values_1.normalizeBytes32)("depositId", w.depositId),
1517
+ quoteHash: (0, witness_values_1.normalizeBytes32)("quoteHash", w.quoteHash),
1518
+ depositRequestHash: (0, witness_values_1.normalizeBytes32)("depositRequestHash", w.depositRequestHash),
1519
+ destinationHash: (0, witness_values_1.normalizeBytes32)("destinationHash", w.destinationHash),
1520
+ depositor: (0, witness_values_1.normalizeAddressField)("depositor", w.depositor),
1521
+ token: (0, witness_values_1.normalizeAddressField)("token", w.token),
1522
+ amount: (0, witness_values_1.normalizeUint256)("amount", w.amount),
1523
+ feeAmount: (0, witness_values_1.normalizeUint256)("feeAmount", w.feeAmount),
1524
+ reserver: (0, witness_values_1.normalizeAddressField)("reserver", w.reserver),
1525
+ releaser: (0, witness_values_1.normalizeAddressField)("releaser", w.releaser),
1526
+ settler: (0, witness_values_1.normalizeAddressField)("settler", w.settler)
1527
+ }
1528
+ };
1529
+ }
1530
+ function computeReleaseDigestWithQuoteHash(input) {
1531
+ const prehash = buildReleaseTypedDataWithQuoteHash(input);
1532
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
1533
+ }
1534
+ }
1535
+ });
1536
+
1537
+ // ../contracts/evm/escrow-encoding/typescript/dist/refund-encoder.js
1538
+ var require_refund_encoder2 = __commonJS({
1539
+ "../contracts/evm/escrow-encoding/typescript/dist/refund-encoder.js"(exports2) {
1540
+ "use strict";
1541
+ Object.defineProperty(exports2, "__esModule", { value: true });
1542
+ exports2.buildRefundTypedDataWithQuoteHash = buildRefundTypedDataWithQuoteHash;
1543
+ exports2.computeRefundDigestWithQuoteHash = computeRefundDigestWithQuoteHash;
1544
+ var ethers_1 = require("ethers");
1545
+ var permit_types_1 = require_permit_types();
1546
+ var witness_values_1 = require_witness_values2();
1547
+ function buildRefundTypedDataWithQuoteHash(input) {
1548
+ const w = input.witness;
1549
+ return {
1550
+ types: permit_types_1.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH,
1551
+ primaryType: "RefundWitness",
1552
+ domain: {
1553
+ name: "Escrow",
1554
+ version: "3",
1555
+ chainId: (0, witness_values_1.chainIdToHex)(input.chainId),
1556
+ verifyingContract: (0, witness_values_1.normalizeAddressField)("escrowContract", input.escrowContract)
1557
+ },
1558
+ message: {
1559
+ depositId: (0, witness_values_1.normalizeBytes32)("depositId", w.depositId),
1560
+ quoteHash: (0, witness_values_1.normalizeBytes32)("quoteHash", w.quoteHash),
1561
+ depositRequestHash: (0, witness_values_1.normalizeBytes32)("depositRequestHash", w.depositRequestHash),
1562
+ destinationHash: (0, witness_values_1.normalizeBytes32)("destinationHash", w.destinationHash),
1563
+ depositor: (0, witness_values_1.normalizeAddressField)("depositor", w.depositor),
1564
+ token: (0, witness_values_1.normalizeAddressField)("token", w.token),
1565
+ amount: (0, witness_values_1.normalizeUint256)("amount", w.amount),
1566
+ feeAmount: (0, witness_values_1.normalizeUint256)("feeAmount", w.feeAmount),
1567
+ reserver: (0, witness_values_1.normalizeAddressField)("reserver", w.reserver),
1568
+ releaser: (0, witness_values_1.normalizeAddressField)("releaser", w.releaser),
1569
+ settler: (0, witness_values_1.normalizeAddressField)("settler", w.settler)
1570
+ }
1571
+ };
1572
+ }
1573
+ function computeRefundDigestWithQuoteHash(input) {
1574
+ const prehash = buildRefundTypedDataWithQuoteHash(input);
1575
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
1576
+ }
752
1577
  }
753
1578
  });
754
1579
 
@@ -757,11 +1582,13 @@ var require_deposit_encoder2 = __commonJS({
757
1582
  "../contracts/evm/escrow-encoding/typescript/dist/deposit-encoder.js"(exports2) {
758
1583
  "use strict";
759
1584
  Object.defineProperty(exports2, "__esModule", { value: true });
760
- exports2.PERMIT2_CONTRACT_ADDRESS = void 0;
1585
+ exports2.MAX_DESTINATION_BYTES = exports2.PERMIT2_CONTRACT_ADDRESS = void 0;
761
1586
  exports2.createPermitWitnessTransferFromPrehash = createPermitWitnessTransferFromPrehash2;
762
1587
  exports2.hashPermitWitnessTransferFrom = hashPermitWitnessTransferFrom2;
1588
+ exports2.createPermitWitnessTransferFromPrehashWithDestination = createPermitWitnessTransferFromPrehashWithDestination;
763
1589
  var ethers_1 = require("ethers");
764
1590
  var permit_types_1 = require_permit_types();
1591
+ var witness_values_1 = require_witness_values2();
765
1592
  exports2.PERMIT2_CONTRACT_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
766
1593
  function createPermitWitnessTransferFromPrehash2(params) {
767
1594
  return {
@@ -790,15 +1617,52 @@ var require_deposit_encoder2 = __commonJS({
790
1617
  function hashPermitWitnessTransferFrom2(prehash) {
791
1618
  return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
792
1619
  }
1620
+ exports2.MAX_DESTINATION_BYTES = 256;
1621
+ function assertDestinationWithinBounds(destination) {
1622
+ if (destination === "") {
1623
+ throw new Error('destination is empty: the escrow reverts DestinationCannotBeEmpty, and because keccak256("") is a valid bytes32 this would otherwise sign a commitment to no destination at all');
1624
+ }
1625
+ const byteLength = (0, ethers_1.toUtf8Bytes)(destination).length;
1626
+ if (byteLength > exports2.MAX_DESTINATION_BYTES) {
1627
+ throw new Error(`destination is ${byteLength} bytes, over the escrow's MAX_DESTINATION_BYTES of ${exports2.MAX_DESTINATION_BYTES}: the contract reverts DestinationTooLong, so this digest could never be redeemed`);
1628
+ }
1629
+ }
1630
+ function createPermitWitnessTransferFromPrehashWithDestination(params) {
1631
+ assertDestinationWithinBounds(params.destination);
1632
+ return {
1633
+ types: permit_types_1.PERMIT_WITNESS_TYPES_WITH_DESTINATION,
1634
+ primaryType: "PermitWitnessTransferFrom",
1635
+ domain: {
1636
+ name: "Permit2",
1637
+ chainId: (0, witness_values_1.chainIdToHex)(params.chainId),
1638
+ verifyingContract: (0, witness_values_1.normalizeAddressField)("verifyingContract", params.verifyingContract)
1639
+ },
1640
+ message: {
1641
+ permitted: {
1642
+ token: (0, witness_values_1.normalizeAddressField)("token", params.token),
1643
+ amount: (0, witness_values_1.normalizeUint256)("amount", params.amount)
1644
+ },
1645
+ spender: (0, witness_values_1.normalizeAddressField)("spender", params.spender),
1646
+ nonce: (0, witness_values_1.normalizeUint256)("nonce", params.nonce),
1647
+ deadline: (0, witness_values_1.normalizeUint256)("deadline", params.deadline),
1648
+ witness: {
1649
+ depositRequestHash: (0, witness_values_1.normalizeBytes32)("depositRequestHash", params.depositRequestHash),
1650
+ destination: params.destination,
1651
+ reserver: (0, witness_values_1.normalizeAddressField)("reserver", params.reserver),
1652
+ releaser: (0, witness_values_1.normalizeAddressField)("releaser", params.releaser)
1653
+ }
1654
+ }
1655
+ };
1656
+ }
793
1657
  }
794
1658
  });
795
1659
 
796
1660
  // ../contracts/evm/escrow-encoding/typescript/dist/index.js
797
- var require_dist2 = __commonJS({
1661
+ var require_dist3 = __commonJS({
798
1662
  "../contracts/evm/escrow-encoding/typescript/dist/index.js"(exports2) {
799
1663
  "use strict";
800
1664
  Object.defineProperty(exports2, "__esModule", { value: true });
801
- 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;
1665
+ exports2.MAX_DESTINATION_BYTES = exports2.createPermitWitnessTransferFromPrehashWithDestination = exports2.PERMIT2_CONTRACT_ADDRESS = exports2.hashPermitWitnessTransferFrom = exports2.createPermitWitnessTransferFromPrehash = exports2.computeRefundDigestWithQuoteHash = exports2.buildRefundTypedDataWithQuoteHash = exports2.computeReleaseDigestWithQuoteHash = exports2.buildReleaseTypedDataWithQuoteHash = exports2.computeReserveDigestWithQuoteSource = exports2.buildReserveTypedDataWithQuoteSource = exports2.computeReserveDigest = exports2.ESCROW_V3_ABI_JSON = exports2.ESCROW_V2_ABI_JSON = exports2.ESCROW_ABI_JSON = exports2.ESCROW_ABI = exports2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH = exports2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH = exports2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE = exports2.PERMIT_WITNESS_TYPES_WITH_DESTINATION = 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;
802
1666
  var payment_id_1 = require_payment_id2();
803
1667
  Object.defineProperty(exports2, "computePaymentId", { enumerable: true, get: function() {
804
1668
  return payment_id_1.computePaymentId;
@@ -832,6 +1696,19 @@ var require_dist2 = __commonJS({
832
1696
  Object.defineProperty(exports2, "REFUND_WITNESS_TYPES", { enumerable: true, get: function() {
833
1697
  return permit_types_1.REFUND_WITNESS_TYPES;
834
1698
  } });
1699
+ var permit_types_2 = require_permit_types();
1700
+ Object.defineProperty(exports2, "PERMIT_WITNESS_TYPES_WITH_DESTINATION", { enumerable: true, get: function() {
1701
+ return permit_types_2.PERMIT_WITNESS_TYPES_WITH_DESTINATION;
1702
+ } });
1703
+ Object.defineProperty(exports2, "RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE", { enumerable: true, get: function() {
1704
+ return permit_types_2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE;
1705
+ } });
1706
+ Object.defineProperty(exports2, "RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH", { enumerable: true, get: function() {
1707
+ return permit_types_2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH;
1708
+ } });
1709
+ Object.defineProperty(exports2, "REFUND_WITNESS_TYPES_WITH_QUOTE_HASH", { enumerable: true, get: function() {
1710
+ return permit_types_2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH;
1711
+ } });
835
1712
  var escrow_abi_1 = require_escrow_abi();
836
1713
  Object.defineProperty(exports2, "ESCROW_ABI", { enumerable: true, get: function() {
837
1714
  return escrow_abi_1.ESCROW_ABI;
@@ -849,6 +1726,27 @@ var require_dist2 = __commonJS({
849
1726
  Object.defineProperty(exports2, "computeReserveDigest", { enumerable: true, get: function() {
850
1727
  return reserve_encoder_1.computeReserveDigest;
851
1728
  } });
1729
+ var reserve_encoder_2 = require_reserve_encoder2();
1730
+ Object.defineProperty(exports2, "buildReserveTypedDataWithQuoteSource", { enumerable: true, get: function() {
1731
+ return reserve_encoder_2.buildReserveTypedDataWithQuoteSource;
1732
+ } });
1733
+ Object.defineProperty(exports2, "computeReserveDigestWithQuoteSource", { enumerable: true, get: function() {
1734
+ return reserve_encoder_2.computeReserveDigestWithQuoteSource;
1735
+ } });
1736
+ var release_encoder_1 = require_release_encoder2();
1737
+ Object.defineProperty(exports2, "buildReleaseTypedDataWithQuoteHash", { enumerable: true, get: function() {
1738
+ return release_encoder_1.buildReleaseTypedDataWithQuoteHash;
1739
+ } });
1740
+ Object.defineProperty(exports2, "computeReleaseDigestWithQuoteHash", { enumerable: true, get: function() {
1741
+ return release_encoder_1.computeReleaseDigestWithQuoteHash;
1742
+ } });
1743
+ var refund_encoder_1 = require_refund_encoder2();
1744
+ Object.defineProperty(exports2, "buildRefundTypedDataWithQuoteHash", { enumerable: true, get: function() {
1745
+ return refund_encoder_1.buildRefundTypedDataWithQuoteHash;
1746
+ } });
1747
+ Object.defineProperty(exports2, "computeRefundDigestWithQuoteHash", { enumerable: true, get: function() {
1748
+ return refund_encoder_1.computeRefundDigestWithQuoteHash;
1749
+ } });
852
1750
  var deposit_encoder_1 = require_deposit_encoder2();
853
1751
  Object.defineProperty(exports2, "createPermitWitnessTransferFromPrehash", { enumerable: true, get: function() {
854
1752
  return deposit_encoder_1.createPermitWitnessTransferFromPrehash;
@@ -859,6 +1757,13 @@ var require_dist2 = __commonJS({
859
1757
  Object.defineProperty(exports2, "PERMIT2_CONTRACT_ADDRESS", { enumerable: true, get: function() {
860
1758
  return deposit_encoder_1.PERMIT2_CONTRACT_ADDRESS;
861
1759
  } });
1760
+ var deposit_encoder_2 = require_deposit_encoder2();
1761
+ Object.defineProperty(exports2, "createPermitWitnessTransferFromPrehashWithDestination", { enumerable: true, get: function() {
1762
+ return deposit_encoder_2.createPermitWitnessTransferFromPrehashWithDestination;
1763
+ } });
1764
+ Object.defineProperty(exports2, "MAX_DESTINATION_BYTES", { enumerable: true, get: function() {
1765
+ return deposit_encoder_2.MAX_DESTINATION_BYTES;
1766
+ } });
862
1767
  }
863
1768
  });
864
1769
 
@@ -899,24 +1804,25 @@ var require_evm = __commonJS({
899
1804
  Object.defineProperty(exports2, "__esModule", { value: true });
900
1805
  exports2.evmAdapter = void 0;
901
1806
  var ethers_1 = require("ethers");
902
- var evm_escrow_encoding_1 = require_dist2();
1807
+ var evm_escrow_encoding_1 = require_dist3();
903
1808
  var utils_js_1 = require_utils();
1809
+ var destination_js_1 = require_destination();
904
1810
  var errors_js_1 = require_errors();
905
1811
  var chain_id_js_1 = require_chain_id2();
906
1812
  exports2.evmAdapter = {
907
- async buildAuthMessage({ sourceAsset, maxSourceAmount, sourceDefaults, deadline, nonce }) {
1813
+ async buildAuthMessage({ sourceAsset, maxSourceAmount, requestId, sourceDefaults, destinationAsset, destinationAccount, deadline, nonce }) {
908
1814
  if (nonce === void 0) {
909
1815
  throw new Error("sender_auth: buildAuthMessage requires an explicit nonce \u2014 derive it deterministically from a stable request id (e.g. an order id) so retries reproduce the same permit; pass generatePermitNonce() only for genuinely one-shot builds");
910
1816
  }
911
1817
  if (deadline === void 0) {
912
1818
  throw new Error("sender_auth: buildAuthMessage requires an explicit permit deadline (absolute Unix seconds) \u2014 the low-level builder does not default it; derive it from the payment's fulfillment/settlement deadline in the calling layer (pgc/mppx)");
913
1819
  }
914
- const sourceChainId = sourceAsset.split("/")[0];
915
- const chainIdNum = parseInt(sourceChainId.split(":")[1]);
916
- const tokenAddress = sourceAsset.split("/")[1].split(":")[1];
917
- const permitParams = {
1820
+ const { network: sourceChainId, asset: tokenAddress } = (0, utils_js_1.parseSourceAsset)(sourceAsset);
1821
+ const chainIdNum = (0, chain_id_js_1.evmChainId)(sourceChainId);
1822
+ const permit2Contract = sourceDefaults.permit2Contract ?? evm_escrow_encoding_1.PERMIT2_CONTRACT_ADDRESS;
1823
+ const basePermit = {
918
1824
  chainId: chainIdNum,
919
- verifyingContract: evm_escrow_encoding_1.PERMIT2_CONTRACT_ADDRESS,
1825
+ verifyingContract: permit2Contract,
920
1826
  token: tokenAddress,
921
1827
  amount: maxSourceAmount,
922
1828
  spender: sourceDefaults.escrowContract,
@@ -925,7 +1831,21 @@ var require_evm = __commonJS({
925
1831
  reserver: sourceDefaults.quoteSelector,
926
1832
  releaser: sourceDefaults.fulfillmentVerifierAccount
927
1833
  };
928
- const messagePrehash = (0, evm_escrow_encoding_1.createPermitWitnessTransferFromPrehash)(permitParams);
1834
+ if ((0, destination_js_1.usesDestinationCommitment)(sourceDefaults.depositWitnessVersion)) {
1835
+ const permitParams = {
1836
+ ...basePermit,
1837
+ // The two escrow commitments. Composed here through the shared helpers rather than
1838
+ // accepted pre-built, so this producer and the release signer cannot disagree about
1839
+ // formatting — a disagreement the escrow cannot detect, because it stores only
1840
+ // keccak256(bytes(destination)).
1841
+ depositRequestHash: (0, destination_js_1.deriveDepositRequestHash)(requestId),
1842
+ destination: (0, destination_js_1.buildEscrowDestination)(destinationAsset, destinationAccount)
1843
+ };
1844
+ const messagePrehash2 = (0, evm_escrow_encoding_1.createPermitWitnessTransferFromPrehashWithDestination)(permitParams);
1845
+ const messageHash2 = (0, evm_escrow_encoding_1.hashPermitWitnessTransferFrom)(messagePrehash2);
1846
+ return { messageScheme: "EVM_PERMIT2", messageHash: messageHash2, messagePrehash: JSON.stringify(messagePrehash2) };
1847
+ }
1848
+ const messagePrehash = (0, evm_escrow_encoding_1.createPermitWitnessTransferFromPrehash)(basePermit);
929
1849
  const messageHash = (0, evm_escrow_encoding_1.hashPermitWitnessTransferFrom)(messagePrehash);
930
1850
  return { messageScheme: "EVM_PERMIT2", messageHash, messagePrehash: JSON.stringify(messagePrehash) };
931
1851
  },
@@ -958,17 +1878,31 @@ var require_evm = __commonJS({
958
1878
  let msg;
959
1879
  try {
960
1880
  msg = JSON.parse(signed.message_prehash).message;
961
- canonical = (0, evm_escrow_encoding_1.createPermitWitnessTransferFromPrehash)({
1881
+ const base = {
962
1882
  chainId: (0, chain_id_js_1.evmChainId)(source.network),
963
- verifyingContract: evm_escrow_encoding_1.PERMIT2_CONTRACT_ADDRESS,
1883
+ // The same Permit2 buildAuthMessage signed against. Taken from the VERIFIER's
1884
+ // expectations, never from msg — the prehash is client-supplied, so reading the domain
1885
+ // out of it would let a caller nominate its own verifying contract and have the
1886
+ // signature check itself. Absent means canonical, matching the build side's default.
1887
+ verifyingContract: expected.permit2Contract ?? evm_escrow_encoding_1.PERMIT2_CONTRACT_ADDRESS,
964
1888
  token: msg.permitted.token,
965
1889
  amount: msg.permitted.amount,
966
1890
  spender: msg.spender,
967
1891
  nonce: BigInt(msg.nonce),
968
1892
  deadline: BigInt(msg.deadline),
969
- reserver: msg.witness.reserver,
970
- releaser: msg.witness.releaser
971
- });
1893
+ reserver: msg.witness?.reserver,
1894
+ releaser: msg.witness?.releaser
1895
+ };
1896
+ const hasHash = typeof msg.witness?.depositRequestHash === "string";
1897
+ const hasDestination = typeof msg.witness?.destination === "string";
1898
+ if (hasHash !== hasDestination) {
1899
+ throw new Error("half-populated deposit witness");
1900
+ }
1901
+ canonical = hasHash ? (0, evm_escrow_encoding_1.createPermitWitnessTransferFromPrehashWithDestination)({
1902
+ ...base,
1903
+ depositRequestHash: msg.witness.depositRequestHash,
1904
+ destination: msg.witness.destination
1905
+ }) : (0, evm_escrow_encoding_1.createPermitWitnessTransferFromPrehash)(base);
972
1906
  } catch {
973
1907
  throw new errors_js_1.MalformedPrehashError();
974
1908
  }
@@ -992,6 +1926,12 @@ var require_evm = __commonJS({
992
1926
  if (expected.reserver !== void 0 && expected.releaser !== void 0) {
993
1927
  (0, utils_js_1.assertWitnessRoles)(msg.witness.reserver, msg.witness.releaser, expected.reserver, expected.releaser, (a) => a);
994
1928
  }
1929
+ if (expected.destination !== void 0) {
1930
+ (0, utils_js_1.assertDestination)(msg.witness.destination, expected.destination);
1931
+ }
1932
+ if (expected.requestId !== void 0) {
1933
+ (0, utils_js_1.assertDepositRequestHash)(msg.witness.depositRequestHash, expected.requestId);
1934
+ }
995
1935
  return {
996
1936
  amount: msg.permitted.amount,
997
1937
  deadlineSec,
@@ -1002,7 +1942,11 @@ var require_evm = __commonJS({
1002
1942
  deadlineSec,
1003
1943
  reserver: msg.witness.reserver,
1004
1944
  releaser: msg.witness.releaser,
1005
- spender: msg.spender
1945
+ spender: msg.spender,
1946
+ // Surfaced whether or not the opt-in checks above ran, so a consumer binding these
1947
+ // downstream does not have to re-parse message_prehash and risk drifting from this parse.
1948
+ destination: msg.witness.destination,
1949
+ depositRequestHash: msg.witness.depositRequestHash
1006
1950
  }
1007
1951
  };
1008
1952
  }
@@ -1021,18 +1965,18 @@ var require_tron = __commonJS({
1021
1965
  var utils_js_1 = require_utils();
1022
1966
  var errors_js_1 = require_errors();
1023
1967
  var chain_id_js_1 = require_chain_id2();
1968
+ var destination_js_1 = require_destination();
1024
1969
  exports2.tronAdapter = {
1025
- async buildAuthMessage({ sourceAsset, maxSourceAmount, sourceDefaults, deadline, nonce }) {
1970
+ async buildAuthMessage({ sourceAsset, maxSourceAmount, requestId, sourceDefaults, destinationAsset, destinationAccount, deadline, nonce }) {
1026
1971
  if (nonce === void 0) {
1027
1972
  throw new Error("sender_auth: buildAuthMessage requires an explicit nonce \u2014 derive it deterministically from a stable request id (e.g. an order id) so retries reproduce the same permit; pass generatePermitNonce() only for genuinely one-shot builds");
1028
1973
  }
1029
1974
  if (deadline === void 0) {
1030
1975
  throw new Error("sender_auth: buildAuthMessage requires an explicit permit deadline (absolute Unix seconds) \u2014 the low-level builder does not default it; derive it from the payment's fulfillment/settlement deadline in the calling layer (pgc/mppx)");
1031
1976
  }
1032
- const sourceChainId = sourceAsset.split("/")[0];
1033
- const tokenAddress = sourceAsset.split("/")[1].split(":")[1];
1977
+ const { network: sourceChainId, asset: tokenAddress } = (0, utils_js_1.parseSourceAsset)(sourceAsset);
1034
1978
  const permit2Address = sourceDefaults.permit2Contract ?? (0, chain_id_js_1.resolveTronPermit2)(sourceChainId);
1035
- const tvmParams = {
1979
+ const baseParams = {
1036
1980
  chainId: (0, chain_id_js_1.tronNumericChainId)(sourceChainId),
1037
1981
  permit2Address,
1038
1982
  tokenAddress,
@@ -1043,7 +1987,21 @@ var require_tron = __commonJS({
1043
1987
  reserverAddress: sourceDefaults.quoteSelector,
1044
1988
  releaserAddress: sourceDefaults.fulfillmentVerifierAccount
1045
1989
  };
1046
- const messagePrehash = (0, tvm_escrow_encoding_1.createTvmPermitWitnessTransferFromPrehash)(tvmParams);
1990
+ if ((0, destination_js_1.usesDestinationCommitment)(sourceDefaults.depositWitnessVersion)) {
1991
+ const tvmParams = {
1992
+ ...baseParams,
1993
+ // The two commitments, composed through the shared helpers rather than accepted
1994
+ // pre-built, so this producer and the Go release signer cannot disagree about
1995
+ // formatting — a disagreement the escrow cannot detect, because it stores only
1996
+ // keccak256(bytes(destination)).
1997
+ depositRequestHash: (0, destination_js_1.deriveDepositRequestHash)(requestId),
1998
+ destination: (0, destination_js_1.buildEscrowDestination)(destinationAsset, destinationAccount)
1999
+ };
2000
+ const messagePrehash2 = (0, tvm_escrow_encoding_1.createTvmPermitWitnessTransferFromPrehashWithDestination)(tvmParams);
2001
+ const messageHash2 = (0, tvm_escrow_encoding_1.hashTvmPermitWitnessTransferFrom)(messagePrehash2);
2002
+ return { messageScheme: "EVM_PERMIT2", messageHash: messageHash2, messagePrehash: JSON.stringify(messagePrehash2) };
2003
+ }
2004
+ const messagePrehash = (0, tvm_escrow_encoding_1.createTvmPermitWitnessTransferFromPrehash)(baseParams);
1047
2005
  const messageHash = (0, tvm_escrow_encoding_1.hashTvmPermitWitnessTransferFrom)(messagePrehash);
1048
2006
  return { messageScheme: "EVM_PERMIT2", messageHash, messagePrehash: JSON.stringify(messagePrehash) };
1049
2007
  },
@@ -1078,17 +2036,31 @@ var require_tron = __commonJS({
1078
2036
  let digest;
1079
2037
  try {
1080
2038
  msg = JSON.parse(signed.message_prehash).message;
1081
- const canonical = (0, tvm_escrow_encoding_1.createTvmPermitWitnessTransferFromPrehash)({
2039
+ const base = {
1082
2040
  chainId: (0, chain_id_js_1.tronNumericChainId)(source.network),
1083
- permit2Address: (0, chain_id_js_1.resolveTronPermit2)(source.network),
2041
+ // The same Permit2 buildAuthMessage signed against, taken from the VERIFIER's
2042
+ // expectations rather than from msg — the prehash is payer-supplied, so reading the
2043
+ // domain out of it would let a caller nominate its own verifying contract. Absent means
2044
+ // the pinned per-chain address, matching the build side's default.
2045
+ permit2Address: expected.permit2Contract ?? (0, chain_id_js_1.resolveTronPermit2)(source.network),
1084
2046
  tokenAddress: msg.permitted.token,
1085
2047
  amount: msg.permitted.amount,
1086
2048
  spenderAddress: msg.spender,
1087
2049
  nonce: BigInt(msg.nonce),
1088
2050
  deadline: BigInt(msg.deadline),
1089
- reserverAddress: msg.witness.reserver,
1090
- releaserAddress: msg.witness.releaser
1091
- });
2051
+ reserverAddress: msg.witness?.reserver,
2052
+ releaserAddress: msg.witness?.releaser
2053
+ };
2054
+ const hasHash = typeof msg.witness?.depositRequestHash === "string";
2055
+ const hasDestination = typeof msg.witness?.destination === "string";
2056
+ if (hasHash !== hasDestination) {
2057
+ throw new Error("half-populated witness");
2058
+ }
2059
+ const canonical = hasHash ? (0, tvm_escrow_encoding_1.createTvmPermitWitnessTransferFromPrehashWithDestination)({
2060
+ ...base,
2061
+ depositRequestHash: msg.witness.depositRequestHash,
2062
+ destination: msg.witness.destination
2063
+ }) : (0, tvm_escrow_encoding_1.createTvmPermitWitnessTransferFromPrehash)(base);
1092
2064
  digest = (0, tvm_escrow_encoding_1.hashTvmPermitWitnessTransferFrom)(canonical);
1093
2065
  } catch {
1094
2066
  throw new errors_js_1.MalformedPrehashError();
@@ -1136,7 +2108,7 @@ var require_errors2 = __commonJS({
1136
2108
  "../contracts/svm/escrow-encoding/typescript/dist/errors.js"(exports2) {
1137
2109
  "use strict";
1138
2110
  Object.defineProperty(exports2, "__esModule", { value: true });
1139
- 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;
2111
+ exports2.InvalidEscrowDomainError = exports2.DestinationTooLongError = exports2.EmptyDestinationError = exports2.ZeroSourceAmountError = exports2.ZeroQuoteHashError = exports2.InvalidHexError = exports2.InvalidBase58Error = exports2.InvalidPubkeyLengthError = exports2.ZeroDepositHashError = exports2.ZeroRecipientError = exports2.ZeroReleaserError = exports2.ZeroReserverError = exports2.ZeroAmountError = exports2.ZeroMintError = exports2.ZeroDepositorError = exports2.ZeroDepositRequestHashError = exports2.EncodingError = void 0;
1140
2112
  var EncodingError = class extends Error {
1141
2113
  constructor(message) {
1142
2114
  super(message);
@@ -1144,13 +2116,13 @@ var require_errors2 = __commonJS({
1144
2116
  }
1145
2117
  };
1146
2118
  exports2.EncodingError = EncodingError;
1147
- var ZeroPaymentIdError = class extends EncodingError {
2119
+ var ZeroDepositRequestHashError = class extends EncodingError {
1148
2120
  constructor() {
1149
- super("payment ID cannot be zero");
1150
- this.name = "ZeroPaymentIdError";
2121
+ super("deposit request hash cannot be zero");
2122
+ this.name = "ZeroDepositRequestHashError";
1151
2123
  }
1152
2124
  };
1153
- exports2.ZeroPaymentIdError = ZeroPaymentIdError;
2125
+ exports2.ZeroDepositRequestHashError = ZeroDepositRequestHashError;
1154
2126
  var ZeroDepositorError = class extends EncodingError {
1155
2127
  constructor() {
1156
2128
  super("depositor cannot be zero");
@@ -1221,6 +2193,41 @@ var require_errors2 = __commonJS({
1221
2193
  }
1222
2194
  };
1223
2195
  exports2.InvalidHexError = InvalidHexError;
2196
+ var ZeroQuoteHashError = class extends EncodingError {
2197
+ constructor() {
2198
+ super("quote hash cannot be zero");
2199
+ this.name = "ZeroQuoteHashError";
2200
+ }
2201
+ };
2202
+ exports2.ZeroQuoteHashError = ZeroQuoteHashError;
2203
+ var ZeroSourceAmountError = class extends EncodingError {
2204
+ constructor() {
2205
+ super("source amount cannot be zero");
2206
+ this.name = "ZeroSourceAmountError";
2207
+ }
2208
+ };
2209
+ exports2.ZeroSourceAmountError = ZeroSourceAmountError;
2210
+ var EmptyDestinationError = class extends EncodingError {
2211
+ constructor() {
2212
+ super("destination cannot be empty");
2213
+ this.name = "EmptyDestinationError";
2214
+ }
2215
+ };
2216
+ exports2.EmptyDestinationError = EmptyDestinationError;
2217
+ var DestinationTooLongError = class extends EncodingError {
2218
+ constructor() {
2219
+ super("destination exceeds the maximum length");
2220
+ this.name = "DestinationTooLongError";
2221
+ }
2222
+ };
2223
+ exports2.DestinationTooLongError = DestinationTooLongError;
2224
+ var InvalidEscrowDomainError = class extends EncodingError {
2225
+ constructor(message) {
2226
+ super(message);
2227
+ this.name = "InvalidEscrowDomainError";
2228
+ }
2229
+ };
2230
+ exports2.InvalidEscrowDomainError = InvalidEscrowDomainError;
1224
2231
  }
1225
2232
  });
1226
2233
 
@@ -1235,7 +2242,7 @@ var require_pubkey = __commonJS({
1235
2242
  exports2.Pubkey = void 0;
1236
2243
  var bs58_1 = __importDefault(require("bs58"));
1237
2244
  var errors_1 = require_errors2();
1238
- var Pubkey2 = class _Pubkey {
2245
+ var Pubkey = class _Pubkey {
1239
2246
  constructor(data) {
1240
2247
  if (data.length !== 32) {
1241
2248
  throw new errors_1.InvalidPubkeyLengthError();
@@ -1328,7 +2335,7 @@ var require_pubkey = __commonJS({
1328
2335
  return this.data.every((b, i) => b === other.data[i]);
1329
2336
  }
1330
2337
  };
1331
- exports2.Pubkey = Pubkey2;
2338
+ exports2.Pubkey = Pubkey;
1332
2339
  }
1333
2340
  });
1334
2341
 
@@ -1929,12 +2936,17 @@ var require_escrow_domain = __commonJS({
1929
2936
  "use strict";
1930
2937
  Object.defineProperty(exports2, "__esModule", { value: true });
1931
2938
  exports2.escrowDomainPrefixBytes = escrowDomainPrefixBytes;
2939
+ exports2.newEscrowDomain = newEscrowDomain;
2940
+ var errors_1 = require_errors2();
1932
2941
  function escrowDomainPrefixBytes(domain) {
1933
2942
  if (domain.clusterId.length !== 32) {
1934
- throw new Error(`EscrowDomain.clusterId must be 32 bytes, got ${domain.clusterId.length}`);
2943
+ throw new errors_1.InvalidEscrowDomainError(`EscrowDomain.clusterId must be 32 bytes, got ${domain.clusterId.length}`);
2944
+ }
2945
+ if (domain.programId.isZero()) {
2946
+ throw new errors_1.InvalidEscrowDomainError("EscrowDomain.programId cannot be zero");
1935
2947
  }
1936
2948
  if (!Number.isInteger(domain.signatureDomainVersion) || domain.signatureDomainVersion < 1 || domain.signatureDomainVersion > 255) {
1937
- throw new Error(`EscrowDomain.signatureDomainVersion must be an integer in 1..=255, got ${domain.signatureDomainVersion}`);
2949
+ throw new errors_1.InvalidEscrowDomainError(`EscrowDomain.signatureDomainVersion must be an integer in 1..=255, got ${domain.signatureDomainVersion}`);
1938
2950
  }
1939
2951
  return [
1940
2952
  new TextEncoder().encode("escrow"),
@@ -1943,6 +2955,25 @@ var require_escrow_domain = __commonJS({
1943
2955
  domain.programId.toBytes()
1944
2956
  ];
1945
2957
  }
2958
+ function newEscrowDomain(clusterName, signatureDomainVersion, programId) {
2959
+ const trimmed = clusterName.trim();
2960
+ if (trimmed.length === 0) {
2961
+ throw new errors_1.InvalidEscrowDomainError("EscrowDomain cluster name cannot be empty");
2962
+ }
2963
+ const encoded = new TextEncoder().encode(trimmed);
2964
+ if (encoded.length > 32) {
2965
+ throw new errors_1.InvalidEscrowDomainError(`EscrowDomain cluster name "${trimmed}" exceeds 32 bytes`);
2966
+ }
2967
+ if (!Number.isInteger(signatureDomainVersion) || signatureDomainVersion < 1 || signatureDomainVersion > 255) {
2968
+ throw new errors_1.InvalidEscrowDomainError(`EscrowDomain.signatureDomainVersion must be an integer in 1..=255, got ${signatureDomainVersion}`);
2969
+ }
2970
+ if (programId.isZero()) {
2971
+ throw new errors_1.InvalidEscrowDomainError("EscrowDomain.programId cannot be zero");
2972
+ }
2973
+ const clusterId = new Uint8Array(32);
2974
+ clusterId.set(encoded);
2975
+ return { clusterId, signatureDomainVersion, programId };
2976
+ }
1946
2977
  }
1947
2978
  });
1948
2979
 
@@ -1951,13 +2982,16 @@ var require_deposit_encoder3 = __commonJS({
1951
2982
  "../contracts/svm/escrow-encoding/typescript/dist/deposit-encoder.js"(exports2) {
1952
2983
  "use strict";
1953
2984
  Object.defineProperty(exports2, "__esModule", { value: true });
1954
- exports2.computeDepositHash = computeDepositHash2;
2985
+ exports2.MAX_DESTINATION_LEN = void 0;
2986
+ exports2.computeDepositHash = computeDepositHash;
2987
+ exports2.computeDestinationHash = computeDestinationHash;
2988
+ exports2.computeDepositHashV2 = computeDepositHashV2;
1955
2989
  var encoding_utils_1 = require_encoding_utils();
1956
2990
  var escrow_domain_1 = require_escrow_domain();
1957
2991
  var errors_1 = require_errors2();
1958
- function computeDepositHash2(params, domain) {
1959
- if (params.paymentId.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.paymentId)) {
1960
- throw new errors_1.ZeroPaymentIdError();
2992
+ function computeDepositHash(params, domain) {
2993
+ if (params.depositRequestHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositRequestHash)) {
2994
+ throw new errors_1.ZeroDepositRequestHashError();
1961
2995
  }
1962
2996
  if (params.depositor.isZero())
1963
2997
  throw new errors_1.ZeroDepositorError();
@@ -1969,7 +3003,48 @@ var require_deposit_encoder3 = __commonJS({
1969
3003
  throw new errors_1.ZeroReserverError();
1970
3004
  if (params.releaser.isZero())
1971
3005
  throw new errors_1.ZeroReleaserError();
1972
- 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));
3006
+ return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("deposit"), params.depositRequestHash, 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));
3007
+ }
3008
+ exports2.MAX_DESTINATION_LEN = 256;
3009
+ function computeDestinationHash(destination) {
3010
+ return (0, encoding_utils_1.keccak256)((0, encoding_utils_1.stringToBytes)(destination));
3011
+ }
3012
+ function computeDepositHashV2(params, destination, domain) {
3013
+ if (params.depositRequestHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositRequestHash)) {
3014
+ throw new errors_1.ZeroDepositRequestHashError();
3015
+ }
3016
+ if (params.depositor.isZero())
3017
+ throw new errors_1.ZeroDepositorError();
3018
+ if (params.mint.isZero())
3019
+ throw new errors_1.ZeroMintError();
3020
+ if (params.amount === 0n)
3021
+ throw new errors_1.ZeroAmountError();
3022
+ if (params.reserver.isZero())
3023
+ throw new errors_1.ZeroReserverError();
3024
+ if (params.releaser.isZero())
3025
+ throw new errors_1.ZeroReleaserError();
3026
+ if (destination.length === 0)
3027
+ throw new errors_1.EmptyDestinationError();
3028
+ if ((0, encoding_utils_1.stringToBytes)(destination).length > exports2.MAX_DESTINATION_LEN) {
3029
+ throw new errors_1.DestinationTooLongError();
3030
+ }
3031
+ return (0, encoding_utils_1.keccak256)(
3032
+ ...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain),
3033
+ (0, encoding_utils_1.stringToBytes)("deposit"),
3034
+ params.depositRequestHash,
3035
+ // Hash first: keccak256 concatenates without length prefixes, so injectivity depends on every
3036
+ // hashed field being fixed-width. Feeding the raw string would make it conditional on the
3037
+ // surrounding widths and diverge from the on-chain program, which hashes it too.
3038
+ computeDestinationHash(destination),
3039
+ params.depositor.toBytes(),
3040
+ params.mint.toBytes(),
3041
+ (0, encoding_utils_1.encodeU64LE)(params.amount),
3042
+ params.reserver.toBytes(),
3043
+ params.releaser.toBytes(),
3044
+ (0, encoding_utils_1.encodeU64LE)(params.nonce),
3045
+ (0, encoding_utils_1.encodeU64LE)(params.issuedAt),
3046
+ (0, encoding_utils_1.encodeU64LE)(params.deadline)
3047
+ );
1973
3048
  }
1974
3049
  }
1975
3050
  });
@@ -1980,6 +3055,8 @@ var require_reserve_encoder3 = __commonJS({
1980
3055
  "use strict";
1981
3056
  Object.defineProperty(exports2, "__esModule", { value: true });
1982
3057
  exports2.computeReserveHash = computeReserveHash;
3058
+ exports2.computeReserveHashV2 = computeReserveHashV2;
3059
+ exports2.computeReserveHashV3 = computeReserveHashV3;
1983
3060
  var encoding_utils_1 = require_encoding_utils();
1984
3061
  var escrow_domain_1 = require_escrow_domain();
1985
3062
  var errors_1 = require_errors2();
@@ -1991,15 +3068,38 @@ var require_reserve_encoder3 = __commonJS({
1991
3068
  throw new errors_1.ZeroRecipientError();
1992
3069
  return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("reserve"), params.recipient.toBytes(), params.depositHash);
1993
3070
  }
3071
+ function computeReserveHashV2(params, quoteHash, domain) {
3072
+ if (params.depositHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositHash)) {
3073
+ throw new errors_1.ZeroDepositHashError();
3074
+ }
3075
+ if (params.recipient.isZero())
3076
+ throw new errors_1.ZeroRecipientError();
3077
+ if (quoteHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(quoteHash))
3078
+ throw new errors_1.ZeroQuoteHashError();
3079
+ return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("reserve"), params.recipient.toBytes(), params.depositHash, quoteHash);
3080
+ }
3081
+ function computeReserveHashV3(params, quoteHash, sourceAmount, domain) {
3082
+ if (params.depositHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositHash)) {
3083
+ throw new errors_1.ZeroDepositHashError();
3084
+ }
3085
+ if (params.recipient.isZero())
3086
+ throw new errors_1.ZeroRecipientError();
3087
+ if (quoteHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(quoteHash))
3088
+ throw new errors_1.ZeroQuoteHashError();
3089
+ if (sourceAmount === 0n)
3090
+ throw new errors_1.ZeroSourceAmountError();
3091
+ return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("reserve"), params.recipient.toBytes(), params.depositHash, quoteHash, (0, encoding_utils_1.encodeU64LE)(sourceAmount));
3092
+ }
1994
3093
  }
1995
3094
  });
1996
3095
 
1997
3096
  // ../contracts/svm/escrow-encoding/typescript/dist/release-encoder.js
1998
- var require_release_encoder = __commonJS({
3097
+ var require_release_encoder3 = __commonJS({
1999
3098
  "../contracts/svm/escrow-encoding/typescript/dist/release-encoder.js"(exports2) {
2000
3099
  "use strict";
2001
3100
  Object.defineProperty(exports2, "__esModule", { value: true });
2002
3101
  exports2.computeReleaseHash = computeReleaseHash;
3102
+ exports2.computeReleaseHashV2 = computeReleaseHashV2;
2003
3103
  var encoding_utils_1 = require_encoding_utils();
2004
3104
  var escrow_domain_1 = require_escrow_domain();
2005
3105
  var errors_1 = require_errors2();
@@ -2009,15 +3109,22 @@ var require_release_encoder = __commonJS({
2009
3109
  }
2010
3110
  return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("release"), params.depositHash);
2011
3111
  }
3112
+ function computeReleaseHashV2(params, quoteHash, domain) {
3113
+ if (params.depositHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositHash)) {
3114
+ throw new errors_1.ZeroDepositHashError();
3115
+ }
3116
+ return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("release"), params.depositHash, quoteHash);
3117
+ }
2012
3118
  }
2013
3119
  });
2014
3120
 
2015
3121
  // ../contracts/svm/escrow-encoding/typescript/dist/refund-encoder.js
2016
- var require_refund_encoder = __commonJS({
3122
+ var require_refund_encoder3 = __commonJS({
2017
3123
  "../contracts/svm/escrow-encoding/typescript/dist/refund-encoder.js"(exports2) {
2018
3124
  "use strict";
2019
3125
  Object.defineProperty(exports2, "__esModule", { value: true });
2020
3126
  exports2.computeRefundHash = computeRefundHash;
3127
+ exports2.computeRefundHashV2 = computeRefundHashV2;
2021
3128
  var encoding_utils_1 = require_encoding_utils();
2022
3129
  var escrow_domain_1 = require_escrow_domain();
2023
3130
  var errors_1 = require_errors2();
@@ -2027,6 +3134,12 @@ var require_refund_encoder = __commonJS({
2027
3134
  }
2028
3135
  return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("refund"), params.depositHash);
2029
3136
  }
3137
+ function computeRefundHashV2(params, quoteHash, domain) {
3138
+ if (params.depositHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositHash)) {
3139
+ throw new errors_1.ZeroDepositHashError();
3140
+ }
3141
+ return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("refund"), params.depositHash, quoteHash);
3142
+ }
2030
3143
  }
2031
3144
  });
2032
3145
 
@@ -2035,16 +3148,16 @@ var require_nonce_generator2 = __commonJS({
2035
3148
  "../contracts/svm/escrow-encoding/typescript/dist/nonce-generator.js"(exports2) {
2036
3149
  "use strict";
2037
3150
  Object.defineProperty(exports2, "__esModule", { value: true });
2038
- exports2.MAX_VALID_SLOT = exports2.REPLAY_SLOTS = void 0;
3151
+ exports2.REPLAY_BUCKETS = exports2.MAX_VALID_SLOT = exports2.REPLAY_SLOTS = exports2.DEPOSIT_COMPUTE_UNIT_LIMIT = void 0;
2039
3152
  exports2.generateNonce = generateNonce2;
2040
3153
  var crypto_1 = require("crypto");
3154
+ exports2.DEPOSIT_COMPUTE_UNIT_LIMIT = 4e5;
2041
3155
  exports2.REPLAY_SLOTS = 235;
2042
3156
  exports2.MAX_VALID_SLOT = exports2.REPLAY_SLOTS - 1;
2043
- var NONCE_BUCKET_MASK = 131071;
3157
+ exports2.REPLAY_BUCKETS = 256;
2044
3158
  var NONCE_BUCKET_SHIFT = 32n;
2045
3159
  function generateNonce2() {
2046
- const bucketBytes = (0, crypto_1.randomBytes)(4);
2047
- const bucketID = bucketBytes.readUInt32LE(0) & NONCE_BUCKET_MASK;
3160
+ const bucketID = (0, crypto_1.randomBytes)(4).readUInt32LE(0) % exports2.REPLAY_BUCKETS;
2048
3161
  let slot;
2049
3162
  do {
2050
3163
  slot = (0, crypto_1.randomBytes)(1)[0];
@@ -2055,11 +3168,11 @@ var require_nonce_generator2 = __commonJS({
2055
3168
  });
2056
3169
 
2057
3170
  // ../contracts/svm/escrow-encoding/typescript/dist/index.js
2058
- var require_dist3 = __commonJS({
3171
+ var require_dist4 = __commonJS({
2059
3172
  "../contracts/svm/escrow-encoding/typescript/dist/index.js"(exports2) {
2060
3173
  "use strict";
2061
3174
  Object.defineProperty(exports2, "__esModule", { value: true });
2062
- 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;
3175
+ exports2.DEPOSIT_COMPUTE_UNIT_LIMIT = exports2.REPLAY_BUCKETS = exports2.MAX_VALID_SLOT = exports2.REPLAY_SLOTS = exports2.generateNonce = exports2.computeRefundHashV2 = exports2.computeRefundHash = exports2.computeReleaseHashV2 = exports2.computeReleaseHash = exports2.computeReserveHashV3 = exports2.computeReserveHashV2 = exports2.computeReserveHash = exports2.MAX_DESTINATION_LEN = exports2.computeDestinationHash = exports2.computeDepositHashV2 = exports2.computeDepositHash = exports2.InvalidHexError = exports2.InvalidBase58Error = exports2.InvalidPubkeyLengthError = exports2.InvalidEscrowDomainError = exports2.ZeroSourceAmountError = exports2.ZeroDepositHashError = exports2.ZeroRecipientError = exports2.ZeroReleaserError = exports2.ZeroReserverError = exports2.ZeroAmountError = exports2.ZeroMintError = exports2.ZeroDepositorError = exports2.DestinationTooLongError = exports2.EmptyDestinationError = exports2.ZeroQuoteHashError = exports2.ZeroDepositRequestHashError = exports2.EncodingError = exports2.newEscrowDomain = exports2.escrowDomainPrefixBytes = exports2.isZeroBytes32 = exports2.stringToBytes = exports2.keccak256 = exports2.encodeU64LE = exports2.Pubkey = void 0;
2063
3176
  var pubkey_1 = require_pubkey();
2064
3177
  Object.defineProperty(exports2, "Pubkey", { enumerable: true, get: function() {
2065
3178
  return pubkey_1.Pubkey;
@@ -2081,12 +3194,24 @@ var require_dist3 = __commonJS({
2081
3194
  Object.defineProperty(exports2, "escrowDomainPrefixBytes", { enumerable: true, get: function() {
2082
3195
  return escrow_domain_1.escrowDomainPrefixBytes;
2083
3196
  } });
3197
+ Object.defineProperty(exports2, "newEscrowDomain", { enumerable: true, get: function() {
3198
+ return escrow_domain_1.newEscrowDomain;
3199
+ } });
2084
3200
  var errors_1 = require_errors2();
2085
3201
  Object.defineProperty(exports2, "EncodingError", { enumerable: true, get: function() {
2086
3202
  return errors_1.EncodingError;
2087
3203
  } });
2088
- Object.defineProperty(exports2, "ZeroPaymentIdError", { enumerable: true, get: function() {
2089
- return errors_1.ZeroPaymentIdError;
3204
+ Object.defineProperty(exports2, "ZeroDepositRequestHashError", { enumerable: true, get: function() {
3205
+ return errors_1.ZeroDepositRequestHashError;
3206
+ } });
3207
+ Object.defineProperty(exports2, "ZeroQuoteHashError", { enumerable: true, get: function() {
3208
+ return errors_1.ZeroQuoteHashError;
3209
+ } });
3210
+ Object.defineProperty(exports2, "EmptyDestinationError", { enumerable: true, get: function() {
3211
+ return errors_1.EmptyDestinationError;
3212
+ } });
3213
+ Object.defineProperty(exports2, "DestinationTooLongError", { enumerable: true, get: function() {
3214
+ return errors_1.DestinationTooLongError;
2090
3215
  } });
2091
3216
  Object.defineProperty(exports2, "ZeroDepositorError", { enumerable: true, get: function() {
2092
3217
  return errors_1.ZeroDepositorError;
@@ -2109,6 +3234,12 @@ var require_dist3 = __commonJS({
2109
3234
  Object.defineProperty(exports2, "ZeroDepositHashError", { enumerable: true, get: function() {
2110
3235
  return errors_1.ZeroDepositHashError;
2111
3236
  } });
3237
+ Object.defineProperty(exports2, "ZeroSourceAmountError", { enumerable: true, get: function() {
3238
+ return errors_1.ZeroSourceAmountError;
3239
+ } });
3240
+ Object.defineProperty(exports2, "InvalidEscrowDomainError", { enumerable: true, get: function() {
3241
+ return errors_1.InvalidEscrowDomainError;
3242
+ } });
2112
3243
  Object.defineProperty(exports2, "InvalidPubkeyLengthError", { enumerable: true, get: function() {
2113
3244
  return errors_1.InvalidPubkeyLengthError;
2114
3245
  } });
@@ -2122,18 +3253,39 @@ var require_dist3 = __commonJS({
2122
3253
  Object.defineProperty(exports2, "computeDepositHash", { enumerable: true, get: function() {
2123
3254
  return deposit_encoder_1.computeDepositHash;
2124
3255
  } });
3256
+ Object.defineProperty(exports2, "computeDepositHashV2", { enumerable: true, get: function() {
3257
+ return deposit_encoder_1.computeDepositHashV2;
3258
+ } });
3259
+ Object.defineProperty(exports2, "computeDestinationHash", { enumerable: true, get: function() {
3260
+ return deposit_encoder_1.computeDestinationHash;
3261
+ } });
3262
+ Object.defineProperty(exports2, "MAX_DESTINATION_LEN", { enumerable: true, get: function() {
3263
+ return deposit_encoder_1.MAX_DESTINATION_LEN;
3264
+ } });
2125
3265
  var reserve_encoder_1 = require_reserve_encoder3();
2126
3266
  Object.defineProperty(exports2, "computeReserveHash", { enumerable: true, get: function() {
2127
3267
  return reserve_encoder_1.computeReserveHash;
2128
3268
  } });
2129
- var release_encoder_1 = require_release_encoder();
3269
+ Object.defineProperty(exports2, "computeReserveHashV2", { enumerable: true, get: function() {
3270
+ return reserve_encoder_1.computeReserveHashV2;
3271
+ } });
3272
+ Object.defineProperty(exports2, "computeReserveHashV3", { enumerable: true, get: function() {
3273
+ return reserve_encoder_1.computeReserveHashV3;
3274
+ } });
3275
+ var release_encoder_1 = require_release_encoder3();
2130
3276
  Object.defineProperty(exports2, "computeReleaseHash", { enumerable: true, get: function() {
2131
3277
  return release_encoder_1.computeReleaseHash;
2132
3278
  } });
2133
- var refund_encoder_1 = require_refund_encoder();
3279
+ Object.defineProperty(exports2, "computeReleaseHashV2", { enumerable: true, get: function() {
3280
+ return release_encoder_1.computeReleaseHashV2;
3281
+ } });
3282
+ var refund_encoder_1 = require_refund_encoder3();
2134
3283
  Object.defineProperty(exports2, "computeRefundHash", { enumerable: true, get: function() {
2135
3284
  return refund_encoder_1.computeRefundHash;
2136
3285
  } });
3286
+ Object.defineProperty(exports2, "computeRefundHashV2", { enumerable: true, get: function() {
3287
+ return refund_encoder_1.computeRefundHashV2;
3288
+ } });
2137
3289
  var nonce_generator_1 = require_nonce_generator2();
2138
3290
  Object.defineProperty(exports2, "generateNonce", { enumerable: true, get: function() {
2139
3291
  return nonce_generator_1.generateNonce;
@@ -2144,6 +3296,12 @@ var require_dist3 = __commonJS({
2144
3296
  Object.defineProperty(exports2, "MAX_VALID_SLOT", { enumerable: true, get: function() {
2145
3297
  return nonce_generator_1.MAX_VALID_SLOT;
2146
3298
  } });
3299
+ Object.defineProperty(exports2, "REPLAY_BUCKETS", { enumerable: true, get: function() {
3300
+ return nonce_generator_1.REPLAY_BUCKETS;
3301
+ } });
3302
+ Object.defineProperty(exports2, "DEPOSIT_COMPUTE_UNIT_LIMIT", { enumerable: true, get: function() {
3303
+ return nonce_generator_1.DEPOSIT_COMPUTE_UNIT_LIMIT;
3304
+ } });
2147
3305
  }
2148
3306
  });
2149
3307
 
@@ -2159,7 +3317,8 @@ var require_solana = __commonJS({
2159
3317
  var ethers_1 = require("ethers");
2160
3318
  var tweetnacl_1 = __importDefault(require("tweetnacl"));
2161
3319
  var bs58_1 = __importDefault(require("bs58"));
2162
- var solana_escrow_encoding_1 = require_dist3();
3320
+ var solana_escrow_encoding_1 = require_dist4();
3321
+ var destination_js_1 = require_destination();
2163
3322
  var utils_js_1 = require_utils();
2164
3323
  var errors_js_1 = require_errors();
2165
3324
  var chain_id_js_1 = require_chain_id2();
@@ -2169,7 +3328,8 @@ var require_solana = __commonJS({
2169
3328
  }
2170
3329
  function hashDeposit(prehash, domain) {
2171
3330
  return (0, ethers_1.hexlify)((0, solana_escrow_encoding_1.computeDepositHash)({
2172
- paymentId: (0, ethers_1.getBytes)(prehash.payment_id),
3331
+ // The encoder field was renamed for cross-VM parity; the prehash WIRE key stays payment_id.
3332
+ depositRequestHash: (0, ethers_1.getBytes)(prehash.payment_id),
2173
3333
  depositor: solana_escrow_encoding_1.Pubkey.fromBase58(prehash.depositor),
2174
3334
  mint: solana_escrow_encoding_1.Pubkey.fromBase58(prehash.mint),
2175
3335
  amount: BigInt(prehash.amount),
@@ -2180,6 +3340,26 @@ var require_solana = __commonJS({
2180
3340
  deadline: BigInt(prehash.deadline)
2181
3341
  }, domain));
2182
3342
  }
3343
+ var SVM_DESTINATION_COMMITMENT_VERSION = 4;
3344
+ function hashDepositV2(prehash, domain) {
3345
+ return (0, ethers_1.hexlify)((0, solana_escrow_encoding_1.computeDepositHashV2)(
3346
+ {
3347
+ depositRequestHash: (0, ethers_1.getBytes)(prehash.deposit_request_hash),
3348
+ depositor: solana_escrow_encoding_1.Pubkey.fromBase58(prehash.depositor),
3349
+ mint: solana_escrow_encoding_1.Pubkey.fromBase58(prehash.mint),
3350
+ amount: BigInt(prehash.amount),
3351
+ reserver: solana_escrow_encoding_1.Pubkey.fromBase58(prehash.reserver),
3352
+ releaser: solana_escrow_encoding_1.Pubkey.fromBase58(prehash.releaser),
3353
+ nonce: BigInt(prehash.nonce),
3354
+ issuedAt: BigInt(prehash.issued_at),
3355
+ deadline: BigInt(prehash.deadline)
3356
+ },
3357
+ // Plaintext, NOT pre-hashed: the encoder hashes it, and hashing an already-hashed
3358
+ // destination yields a well-formed commitment no on-chain state can satisfy.
3359
+ prehash.destination,
3360
+ domain
3361
+ ));
3362
+ }
2183
3363
  function domainFrom(defaults) {
2184
3364
  if (!defaults.escrowContract) {
2185
3365
  throw new Error("sender_auth: Solana source requires escrowContract (escrow program id) for the deposit-hash domain");
@@ -2194,12 +3374,11 @@ var require_solana = __commonJS({
2194
3374
  };
2195
3375
  }
2196
3376
  exports2.solanaAdapter = {
2197
- async buildAuthMessage({ sourceAsset, depositor, maxSourceAmount, requestId, sourceDefaults, nonce, solanaClockReader }) {
3377
+ async buildAuthMessage({ sourceAsset, depositor, maxSourceAmount, requestId, sourceDefaults, destinationAsset, destinationAccount, nonce, solanaClockReader }) {
2198
3378
  if (!requestId) {
2199
3379
  throw new Error("sender_auth: request_id is required");
2200
3380
  }
2201
- const sourceChainId = sourceAsset.split("/")[0];
2202
- const tokenMint = sourceAsset.split("/")[1].split(":")[1];
3381
+ const { network: sourceChainId, asset: tokenMint } = (0, utils_js_1.parseSourceAsset)(sourceAsset);
2203
3382
  const depositNonce = nonce !== void 0 ? BigInt(nonce) : (0, solana_escrow_encoding_1.generateNonce)();
2204
3383
  if (nonce !== void 0) {
2205
3384
  if (depositNonce < 0n || depositNonce >= 1n << 64n) {
@@ -2212,8 +3391,8 @@ var require_solana = __commonJS({
2212
3391
  const issuedAt = solanaClockReader ? await solanaClockReader(sourceChainId) : BigInt(Math.floor(Date.now() / 1e3));
2213
3392
  const deadline = issuedAt + BigInt(utils_js_1.REPLAY_HORIZON_SECS - 8);
2214
3393
  const paymentId = generateSolanaPaymentIdV3(requestId);
2215
- const prehash = {
2216
- payment_id: paymentId,
3394
+ const domain = domainFrom(sourceDefaults);
3395
+ const common = {
2217
3396
  depositor,
2218
3397
  mint: tokenMint,
2219
3398
  amount: BigInt(maxSourceAmount).toString(),
@@ -2223,7 +3402,20 @@ var require_solana = __commonJS({
2223
3402
  issued_at: issuedAt.toString(),
2224
3403
  deadline: deadline.toString()
2225
3404
  };
2226
- const depositHash = hashDeposit(prehash, domainFrom(sourceDefaults));
3405
+ if (domain.signatureDomainVersion >= SVM_DESTINATION_COMMITMENT_VERSION) {
3406
+ const prehashV2 = {
3407
+ deposit_request_hash: paymentId,
3408
+ destination: (0, destination_js_1.buildEscrowDestination)(destinationAsset, destinationAccount),
3409
+ ...common
3410
+ };
3411
+ return {
3412
+ messageScheme: "SOLANA",
3413
+ messageHash: hashDepositV2(prehashV2, domain),
3414
+ messagePrehash: JSON.stringify(prehashV2)
3415
+ };
3416
+ }
3417
+ const prehash = { payment_id: paymentId, ...common };
3418
+ const depositHash = hashDeposit(prehash, domain);
2227
3419
  return { messageScheme: "SOLANA", messageHash: depositHash, messagePrehash: JSON.stringify(prehash) };
2228
3420
  },
2229
3421
  async sign(signedMessage, privateKey) {
@@ -2269,8 +3461,18 @@ var require_solana = __commonJS({
2269
3461
  let prehash;
2270
3462
  let canonicalHash;
2271
3463
  try {
2272
- prehash = JSON.parse(signed.message_prehash);
2273
- canonicalHash = hashDeposit(prehash, domainFrom(expected));
3464
+ const domain = domainFrom(expected);
3465
+ if (domain.signatureDomainVersion >= SVM_DESTINATION_COMMITMENT_VERSION) {
3466
+ const v2 = JSON.parse(signed.message_prehash);
3467
+ if (typeof v2.deposit_request_hash !== "string" || typeof v2.destination !== "string") {
3468
+ throw new Error("pre-widening V1 prehash on a destination-committing domain");
3469
+ }
3470
+ canonicalHash = hashDepositV2(v2, domain);
3471
+ prehash = { payment_id: v2.deposit_request_hash, ...v2 };
3472
+ } else {
3473
+ prehash = JSON.parse(signed.message_prehash);
3474
+ canonicalHash = hashDeposit(prehash, domain);
3475
+ }
2274
3476
  } catch {
2275
3477
  throw new errors_js_1.MalformedPrehashError();
2276
3478
  }
@@ -2362,14 +3564,7 @@ var require_verify = __commonJS({
2362
3564
  Object.defineProperty(exports2, "__esModule", { value: true });
2363
3565
  exports2.verifyPaymentRequest = verifyPaymentRequest;
2364
3566
  var index_js_1 = require_adapters();
2365
- function parseSourceAsset(assetIdentifier) {
2366
- const parts = assetIdentifier.split("/");
2367
- const nsParts = parts[1]?.split(":");
2368
- if (parts.length < 2 || !nsParts || nsParts.length < 2 || !nsParts[1]) {
2369
- throw new Error(`sender_auth: invalid source asset "${assetIdentifier}"`);
2370
- }
2371
- return { network: parts[0], asset: nsParts[1] };
2372
- }
3567
+ var utils_js_1 = require_utils();
2373
3568
  function verifyPaymentRequest(request2, expected = {}) {
2374
3569
  const senderAuth = request2.sender_auth;
2375
3570
  if (!senderAuth?.signed_messages?.length) {
@@ -2378,87 +3573,473 @@ var require_verify = __commonJS({
2378
3573
  if (!request2.source) {
2379
3574
  throw new Error("sender_auth: request has no source");
2380
3575
  }
2381
- const requestSource = parseSourceAsset(request2.source.asset_identifier);
2382
- const { sourceAsset, network: networkOverride, maxSourceAmount: amountOverride, ...scheme } = expected;
2383
- const network = networkOverride ?? requestSource.network;
2384
- const asset = sourceAsset ?? requestSource.asset;
2385
- const maxSourceAmount = amountOverride ?? request2.max_source_amount ?? "0";
2386
- const source = { network, asset, account: request2.source.account };
2387
- const perMessage = { ...scheme, maxSourceAmount };
2388
- const adapter = (0, index_js_1.getChainAdapter)(network);
2389
- const results = senderAuth.signed_messages.map((m) => adapter.recoverAndVerify(m, source, perMessage));
2390
- return { results, recoveredAccount: source.account };
3576
+ const requestSource = (0, utils_js_1.parseSourceAsset)(request2.source.asset_identifier);
3577
+ const { sourceAsset, network: networkOverride, maxSourceAmount: amountOverride, ...scheme } = expected;
3578
+ const network = networkOverride ?? requestSource.network;
3579
+ const asset = sourceAsset ?? requestSource.asset;
3580
+ const maxSourceAmount = amountOverride ?? request2.max_source_amount ?? "0";
3581
+ const source = { network, asset, account: request2.source.account };
3582
+ const perMessage = { ...scheme, maxSourceAmount };
3583
+ const adapter = (0, index_js_1.getChainAdapter)(network);
3584
+ const results = senderAuth.signed_messages.map((m) => adapter.recoverAndVerify(m, source, perMessage));
3585
+ return { results, recoveredAccount: source.account };
3586
+ }
3587
+ }
3588
+ });
3589
+
3590
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/signer.js
3591
+ var require_signer = __commonJS({
3592
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/signer.js"(exports2) {
3593
+ "use strict";
3594
+ Object.defineProperty(exports2, "__esModule", { value: true });
3595
+ exports2.localKeySigner = localKeySigner2;
3596
+ var index_js_1 = require_adapters();
3597
+ function localKeySigner2(network, privateKey) {
3598
+ const adapter = (0, index_js_1.getChainAdapter)(network);
3599
+ return {
3600
+ async sign(signedMessage) {
3601
+ const signature = await adapter.sign(signedMessage, privateKey);
3602
+ const delegateSigner = adapter.deriveDelegateSigner?.(privateKey);
3603
+ return delegateSigner !== void 0 ? { signature, delegateSigner } : { signature };
3604
+ }
3605
+ };
3606
+ }
3607
+ }
3608
+ });
3609
+
3610
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/index.js
3611
+ var require_dist5 = __commonJS({
3612
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/index.js"(exports2) {
3613
+ "use strict";
3614
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
3615
+ if (k2 === void 0) k2 = k;
3616
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3617
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3618
+ desc = { enumerable: true, get: function() {
3619
+ return m[k];
3620
+ } };
3621
+ }
3622
+ Object.defineProperty(o, k2, desc);
3623
+ }) : (function(o, m, k, k2) {
3624
+ if (k2 === void 0) k2 = k;
3625
+ o[k2] = m[k];
3626
+ }));
3627
+ var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
3628
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
3629
+ };
3630
+ Object.defineProperty(exports2, "__esModule", { value: true });
3631
+ exports2.localKeySigner = exports2.SignerMismatchError = exports2.RecoveryFailedError = exports2.MalformedPrehashError = exports2.verifyPaymentRequest = exports2.DESTINATION_COMMITMENT_WITNESS_VERSION = exports2.usesDestinationCommitment = exports2.MAX_DESTINATION_BYTES = exports2.deriveDepositRequestHash = exports2.buildEscrowDestination = exports2.getChainAdapter = void 0;
3632
+ __exportStar(require_types(), exports2);
3633
+ __exportStar(require_utils(), exports2);
3634
+ __exportStar(require_chain_id2(), exports2);
3635
+ var index_js_1 = require_adapters();
3636
+ Object.defineProperty(exports2, "getChainAdapter", { enumerable: true, get: function() {
3637
+ return index_js_1.getChainAdapter;
3638
+ } });
3639
+ var destination_js_1 = require_destination();
3640
+ Object.defineProperty(exports2, "buildEscrowDestination", { enumerable: true, get: function() {
3641
+ return destination_js_1.buildEscrowDestination;
3642
+ } });
3643
+ Object.defineProperty(exports2, "deriveDepositRequestHash", { enumerable: true, get: function() {
3644
+ return destination_js_1.deriveDepositRequestHash;
3645
+ } });
3646
+ Object.defineProperty(exports2, "MAX_DESTINATION_BYTES", { enumerable: true, get: function() {
3647
+ return destination_js_1.MAX_DESTINATION_BYTES;
3648
+ } });
3649
+ Object.defineProperty(exports2, "usesDestinationCommitment", { enumerable: true, get: function() {
3650
+ return destination_js_1.usesDestinationCommitment;
3651
+ } });
3652
+ Object.defineProperty(exports2, "DESTINATION_COMMITMENT_WITNESS_VERSION", { enumerable: true, get: function() {
3653
+ return destination_js_1.DESTINATION_COMMITMENT_WITNESS_VERSION;
3654
+ } });
3655
+ var verify_js_1 = require_verify();
3656
+ Object.defineProperty(exports2, "verifyPaymentRequest", { enumerable: true, get: function() {
3657
+ return verify_js_1.verifyPaymentRequest;
3658
+ } });
3659
+ var errors_js_1 = require_errors();
3660
+ Object.defineProperty(exports2, "MalformedPrehashError", { enumerable: true, get: function() {
3661
+ return errors_js_1.MalformedPrehashError;
3662
+ } });
3663
+ Object.defineProperty(exports2, "RecoveryFailedError", { enumerable: true, get: function() {
3664
+ return errors_js_1.RecoveryFailedError;
3665
+ } });
3666
+ Object.defineProperty(exports2, "SignerMismatchError", { enumerable: true, get: function() {
3667
+ return errors_js_1.SignerMismatchError;
3668
+ } });
3669
+ var signer_js_1 = require_signer();
3670
+ Object.defineProperty(exports2, "localKeySigner", { enumerable: true, get: function() {
3671
+ return signer_js_1.localKeySigner;
3672
+ } });
3673
+ }
3674
+ });
3675
+
3676
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/allowance.js
3677
+ var require_allowance = __commonJS({
3678
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/allowance.js"(exports2) {
3679
+ "use strict";
3680
+ Object.defineProperty(exports2, "__esModule", { value: true });
3681
+ exports2.UNLIMITED_APPROVAL_FLOOR = exports2.UNLIMITED_APPROVAL = void 0;
3682
+ exports2.isAllowanceSufficient = isAllowanceSufficient;
3683
+ exports2.effectiveRequirement = effectiveRequirement;
3684
+ exports2.resolveApprovalAmount = resolveApprovalAmount;
3685
+ var ethers_1 = require("ethers");
3686
+ exports2.UNLIMITED_APPROVAL = ethers_1.MaxUint256;
3687
+ exports2.UNLIMITED_APPROVAL_FLOOR = ethers_1.MaxUint256 / 2n;
3688
+ function isAllowanceSufficient(current, requiredAllowance) {
3689
+ return requiredAllowance !== void 0 ? current >= requiredAllowance : current >= exports2.UNLIMITED_APPROVAL_FLOOR;
3690
+ }
3691
+ function effectiveRequirement(requiredAllowance, approvalAmount) {
3692
+ return requiredAllowance ?? approvalAmount;
3693
+ }
3694
+ function resolveApprovalAmount(approvalAmount, requiredAllowance) {
3695
+ if (approvalAmount === void 0)
3696
+ return exports2.UNLIMITED_APPROVAL;
3697
+ if (approvalAmount <= 0n) {
3698
+ throw new Error(`token_approval: approvalAmount must be positive, got ${approvalAmount}`);
3699
+ }
3700
+ if (requiredAllowance !== void 0 && approvalAmount < requiredAllowance) {
3701
+ throw new Error(`token_approval: approvalAmount ${approvalAmount} is below requiredAllowance ${requiredAllowance}, so the approval would still fall short and every call would send another one`);
3702
+ }
3703
+ return approvalAmount;
3704
+ }
3705
+ }
3706
+ });
3707
+
3708
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/unconfirmed.js
3709
+ var require_unconfirmed = __commonJS({
3710
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/unconfirmed.js"(exports2) {
3711
+ "use strict";
3712
+ Object.defineProperty(exports2, "__esModule", { value: true });
3713
+ exports2.unconfirmed = unconfirmed;
3714
+ exports2.isUnconfirmed = isUnconfirmed2;
3715
+ function unconfirmed(message) {
3716
+ return Object.assign(new Error(message), { unconfirmed: true });
3717
+ }
3718
+ function isUnconfirmed2(error) {
3719
+ return error?.unconfirmed === true;
3720
+ }
3721
+ }
3722
+ });
3723
+
3724
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/evm.js
3725
+ var require_evm2 = __commonJS({
3726
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/evm.js"(exports2) {
3727
+ "use strict";
3728
+ Object.defineProperty(exports2, "__esModule", { value: true });
3729
+ exports2.evmAdapter = exports2.ERC20_ALLOWANCE_ABI = void 0;
3730
+ var ethers_1 = require("ethers");
3731
+ var evm_escrow_encoding_1 = require_dist3();
3732
+ var unconfirmed_js_1 = require_unconfirmed();
3733
+ exports2.ERC20_ALLOWANCE_ABI = [
3734
+ "function allowance(address owner, address spender) view returns (uint256)",
3735
+ "function approve(address spender, uint256 amount) returns (bool)"
3736
+ ];
3737
+ var DEFAULT_CONFIRMATION_TIMEOUT_MS = 6e4;
3738
+ function requireSigner(params) {
3739
+ if (!params.signer) {
3740
+ throw new Error(`token_approval: approving on ${params.network} needs an ethers signer connected to that chain (params.signer)`);
3741
+ }
3742
+ return params.signer;
3743
+ }
3744
+ function erc20(params) {
3745
+ return new ethers_1.Contract(params.token, exports2.ERC20_ALLOWANCE_ABI, requireSigner(params));
3746
+ }
3747
+ async function send(params, call, purpose) {
3748
+ const tx = await call;
3749
+ params.onSubmitted?.(tx.hash, purpose);
3750
+ const timeoutMs = params.confirmation?.timeoutMs ?? DEFAULT_CONFIRMATION_TIMEOUT_MS;
3751
+ try {
3752
+ await tx.wait(1, timeoutMs);
3753
+ } catch (error) {
3754
+ if (isTimeout(error)) {
3755
+ throw (0, unconfirmed_js_1.unconfirmed)(`token_approval: the ${purpose === "reset" ? "allowance reset" : "approval"} ${tx.hash} was not confirmed within ${timeoutMs}ms. It may still confirm \u2014 check the transaction before approving again.`);
3756
+ }
3757
+ throw error;
3758
+ }
3759
+ return tx.hash;
3760
+ }
3761
+ function isTimeout(error) {
3762
+ return error?.code === "TIMEOUT";
3763
+ }
3764
+ exports2.evmAdapter = {
3765
+ applicable: true,
3766
+ resolveSpender(params) {
3767
+ return params.spender ?? evm_escrow_encoding_1.PERMIT2_CONTRACT_ADDRESS;
3768
+ },
3769
+ async senderAddress(params) {
3770
+ return await requireSigner(params).getAddress();
3771
+ },
3772
+ async readAllowance(params, spender) {
3773
+ return await erc20(params).allowance(params.owner, spender);
3774
+ },
3775
+ async approve(params, spender, amount, current) {
3776
+ const token = erc20(params);
3777
+ if (current !== 0n && await refusesOverwrite(params, token, spender, amount)) {
3778
+ const nonce = await requireSigner(params).getNonce("pending");
3779
+ const resetTxHash = await send(params, token.approve(spender, 0n, { nonce }), "reset");
3780
+ try {
3781
+ return {
3782
+ txHash: await send(params, token.approve(spender, amount, { nonce: nonce + 1 }), "approval"),
3783
+ resetTxHash
3784
+ };
3785
+ } catch (error) {
3786
+ const detail = error instanceof Error ? error.message : String(error);
3787
+ if ((0, unconfirmed_js_1.isUnconfirmed)(error)) {
3788
+ throw (0, unconfirmed_js_1.unconfirmed)(`token_approval: the allowance was reset to 0 in ${resetTxHash} and the new approval was broadcast but not confirmed (${detail}). If it lands the allowance is ${amount}; if it does not, it stays 0. Check that transaction before approving again.`);
3789
+ }
3790
+ throw new Error(`token_approval: the allowance was reset to 0 in ${resetTxHash}, but the new approval did not go through (${detail}). The allowance is currently 0 \u2014 re-run to finish.`);
3791
+ }
3792
+ }
3793
+ return { txHash: await send(params, token.approve(spender, amount), "approval") };
3794
+ }
3795
+ };
3796
+ async function refusesOverwrite(params, token, spender, amount) {
3797
+ const data = token.interface.encodeFunctionData("approve", [spender, amount]);
3798
+ try {
3799
+ await requireSigner(params).call({ to: params.token, data });
3800
+ return false;
3801
+ } catch (error) {
3802
+ if (isRevert(error))
3803
+ return true;
3804
+ throw error;
3805
+ }
3806
+ }
3807
+ function isRevert(error) {
3808
+ return error?.code === "CALL_EXCEPTION";
3809
+ }
3810
+ }
3811
+ });
3812
+
3813
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/tron.js
3814
+ var require_tron2 = __commonJS({
3815
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/tron.js"(exports2) {
3816
+ "use strict";
3817
+ Object.defineProperty(exports2, "__esModule", { value: true });
3818
+ exports2.tronAdapter = exports2.TRC20_ALLOWANCE_ABI = void 0;
3819
+ var payment_request_sender_auth_1 = require_dist5();
3820
+ var unconfirmed_js_1 = require_unconfirmed();
3821
+ exports2.TRC20_ALLOWANCE_ABI = [
3822
+ {
3823
+ name: "allowance",
3824
+ type: "function",
3825
+ stateMutability: "View",
3826
+ inputs: [
3827
+ { name: "owner", type: "address" },
3828
+ { name: "spender", type: "address" }
3829
+ ],
3830
+ outputs: [{ type: "uint256" }]
3831
+ },
3832
+ {
3833
+ name: "approve",
3834
+ type: "function",
3835
+ stateMutability: "Nonpayable",
3836
+ inputs: [
3837
+ { name: "spender", type: "address" },
3838
+ { name: "amount", type: "uint256" }
3839
+ ],
3840
+ outputs: [{ type: "bool" }]
3841
+ }
3842
+ ];
3843
+ var DEFAULT_FEE_LIMIT = 1e8;
3844
+ var DEFAULT_CONFIRMATION_TIMEOUT_MS = 6e4;
3845
+ var DEFAULT_POLL_INTERVAL_MS2 = 1500;
3846
+ function requireTronWeb(params) {
3847
+ if (!params.tronWeb) {
3848
+ throw new Error(`token_approval: approving on ${params.network} needs a TronWeb instance configured for that chain (params.tronWeb)`);
3849
+ }
3850
+ return params.tronWeb;
3851
+ }
3852
+ function token(params) {
3853
+ return requireTronWeb(params).contract(exports2.TRC20_ALLOWANCE_ABI, params.token);
3854
+ }
3855
+ var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
3856
+ async function waitForConfirmation(tronWeb, txId, options) {
3857
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_CONFIRMATION_TIMEOUT_MS;
3858
+ const pollIntervalMs = options?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS2;
3859
+ const deadline = Date.now() + timeoutMs;
3860
+ for (; ; ) {
3861
+ let result;
3862
+ try {
3863
+ result = (await tronWeb.trx.getTransactionInfo(txId))?.receipt?.result;
3864
+ } catch {
3865
+ }
3866
+ if (result === "SUCCESS")
3867
+ return;
3868
+ if (result !== void 0) {
3869
+ throw new Error(`token_approval: Tron approval ${txId} failed on-chain (${result})`);
3870
+ }
3871
+ if (Date.now() >= deadline) {
3872
+ throw (0, unconfirmed_js_1.unconfirmed)(`token_approval: Tron approval ${txId} was not confirmed within ${timeoutMs}ms. It may still confirm \u2014 check the transaction before approving again.`);
3873
+ }
3874
+ await sleep(pollIntervalMs);
3875
+ }
3876
+ }
3877
+ async function send(params, contract, spender, amount, purpose) {
3878
+ const txId = await contract.approve(spender, amount.toString()).send({ feeLimit: params.confirmation?.feeLimit ?? DEFAULT_FEE_LIMIT });
3879
+ params.onSubmitted?.(txId, purpose);
3880
+ await waitForConfirmation(requireTronWeb(params), txId, params.confirmation);
3881
+ return txId;
3882
+ }
3883
+ exports2.tronAdapter = {
3884
+ applicable: true,
3885
+ resolveSpender(params) {
3886
+ return params.spender ?? (0, payment_request_sender_auth_1.resolveTronPermit2)(params.network);
3887
+ },
3888
+ async senderAddress(params) {
3889
+ return requireTronWeb(params).defaultAddress?.base58 || void 0;
3890
+ },
3891
+ async readAllowance(params, spender) {
3892
+ const raw = await token(params).allowance(params.owner, spender).call();
3893
+ return BigInt(String(raw));
3894
+ },
3895
+ async approve(params, spender, amount, current) {
3896
+ const contract = token(params);
3897
+ try {
3898
+ return { txHash: await send(params, contract, spender, amount, "approval") };
3899
+ } catch (error) {
3900
+ if (current === 0n || (0, unconfirmed_js_1.isUnconfirmed)(error))
3901
+ throw error;
3902
+ throw new Error(`token_approval: the approval on ${params.network} failed while an allowance of ${current} was already set (${error instanceof Error ? error.message : String(error)}). Some tokens refuse to replace a non-zero allowance in place: approve 0 first, then retry.`);
3903
+ }
3904
+ }
3905
+ };
3906
+ }
3907
+ });
3908
+
3909
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/solana.js
3910
+ var require_solana2 = __commonJS({
3911
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/solana.js"(exports2) {
3912
+ "use strict";
3913
+ Object.defineProperty(exports2, "__esModule", { value: true });
3914
+ exports2.solanaAdapter = void 0;
3915
+ exports2.solanaAdapter = {
3916
+ applicable: false,
3917
+ resolveSpender() {
3918
+ throw new Error("token_approval: Solana does not use a Permit2-style allowance");
3919
+ },
3920
+ async senderAddress() {
3921
+ throw new Error("token_approval: Solana does not use a Permit2-style allowance");
3922
+ },
3923
+ async readAllowance() {
3924
+ throw new Error("token_approval: Solana does not use a Permit2-style allowance");
3925
+ },
3926
+ async approve() {
3927
+ throw new Error("token_approval: Solana does not use a Permit2-style allowance");
3928
+ }
3929
+ };
3930
+ }
3931
+ });
3932
+
3933
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/index.js
3934
+ var require_adapters2 = __commonJS({
3935
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/index.js"(exports2) {
3936
+ "use strict";
3937
+ Object.defineProperty(exports2, "__esModule", { value: true });
3938
+ exports2.approvalAdapterFor = approvalAdapterFor;
3939
+ var payment_request_sender_auth_1 = require_dist5();
3940
+ var evm_js_1 = require_evm2();
3941
+ var tron_js_1 = require_tron2();
3942
+ var solana_js_1 = require_solana2();
3943
+ var ADAPTERS = {
3944
+ eip155: evm_js_1.evmAdapter,
3945
+ tron: tron_js_1.tronAdapter,
3946
+ solana: solana_js_1.solanaAdapter
3947
+ };
3948
+ function approvalAdapterFor(network) {
3949
+ const namespace = (0, payment_request_sender_auth_1.namespaceOf)(network);
3950
+ const adapter = Object.hasOwn(ADAPTERS, namespace) ? ADAPTERS[namespace] : void 0;
3951
+ if (!adapter) {
3952
+ throw new Error(`token_approval: no approval adapter for network '${network}'`);
3953
+ }
3954
+ return adapter;
2391
3955
  }
2392
3956
  }
2393
3957
  });
2394
3958
 
2395
- // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/signer.js
2396
- var require_signer = __commonJS({
2397
- "../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/signer.js"(exports2) {
3959
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/sender.js
3960
+ var require_sender = __commonJS({
3961
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/sender.js"(exports2) {
2398
3962
  "use strict";
2399
3963
  Object.defineProperty(exports2, "__esModule", { value: true });
2400
- exports2.localKeySigner = localKeySigner2;
2401
- var index_js_1 = require_adapters();
2402
- function localKeySigner2(network, privateKey) {
2403
- const adapter = (0, index_js_1.getChainAdapter)(network);
2404
- return {
2405
- async sign(signedMessage) {
2406
- const signature = await adapter.sign(signedMessage, privateKey);
2407
- const delegateSigner = adapter.deriveDelegateSigner?.(privateKey);
2408
- return delegateSigner !== void 0 ? { signature, delegateSigner } : { signature };
2409
- }
2410
- };
3964
+ exports2.assertSenderIsOwner = assertSenderIsOwner;
3965
+ function assertSenderIsOwner(owner, sender) {
3966
+ if (sender === void 0 || sender.toLowerCase() === owner.toLowerCase())
3967
+ return;
3968
+ throw new Error(`token_approval: the approval would be sent by ${sender}, but the allowance is being granted for ${owner}. An approval only ever applies to the account that sends it, so this would approve ${sender} and leave ${owner} unable to pay. Pass a signer for ${owner}, or read the allowance for ${sender}.`);
2411
3969
  }
2412
3970
  }
2413
3971
  });
2414
3972
 
2415
- // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/index.js
2416
- var require_dist4 = __commonJS({
2417
- "../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/index.js"(exports2) {
3973
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/index.js
3974
+ var require_dist6 = __commonJS({
3975
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/index.js"(exports2) {
2418
3976
  "use strict";
2419
- var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
2420
- if (k2 === void 0) k2 = k;
2421
- var desc = Object.getOwnPropertyDescriptor(m, k);
2422
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
2423
- desc = { enumerable: true, get: function() {
2424
- return m[k];
2425
- } };
2426
- }
2427
- Object.defineProperty(o, k2, desc);
2428
- }) : (function(o, m, k, k2) {
2429
- if (k2 === void 0) k2 = k;
2430
- o[k2] = m[k];
2431
- }));
2432
- var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
2433
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
2434
- };
2435
3977
  Object.defineProperty(exports2, "__esModule", { value: true });
2436
- exports2.localKeySigner = exports2.SignerMismatchError = exports2.RecoveryFailedError = exports2.MalformedPrehashError = exports2.verifyPaymentRequest = exports2.getChainAdapter = void 0;
2437
- __exportStar(require_types(), exports2);
2438
- __exportStar(require_utils(), exports2);
2439
- __exportStar(require_chain_id2(), exports2);
2440
- var index_js_1 = require_adapters();
2441
- Object.defineProperty(exports2, "getChainAdapter", { enumerable: true, get: function() {
2442
- return index_js_1.getChainAdapter;
3978
+ exports2.approvalAdapterFor = exports2.isUnconfirmed = exports2.assertSenderIsOwner = exports2.resolveApprovalAmount = exports2.isAllowanceSufficient = exports2.effectiveRequirement = exports2.UNLIMITED_APPROVAL_FLOOR = exports2.UNLIMITED_APPROVAL = void 0;
3979
+ exports2.needsSourceApproval = needsSourceApproval2;
3980
+ exports2.ensureSourceApproval = ensureSourceApproval2;
3981
+ var allowance_js_1 = require_allowance();
3982
+ var index_js_1 = require_adapters2();
3983
+ var sender_js_1 = require_sender();
3984
+ var allowance_js_2 = require_allowance();
3985
+ Object.defineProperty(exports2, "UNLIMITED_APPROVAL", { enumerable: true, get: function() {
3986
+ return allowance_js_2.UNLIMITED_APPROVAL;
2443
3987
  } });
2444
- var verify_js_1 = require_verify();
2445
- Object.defineProperty(exports2, "verifyPaymentRequest", { enumerable: true, get: function() {
2446
- return verify_js_1.verifyPaymentRequest;
3988
+ Object.defineProperty(exports2, "UNLIMITED_APPROVAL_FLOOR", { enumerable: true, get: function() {
3989
+ return allowance_js_2.UNLIMITED_APPROVAL_FLOOR;
2447
3990
  } });
2448
- var errors_js_1 = require_errors();
2449
- Object.defineProperty(exports2, "MalformedPrehashError", { enumerable: true, get: function() {
2450
- return errors_js_1.MalformedPrehashError;
3991
+ Object.defineProperty(exports2, "effectiveRequirement", { enumerable: true, get: function() {
3992
+ return allowance_js_2.effectiveRequirement;
2451
3993
  } });
2452
- Object.defineProperty(exports2, "RecoveryFailedError", { enumerable: true, get: function() {
2453
- return errors_js_1.RecoveryFailedError;
3994
+ Object.defineProperty(exports2, "isAllowanceSufficient", { enumerable: true, get: function() {
3995
+ return allowance_js_2.isAllowanceSufficient;
2454
3996
  } });
2455
- Object.defineProperty(exports2, "SignerMismatchError", { enumerable: true, get: function() {
2456
- return errors_js_1.SignerMismatchError;
3997
+ Object.defineProperty(exports2, "resolveApprovalAmount", { enumerable: true, get: function() {
3998
+ return allowance_js_2.resolveApprovalAmount;
2457
3999
  } });
2458
- var signer_js_1 = require_signer();
2459
- Object.defineProperty(exports2, "localKeySigner", { enumerable: true, get: function() {
2460
- return signer_js_1.localKeySigner;
4000
+ var sender_js_2 = require_sender();
4001
+ Object.defineProperty(exports2, "assertSenderIsOwner", { enumerable: true, get: function() {
4002
+ return sender_js_2.assertSenderIsOwner;
2461
4003
  } });
4004
+ var unconfirmed_js_1 = require_unconfirmed();
4005
+ Object.defineProperty(exports2, "isUnconfirmed", { enumerable: true, get: function() {
4006
+ return unconfirmed_js_1.isUnconfirmed;
4007
+ } });
4008
+ var index_js_2 = require_adapters2();
4009
+ Object.defineProperty(exports2, "approvalAdapterFor", { enumerable: true, get: function() {
4010
+ return index_js_2.approvalAdapterFor;
4011
+ } });
4012
+ async function needsSourceApproval2(params) {
4013
+ const adapter = (0, index_js_1.approvalAdapterFor)(params.network);
4014
+ if (!adapter.applicable)
4015
+ return false;
4016
+ const required = (0, allowance_js_1.effectiveRequirement)(params.requiredAllowance, params.approvalAmount);
4017
+ (0, allowance_js_1.resolveApprovalAmount)(params.approvalAmount, required);
4018
+ const spender = adapter.resolveSpender(params);
4019
+ const current = await adapter.readAllowance(params, spender);
4020
+ return !(0, allowance_js_1.isAllowanceSufficient)(current, required);
4021
+ }
4022
+ async function ensureSourceApproval2(params) {
4023
+ const adapter = (0, index_js_1.approvalAdapterFor)(params.network);
4024
+ if (!adapter.applicable)
4025
+ return { alreadySufficient: true };
4026
+ const required = (0, allowance_js_1.effectiveRequirement)(params.requiredAllowance, params.approvalAmount);
4027
+ const amount = (0, allowance_js_1.resolveApprovalAmount)(params.approvalAmount, required);
4028
+ const spender = adapter.resolveSpender(params);
4029
+ const current = await adapter.readAllowance(params, spender);
4030
+ if ((0, allowance_js_1.isAllowanceSufficient)(current, required)) {
4031
+ return { alreadySufficient: true };
4032
+ }
4033
+ (0, sender_js_1.assertSenderIsOwner)(params.owner, await adapter.senderAddress(params));
4034
+ return { alreadySufficient: false, ...await adapter.approve(params, spender, amount, current) };
4035
+ }
4036
+ }
4037
+ });
4038
+
4039
+ // src/signers/pinned-address.ts
4040
+ var init_pinned_address = __esm({
4041
+ "src/signers/pinned-address.ts"() {
4042
+ "use strict";
2462
4043
  }
2463
4044
  });
2464
4045
 
@@ -2940,7 +4521,7 @@ payment.
2940
4521
  `,
2941
4522
  413: "Payment request too large to process",
2942
4523
  500: "Internal server error",
2943
- 503: "A dependency is temporarily unavailable"
4524
+ 503: "The request was not accepted: a dependency is temporarily unavailable, or this operation is paused (`SERVICE_PAUSED`). Nothing was submitted, so the request is safe to retry."
2944
4525
  }
2945
4526
  });
2946
4527
  }
@@ -3025,6 +4606,9 @@ payment.
3025
4606
  *
3026
4607
  * The response includes everything needed to sign and submit a payment, except the signature itself.
3027
4608
  *
4609
+ * Not available on every gateway or every source chain; where it is not, this
4610
+ * returns `501`. Sign the returned request and submit it to `POST /v1/payments`.
4611
+ *
3028
4612
  * @param data The data for the request.
3029
4613
  * @param data.requestBody
3030
4614
  * @returns PreparePaymentResponse Payment request prepared successfully
@@ -3071,11 +4655,30 @@ var AuthorizationsService = class {
3071
4655
  body: data.requestBody,
3072
4656
  mediaType: "application/json",
3073
4657
  errors: {
3074
- 400: "Invalid payment request",
3075
- 404: "Counterparty not found (no registration for the resolved DID)",
3076
- 500: "Internal server error",
3077
- 502: "Counterparty webhook error (HTTP error or connection failure)",
3078
- 504: "Authorization timed out (counterparty did not respond)"
4658
+ 400: `The request was rejected before authorization was attempted, so no
4659
+ authorization outcome exists.
4660
+ `,
4661
+ 401: `The counterparty's proof was rejected (\`PROOF_INVALID\` or \`PROOF_STALE\`).
4662
+ This is an authorization outcome, so the body is an \`AuthorizationResult\`
4663
+ with \`status: error\`.
4664
+ `,
4665
+ 404: `Counterparty not found (no registration for the resolved DID). An
4666
+ authorization outcome, so the body is an \`AuthorizationResult\` with
4667
+ \`status: error\` and \`error_code: COUNTERPARTY_NOT_FOUND\`.
4668
+ `,
4669
+ 500: `Either shape, depending on where the failure happened. A failure before
4670
+ authorization was attempted returns \`ErrorResponse\`. A failure carrying an
4671
+ authorization outcome returns \`AuthorizationResult\` with \`status: error\`.
4672
+ `,
4673
+ 502: `Counterparty webhook error (HTTP error or connection failure). An
4674
+ authorization outcome, so the body is an \`AuthorizationResult\` with
4675
+ \`status: error\` and \`error_code: WEBHOOK_ERROR\` or
4676
+ \`WEBHOOK_CONNECTION_ERROR\`.
4677
+ `,
4678
+ 504: `Authorization timed out (the counterparty did not respond). An
4679
+ authorization outcome, so the body is an \`AuthorizationResult\` with
4680
+ \`status: timeout\`.
4681
+ `
3079
4682
  }
3080
4683
  });
3081
4684
  }
@@ -3102,6 +4705,31 @@ var QuoteRequestsService = class {
3102
4705
  * Collection continues server-side until the quote deadline regardless of the HTTP
3103
4706
  * connection, so quotes remain retrievable via the status endpoint in either mode.
3104
4707
  *
4708
+ * **Idempotency.** `request_id` is the idempotency key, scoped to the source account
4709
+ * and originator — the same key, and the same contract, as POST /v1/payments.
4710
+ * Submitting the same `request_id` again returns the ORIGINAL batch instead of opening
4711
+ * a second one, so a client whose request timed out or failed in transit can safely
4712
+ * re-submit and recover its `quote_request_id`.
4713
+ *
4714
+ * Because a re-submission must be admissible on its own, some fields legitimately
4715
+ * differ between attempts and are excluded from the comparison: `quote_deadline` and
4716
+ * `fulfillment_deadline` (both must be in the future, so a later attempt has to move
4717
+ * them) and the `proof` that covers them. An expired `quote_deadline` on a
4718
+ * re-submission is NOT an error — the request is resolved onto the batch that already
4719
+ * exists rather than used to open one. There is no `sender_auth` to re-sign here: this
4720
+ * endpoint rejects it, because the spend authorization belongs to the award call.
4721
+ *
4722
+ * The collection window belongs to the BATCH, not to the request. Asking again with a
4723
+ * later `quote_deadline` does not extend a window already open; `quote_deadline` in the
4724
+ * response is the batch's own, and `status` says whether collection is still running.
4725
+ *
4726
+ * What must NOT differ is the corridor's economics — source account and asset,
4727
+ * destination accounts and assets, `fulfillment_amount`, and `max_source_amount`.
4728
+ * Re-using one `request_id` for a genuinely different corridor is a client bug that
4729
+ * would otherwise be silently collapsed onto the first batch, returning quotes for a
4730
+ * corridor that was never requested. It is rejected with `409` and
4731
+ * `IDEMPOTENCY_TERMS_MISMATCH`. Use a distinct `request_id` per quote-request.
4732
+ *
3105
4733
  * @param data The data for the request.
3106
4734
  * @param data.requestBody
3107
4735
  * @param data.wait Return a handle immediately (`false`, default) or hold the connection for collected quotes (`true`).
@@ -3121,8 +4749,19 @@ var QuoteRequestsService = class {
3121
4749
  body: data.requestBody,
3122
4750
  mediaType: "application/json",
3123
4751
  errors: {
3124
- 400: "Invalid request",
3125
- 500: "Internal server error"
4752
+ 400: `Invalid request. \`QUOTE_DEADLINE_NOT_FUTURE\` is the one worth planning for: a NEW
4753
+ quote-request whose \`quote_deadline\` has already passed is refused, because there is
4754
+ no window left to collect quotes in. It does not apply to a re-submission \u2014 an
4755
+ already-used \`request_id\` resolves onto the batch that exists and its expired
4756
+ deadline is ignored, which is what makes a retry recoverable.
4757
+ `,
4758
+ 409: `The \`request_id\` has already been used for a quote-request with different
4759
+ economics (\`IDEMPOTENCY_TERMS_MISMATCH\`). Re-submitting one \`request_id\` is how a
4760
+ retry is made safe, so it must identify one batch; use a distinct \`request_id\`
4761
+ per quote-request.
4762
+ `,
4763
+ 500: "Internal server error",
4764
+ 503: "The request was not accepted: a dependency is temporarily unavailable, or this operation is paused (`SERVICE_PAUSED`). Nothing was submitted, so the request is safe to retry."
3126
4765
  }
3127
4766
  });
3128
4767
  }
@@ -3205,6 +4844,43 @@ var QuoteRequestsService = class {
3205
4844
  });
3206
4845
  }
3207
4846
  };
4847
+ var ChainDefaultsService = class {
4848
+ constructor(httpRequest) {
4849
+ this.httpRequest = httpRequest;
4850
+ }
4851
+ /**
4852
+ * Get chain defaults
4853
+ * The addresses needed to build a payment on a chain: the escrow, the accounts named
4854
+ * in the deposit authorization, and the fulfillment verifier. Fetch these rather than
4855
+ * hardcoding them - they change when a chain's contracts are redeployed.
4856
+ *
4857
+ * With `chain_id`, returns that chain. Without it, or with an empty value, returns
4858
+ * every chain the gateway serves, keyed by CAIP-2 chain id.
4859
+ *
4860
+ * A chain that is not fully configured is still returned when asked for by
4861
+ * `chain_id`, with the missing address empty, but is left out of the full listing.
4862
+ * Treat an empty address as a chain you cannot pay on.
4863
+ *
4864
+ * @param data The data for the request.
4865
+ * @param data.chainId CAIP-2 chain identifier. Omit it, or send it empty, to receive every chain the gateway serves, keyed by chain id.
4866
+ * @returns GetDefaultsResult Chain defaults. A single object when `chain_id` was supplied, otherwise an object keyed by CAIP-2 chain id.
4867
+ * @throws ApiError
4868
+ */
4869
+ getDefaults(data = {}) {
4870
+ return this.httpRequest.request({
4871
+ method: "GET",
4872
+ url: "/v1/defaults",
4873
+ query: {
4874
+ chain_id: data.chainId
4875
+ },
4876
+ errors: {
4877
+ 400: "The `chain_id` is not a valid CAIP-2 chain identifier",
4878
+ 404: "The requested chain is not served by this gateway, or - when `chain_id` was omitted - no chain could be resolved at all",
4879
+ 503: "A dependency is temporarily unavailable"
4880
+ }
4881
+ });
4882
+ }
4883
+ };
3208
4884
  var HealthService = class {
3209
4885
  constructor(httpRequest) {
3210
4886
  this.httpRequest = httpRequest;
@@ -3242,19 +4918,140 @@ var PaymentGatewayClient = class {
3242
4918
  }
3243
4919
  });
3244
4920
  this.authorizations = new AuthorizationsService(this.request);
4921
+ this.chainDefaults = new ChainDefaultsService(this.request);
3245
4922
  this.health = new HealthService(this.request);
3246
4923
  this.payments = new PaymentsService(this.request);
3247
4924
  this.quoteRequests = new QuoteRequestsService(this.request);
3248
4925
  }
3249
4926
  };
3250
4927
 
4928
+ // src/timeout-http-request.ts
4929
+ var import_axios2 = __toESM(require("axios"));
4930
+
4931
+ // src/errors.ts
4932
+ var GatewayTimeoutError = class extends Error {
4933
+ constructor(baseUrl, timeoutMs) {
4934
+ super(
4935
+ `Gateway at ${baseUrl || "(same origin)"} did not respond within ${formatSeconds(timeoutMs)}`
4936
+ );
4937
+ this.baseUrl = baseUrl;
4938
+ this.timeoutMs = timeoutMs;
4939
+ this.name = "GatewayTimeoutError";
4940
+ }
4941
+ };
4942
+ function formatSeconds(ms) {
4943
+ const seconds = ms / 1e3;
4944
+ return `${Number.isInteger(seconds) ? seconds : seconds.toFixed(1)}s`;
4945
+ }
4946
+ function isGatewayTimeoutError(err) {
4947
+ return err instanceof GatewayTimeoutError;
4948
+ }
4949
+ function isApiError(err) {
4950
+ return err instanceof ApiError;
4951
+ }
4952
+
4953
+ // src/request-timeout.ts
4954
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
4955
+ var DEFAULT_SYNC_WAIT_TIMEOUT_MS = 12e4;
4956
+ var SYNC_HOLD_PATHS = ["/v1/payments", "/v1/payments/awards"];
4957
+ function pathOf(url) {
4958
+ if (!url) return "";
4959
+ const path = url.split("?")[0];
4960
+ const scheme = path.indexOf("://");
4961
+ if (scheme === -1) return path;
4962
+ const host = path.indexOf("/", scheme + 3);
4963
+ return host === -1 ? "" : path.slice(host);
4964
+ }
4965
+ function hasWaitTrueQuery(url) {
4966
+ const query = url?.indexOf("?") ?? -1;
4967
+ if (query === -1) return false;
4968
+ return new URLSearchParams(url.slice(query + 1)).get("wait") === "true";
4969
+ }
4970
+ function isSyncWaitRequest({ method, url, wait }) {
4971
+ if (wait === true || wait === "true" || hasWaitTrueQuery(url)) return true;
4972
+ if (method?.toUpperCase() !== "POST") return false;
4973
+ const path = pathOf(url);
4974
+ return SYNC_HOLD_PATHS.some((held) => path === held || path.endsWith(held));
4975
+ }
4976
+ function ordinaryTimeout(timeouts = {}) {
4977
+ return timeouts.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
4978
+ }
4979
+ function timeoutForRequest(request2, timeouts = {}) {
4980
+ return isSyncWaitRequest(request2) ? timeouts.syncWaitTimeoutMs ?? DEFAULT_SYNC_WAIT_TIMEOUT_MS : ordinaryTimeout(timeouts);
4981
+ }
4982
+ function applyRequestTimeout(timeouts = {}) {
4983
+ return (config2) => ({
4984
+ ...config2,
4985
+ timeout: config2.timeout ?? timeoutForRequest({ method: config2.method, url: config2.url }, timeouts)
4986
+ });
4987
+ }
4988
+ function isAxiosTimeout(error) {
4989
+ const failure = error;
4990
+ if (!failure) return false;
4991
+ if (failure.code === "ECONNABORTED" || failure.code === "ETIMEDOUT") return true;
4992
+ return failure.code === "ERR_BAD_RESPONSE" && /stream has been aborted/i.test(failure.message ?? "");
4993
+ }
4994
+ function dropPartialResponseOnTimeout(error) {
4995
+ if (isAxiosTimeout(error) && error !== null && typeof error === "object" && "response" in error) {
4996
+ delete error.response;
4997
+ }
4998
+ return error;
4999
+ }
5000
+ function translateTimeout(error, baseUrl, fallbackTimeoutMs) {
5001
+ if (!isAxiosTimeout(error)) return error;
5002
+ const configured = error.config?.timeout;
5003
+ return new GatewayTimeoutError(baseUrl, configured ?? fallbackTimeoutMs);
5004
+ }
5005
+
5006
+ // src/timeout-http-request.ts
5007
+ var timeoutAxios = import_axios2.default.create();
5008
+ timeoutAxios.interceptors.response.use(
5009
+ void 0,
5010
+ (error) => Promise.reject(dropPartialResponseOnTimeout(error))
5011
+ );
5012
+ function withRequestTimeout(config2, timeouts) {
5013
+ const request2 = new Interceptors();
5014
+ for (const fn of config2?.interceptors?.request?._fns ?? []) request2.use(fn);
5015
+ request2.use(applyRequestTimeout(timeouts));
5016
+ return {
5017
+ interceptors: { request: request2, response: config2?.interceptors?.response ?? new Interceptors() }
5018
+ };
5019
+ }
5020
+ var TimeoutHttpRequest = class extends AxiosHttpRequest {
5021
+ constructor(config2, timeouts = {}) {
5022
+ super(config2);
5023
+ this.timeouts = timeouts;
5024
+ }
5025
+ request(options) {
5026
+ return new CancelablePromise((resolve2, reject, onCancel) => {
5027
+ const pending = request(this.config, options, timeoutAxios);
5028
+ onCancel(() => pending.cancel());
5029
+ pending.then(resolve2, (error) => {
5030
+ const request2 = { method: options.method, url: options.url, wait: options.query?.wait };
5031
+ reject(
5032
+ translateTimeout(error, this.config.BASE, timeoutForRequest(request2, this.timeouts))
5033
+ );
5034
+ });
5035
+ });
5036
+ }
5037
+ };
5038
+ function timeoutHttpRequest(timeouts) {
5039
+ return class extends TimeoutHttpRequest {
5040
+ constructor(config2) {
5041
+ super(config2, timeouts);
5042
+ }
5043
+ };
5044
+ }
5045
+
3251
5046
  // src/chain-adapters/evm.ts
3252
5047
  var import_ethers = require("ethers");
3253
5048
 
3254
5049
  // src/chain-adapters/types.ts
3255
5050
  function assertKeyMatchesSender(matches, sender, derived) {
3256
5051
  if (!matches) {
3257
- throw new Error(`The private key derives ${derived}, which does not match the sender address ${sender}`);
5052
+ throw new Error(
5053
+ `The private key derives ${derived}, which does not match the sender address ${sender}`
5054
+ );
3258
5055
  }
3259
5056
  }
3260
5057
 
@@ -3306,10 +5103,9 @@ var tronAdapter = {
3306
5103
  throw new Error("Invalid private key");
3307
5104
  }
3308
5105
  },
3309
- // Tron addresses are the same secp256k1-derived 20 bytes as EVM. Compare the
3310
- // derived hex directly against the canonical sender; do NOT run normalizeAddress
3311
- // on the derived side — it strips a leading 41, which would corrupt an address
3312
- // whose first byte is 0x41.
5106
+ // Tron addresses are the same secp256k1-derived 20 bytes as EVM. The derived
5107
+ // address is already canonical 20-byte hex, so only the sender side — which
5108
+ // arrives in whichever spelling the caller chose — needs normalizing.
3313
5109
  verifyAddressMatchesKey(privateKey, address) {
3314
5110
  const key = privateKey.startsWith("0x") ? privateKey : "0x" + privateKey;
3315
5111
  const derived = new import_ethers2.ethers.Wallet(key).address;
@@ -3348,22 +5144,133 @@ function secretKeyFromPrivate(privateKey) {
3348
5144
  if (decoded.length === 32) {
3349
5145
  return import_tweetnacl.default.sign.keyPair.fromSeed(decoded).secretKey;
3350
5146
  }
3351
- throw new Error(`Invalid Solana private key length: expected 32 or 64 bytes, got ${decoded.length}`);
5147
+ throw new Error(
5148
+ `Invalid Solana private key length: expected 32 or 64 bytes, got ${decoded.length}`
5149
+ );
3352
5150
  }
3353
5151
 
3354
5152
  // src/chain-adapters/index.ts
3355
5153
  var adapters = {
3356
- "eip155": evmAdapter,
3357
- "tron": tronAdapter,
3358
- "solana": solanaAdapter
5154
+ eip155: evmAdapter,
5155
+ tron: tronAdapter,
5156
+ solana: solanaAdapter
3359
5157
  };
3360
5158
  function getChainAdapter(sourceChainId) {
3361
- const prefix = sourceChainId.split(":")[0];
5159
+ const prefix = sourceChainId.split(":")[0]?.toLowerCase() ?? "";
3362
5160
  const adapter = adapters[prefix];
3363
5161
  if (!adapter) throw new Error(`Unsupported source chain: ${sourceChainId}`);
3364
5162
  return adapter;
3365
5163
  }
3366
5164
 
5165
+ // src/asset-identifier.ts
5166
+ var import_ethers3 = require("ethers");
5167
+ var SHAPE_EXAMPLE = "eip155:421614/erc20:0x...";
5168
+ var NAMESPACE = /^[a-z0-9]+$/;
5169
+ var CHAIN_REFERENCE = /^[a-zA-Z0-9_-]+$/;
5170
+ var ASSET_NAMESPACE = /^[a-z0-9-]{3,8}$/;
5171
+ var ASSET_REFERENCE = /^[-.%a-zA-Z0-9]{1,128}$/;
5172
+ var TOKEN_ID = /^[-.%a-zA-Z0-9]{1,78}$/;
5173
+ var EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
5174
+ var EIP155_REFERENCE = /^[0-9]+$/;
5175
+ var HEX_REFERENCE = /^0[xX][0-9a-fA-F]{1,16}$/;
5176
+ var MAX_ECHO = 120;
5177
+ var MAX_REFERENCE_ECHO = 32;
5178
+ function parseAssetIdentifier(value) {
5179
+ if (typeof value !== "string" || value === "") {
5180
+ throw new Error(shapeError(value));
5181
+ }
5182
+ const firstSlash = value.indexOf("/");
5183
+ if (firstSlash === -1) {
5184
+ throw new Error(shapeError(value));
5185
+ }
5186
+ const chainSegments = value.slice(0, firstSlash).split(":");
5187
+ if (chainSegments.length !== 2) {
5188
+ throw new Error(shapeError(value));
5189
+ }
5190
+ const namespace = chainSegments[0].toLowerCase();
5191
+ const reference = namespace === "tron" ? chainSegments[1].toLowerCase() : chainSegments[1];
5192
+ if (!NAMESPACE.test(namespace) || !CHAIN_REFERENCE.test(reference)) {
5193
+ throw new Error(shapeError(value));
5194
+ }
5195
+ if (namespace === "eip155" && !EIP155_REFERENCE.test(reference)) {
5196
+ throw new Error(eip155ReferenceError(reference, value));
5197
+ }
5198
+ const assetPart = value.slice(firstSlash + 1);
5199
+ const separator = assetPart.indexOf(":");
5200
+ if (separator === -1) {
5201
+ throw new Error(tokenAddressError(value));
5202
+ }
5203
+ const assetNamespace = assetPart.slice(0, separator).toLowerCase();
5204
+ const rest = assetPart.slice(separator + 1);
5205
+ const referenceSlash = rest.indexOf("/");
5206
+ const tokenAddress = referenceSlash === -1 ? rest : rest.slice(0, referenceSlash);
5207
+ const tokenId = referenceSlash === -1 ? void 0 : rest.slice(referenceSlash + 1);
5208
+ if (!ASSET_NAMESPACE.test(assetNamespace)) {
5209
+ throw new Error(tokenAddressError(value));
5210
+ }
5211
+ if (assetNamespace === "slip44") {
5212
+ throw new Error(nativeAssetError(value));
5213
+ }
5214
+ if (!ASSET_REFERENCE.test(tokenAddress)) {
5215
+ throw new Error(tokenAddressError(value));
5216
+ }
5217
+ if (tokenId !== void 0 && !TOKEN_ID.test(tokenId)) {
5218
+ throw new Error(tokenAddressError(value));
5219
+ }
5220
+ assertTokenAddress(namespace, tokenAddress, value);
5221
+ const chainId = `${namespace}:${reference}`;
5222
+ return {
5223
+ chainId,
5224
+ namespace,
5225
+ reference,
5226
+ assetNamespace,
5227
+ tokenAddress,
5228
+ ...tokenId === void 0 ? {} : { tokenId },
5229
+ normalized: `${chainId}/${assetNamespace}:${tokenAddress}${tokenId === void 0 ? "" : `/${tokenId}`}`
5230
+ };
5231
+ }
5232
+ function assetChainId(value) {
5233
+ return parseAssetIdentifier(value).chainId;
5234
+ }
5235
+ function echo(value, limit = MAX_ECHO) {
5236
+ const shown = typeof value === "string" ? value : String(value);
5237
+ return shown.length > limit ? `${shown.slice(0, limit)}\u2026` : shown;
5238
+ }
5239
+ function shapeError(value) {
5240
+ return `Invalid asset identifier "${echo(value)}": expected CAIP-19 "<chain>/<type>:<address>", e.g. ${SHAPE_EXAMPLE}`;
5241
+ }
5242
+ function tokenAddressError(value) {
5243
+ return `Invalid token address in asset "${echo(value)}".`;
5244
+ }
5245
+ function eip155ReferenceError(reference, value) {
5246
+ const prefix = `Invalid eip155 chain id "${echo(reference, MAX_REFERENCE_ECHO)}" in asset "${echo(value)}"`;
5247
+ if (HEX_REFERENCE.test(reference)) {
5248
+ return `${prefix}: use the decimal chain id (${BigInt(reference)}), not hex.`;
5249
+ }
5250
+ return `${prefix}: an eip155 chain id is decimal, e.g. 421614.`;
5251
+ }
5252
+ function nativeAssetError(value) {
5253
+ return `Asset "${echo(value)}" is a native asset (slip44) and has no contract to deposit. Use the wrapped token's erc20 identifier.`;
5254
+ }
5255
+ function assertTokenAddress(namespace, tokenAddress, value) {
5256
+ if (namespace !== "eip155") return;
5257
+ if (!EVM_ADDRESS.test(tokenAddress)) {
5258
+ throw new Error(tokenAddressError(value));
5259
+ }
5260
+ const body = tokenAddress.slice(2);
5261
+ if (body === body.toLowerCase() || body === body.toUpperCase()) return;
5262
+ try {
5263
+ (0, import_ethers3.getAddress)(tokenAddress);
5264
+ } catch {
5265
+ throw new Error(
5266
+ `Token address "${tokenAddress}" has an invalid checksum. Fix the capitalization or use the all-lowercase form.`
5267
+ );
5268
+ }
5269
+ }
5270
+
5271
+ // src/index.ts
5272
+ var import_chain_address = __toESM(require_dist2());
5273
+
3367
5274
  // src/chain-adapters/solana-clock.ts
3368
5275
  var DEFAULT_SOLANA_RPC_URLS = {
3369
5276
  "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "https://api.mainnet-beta.solana.com",
@@ -3432,22 +5339,39 @@ async function resolveSolanaIssuedAt(opts) {
3432
5339
  }
3433
5340
 
3434
5341
  // src/index.ts
3435
- var import_payment_request_sender_auth2 = __toESM(require_dist4());
5342
+ var import_payment_request_sender_auth2 = __toESM(require_dist5());
5343
+ var import_chain_address2 = __toESM(require_dist2());
5344
+
5345
+ // src/payment-tracking.ts
5346
+ var DEFAULT_WAIT_SECONDS = 60;
5347
+ var DEFAULT_WAIT_BUDGET_MS = DEFAULT_WAIT_SECONDS * 1e3;
5348
+
5349
+ // src/index.ts
5350
+ var import_payment_request_token_approval = __toESM(require_dist6());
3436
5351
 
3437
5352
  // src/sender_auth_schemes/evm_permit2.ts
3438
- var import_ethers3 = require("ethers");
3439
- var import_evm_escrow_encoding = __toESM(require_dist2());
5353
+ var import_ethers4 = require("ethers");
5354
+ var import_evm_escrow_encoding = __toESM(require_dist3());
3440
5355
 
3441
5356
  // src/sender_auth_schemes/solana.ts
3442
- var import_ethers4 = require("ethers");
5357
+ var import_ethers5 = require("ethers");
3443
5358
  var import_bs582 = __toESM(require("bs58"));
3444
- var import_solana_escrow_encoding = __toESM(require_dist3());
5359
+ var import_solana_escrow_encoding = __toESM(require_dist4());
5360
+
5361
+ // src/signers/index.ts
5362
+ init_pinned_address();
3445
5363
 
3446
5364
  // src/signers/raw.ts
3447
- var import_payment_request_sender_auth = __toESM(require_dist4());
5365
+ var import_payment_request_sender_auth = __toESM(require_dist5());
5366
+
5367
+ // src/signers/turnkey.ts
5368
+ init_pinned_address();
3448
5369
 
3449
5370
  // src/index.ts
3450
5371
  var PAYMENT_REQUEST_VERSION = "1.0";
5372
+ function assertPayableAccount(assetIdentifier, account) {
5373
+ (0, import_chain_address.validate)(assetChainId(assetIdentifier), account);
5374
+ }
3451
5375
  var defaultGateway = "https://payment-gw.production-testnet.atum.xyz";
3452
5376
  var OpenAPI2 = { ...OpenAPI, BASE: defaultGateway };
3453
5377
  var DEFAULT_QUOTE_DEADLINE_SECONDS = 5;
@@ -3464,10 +5388,14 @@ function resolveDeadlines(params, defaultQuoteSeconds) {
3464
5388
  const quoteDeadlineSeconds = params.quoteDeadlineSeconds ?? defaultQuoteSeconds;
3465
5389
  const fulfillmentDeadlineSeconds = params.fulfillmentDeadlineSeconds ?? DEFAULT_FULFILLMENT_DEADLINE_SECONDS;
3466
5390
  if (!Number.isFinite(quoteDeadlineSeconds) || !Number.isFinite(fulfillmentDeadlineSeconds)) {
3467
- throw new Error("quoteDeadlineSeconds and fulfillmentDeadlineSeconds must be finite numbers of seconds.");
5391
+ throw new Error(
5392
+ "quoteDeadlineSeconds and fulfillmentDeadlineSeconds must be finite numbers of seconds."
5393
+ );
3468
5394
  }
3469
5395
  if (quoteDeadlineSeconds <= 0 || fulfillmentDeadlineSeconds <= 0) {
3470
- throw new Error("quoteDeadlineSeconds and fulfillmentDeadlineSeconds must be positive numbers of seconds.");
5396
+ throw new Error(
5397
+ "quoteDeadlineSeconds and fulfillmentDeadlineSeconds must be positive numbers of seconds."
5398
+ );
3471
5399
  }
3472
5400
  if (quoteDeadlineSeconds >= fulfillmentDeadlineSeconds) {
3473
5401
  throw new Error(
@@ -3480,18 +5408,67 @@ function resolveDeadlines(params, defaultQuoteSeconds) {
3480
5408
  fulfillment_deadline: new Date(now + fulfillmentDeadlineSeconds * 1e3).toISOString()
3481
5409
  };
3482
5410
  }
5411
+ function defaultsErrorDetail(error) {
5412
+ if (!isApiError(error)) {
5413
+ return error instanceof Error ? error.message : String(error);
5414
+ }
5415
+ const body = error.body;
5416
+ const parts = [];
5417
+ if (typeof body?.code === "string" && body.code.trim() !== "") parts.push(body.code);
5418
+ if (typeof body?.message === "string" && body.message.trim() !== "") parts.push(body.message);
5419
+ const requestId = typeof body?.request_id === "string" && body.request_id.trim() !== "" ? body.request_id : "";
5420
+ if (parts.length > 0) {
5421
+ return `${parts.join(": ")}${requestId === "" ? "" : ` (request_id=${requestId})`}`;
5422
+ }
5423
+ return error.statusText || `HTTP ${error.status}`;
5424
+ }
5425
+ function singleChainOf(response, chainId) {
5426
+ if (typeof response !== "object" || response === null) {
5427
+ throw new Error(
5428
+ `Failed to fetch defaults for chain ${chainId}: the gateway did not return a JSON object. Check that the configured base URL points at the payment gateway.`
5429
+ );
5430
+ }
5431
+ const single = response;
5432
+ if (typeof single.chain_id !== "string") {
5433
+ throw new Error(
5434
+ `Failed to fetch defaults for chain ${chainId}: the gateway answered with defaults for every chain rather than the one requested`
5435
+ );
5436
+ }
5437
+ if (single.chain_id.toLowerCase() !== chainId.toLowerCase()) {
5438
+ throw new Error(
5439
+ `Failed to fetch defaults for chain ${chainId}: the gateway answered with defaults for ` + single.chain_id
5440
+ );
5441
+ }
5442
+ return single;
5443
+ }
3483
5444
  async function assemblePaymentRequest(params) {
3484
- const sourceChainId = params.sourceAsset.split("/")[0];
3485
- const namespace = sourceChainId.split(":")[0];
5445
+ const source = parseAssetIdentifier(params.sourceAsset);
5446
+ const destination = parseAssetIdentifier(params.destinationAsset);
5447
+ const { chainId: sourceChainId, namespace } = source;
3486
5448
  const adapter = getChainAdapter(sourceChainId);
3487
5449
  const nonce = params.nonce ?? (namespace === "solana" ? (0, import_payment_request_sender_auth2.deterministicSolanaNonce)({ requestId: params.requestId, depositor: params.depositor }) : (0, import_payment_request_sender_auth2.deterministicPermitNonce)({ requestId: params.requestId, depositor: params.depositor }));
3488
5450
  const auth = await (0, import_payment_request_sender_auth2.getChainAdapter)(sourceChainId).buildAuthMessage({
3489
- sourceAsset: params.sourceAsset,
5451
+ // Canonicalized: the Tron adapter resolves its Permit2 address by exact chain-id key, so an
5452
+ // uppercase namespace would miss the lookup and fail inside the SDK.
5453
+ sourceAsset: source.normalized,
3490
5454
  depositor: params.depositor,
3491
5455
  // The gateway pins the signed deposit amount to max_source_amount (the cap).
3492
5456
  maxSourceAmount: params.maxSourceAmount,
3493
5457
  requestId: params.requestId,
3494
5458
  sourceDefaults: params.sourceDefaults,
5459
+ // The payee the deposit commits to. Passed as CAIP components, not a composed string:
5460
+ // the adapter composes it through the shared buildEscrowDestination so this producer
5461
+ // and the release signer cannot disagree by a byte. These are the SAME two values that
5462
+ // become paymentRequest.destination[0] below, so the signed commitment and the request
5463
+ // body cannot describe different payees.
5464
+ // Canonicalized for the same reason `sourceAsset` is, and additionally because the claim
5465
+ // three lines up has to be TRUE: destination[0] below carries `destination.normalized`, so
5466
+ // passing the raw string here would sign a commitment over different bytes than the request
5467
+ // body names whenever a caller supplies a non-canonical namespace (e.g. "EIP155:42220").
5468
+ // `normalized` lowercases only the namespaces and the asset namespace — the chain reference
5469
+ // and token address keep their case, so base58 (Solana genesis reference, SPL mint) survives.
5470
+ destinationAsset: destination.normalized,
5471
+ destinationAccount: params.destinationAccount,
3495
5472
  deadline: params.deadline,
3496
5473
  nonce,
3497
5474
  ...namespace === "solana" ? {
@@ -3507,13 +5484,15 @@ async function assemblePaymentRequest(params) {
3507
5484
  version: params.version ?? PAYMENT_REQUEST_VERSION,
3508
5485
  request_id: params.requestId,
3509
5486
  source: {
3510
- asset_identifier: params.sourceAsset,
5487
+ asset_identifier: source.normalized,
3511
5488
  account: params.depositor
3512
5489
  },
3513
- destination: [{
3514
- asset_identifier: params.destinationAsset,
3515
- account: params.destinationAccount
3516
- }],
5490
+ destination: [
5491
+ {
5492
+ asset_identifier: destination.normalized,
5493
+ account: params.destinationAccount
5494
+ }
5495
+ ],
3517
5496
  fulfillment_amount: params.fulfillmentAmount,
3518
5497
  max_source_amount: params.maxSourceAmount,
3519
5498
  quote_deadline: params.quoteDeadline,
@@ -3528,43 +5507,58 @@ async function assemblePaymentRequest(params) {
3528
5507
  ...params.settlerRequirements ? { settler_requirements: params.settlerRequirements } : {},
3529
5508
  sender_auth: {
3530
5509
  message_scheme: auth.messageScheme,
3531
- signed_messages: [{
3532
- message: auth.messageHash,
3533
- message_prehash: auth.messagePrehash,
3534
- signature: ""
3535
- }]
5510
+ signed_messages: [
5511
+ {
5512
+ message: auth.messageHash,
5513
+ message_prehash: auth.messagePrehash,
5514
+ signature: ""
5515
+ }
5516
+ ]
3536
5517
  }
3537
5518
  };
3538
5519
  }
3539
5520
  var PaymentGatewayClient2 = class extends PaymentGatewayClient {
3540
- constructor(config2, HttpRequest = AxiosHttpRequest) {
5521
+ constructor(config2, HttpRequest) {
3541
5522
  const envBase = (typeof process !== "undefined" ? process.env.GATEWAY_URL : void 0)?.trim();
3542
5523
  const base = config2?.BASE ?? (envBase || defaultGateway);
3543
- super({ ...config2, BASE: base }, HttpRequest);
3544
- this.baseUrl = base;
5524
+ const timeouts = {
5525
+ timeoutMs: config2?.timeoutMs,
5526
+ syncWaitTimeoutMs: config2?.syncWaitTimeoutMs
5527
+ };
5528
+ super(
5529
+ { ...config2, BASE: base, ...withRequestTimeout(config2, timeouts) },
5530
+ HttpRequest ?? timeoutHttpRequest(timeouts)
5531
+ );
3545
5532
  }
3546
5533
  /**
3547
5534
  * Fetches chain defaults from the payment gateway.
3548
- *
5535
+ *
5536
+ * Goes through the generated typed client, so the request shares the payment calls'
5537
+ * transport: one base URL, one timeout policy, and `/v1/defaults` is described by the
5538
+ * OpenAPI contract rather than assembled by hand here.
5539
+ *
3549
5540
  * @param chainId The CAIP-2 chain identifier (e.g., "eip155:42161")
3550
5541
  * @returns The chain defaults including escrow, quote selector, and fulfillment verifier
3551
5542
  */
3552
5543
  async fetchChainDefaults(chainId) {
3553
- const response = await fetch(`${this.baseUrl}/defaults?chain_id=${chainId}`);
3554
- if (!response.ok) {
3555
- let availableDefaults = null;
3556
- try {
3557
- const allDefaultsResponse = await fetch(`${this.baseUrl}/defaults`);
3558
- if (allDefaultsResponse.ok) {
3559
- availableDefaults = await allDefaultsResponse.json();
5544
+ if (chainId.trim() === "") {
5545
+ throw new Error(
5546
+ 'payment-gateway-client: fetchChainDefaults requires a CAIP-2 chain id, for example "eip155:8453"'
5547
+ );
5548
+ }
5549
+ let response;
5550
+ try {
5551
+ response = await this.chainDefaults.getDefaults({ chainId });
5552
+ } catch (error) {
5553
+ if (isGatewayTimeoutError(error)) throw error;
5554
+ throw new Error(
5555
+ `Failed to fetch defaults for chain ${chainId}: ${defaultsErrorDetail(error)}`,
5556
+ {
5557
+ cause: error
3560
5558
  }
3561
- } catch {
3562
- }
3563
- const error = new Error(`Failed to fetch defaults for chain ${chainId}: ${response.statusText}`);
3564
- error.availableDefaults = availableDefaults;
3565
- throw error;
5559
+ );
3566
5560
  }
3567
- const data = await response.json();
5561
+ const data = singleChainOf(response, chainId);
3568
5562
  if (!data.escrow_contract) {
3569
5563
  throw new Error("defaults missing escrow_contract");
3570
5564
  }
@@ -3583,23 +5577,34 @@ var PaymentGatewayClient2 = class extends PaymentGatewayClient {
3583
5577
  if (!data.fulfillment_verifier.endpoint) {
3584
5578
  throw new Error("defaults missing fulfillment_verifier.endpoint");
3585
5579
  }
5580
+ if (typeof data.permit2_contract === "string" && data.permit2_contract.trim() === "") {
5581
+ throw new Error("defaults returned an empty permit2_contract");
5582
+ }
3586
5583
  return {
3587
5584
  escrowContract: data.escrow_contract,
3588
5585
  quoteSelector: data.quote_selector,
3589
5586
  fulfillmentVerifierAccount: data.fulfillment_verifier.account,
3590
5587
  fulfillmentVerifierEndpoint: data.fulfillment_verifier.endpoint,
3591
5588
  fulfillmentProxy: data.fulfillment_proxy,
3592
- permit2Contract: data.permit2_contract,
5589
+ // `?? undefined` normalises a JSON null at the boundary. The declared type is
5590
+ // `string | undefined`, and a consumer testing `!== undefined` or `in` - both
5591
+ // reasonable against that type - would otherwise build an EIP-712 domain around a
5592
+ // null verifyingContract.
5593
+ permit2Contract: data.permit2_contract ?? void 0,
5594
+ // Which deposit witness the escrow on this chain pins. Absent means the
5595
+ // four-member witness — see ChainDefaults.depositWitnessVersion for why
5596
+ // absence is the permissive default. EVM/Tron only; Solana uses the svm_* fields below.
5597
+ depositWitnessVersion: data.deposit_witness_version ?? void 0,
3593
5598
  // V3 Solana escrow domain separation. Present only for Solana
3594
5599
  // source chains; the Solana adapter requires them to build the deposit hash.
3595
- svmSignatureClusterId: data.svm_signature_cluster_id,
3596
- svmSignatureDomainVersion: data.svm_signature_domain_version
5600
+ svmSignatureClusterId: data.svm_signature_cluster_id ?? void 0,
5601
+ svmSignatureDomainVersion: data.svm_signature_domain_version ?? void 0
3597
5602
  };
3598
5603
  }
3599
5604
  /**
3600
5605
  * Prepares a payment request with defaults, ready for signing.
3601
5606
  *
3602
- * By default this resolves the corridor addresses from the gateway `/defaults`
5607
+ * By default this resolves the corridor addresses from the gateway `/v1/defaults`
3603
5608
  * endpoint. It reaches the gateway only for what the caller has NOT already
3604
5609
  * supplied via `resolvedDefaults`: supply `resolvedDefaults.source` to skip the
3605
5610
  * source-chain fetch and `resolvedDefaults.destination` to skip the destination
@@ -3629,10 +5634,14 @@ var PaymentGatewayClient2 = class extends PaymentGatewayClient {
3629
5634
  * @returns A complete PaymentRequest object without the signature
3630
5635
  */
3631
5636
  async preparePaymentRequest(params) {
5637
+ assertPayableAccount(params.destinationAsset, params.destinationAccount);
3632
5638
  const now = (params.now ?? Date.now)();
3633
- const { quote_deadline, fulfillment_deadline } = resolveDeadlines({ ...params, now: () => now }, DEFAULT_PAYMENT_QUOTE_DEADLINE_SECONDS);
3634
- const sourceChainId = params.sourceAsset.split("/")[0];
3635
- const destChainId = params.destinationAsset.split("/")[0];
5639
+ const { quote_deadline, fulfillment_deadline } = resolveDeadlines(
5640
+ { ...params, now: () => now },
5641
+ DEFAULT_PAYMENT_QUOTE_DEADLINE_SECONDS
5642
+ );
5643
+ const sourceChainId = assetChainId(params.sourceAsset);
5644
+ const destChainId = assetChainId(params.destinationAsset);
3636
5645
  const [sourceDefaults, fulfillmentProxy] = await Promise.all([
3637
5646
  params.resolvedDefaults?.source ?? this.fetchChainDefaults(sourceChainId),
3638
5647
  params.resolvedDefaults?.destination?.fulfillmentProxy ?? this.fetchChainDefaults(destChainId).then((d) => d.fulfillmentProxy)
@@ -3702,7 +5711,7 @@ var PaymentGatewayClient2 = class extends PaymentGatewayClient {
3702
5711
  * defaults and populates the SAME contract fields (`escrow_contract_address`,
3703
5712
  * `quote_selector`, `fulfillment_verifier`, `fulfillment_proxy`). These are not
3704
5713
  * optional in practice: the gateway requires `fulfillment_verifier` to build the
3705
- * QuoteRequested event it broadcasts to settlers, so the quote-request body
5714
+ * request event it broadcasts to settlers, so the quote-request body
3706
5715
  * must carry the identical contract fields the payment flow does. The ONLY
3707
5716
  * field this drops relative to `preparePaymentRequest` is `sender_auth`, which
3708
5717
  * is supplied at award time (quote-time is unauthenticated — no signing, no
@@ -3712,26 +5721,38 @@ var PaymentGatewayClient2 = class extends PaymentGatewayClient {
3712
5721
  * @returns A complete `CreateQuoteRequest` body (no signature step needed)
3713
5722
  */
3714
5723
  async prepareQuoteRequest(params) {
3715
- const { quote_deadline, fulfillment_deadline } = resolveDeadlines(params, DEFAULT_QUOTE_DEADLINE_SECONDS);
3716
- const sourceChainId = params.sourceAsset.split("/")[0];
3717
- const destChainId = params.destinationAsset.split("/")[0];
5724
+ assertPayableAccount(params.destinationAsset, params.destinationAccount);
5725
+ if (!params.requestId) {
5726
+ throw new Error(
5727
+ "payment-gateway-client: requestId is required \u2014 it is the idempotency key the gateway dedups on; supply a stable id per logical quote-request and reuse it on retry"
5728
+ );
5729
+ }
5730
+ const { quote_deadline, fulfillment_deadline } = resolveDeadlines(
5731
+ params,
5732
+ DEFAULT_QUOTE_DEADLINE_SECONDS
5733
+ );
5734
+ const source = parseAssetIdentifier(params.sourceAsset);
5735
+ const destination = parseAssetIdentifier(params.destinationAsset);
5736
+ const sourceChainId = source.chainId;
5737
+ const destChainId = destination.chainId;
3718
5738
  const [sourceDefaults, destDefaults] = await Promise.all([
3719
5739
  this.fetchChainDefaults(sourceChainId),
3720
5740
  this.fetchChainDefaults(destChainId)
3721
5741
  ]);
3722
5742
  const contractOverrides = getChainAdapter(sourceChainId).resolveContractOverrides?.(sourceDefaults);
3723
- const requestId = params.requestId || `${params.requestIdPrefix || "quote-gw-sdk"}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
3724
5743
  return {
3725
5744
  version: PAYMENT_REQUEST_VERSION,
3726
- request_id: requestId,
5745
+ request_id: params.requestId,
3727
5746
  source: {
3728
- asset_identifier: params.sourceAsset,
5747
+ asset_identifier: source.normalized,
3729
5748
  account: params.depositor
3730
5749
  },
3731
- destination: [{
3732
- asset_identifier: params.destinationAsset,
3733
- account: params.destinationAccount
3734
- }],
5750
+ destination: [
5751
+ {
5752
+ asset_identifier: destination.normalized,
5753
+ account: params.destinationAccount
5754
+ }
5755
+ ],
3735
5756
  fulfillment_amount: params.fulfillmentAmount,
3736
5757
  max_source_amount: params.maxSourceAmount ?? defaultMaxSourceAmount(params.fulfillmentAmount),
3737
5758
  // Required + originator-supplied: the gateway injects no default and never
@@ -3757,7 +5778,7 @@ var PaymentGatewayClient2 = class extends PaymentGatewayClient {
3757
5778
  };
3758
5779
 
3759
5780
  // src/version.ts
3760
- var PACKAGE_VERSION = true ? "2.2.0" : "0.0.0-dev";
5781
+ var PACKAGE_VERSION = true ? "3.0.1" : "0.0.0-dev";
3761
5782
 
3762
5783
  // src/cli/load-env.ts
3763
5784
  var import_dotenv = require("dotenv");
@@ -3765,17 +5786,42 @@ function loadCliEnv() {
3765
5786
  (0, import_dotenv.config)({ override: false, quiet: true });
3766
5787
  }
3767
5788
 
5789
+ // src/cli/cli-input-error.ts
5790
+ var CliInputError = class extends Error {
5791
+ constructor(message) {
5792
+ super(message);
5793
+ this.name = "CliInputError";
5794
+ }
5795
+ };
5796
+
5797
+ // src/cli/run-cli.ts
5798
+ function runCli(program2, ...parseArgs) {
5799
+ try {
5800
+ program2.parse(...parseArgs);
5801
+ } catch (error) {
5802
+ if (!(error instanceof CliInputError)) throw error;
5803
+ console.error("\n\u274C Error:", error.message);
5804
+ process.exit(1);
5805
+ }
5806
+ }
5807
+
3768
5808
  // src/cli/quote-status.ts
3769
5809
  loadCliEnv();
3770
5810
  var program = new import_commander.Command();
3771
- program.name("quote-status").description("Fetch the status of a quote-request batch (no signing required)").version(PACKAGE_VERSION).argument("<quoteRequestId>", "The quote_request_id (qr_...) returned by request-quote").option("--gateway <url>", "Payment gateway URL (overrides GATEWAY_URL env; default: production-testnet)").addHelpText("after", `
5811
+ program.name("quote-status").description("Fetch the status of a quote-request batch (no signing required)").version(PACKAGE_VERSION).argument("<quoteRequestId>", "The quote_request_id (qr_...) returned by request-quote").option(
5812
+ "--gateway <url>",
5813
+ "Payment gateway URL (overrides GATEWAY_URL env; default: production-testnet)"
5814
+ ).addHelpText(
5815
+ "after",
5816
+ `
3772
5817
  Example:
3773
5818
  quote-status --gateway http://localhost:8080 qr_019f27b9-420d-7353-8263-0cf310670a77
3774
5819
 
3775
5820
  Status values: collecting | ready | awarded | expired
3776
5821
 
3777
5822
  Output:
3778
- Response JSON -> stdout (for parsing/automation, e.g. | jq)`).action(async (quoteRequestId, options) => {
5823
+ Response JSON -> stdout (for parsing/automation, e.g. | jq)`
5824
+ ).action(async (quoteRequestId, options) => {
3779
5825
  try {
3780
5826
  const client = new PaymentGatewayClient2({ BASE: options.gateway });
3781
5827
  const response = await client.quoteRequests.getQuoteRequestStatus({ quoteRequestId });
@@ -3790,7 +5836,7 @@ Output:
3790
5836
  process.exit(1);
3791
5837
  }
3792
5838
  });
3793
- program.parse();
5839
+ runCli(program);
3794
5840
  /*! Bundled license information:
3795
5841
 
3796
5842
  @noble/hashes/utils.js: