@atumlabs/payment-gateway-client 2.2.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,6 +12,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
12
  var __getOwnPropNames = Object.getOwnPropertyNames;
13
13
  var __getProtoOf = Object.getPrototypeOf;
14
14
  var __hasOwnProp = Object.prototype.hasOwnProperty;
15
+ var __esm = (fn, res) => function __init() {
16
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
17
+ };
15
18
  var __commonJS = (cb, mod) => function __require() {
16
19
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
20
  };
@@ -82,7 +85,7 @@ var require_tron_address = __commonJS({
82
85
  hexAddress = base58ToHex2(address);
83
86
  }
84
87
  hexAddress = hexAddress.replace(/^0x/, "");
85
- if (hexAddress.startsWith(TVM_MAINNET_PREFIX)) {
88
+ if (hexAddress.length === 42 && hexAddress.startsWith(TVM_MAINNET_PREFIX)) {
86
89
  hexAddress = hexAddress.substring(2);
87
90
  }
88
91
  if (hexAddress.length !== 40) {
@@ -96,14 +99,62 @@ var require_tron_address = __commonJS({
96
99
  }
97
100
  });
98
101
 
102
+ // ../contracts/tvm/escrow-encoding/typescript/dist/witness-values.js
103
+ var require_witness_values = __commonJS({
104
+ "../contracts/tvm/escrow-encoding/typescript/dist/witness-values.js"(exports2) {
105
+ "use strict";
106
+ Object.defineProperty(exports2, "__esModule", { value: true });
107
+ exports2.normalizeBytes32 = normalizeBytes32;
108
+ exports2.normalizeUint256 = normalizeUint256;
109
+ exports2.maskedChainIdToHex = maskedChainIdToHex;
110
+ var ethers_1 = require("ethers");
111
+ var chain_id_1 = require_chain_id();
112
+ function normalizeBytes32(label, value) {
113
+ let bytes;
114
+ try {
115
+ bytes = (0, ethers_1.getBytes)(value);
116
+ } catch {
117
+ throw new Error(`${label} must be 0x-prefixed hex (32 bytes), got ${JSON.stringify(value)}`);
118
+ }
119
+ if (bytes.length !== 32) {
120
+ throw new Error(`${label} must be exactly 32 bytes, got ${bytes.length}`);
121
+ }
122
+ return (0, ethers_1.hexlify)(bytes);
123
+ }
124
+ function normalizeUint256(label, value) {
125
+ let n;
126
+ try {
127
+ n = BigInt(value);
128
+ } catch {
129
+ throw new Error(`${label} must be an integer (bigint or decimal string), got ${JSON.stringify(value)}`);
130
+ }
131
+ if (n < 0n) {
132
+ throw new Error(`${label} must be non-negative (uint256), got ${n.toString()}`);
133
+ }
134
+ return n.toString();
135
+ }
136
+ function maskedChainIdToHex(chainId) {
137
+ if (!Number.isSafeInteger(chainId) || chainId < 0) {
138
+ throw new Error(`chainId must be a non-negative safe integer, got ${chainId}`);
139
+ }
140
+ return `0x${(0, chain_id_1.maskChainId)(chainId).toString(16)}`;
141
+ }
142
+ }
143
+ });
144
+
99
145
  // ../contracts/tvm/escrow-encoding/typescript/dist/reserve-encoder.js
100
146
  var require_reserve_encoder = __commonJS({
101
147
  "../contracts/tvm/escrow-encoding/typescript/dist/reserve-encoder.js"(exports2) {
102
148
  "use strict";
103
149
  Object.defineProperty(exports2, "__esModule", { value: true });
150
+ exports2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE = void 0;
104
151
  exports2.computeReserveDigest = computeReserveDigest;
152
+ exports2.buildTvmReserveTypedDataWithQuoteSource = buildTvmReserveTypedDataWithQuoteSource;
153
+ exports2.computeTvmReserveDigestWithQuoteSource = computeTvmReserveDigestWithQuoteSource;
105
154
  var ethers_1 = require("ethers");
106
155
  var chain_id_1 = require_chain_id();
156
+ var tron_address_1 = require_tron_address();
157
+ var witness_values_1 = require_witness_values();
107
158
  var RESERVE_WITNESS_TYPES = {
108
159
  ReserveWitness: [
109
160
  { name: "paymentId", type: "bytes32" },
@@ -122,6 +173,36 @@ var require_reserve_encoder = __commonJS({
122
173
  settler: input.settler
123
174
  });
124
175
  }
176
+ exports2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE = {
177
+ ReserveWitness: [
178
+ { name: "depositId", type: "bytes32" },
179
+ { name: "quoteHash", type: "bytes32" },
180
+ { name: "settler", type: "address" },
181
+ { name: "sourceAmount", type: "uint256" }
182
+ ]
183
+ };
184
+ function buildTvmReserveTypedDataWithQuoteSource(input) {
185
+ return {
186
+ types: exports2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE,
187
+ primaryType: "ReserveWitness",
188
+ domain: {
189
+ name: "Escrow",
190
+ version: "3",
191
+ chainId: (0, witness_values_1.maskedChainIdToHex)(input.chainId),
192
+ verifyingContract: (0, tron_address_1.normalizeAddress)(input.escrowContract)
193
+ },
194
+ message: {
195
+ depositId: (0, witness_values_1.normalizeBytes32)("depositId", input.depositId),
196
+ quoteHash: (0, witness_values_1.normalizeBytes32)("quoteHash", input.quoteHash),
197
+ settler: (0, tron_address_1.normalizeAddress)(input.settler),
198
+ sourceAmount: (0, witness_values_1.normalizeUint256)("sourceAmount", input.sourceAmount)
199
+ }
200
+ };
201
+ }
202
+ function computeTvmReserveDigestWithQuoteSource(input) {
203
+ const prehash = buildTvmReserveTypedDataWithQuoteSource(input);
204
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
205
+ }
125
206
  }
126
207
  });
127
208
 
@@ -148,11 +229,14 @@ var require_deposit_encoder = __commonJS({
148
229
  "../contracts/tvm/escrow-encoding/typescript/dist/deposit-encoder.js"(exports2) {
149
230
  "use strict";
150
231
  Object.defineProperty(exports2, "__esModule", { value: true });
232
+ exports2.MAX_DESTINATION_BYTES = exports2.PERMIT_WITNESS_TYPES_WITH_DESTINATION = void 0;
151
233
  exports2.createTvmPermitWitnessTransferFromPrehash = createTvmPermitWitnessTransferFromPrehash2;
152
234
  exports2.hashTvmPermitWitnessTransferFrom = hashTvmPermitWitnessTransferFrom2;
235
+ exports2.createTvmPermitWitnessTransferFromPrehashWithDestination = createTvmPermitWitnessTransferFromPrehashWithDestination;
153
236
  var ethers_1 = require("ethers");
154
237
  var chain_id_1 = require_chain_id();
155
238
  var tron_address_1 = require_tron_address();
239
+ var witness_values_1 = require_witness_values();
156
240
  var PERMIT_WITNESS_TYPES_V2 = {
157
241
  PermitWitnessTransferFrom: [
158
242
  { name: "permitted", type: "TokenPermissions" },
@@ -198,6 +282,180 @@ var require_deposit_encoder = __commonJS({
198
282
  function hashTvmPermitWitnessTransferFrom2(prehash) {
199
283
  return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
200
284
  }
285
+ exports2.PERMIT_WITNESS_TYPES_WITH_DESTINATION = {
286
+ PermitWitnessTransferFrom: [
287
+ { name: "permitted", type: "TokenPermissions" },
288
+ { name: "spender", type: "address" },
289
+ { name: "nonce", type: "uint256" },
290
+ { name: "deadline", type: "uint256" },
291
+ { name: "witness", type: "DepositWitness" }
292
+ ],
293
+ TokenPermissions: [
294
+ { name: "token", type: "address" },
295
+ { name: "amount", type: "uint256" }
296
+ ],
297
+ DepositWitness: [
298
+ { name: "depositRequestHash", type: "bytes32" },
299
+ { name: "destination", type: "string" },
300
+ { name: "reserver", type: "address" },
301
+ { name: "releaser", type: "address" }
302
+ ]
303
+ };
304
+ exports2.MAX_DESTINATION_BYTES = 256;
305
+ function assertDestinationWithinBounds(destination) {
306
+ if (destination === "") {
307
+ 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');
308
+ }
309
+ const byteLength = (0, ethers_1.toUtf8Bytes)(destination).length;
310
+ if (byteLength > exports2.MAX_DESTINATION_BYTES) {
311
+ 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`);
312
+ }
313
+ }
314
+ function createTvmPermitWitnessTransferFromPrehashWithDestination(params) {
315
+ assertDestinationWithinBounds(params.destination);
316
+ return {
317
+ types: exports2.PERMIT_WITNESS_TYPES_WITH_DESTINATION,
318
+ primaryType: "PermitWitnessTransferFrom",
319
+ domain: {
320
+ name: "Permit2",
321
+ chainId: (0, witness_values_1.maskedChainIdToHex)(params.chainId),
322
+ verifyingContract: (0, tron_address_1.normalizeAddress)(params.permit2Address)
323
+ },
324
+ message: {
325
+ permitted: {
326
+ token: (0, tron_address_1.normalizeAddress)(params.tokenAddress),
327
+ amount: (0, witness_values_1.normalizeUint256)("amount", params.amount)
328
+ },
329
+ spender: (0, tron_address_1.normalizeAddress)(params.spenderAddress),
330
+ nonce: (0, witness_values_1.normalizeUint256)("nonce", params.nonce),
331
+ deadline: (0, witness_values_1.normalizeUint256)("deadline", params.deadline),
332
+ witness: {
333
+ depositRequestHash: (0, witness_values_1.normalizeBytes32)("depositRequestHash", params.depositRequestHash),
334
+ destination: params.destination,
335
+ reserver: (0, tron_address_1.normalizeAddress)(params.reserverAddress),
336
+ releaser: (0, tron_address_1.normalizeAddress)(params.releaserAddress)
337
+ }
338
+ }
339
+ };
340
+ }
341
+ }
342
+ });
343
+
344
+ // ../contracts/tvm/escrow-encoding/typescript/dist/release-encoder.js
345
+ var require_release_encoder = __commonJS({
346
+ "../contracts/tvm/escrow-encoding/typescript/dist/release-encoder.js"(exports2) {
347
+ "use strict";
348
+ Object.defineProperty(exports2, "__esModule", { value: true });
349
+ exports2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH = void 0;
350
+ exports2.buildTvmReleaseTypedDataWithQuoteHash = buildTvmReleaseTypedDataWithQuoteHash;
351
+ exports2.computeTvmReleaseDigestWithQuoteHash = computeTvmReleaseDigestWithQuoteHash;
352
+ var ethers_1 = require("ethers");
353
+ var tron_address_1 = require_tron_address();
354
+ var witness_values_1 = require_witness_values();
355
+ exports2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH = {
356
+ ReleaseWitness: [
357
+ { name: "depositId", type: "bytes32" },
358
+ { name: "quoteHash", type: "bytes32" },
359
+ { name: "depositRequestHash", type: "bytes32" },
360
+ { name: "destinationHash", type: "bytes32" },
361
+ { name: "depositor", type: "address" },
362
+ { name: "token", type: "address" },
363
+ { name: "amount", type: "uint256" },
364
+ { name: "feeAmount", type: "uint256" },
365
+ { name: "reserver", type: "address" },
366
+ { name: "releaser", type: "address" },
367
+ { name: "settler", type: "address" }
368
+ ]
369
+ };
370
+ function buildTvmReleaseTypedDataWithQuoteHash(input) {
371
+ const w = input.witness;
372
+ return {
373
+ types: exports2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH,
374
+ primaryType: "ReleaseWitness",
375
+ domain: {
376
+ name: "Escrow",
377
+ version: "3",
378
+ chainId: (0, witness_values_1.maskedChainIdToHex)(input.chainId),
379
+ verifyingContract: (0, tron_address_1.normalizeAddress)(input.escrowContract)
380
+ },
381
+ message: {
382
+ depositId: (0, witness_values_1.normalizeBytes32)("depositId", w.depositId),
383
+ quoteHash: (0, witness_values_1.normalizeBytes32)("quoteHash", w.quoteHash),
384
+ depositRequestHash: (0, witness_values_1.normalizeBytes32)("depositRequestHash", w.depositRequestHash),
385
+ destinationHash: (0, witness_values_1.normalizeBytes32)("destinationHash", w.destinationHash),
386
+ depositor: (0, tron_address_1.normalizeAddress)(w.depositor),
387
+ token: (0, tron_address_1.normalizeAddress)(w.token),
388
+ amount: (0, witness_values_1.normalizeUint256)("amount", w.amount),
389
+ feeAmount: (0, witness_values_1.normalizeUint256)("feeAmount", w.feeAmount),
390
+ reserver: (0, tron_address_1.normalizeAddress)(w.reserver),
391
+ releaser: (0, tron_address_1.normalizeAddress)(w.releaser),
392
+ settler: (0, tron_address_1.normalizeAddress)(w.settler)
393
+ }
394
+ };
395
+ }
396
+ function computeTvmReleaseDigestWithQuoteHash(input) {
397
+ const prehash = buildTvmReleaseTypedDataWithQuoteHash(input);
398
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
399
+ }
400
+ }
401
+ });
402
+
403
+ // ../contracts/tvm/escrow-encoding/typescript/dist/refund-encoder.js
404
+ var require_refund_encoder = __commonJS({
405
+ "../contracts/tvm/escrow-encoding/typescript/dist/refund-encoder.js"(exports2) {
406
+ "use strict";
407
+ Object.defineProperty(exports2, "__esModule", { value: true });
408
+ exports2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH = void 0;
409
+ exports2.buildTvmRefundTypedDataWithQuoteHash = buildTvmRefundTypedDataWithQuoteHash;
410
+ exports2.computeTvmRefundDigestWithQuoteHash = computeTvmRefundDigestWithQuoteHash;
411
+ var ethers_1 = require("ethers");
412
+ var tron_address_1 = require_tron_address();
413
+ var witness_values_1 = require_witness_values();
414
+ exports2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH = {
415
+ RefundWitness: [
416
+ { name: "depositId", type: "bytes32" },
417
+ { name: "quoteHash", type: "bytes32" },
418
+ { name: "depositRequestHash", type: "bytes32" },
419
+ { name: "destinationHash", type: "bytes32" },
420
+ { name: "depositor", type: "address" },
421
+ { name: "token", type: "address" },
422
+ { name: "amount", type: "uint256" },
423
+ { name: "feeAmount", type: "uint256" },
424
+ { name: "reserver", type: "address" },
425
+ { name: "releaser", type: "address" },
426
+ { name: "settler", type: "address" }
427
+ ]
428
+ };
429
+ function buildTvmRefundTypedDataWithQuoteHash(input) {
430
+ const w = input.witness;
431
+ return {
432
+ types: exports2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH,
433
+ primaryType: "RefundWitness",
434
+ domain: {
435
+ name: "Escrow",
436
+ version: "3",
437
+ chainId: (0, witness_values_1.maskedChainIdToHex)(input.chainId),
438
+ verifyingContract: (0, tron_address_1.normalizeAddress)(input.escrowContract)
439
+ },
440
+ message: {
441
+ depositId: (0, witness_values_1.normalizeBytes32)("depositId", w.depositId),
442
+ quoteHash: (0, witness_values_1.normalizeBytes32)("quoteHash", w.quoteHash),
443
+ depositRequestHash: (0, witness_values_1.normalizeBytes32)("depositRequestHash", w.depositRequestHash),
444
+ destinationHash: (0, witness_values_1.normalizeBytes32)("destinationHash", w.destinationHash),
445
+ depositor: (0, tron_address_1.normalizeAddress)(w.depositor),
446
+ token: (0, tron_address_1.normalizeAddress)(w.token),
447
+ amount: (0, witness_values_1.normalizeUint256)("amount", w.amount),
448
+ feeAmount: (0, witness_values_1.normalizeUint256)("feeAmount", w.feeAmount),
449
+ reserver: (0, tron_address_1.normalizeAddress)(w.reserver),
450
+ releaser: (0, tron_address_1.normalizeAddress)(w.releaser),
451
+ settler: (0, tron_address_1.normalizeAddress)(w.settler)
452
+ }
453
+ };
454
+ }
455
+ function computeTvmRefundDigestWithQuoteHash(input) {
456
+ const prehash = buildTvmRefundTypedDataWithQuoteHash(input);
457
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
458
+ }
201
459
  }
202
460
  });
203
461
 
@@ -206,7 +464,7 @@ var require_dist = __commonJS({
206
464
  "../contracts/tvm/escrow-encoding/typescript/dist/index.js"(exports2) {
207
465
  "use strict";
208
466
  Object.defineProperty(exports2, "__esModule", { value: true });
209
- exports2.hashTvmPermitWitnessTransferFrom = exports2.createTvmPermitWitnessTransferFromPrehash = exports2.computePaymentId = exports2.computeReserveDigest = exports2.normalizeAddress = exports2.base58ToHex = exports2.maskChainId = void 0;
467
+ 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
468
  var chain_id_1 = require_chain_id();
211
469
  Object.defineProperty(exports2, "maskChainId", { enumerable: true, get: function() {
212
470
  return chain_id_1.maskChainId;
@@ -233,6 +491,222 @@ var require_dist = __commonJS({
233
491
  Object.defineProperty(exports2, "hashTvmPermitWitnessTransferFrom", { enumerable: true, get: function() {
234
492
  return deposit_encoder_1.hashTvmPermitWitnessTransferFrom;
235
493
  } });
494
+ var reserve_encoder_2 = require_reserve_encoder();
495
+ Object.defineProperty(exports2, "RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE", { enumerable: true, get: function() {
496
+ return reserve_encoder_2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE;
497
+ } });
498
+ Object.defineProperty(exports2, "buildTvmReserveTypedDataWithQuoteSource", { enumerable: true, get: function() {
499
+ return reserve_encoder_2.buildTvmReserveTypedDataWithQuoteSource;
500
+ } });
501
+ Object.defineProperty(exports2, "computeTvmReserveDigestWithQuoteSource", { enumerable: true, get: function() {
502
+ return reserve_encoder_2.computeTvmReserveDigestWithQuoteSource;
503
+ } });
504
+ var release_encoder_1 = require_release_encoder();
505
+ Object.defineProperty(exports2, "RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH", { enumerable: true, get: function() {
506
+ return release_encoder_1.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH;
507
+ } });
508
+ Object.defineProperty(exports2, "buildTvmReleaseTypedDataWithQuoteHash", { enumerable: true, get: function() {
509
+ return release_encoder_1.buildTvmReleaseTypedDataWithQuoteHash;
510
+ } });
511
+ Object.defineProperty(exports2, "computeTvmReleaseDigestWithQuoteHash", { enumerable: true, get: function() {
512
+ return release_encoder_1.computeTvmReleaseDigestWithQuoteHash;
513
+ } });
514
+ var refund_encoder_1 = require_refund_encoder();
515
+ Object.defineProperty(exports2, "REFUND_WITNESS_TYPES_WITH_QUOTE_HASH", { enumerable: true, get: function() {
516
+ return refund_encoder_1.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH;
517
+ } });
518
+ Object.defineProperty(exports2, "buildTvmRefundTypedDataWithQuoteHash", { enumerable: true, get: function() {
519
+ return refund_encoder_1.buildTvmRefundTypedDataWithQuoteHash;
520
+ } });
521
+ Object.defineProperty(exports2, "computeTvmRefundDigestWithQuoteHash", { enumerable: true, get: function() {
522
+ return refund_encoder_1.computeTvmRefundDigestWithQuoteHash;
523
+ } });
524
+ var deposit_encoder_2 = require_deposit_encoder();
525
+ Object.defineProperty(exports2, "PERMIT_WITNESS_TYPES_WITH_DESTINATION", { enumerable: true, get: function() {
526
+ return deposit_encoder_2.PERMIT_WITNESS_TYPES_WITH_DESTINATION;
527
+ } });
528
+ Object.defineProperty(exports2, "createTvmPermitWitnessTransferFromPrehashWithDestination", { enumerable: true, get: function() {
529
+ return deposit_encoder_2.createTvmPermitWitnessTransferFromPrehashWithDestination;
530
+ } });
531
+ Object.defineProperty(exports2, "MAX_DESTINATION_BYTES", { enumerable: true, get: function() {
532
+ return deposit_encoder_2.MAX_DESTINATION_BYTES;
533
+ } });
534
+ }
535
+ });
536
+
537
+ // ../schemas/declarations/common/chain-address/typescript/dist/index.js
538
+ var require_dist2 = __commonJS({
539
+ "../schemas/declarations/common/chain-address/typescript/dist/index.js"(exports2) {
540
+ "use strict";
541
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
542
+ return mod && mod.__esModule ? mod : { "default": mod };
543
+ };
544
+ Object.defineProperty(exports2, "__esModule", { value: true });
545
+ exports2.InvalidAccountError = exports2.REASONS = exports2.NAMESPACE_SOLANA = exports2.NAMESPACE_TRON = exports2.NAMESPACE_EIP155 = void 0;
546
+ exports2.supportedNamespaces = supportedNamespaces;
547
+ exports2.parse = parse;
548
+ exports2.validate = validate;
549
+ exports2.checkAccount = checkAccount;
550
+ var bs58_1 = __importDefault(require("bs58"));
551
+ var ethers_1 = require("ethers");
552
+ var tvm_escrow_encoding_1 = require_dist();
553
+ exports2.NAMESPACE_EIP155 = "eip155";
554
+ exports2.NAMESPACE_TRON = "tron";
555
+ exports2.NAMESPACE_SOLANA = "solana";
556
+ exports2.REASONS = [
557
+ "EMPTY",
558
+ "SURROUNDING_WHITESPACE",
559
+ "UNSUPPORTED_NAMESPACE",
560
+ "UNPARSEABLE",
561
+ "ZERO"
562
+ ];
563
+ var InvalidAccountError2 = class extends Error {
564
+ reason;
565
+ network;
566
+ account;
567
+ detail;
568
+ constructor(reason, network, account, detail = "") {
569
+ super(messageFor(reason, network, detail));
570
+ this.name = "InvalidAccountError";
571
+ this.reason = reason;
572
+ this.network = network;
573
+ this.account = account;
574
+ this.detail = detail;
575
+ }
576
+ };
577
+ exports2.InvalidAccountError = InvalidAccountError2;
578
+ function messageFor(reason, network, detail) {
579
+ switch (reason) {
580
+ case "EMPTY":
581
+ return "account is required and cannot be empty";
582
+ case "SURROUNDING_WHITESPACE":
583
+ return "account must not contain leading or trailing whitespace";
584
+ case "UNSUPPORTED_NAMESPACE":
585
+ return `no address rules are known for chain ${network}`;
586
+ case "ZERO":
587
+ return `account is the zero address on ${network}, which cannot receive a payout`;
588
+ default:
589
+ return `account is not a valid address for ${network}`;
590
+ }
591
+ }
592
+ function supportedNamespaces() {
593
+ return [exports2.NAMESPACE_EIP155, exports2.NAMESPACE_SOLANA, exports2.NAMESPACE_TRON];
594
+ }
595
+ function trimSurrounding(value) {
596
+ return value.replace(/^[\s\u0085]+|[\s\u0085]+$/gu, "");
597
+ }
598
+ function parse(network, account) {
599
+ if (trimSurrounding(account) === "") {
600
+ throw new InvalidAccountError2("EMPTY", network, account);
601
+ }
602
+ if (account !== trimSurrounding(account)) {
603
+ throw new InvalidAccountError2("SURROUNDING_WHITESPACE", network, account);
604
+ }
605
+ const separator = network.indexOf(":");
606
+ if (separator <= 0) {
607
+ throw new InvalidAccountError2("UNSUPPORTED_NAMESPACE", network, account);
608
+ }
609
+ const namespace = network.slice(0, separator);
610
+ let bytes;
611
+ try {
612
+ switch (namespace) {
613
+ case exports2.NAMESPACE_EIP155:
614
+ bytes = parseEvm(account);
615
+ break;
616
+ case exports2.NAMESPACE_TRON:
617
+ bytes = parseTron(account);
618
+ break;
619
+ case exports2.NAMESPACE_SOLANA:
620
+ bytes = parseSolana(account);
621
+ break;
622
+ default:
623
+ throw new InvalidAccountError2("UNSUPPORTED_NAMESPACE", network, account);
624
+ }
625
+ } catch (error) {
626
+ if (error instanceof InvalidAccountError2)
627
+ throw error;
628
+ throw new InvalidAccountError2("UNPARSEABLE", network, account, error.message);
629
+ }
630
+ return { namespace, bytes };
631
+ }
632
+ function validate(network, account) {
633
+ const parsed = parse(network, account);
634
+ if (isZero(parsed.bytes)) {
635
+ throw new InvalidAccountError2("ZERO", network, account);
636
+ }
637
+ return parsed;
638
+ }
639
+ function checkAccount(network, account) {
640
+ try {
641
+ validate(network, account);
642
+ return null;
643
+ } catch (error) {
644
+ if (error instanceof InvalidAccountError2)
645
+ return error;
646
+ throw error;
647
+ }
648
+ }
649
+ function isZero(bytes) {
650
+ return bytes.length > 0 && bytes.every((one) => one === 0);
651
+ }
652
+ var HEX_40 = /^(0[xX])?[0-9a-fA-F]{40}$/;
653
+ function parseEvm(account) {
654
+ if (!HEX_40.test(account)) {
655
+ throw new Error("expected 40 hex characters, optionally 0x-prefixed");
656
+ }
657
+ const body = account.replace(/^0[xX]/, "");
658
+ const lower = body.toLowerCase();
659
+ if (body !== lower && body !== body.toUpperCase()) {
660
+ if ((0, ethers_1.getAddress)(`0x${lower}`) !== account) {
661
+ throw new Error("mixed-case address fails its EIP-55 checksum");
662
+ }
663
+ }
664
+ return hexToBytes2(lower);
665
+ }
666
+ function parseTron(account) {
667
+ let hexBody;
668
+ if (account.startsWith("T") && account.length === 34) {
669
+ try {
670
+ hexBody = (0, tvm_escrow_encoding_1.base58ToHex)(account);
671
+ } catch (error) {
672
+ throw new Error(`base58 address failed its checksum: ${error.message}`);
673
+ }
674
+ } else if (account.toLowerCase().startsWith("0x41") && account.length === 44) {
675
+ hexBody = account.slice(2);
676
+ } else if (HEX_40.test(account)) {
677
+ return parseEvm(account);
678
+ } else {
679
+ throw new Error("expected a T-prefixed base58 address or 40 hex characters");
680
+ }
681
+ hexBody = hexBody.startsWith("41") ? hexBody.slice(2) : hexBody;
682
+ if (hexBody.length !== 40) {
683
+ throw new Error(`expected 40 hex characters after conversion, got ${hexBody.length}`);
684
+ }
685
+ return hexToBytes2(hexBody);
686
+ }
687
+ function parseSolana(account) {
688
+ let decoded;
689
+ try {
690
+ decoded = bs58_1.default.decode(account);
691
+ } catch {
692
+ throw new Error("expected a 32-byte base58 public key");
693
+ }
694
+ if (decoded.length !== 32) {
695
+ throw new Error(`expected a 32-byte base58 public key, got ${decoded.length} bytes`);
696
+ }
697
+ return decoded;
698
+ }
699
+ var HEX_BODY = /^[0-9a-fA-F]*$/;
700
+ function hexToBytes2(hex) {
701
+ if (hex.length % 2 !== 0 || !HEX_BODY.test(hex)) {
702
+ throw new Error("expected hex characters");
703
+ }
704
+ const out = new Uint8Array(hex.length / 2);
705
+ for (let i = 0; i < out.length; i += 1) {
706
+ out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
707
+ }
708
+ return out;
709
+ }
236
710
  }
237
711
  });
238
712
 
@@ -244,12 +718,96 @@ var require_types = __commonJS({
244
718
  }
245
719
  });
246
720
 
721
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/destination.js
722
+ var require_destination = __commonJS({
723
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/destination.js"(exports2) {
724
+ "use strict";
725
+ Object.defineProperty(exports2, "__esModule", { value: true });
726
+ exports2.DESTINATION_COMMITMENT_WITNESS_VERSION = exports2.MAX_DESTINATION_BYTES = void 0;
727
+ exports2.usesDestinationCommitment = usesDestinationCommitment;
728
+ exports2.deriveDepositRequestHash = deriveDepositRequestHash;
729
+ exports2.buildEscrowDestination = buildEscrowDestination;
730
+ var ethers_1 = require("ethers");
731
+ exports2.MAX_DESTINATION_BYTES = 256;
732
+ var NAMESPACE_EIP155 = "eip155";
733
+ exports2.DESTINATION_COMMITMENT_WITNESS_VERSION = 4;
734
+ function usesDestinationCommitment(depositWitnessVersion) {
735
+ return depositWitnessVersion === void 0 || depositWitnessVersion >= exports2.DESTINATION_COMMITMENT_WITNESS_VERSION;
736
+ }
737
+ function deriveDepositRequestHash(requestId) {
738
+ if (requestId === "") {
739
+ 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');
740
+ }
741
+ return (0, ethers_1.keccak256)((0, ethers_1.toUtf8Bytes)(requestId));
742
+ }
743
+ function buildEscrowDestination(assetIdentifier, account) {
744
+ if (assetIdentifier === "") {
745
+ throw new Error("sender_auth: destination asset_identifier is empty");
746
+ }
747
+ if (account === "") {
748
+ throw new Error("sender_auth: destination account is empty");
749
+ }
750
+ if (assetIdentifier.includes("@") || account.includes("@")) {
751
+ 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`);
752
+ }
753
+ const namespace = caip2Namespace(assetIdentifier);
754
+ let asset = assetIdentifier;
755
+ let acct = account;
756
+ if (namespace === NAMESPACE_EIP155) {
757
+ asset = asset.toLowerCase();
758
+ acct = acct.toLowerCase();
759
+ }
760
+ const destination = `${asset}@${acct}`;
761
+ const byteLength = (0, ethers_1.toUtf8Bytes)(destination).length;
762
+ if (byteLength > exports2.MAX_DESTINATION_BYTES) {
763
+ 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`);
764
+ }
765
+ return destination;
766
+ }
767
+ function caip2Namespace(assetIdentifier) {
768
+ const slash = assetIdentifier.indexOf("/");
769
+ const chainPart = slash === -1 ? "" : assetIdentifier.slice(0, slash);
770
+ const assetPart = slash === -1 ? "" : assetIdentifier.slice(slash + 1);
771
+ if (slash === -1 || chainPart === "" || assetPart === "") {
772
+ const looksLegacy = !assetIdentifier.includes("/") && countChar(assetIdentifier, ":") === 2;
773
+ const hint = looksLegacy ? " (this looks like the deprecated `<chain>:<ref>:<asset>` form; migrate it to `<chain>:<ref>/<asset-namespace>:<asset-reference>`)" : "";
774
+ throw new Error(`sender_auth: destination asset_identifier ${JSON.stringify(assetIdentifier)} is not CAIP-19: expected <caip2-chain-id>/<asset-namespace>:<asset-reference>${hint}`);
775
+ }
776
+ const assetColon = assetPart.indexOf(":");
777
+ if (assetColon <= 0 || assetColon === assetPart.length - 1) {
778
+ throw new Error(`sender_auth: destination asset_identifier ${JSON.stringify(assetIdentifier)} has a malformed asset part ${JSON.stringify(assetPart)}: expected <asset-namespace>:<asset-reference>`);
779
+ }
780
+ const assetNamespace = assetPart.slice(0, assetColon);
781
+ if (assetNamespace !== assetNamespace.toLowerCase()) {
782
+ 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`);
783
+ }
784
+ const chainColon = chainPart.indexOf(":");
785
+ if (chainColon <= 0 || chainColon === chainPart.length - 1) {
786
+ throw new Error(`sender_auth: destination asset_identifier ${JSON.stringify(assetIdentifier)} has a malformed chain part ${JSON.stringify(chainPart)}: expected <namespace>:<reference>`);
787
+ }
788
+ const namespace = chainPart.slice(0, chainColon);
789
+ if (namespace !== namespace.toLowerCase()) {
790
+ 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`);
791
+ }
792
+ return namespace;
793
+ }
794
+ function countChar(s, c) {
795
+ let n = 0;
796
+ for (const ch of s) {
797
+ if (ch === c)
798
+ n++;
799
+ }
800
+ return n;
801
+ }
802
+ }
803
+ });
804
+
247
805
  // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/utils.js
248
806
  var require_utils = __commonJS({
249
807
  "../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/utils.js"(exports2) {
250
808
  "use strict";
251
809
  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;
810
+ exports2.REQUEST_ID_DOMAIN = exports2.SOLANA_REPLAY_BUCKETS = exports2.SOLANA_REPLAY_SLOTS = exports2.PERMIT_NONCE_DOMAIN = exports2.REPLAY_HORIZON_SECS = void 0;
253
811
  exports2.resolvePermitDeadline = resolvePermitDeadline;
254
812
  exports2.generatePermitNonce = generatePermitNonce;
255
813
  exports2.resolvePermitNonce = resolvePermitNonce;
@@ -257,6 +815,7 @@ var require_utils = __commonJS({
257
815
  exports2.deterministicPermitNonce = deterministicPermitNonce2;
258
816
  exports2.deterministicSolanaNonce = deterministicSolanaNonce2;
259
817
  exports2.deterministicRequestId = deterministicRequestId;
818
+ exports2.parseSourceAsset = parseSourceAsset;
260
819
  exports2.sameAddress = sameAddress;
261
820
  exports2.assertKeyMatchesSender = assertKeyMatchesSender2;
262
821
  exports2.assertToken = assertToken;
@@ -265,8 +824,11 @@ var require_utils = __commonJS({
265
824
  exports2.assertSpender = assertSpender;
266
825
  exports2.assertWitnessRoles = assertWitnessRoles;
267
826
  exports2.assertRolePairComplete = assertRolePairComplete;
827
+ exports2.assertDestination = assertDestination;
828
+ exports2.assertDepositRequestHash = assertDepositRequestHash;
268
829
  exports2.nowSec = nowSec;
269
830
  var ethers_1 = require("ethers");
831
+ var destination_js_1 = require_destination();
270
832
  exports2.REPLAY_HORIZON_SECS = 128;
271
833
  function resolvePermitDeadline(deadline) {
272
834
  return BigInt(deadline);
@@ -281,7 +843,7 @@ var require_utils = __commonJS({
281
843
  }
282
844
  exports2.PERMIT_NONCE_DOMAIN = "atum-permit:v1:";
283
845
  exports2.SOLANA_REPLAY_SLOTS = 235n;
284
- var SOLANA_BUCKET_BITS = 17n;
846
+ exports2.SOLANA_REPLAY_BUCKETS = 256n;
285
847
  function canonicalDepositor(depositor) {
286
848
  const lower = depositor.toLowerCase();
287
849
  return lower.startsWith("0x") ? lower : depositor;
@@ -298,7 +860,7 @@ var require_utils = __commonJS({
298
860
  function deterministicSolanaNonce2(params) {
299
861
  const seed = permitNonceSeed(params.requestId, params.depositor);
300
862
  const slot = seed % exports2.SOLANA_REPLAY_SLOTS;
301
- const bucket = (seed >> 8n) % (1n << SOLANA_BUCKET_BITS);
863
+ const bucket = (seed >> 8n) % exports2.SOLANA_REPLAY_BUCKETS;
302
864
  return bucket << 32n | slot;
303
865
  }
304
866
  exports2.REQUEST_ID_DOMAIN = "atum-request:v1:";
@@ -315,6 +877,17 @@ var require_utils = __commonJS({
315
877
  const digest = (0, ethers_1.keccak256)((0, ethers_1.toUtf8Bytes)(`${exports2.REQUEST_ID_DOMAIN}${params.anchor}:${canonicalDepositor(params.account)}`));
316
878
  return `${params.prefix}${digest.slice(2, 26)}`;
317
879
  }
880
+ function parseSourceAsset(assetIdentifier) {
881
+ const parts = typeof assetIdentifier === "string" ? assetIdentifier.split("/") : [];
882
+ const nsParts = parts[1]?.split(":");
883
+ if (parts.length === 3 && parts[0] && parts[1] && parts[2]) {
884
+ throw new Error(`sender_auth: source asset ${JSON.stringify(assetIdentifier)} names a token id, which a deposit cannot bind`);
885
+ }
886
+ if (parts.length !== 2 || !parts[0] || !nsParts || nsParts.length !== 2 || !nsParts[0] || !nsParts[1]) {
887
+ throw new Error(`sender_auth: invalid source asset ${JSON.stringify(assetIdentifier)}`);
888
+ }
889
+ return { network: parts[0], asset: nsParts[1] };
890
+ }
318
891
  function sameAddress(a, b) {
319
892
  if (a.startsWith("0x") && b.startsWith("0x")) {
320
893
  return a.toLowerCase() === b.toLowerCase();
@@ -356,6 +929,17 @@ var require_utils = __commonJS({
356
929
  throw new Error("sender_auth: reserver and releaser must be supplied together");
357
930
  }
358
931
  }
932
+ function assertDestination(signed, expected) {
933
+ if (signed !== expected) {
934
+ 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`);
935
+ }
936
+ }
937
+ function assertDepositRequestHash(signedHex, expectedRequestId) {
938
+ const expected = (0, destination_js_1.deriveDepositRequestHash)(expectedRequestId);
939
+ if (signedHex.toLowerCase() !== expected.toLowerCase()) {
940
+ 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`);
941
+ }
942
+ }
359
943
  function nowSec() {
360
944
  return Math.floor(Date.now() / 1e3);
361
945
  }
@@ -367,7 +951,7 @@ var require_chain_id2 = __commonJS({
367
951
  "../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/chain-id.js"(exports2) {
368
952
  "use strict";
369
953
  Object.defineProperty(exports2, "__esModule", { value: true });
370
- exports2.TRON_PERMIT2_FALLBACKS = exports2.TRON_CHAIN_IDS = void 0;
954
+ exports2.TRON_PERMIT2_FALLBACKS = exports2.TRON_CHAIN_IDS = exports2.MAX_EVM_CHAIN_ID = void 0;
371
955
  exports2.namespaceOf = namespaceOf;
372
956
  exports2.evmChainId = evmChainId;
373
957
  exports2.tronNumericChainId = tronNumericChainId;
@@ -376,21 +960,30 @@ var require_chain_id2 = __commonJS({
376
960
  function namespaceOf(network) {
377
961
  return network.split(":")[0];
378
962
  }
963
+ exports2.MAX_EVM_CHAIN_ID = Number.MAX_SAFE_INTEGER;
379
964
  function evmChainId(network) {
380
965
  const match = /^eip155:([0-9]+)$/.exec(network);
381
966
  if (!match) {
382
967
  throw new Error(`sender_auth: expected an eip155 network, got ${network}`);
383
968
  }
384
- return Number(match[1]);
969
+ const chainId = Number(match[1]);
970
+ if (chainId > exports2.MAX_EVM_CHAIN_ID) {
971
+ throw new Error(`sender_auth: eip155 chain id ${match[1]} exceeds the EIP-2294 maximum (${exports2.MAX_EVM_CHAIN_ID})`);
972
+ }
973
+ return chainId;
385
974
  }
386
975
  exports2.TRON_CHAIN_IDS = {
387
976
  mainnet: 728126428,
388
977
  shasta: 2494104990
389
978
  };
390
979
  function tronNumericChainId(network) {
391
- const cluster = network.split(":")[1];
392
- const id = exports2.TRON_CHAIN_IDS[cluster ?? ""];
393
- if (id === void 0) {
980
+ if (namespaceOf(network) !== "tron") {
981
+ throw new Error(`sender_auth: expected a tron network, got ${network}`);
982
+ }
983
+ const segments = network.split(":");
984
+ const cluster = segments.length === 2 ? segments[1] : void 0;
985
+ const id = cluster !== void 0 && Object.hasOwn(exports2.TRON_CHAIN_IDS, cluster) ? exports2.TRON_CHAIN_IDS[cluster] : void 0;
986
+ if (typeof id !== "number") {
394
987
  throw new Error(`sender_auth: unsupported Tron network '${network}'`);
395
988
  }
396
989
  return id;
@@ -400,8 +993,8 @@ var require_chain_id2 = __commonJS({
400
993
  "tron:shasta": "TPUqJPASUn1zLvbLBgRZ5pBYrx7WSe5ahp"
401
994
  };
402
995
  function resolveTronPermit2(network) {
403
- const resolved = exports2.TRON_PERMIT2_FALLBACKS[network];
404
- if (!resolved) {
996
+ const resolved = Object.hasOwn(exports2.TRON_PERMIT2_FALLBACKS, network) ? exports2.TRON_PERMIT2_FALLBACKS[network] : void 0;
997
+ if (typeof resolved !== "string" || resolved === "") {
405
998
  throw new Error(`sender_auth: no Permit2 address known for Tron network '${network}'`);
406
999
  }
407
1000
  return resolved;
@@ -457,7 +1050,7 @@ var require_permit_types = __commonJS({
457
1050
  "../contracts/evm/escrow-encoding/typescript/dist/permit-types.js"(exports2) {
458
1051
  "use strict";
459
1052
  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;
1053
+ 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
1054
  exports2.createPermit2Domain = createPermit2Domain;
462
1055
  exports2.createEscrowDomain = createEscrowDomain;
463
1056
  exports2.PERMIT_WITNESS_TYPES = {
@@ -540,6 +1133,63 @@ var require_permit_types = __commonJS({
540
1133
  { name: "settler", type: "address" }
541
1134
  ]
542
1135
  };
1136
+ exports2.PERMIT_WITNESS_TYPES_WITH_DESTINATION = {
1137
+ PermitWitnessTransferFrom: [
1138
+ { name: "permitted", type: "TokenPermissions" },
1139
+ { name: "spender", type: "address" },
1140
+ { name: "nonce", type: "uint256" },
1141
+ { name: "deadline", type: "uint256" },
1142
+ { name: "witness", type: "DepositWitness" }
1143
+ ],
1144
+ TokenPermissions: [
1145
+ { name: "token", type: "address" },
1146
+ { name: "amount", type: "uint256" }
1147
+ ],
1148
+ DepositWitness: [
1149
+ { name: "depositRequestHash", type: "bytes32" },
1150
+ { name: "destination", type: "string" },
1151
+ { name: "reserver", type: "address" },
1152
+ { name: "releaser", type: "address" }
1153
+ ]
1154
+ };
1155
+ exports2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE = {
1156
+ ReserveWitness: [
1157
+ { name: "depositId", type: "bytes32" },
1158
+ { name: "quoteHash", type: "bytes32" },
1159
+ { name: "settler", type: "address" },
1160
+ { name: "sourceAmount", type: "uint256" }
1161
+ ]
1162
+ };
1163
+ exports2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH = {
1164
+ ReleaseWitness: [
1165
+ { name: "depositId", type: "bytes32" },
1166
+ { name: "quoteHash", type: "bytes32" },
1167
+ { name: "depositRequestHash", type: "bytes32" },
1168
+ { name: "destinationHash", type: "bytes32" },
1169
+ { name: "depositor", type: "address" },
1170
+ { name: "token", type: "address" },
1171
+ { name: "amount", type: "uint256" },
1172
+ { name: "feeAmount", type: "uint256" },
1173
+ { name: "reserver", type: "address" },
1174
+ { name: "releaser", type: "address" },
1175
+ { name: "settler", type: "address" }
1176
+ ]
1177
+ };
1178
+ exports2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH = {
1179
+ RefundWitness: [
1180
+ { name: "depositId", type: "bytes32" },
1181
+ { name: "quoteHash", type: "bytes32" },
1182
+ { name: "depositRequestHash", type: "bytes32" },
1183
+ { name: "destinationHash", type: "bytes32" },
1184
+ { name: "depositor", type: "address" },
1185
+ { name: "token", type: "address" },
1186
+ { name: "amount", type: "uint256" },
1187
+ { name: "feeAmount", type: "uint256" },
1188
+ { name: "reserver", type: "address" },
1189
+ { name: "releaser", type: "address" },
1190
+ { name: "settler", type: "address" }
1191
+ ]
1192
+ };
543
1193
  }
544
1194
  });
545
1195
 
@@ -666,6 +1316,8 @@ var require_escrow_abi = __commonJS({
666
1316
  name: "depositWitness",
667
1317
  type: "tuple",
668
1318
  components: [
1319
+ { name: "depositRequestHash", type: "bytes32" },
1320
+ { name: "destination", type: "string" },
669
1321
  { name: "reserver", type: "address" },
670
1322
  { name: "releaser", type: "address" }
671
1323
  ]
@@ -675,15 +1327,17 @@ var require_escrow_abi = __commonJS({
675
1327
  name: "reserveWitness",
676
1328
  type: "tuple",
677
1329
  components: [
678
- { name: "paymentId", type: "bytes32" },
679
- { name: "settler", type: "address" }
1330
+ { name: "depositId", type: "bytes32" },
1331
+ { name: "quoteHash", type: "bytes32" },
1332
+ { name: "settler", type: "address" },
1333
+ { name: "sourceAmount", type: "uint256" }
680
1334
  ]
681
1335
  },
682
1336
  { name: "reserveSignature", type: "bytes" }
683
1337
  ]
684
1338
  }
685
1339
  ],
686
- outputs: [{ name: "paymentId", type: "bytes32" }],
1340
+ outputs: [{ name: "depositId", type: "bytes32" }],
687
1341
  stateMutability: "nonpayable"
688
1342
  },
689
1343
  {
@@ -698,7 +1352,10 @@ var require_escrow_abi = __commonJS({
698
1352
  name: "refundWitness",
699
1353
  type: "tuple",
700
1354
  components: [
701
- { name: "paymentId", type: "bytes32" },
1355
+ { name: "depositId", type: "bytes32" },
1356
+ { name: "quoteHash", type: "bytes32" },
1357
+ { name: "depositRequestHash", type: "bytes32" },
1358
+ { name: "destinationHash", type: "bytes32" },
702
1359
  { name: "depositor", type: "address" },
703
1360
  { name: "token", type: "address" },
704
1361
  { name: "amount", type: "uint256" },
@@ -718,7 +1375,7 @@ var require_escrow_abi = __commonJS({
718
1375
  {
719
1376
  type: "function",
720
1377
  name: "getDepositHash",
721
- inputs: [{ name: "paymentId", type: "bytes32" }],
1378
+ inputs: [{ name: "depositId", type: "bytes32" }],
722
1379
  outputs: [{ name: "", type: "bytes32" }],
723
1380
  stateMutability: "view"
724
1381
  },
@@ -734,14 +1391,67 @@ var require_escrow_abi = __commonJS({
734
1391
  }
735
1392
  });
736
1393
 
1394
+ // ../contracts/evm/escrow-encoding/typescript/dist/witness-values.js
1395
+ var require_witness_values2 = __commonJS({
1396
+ "../contracts/evm/escrow-encoding/typescript/dist/witness-values.js"(exports2) {
1397
+ "use strict";
1398
+ Object.defineProperty(exports2, "__esModule", { value: true });
1399
+ exports2.normalizeBytes32 = normalizeBytes32;
1400
+ exports2.normalizeAddressField = normalizeAddressField;
1401
+ exports2.normalizeUint256 = normalizeUint256;
1402
+ exports2.chainIdToHex = chainIdToHex;
1403
+ var ethers_1 = require("ethers");
1404
+ function normalizeBytes32(label, value) {
1405
+ let bytes;
1406
+ try {
1407
+ bytes = (0, ethers_1.getBytes)(value);
1408
+ } catch {
1409
+ throw new Error(`${label} must be 0x-prefixed hex (32 bytes), got ${JSON.stringify(value)}`);
1410
+ }
1411
+ if (bytes.length !== 32) {
1412
+ throw new Error(`${label} must be exactly 32 bytes, got ${bytes.length}`);
1413
+ }
1414
+ return (0, ethers_1.hexlify)(bytes);
1415
+ }
1416
+ function normalizeAddressField(label, value) {
1417
+ try {
1418
+ return (0, ethers_1.getAddress)(value);
1419
+ } catch {
1420
+ throw new Error(`${label} must be a 20-byte hex address, got ${JSON.stringify(value)}`);
1421
+ }
1422
+ }
1423
+ function normalizeUint256(label, value) {
1424
+ let n;
1425
+ try {
1426
+ n = BigInt(value);
1427
+ } catch {
1428
+ throw new Error(`${label} must be an integer (bigint or decimal string), got ${JSON.stringify(value)}`);
1429
+ }
1430
+ if (n < 0n) {
1431
+ throw new Error(`${label} must be non-negative (uint256), got ${n.toString()}`);
1432
+ }
1433
+ return n.toString();
1434
+ }
1435
+ function chainIdToHex(chainId) {
1436
+ if (!Number.isSafeInteger(chainId) || chainId < 0) {
1437
+ throw new Error(`chainId must be a non-negative safe integer, got ${chainId}`);
1438
+ }
1439
+ return `0x${chainId.toString(16)}`;
1440
+ }
1441
+ }
1442
+ });
1443
+
737
1444
  // ../contracts/evm/escrow-encoding/typescript/dist/reserve-encoder.js
738
1445
  var require_reserve_encoder2 = __commonJS({
739
1446
  "../contracts/evm/escrow-encoding/typescript/dist/reserve-encoder.js"(exports2) {
740
1447
  "use strict";
741
1448
  Object.defineProperty(exports2, "__esModule", { value: true });
742
1449
  exports2.computeReserveDigest = computeReserveDigest;
1450
+ exports2.buildReserveTypedDataWithQuoteSource = buildReserveTypedDataWithQuoteSource;
1451
+ exports2.computeReserveDigestWithQuoteSource = computeReserveDigestWithQuoteSource;
743
1452
  var ethers_1 = require("ethers");
744
1453
  var permit_types_1 = require_permit_types();
1454
+ var witness_values_1 = require_witness_values2();
745
1455
  function computeReserveDigest(input) {
746
1456
  const domain = (0, permit_types_1.createEscrowDomain)(input.chainId, input.escrowContract);
747
1457
  return ethers_1.TypedDataEncoder.hash(domain, permit_types_1.RESERVE_WITNESS_TYPES, {
@@ -749,6 +1459,114 @@ var require_reserve_encoder2 = __commonJS({
749
1459
  settler: input.settler
750
1460
  });
751
1461
  }
1462
+ function buildReserveTypedDataWithQuoteSource(input) {
1463
+ return {
1464
+ types: permit_types_1.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE,
1465
+ primaryType: "ReserveWitness",
1466
+ domain: {
1467
+ name: "Escrow",
1468
+ version: "3",
1469
+ chainId: (0, witness_values_1.chainIdToHex)(input.chainId),
1470
+ verifyingContract: (0, witness_values_1.normalizeAddressField)("escrowContract", input.escrowContract)
1471
+ },
1472
+ message: {
1473
+ depositId: (0, witness_values_1.normalizeBytes32)("depositId", input.depositId),
1474
+ quoteHash: (0, witness_values_1.normalizeBytes32)("quoteHash", input.quoteHash),
1475
+ settler: (0, witness_values_1.normalizeAddressField)("settler", input.settler),
1476
+ sourceAmount: (0, witness_values_1.normalizeUint256)("sourceAmount", input.sourceAmount)
1477
+ }
1478
+ };
1479
+ }
1480
+ function computeReserveDigestWithQuoteSource(input) {
1481
+ const prehash = buildReserveTypedDataWithQuoteSource(input);
1482
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
1483
+ }
1484
+ }
1485
+ });
1486
+
1487
+ // ../contracts/evm/escrow-encoding/typescript/dist/release-encoder.js
1488
+ var require_release_encoder2 = __commonJS({
1489
+ "../contracts/evm/escrow-encoding/typescript/dist/release-encoder.js"(exports2) {
1490
+ "use strict";
1491
+ Object.defineProperty(exports2, "__esModule", { value: true });
1492
+ exports2.buildReleaseTypedDataWithQuoteHash = buildReleaseTypedDataWithQuoteHash;
1493
+ exports2.computeReleaseDigestWithQuoteHash = computeReleaseDigestWithQuoteHash;
1494
+ var ethers_1 = require("ethers");
1495
+ var permit_types_1 = require_permit_types();
1496
+ var witness_values_1 = require_witness_values2();
1497
+ function buildReleaseTypedDataWithQuoteHash(input) {
1498
+ const w = input.witness;
1499
+ return {
1500
+ types: permit_types_1.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH,
1501
+ primaryType: "ReleaseWitness",
1502
+ domain: {
1503
+ name: "Escrow",
1504
+ version: "3",
1505
+ chainId: (0, witness_values_1.chainIdToHex)(input.chainId),
1506
+ verifyingContract: (0, witness_values_1.normalizeAddressField)("escrowContract", input.escrowContract)
1507
+ },
1508
+ message: {
1509
+ depositId: (0, witness_values_1.normalizeBytes32)("depositId", w.depositId),
1510
+ quoteHash: (0, witness_values_1.normalizeBytes32)("quoteHash", w.quoteHash),
1511
+ depositRequestHash: (0, witness_values_1.normalizeBytes32)("depositRequestHash", w.depositRequestHash),
1512
+ destinationHash: (0, witness_values_1.normalizeBytes32)("destinationHash", w.destinationHash),
1513
+ depositor: (0, witness_values_1.normalizeAddressField)("depositor", w.depositor),
1514
+ token: (0, witness_values_1.normalizeAddressField)("token", w.token),
1515
+ amount: (0, witness_values_1.normalizeUint256)("amount", w.amount),
1516
+ feeAmount: (0, witness_values_1.normalizeUint256)("feeAmount", w.feeAmount),
1517
+ reserver: (0, witness_values_1.normalizeAddressField)("reserver", w.reserver),
1518
+ releaser: (0, witness_values_1.normalizeAddressField)("releaser", w.releaser),
1519
+ settler: (0, witness_values_1.normalizeAddressField)("settler", w.settler)
1520
+ }
1521
+ };
1522
+ }
1523
+ function computeReleaseDigestWithQuoteHash(input) {
1524
+ const prehash = buildReleaseTypedDataWithQuoteHash(input);
1525
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
1526
+ }
1527
+ }
1528
+ });
1529
+
1530
+ // ../contracts/evm/escrow-encoding/typescript/dist/refund-encoder.js
1531
+ var require_refund_encoder2 = __commonJS({
1532
+ "../contracts/evm/escrow-encoding/typescript/dist/refund-encoder.js"(exports2) {
1533
+ "use strict";
1534
+ Object.defineProperty(exports2, "__esModule", { value: true });
1535
+ exports2.buildRefundTypedDataWithQuoteHash = buildRefundTypedDataWithQuoteHash;
1536
+ exports2.computeRefundDigestWithQuoteHash = computeRefundDigestWithQuoteHash;
1537
+ var ethers_1 = require("ethers");
1538
+ var permit_types_1 = require_permit_types();
1539
+ var witness_values_1 = require_witness_values2();
1540
+ function buildRefundTypedDataWithQuoteHash(input) {
1541
+ const w = input.witness;
1542
+ return {
1543
+ types: permit_types_1.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH,
1544
+ primaryType: "RefundWitness",
1545
+ domain: {
1546
+ name: "Escrow",
1547
+ version: "3",
1548
+ chainId: (0, witness_values_1.chainIdToHex)(input.chainId),
1549
+ verifyingContract: (0, witness_values_1.normalizeAddressField)("escrowContract", input.escrowContract)
1550
+ },
1551
+ message: {
1552
+ depositId: (0, witness_values_1.normalizeBytes32)("depositId", w.depositId),
1553
+ quoteHash: (0, witness_values_1.normalizeBytes32)("quoteHash", w.quoteHash),
1554
+ depositRequestHash: (0, witness_values_1.normalizeBytes32)("depositRequestHash", w.depositRequestHash),
1555
+ destinationHash: (0, witness_values_1.normalizeBytes32)("destinationHash", w.destinationHash),
1556
+ depositor: (0, witness_values_1.normalizeAddressField)("depositor", w.depositor),
1557
+ token: (0, witness_values_1.normalizeAddressField)("token", w.token),
1558
+ amount: (0, witness_values_1.normalizeUint256)("amount", w.amount),
1559
+ feeAmount: (0, witness_values_1.normalizeUint256)("feeAmount", w.feeAmount),
1560
+ reserver: (0, witness_values_1.normalizeAddressField)("reserver", w.reserver),
1561
+ releaser: (0, witness_values_1.normalizeAddressField)("releaser", w.releaser),
1562
+ settler: (0, witness_values_1.normalizeAddressField)("settler", w.settler)
1563
+ }
1564
+ };
1565
+ }
1566
+ function computeRefundDigestWithQuoteHash(input) {
1567
+ const prehash = buildRefundTypedDataWithQuoteHash(input);
1568
+ return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
1569
+ }
752
1570
  }
753
1571
  });
754
1572
 
@@ -757,11 +1575,13 @@ var require_deposit_encoder2 = __commonJS({
757
1575
  "../contracts/evm/escrow-encoding/typescript/dist/deposit-encoder.js"(exports2) {
758
1576
  "use strict";
759
1577
  Object.defineProperty(exports2, "__esModule", { value: true });
760
- exports2.PERMIT2_CONTRACT_ADDRESS = void 0;
1578
+ exports2.MAX_DESTINATION_BYTES = exports2.PERMIT2_CONTRACT_ADDRESS = void 0;
761
1579
  exports2.createPermitWitnessTransferFromPrehash = createPermitWitnessTransferFromPrehash2;
762
1580
  exports2.hashPermitWitnessTransferFrom = hashPermitWitnessTransferFrom2;
1581
+ exports2.createPermitWitnessTransferFromPrehashWithDestination = createPermitWitnessTransferFromPrehashWithDestination;
763
1582
  var ethers_1 = require("ethers");
764
1583
  var permit_types_1 = require_permit_types();
1584
+ var witness_values_1 = require_witness_values2();
765
1585
  exports2.PERMIT2_CONTRACT_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
766
1586
  function createPermitWitnessTransferFromPrehash2(params) {
767
1587
  return {
@@ -790,15 +1610,52 @@ var require_deposit_encoder2 = __commonJS({
790
1610
  function hashPermitWitnessTransferFrom2(prehash) {
791
1611
  return ethers_1.TypedDataEncoder.hash(prehash.domain, prehash.types, prehash.message);
792
1612
  }
1613
+ exports2.MAX_DESTINATION_BYTES = 256;
1614
+ function assertDestinationWithinBounds(destination) {
1615
+ if (destination === "") {
1616
+ 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');
1617
+ }
1618
+ const byteLength = (0, ethers_1.toUtf8Bytes)(destination).length;
1619
+ if (byteLength > exports2.MAX_DESTINATION_BYTES) {
1620
+ 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`);
1621
+ }
1622
+ }
1623
+ function createPermitWitnessTransferFromPrehashWithDestination(params) {
1624
+ assertDestinationWithinBounds(params.destination);
1625
+ return {
1626
+ types: permit_types_1.PERMIT_WITNESS_TYPES_WITH_DESTINATION,
1627
+ primaryType: "PermitWitnessTransferFrom",
1628
+ domain: {
1629
+ name: "Permit2",
1630
+ chainId: (0, witness_values_1.chainIdToHex)(params.chainId),
1631
+ verifyingContract: (0, witness_values_1.normalizeAddressField)("verifyingContract", params.verifyingContract)
1632
+ },
1633
+ message: {
1634
+ permitted: {
1635
+ token: (0, witness_values_1.normalizeAddressField)("token", params.token),
1636
+ amount: (0, witness_values_1.normalizeUint256)("amount", params.amount)
1637
+ },
1638
+ spender: (0, witness_values_1.normalizeAddressField)("spender", params.spender),
1639
+ nonce: (0, witness_values_1.normalizeUint256)("nonce", params.nonce),
1640
+ deadline: (0, witness_values_1.normalizeUint256)("deadline", params.deadline),
1641
+ witness: {
1642
+ depositRequestHash: (0, witness_values_1.normalizeBytes32)("depositRequestHash", params.depositRequestHash),
1643
+ destination: params.destination,
1644
+ reserver: (0, witness_values_1.normalizeAddressField)("reserver", params.reserver),
1645
+ releaser: (0, witness_values_1.normalizeAddressField)("releaser", params.releaser)
1646
+ }
1647
+ }
1648
+ };
1649
+ }
793
1650
  }
794
1651
  });
795
1652
 
796
1653
  // ../contracts/evm/escrow-encoding/typescript/dist/index.js
797
- var require_dist2 = __commonJS({
1654
+ var require_dist3 = __commonJS({
798
1655
  "../contracts/evm/escrow-encoding/typescript/dist/index.js"(exports2) {
799
1656
  "use strict";
800
1657
  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;
1658
+ 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
1659
  var payment_id_1 = require_payment_id2();
803
1660
  Object.defineProperty(exports2, "computePaymentId", { enumerable: true, get: function() {
804
1661
  return payment_id_1.computePaymentId;
@@ -832,6 +1689,19 @@ var require_dist2 = __commonJS({
832
1689
  Object.defineProperty(exports2, "REFUND_WITNESS_TYPES", { enumerable: true, get: function() {
833
1690
  return permit_types_1.REFUND_WITNESS_TYPES;
834
1691
  } });
1692
+ var permit_types_2 = require_permit_types();
1693
+ Object.defineProperty(exports2, "PERMIT_WITNESS_TYPES_WITH_DESTINATION", { enumerable: true, get: function() {
1694
+ return permit_types_2.PERMIT_WITNESS_TYPES_WITH_DESTINATION;
1695
+ } });
1696
+ Object.defineProperty(exports2, "RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE", { enumerable: true, get: function() {
1697
+ return permit_types_2.RESERVE_WITNESS_TYPES_WITH_QUOTE_SOURCE;
1698
+ } });
1699
+ Object.defineProperty(exports2, "RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH", { enumerable: true, get: function() {
1700
+ return permit_types_2.RELEASE_WITNESS_TYPES_WITH_QUOTE_HASH;
1701
+ } });
1702
+ Object.defineProperty(exports2, "REFUND_WITNESS_TYPES_WITH_QUOTE_HASH", { enumerable: true, get: function() {
1703
+ return permit_types_2.REFUND_WITNESS_TYPES_WITH_QUOTE_HASH;
1704
+ } });
835
1705
  var escrow_abi_1 = require_escrow_abi();
836
1706
  Object.defineProperty(exports2, "ESCROW_ABI", { enumerable: true, get: function() {
837
1707
  return escrow_abi_1.ESCROW_ABI;
@@ -849,6 +1719,27 @@ var require_dist2 = __commonJS({
849
1719
  Object.defineProperty(exports2, "computeReserveDigest", { enumerable: true, get: function() {
850
1720
  return reserve_encoder_1.computeReserveDigest;
851
1721
  } });
1722
+ var reserve_encoder_2 = require_reserve_encoder2();
1723
+ Object.defineProperty(exports2, "buildReserveTypedDataWithQuoteSource", { enumerable: true, get: function() {
1724
+ return reserve_encoder_2.buildReserveTypedDataWithQuoteSource;
1725
+ } });
1726
+ Object.defineProperty(exports2, "computeReserveDigestWithQuoteSource", { enumerable: true, get: function() {
1727
+ return reserve_encoder_2.computeReserveDigestWithQuoteSource;
1728
+ } });
1729
+ var release_encoder_1 = require_release_encoder2();
1730
+ Object.defineProperty(exports2, "buildReleaseTypedDataWithQuoteHash", { enumerable: true, get: function() {
1731
+ return release_encoder_1.buildReleaseTypedDataWithQuoteHash;
1732
+ } });
1733
+ Object.defineProperty(exports2, "computeReleaseDigestWithQuoteHash", { enumerable: true, get: function() {
1734
+ return release_encoder_1.computeReleaseDigestWithQuoteHash;
1735
+ } });
1736
+ var refund_encoder_1 = require_refund_encoder2();
1737
+ Object.defineProperty(exports2, "buildRefundTypedDataWithQuoteHash", { enumerable: true, get: function() {
1738
+ return refund_encoder_1.buildRefundTypedDataWithQuoteHash;
1739
+ } });
1740
+ Object.defineProperty(exports2, "computeRefundDigestWithQuoteHash", { enumerable: true, get: function() {
1741
+ return refund_encoder_1.computeRefundDigestWithQuoteHash;
1742
+ } });
852
1743
  var deposit_encoder_1 = require_deposit_encoder2();
853
1744
  Object.defineProperty(exports2, "createPermitWitnessTransferFromPrehash", { enumerable: true, get: function() {
854
1745
  return deposit_encoder_1.createPermitWitnessTransferFromPrehash;
@@ -859,6 +1750,13 @@ var require_dist2 = __commonJS({
859
1750
  Object.defineProperty(exports2, "PERMIT2_CONTRACT_ADDRESS", { enumerable: true, get: function() {
860
1751
  return deposit_encoder_1.PERMIT2_CONTRACT_ADDRESS;
861
1752
  } });
1753
+ var deposit_encoder_2 = require_deposit_encoder2();
1754
+ Object.defineProperty(exports2, "createPermitWitnessTransferFromPrehashWithDestination", { enumerable: true, get: function() {
1755
+ return deposit_encoder_2.createPermitWitnessTransferFromPrehashWithDestination;
1756
+ } });
1757
+ Object.defineProperty(exports2, "MAX_DESTINATION_BYTES", { enumerable: true, get: function() {
1758
+ return deposit_encoder_2.MAX_DESTINATION_BYTES;
1759
+ } });
862
1760
  }
863
1761
  });
864
1762
 
@@ -899,24 +1797,25 @@ var require_evm = __commonJS({
899
1797
  Object.defineProperty(exports2, "__esModule", { value: true });
900
1798
  exports2.evmAdapter = void 0;
901
1799
  var ethers_1 = require("ethers");
902
- var evm_escrow_encoding_1 = require_dist2();
1800
+ var evm_escrow_encoding_1 = require_dist3();
903
1801
  var utils_js_1 = require_utils();
1802
+ var destination_js_1 = require_destination();
904
1803
  var errors_js_1 = require_errors();
905
1804
  var chain_id_js_1 = require_chain_id2();
906
1805
  exports2.evmAdapter = {
907
- async buildAuthMessage({ sourceAsset, maxSourceAmount, sourceDefaults, deadline, nonce }) {
1806
+ async buildAuthMessage({ sourceAsset, maxSourceAmount, requestId, sourceDefaults, destinationAsset, destinationAccount, deadline, nonce }) {
908
1807
  if (nonce === void 0) {
909
1808
  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
1809
  }
911
1810
  if (deadline === void 0) {
912
1811
  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
1812
  }
914
- const sourceChainId = sourceAsset.split("/")[0];
915
- const chainIdNum = parseInt(sourceChainId.split(":")[1]);
916
- const tokenAddress = sourceAsset.split("/")[1].split(":")[1];
917
- const permitParams = {
1813
+ const { network: sourceChainId, asset: tokenAddress } = (0, utils_js_1.parseSourceAsset)(sourceAsset);
1814
+ const chainIdNum = (0, chain_id_js_1.evmChainId)(sourceChainId);
1815
+ const permit2Contract = sourceDefaults.permit2Contract ?? evm_escrow_encoding_1.PERMIT2_CONTRACT_ADDRESS;
1816
+ const basePermit = {
918
1817
  chainId: chainIdNum,
919
- verifyingContract: evm_escrow_encoding_1.PERMIT2_CONTRACT_ADDRESS,
1818
+ verifyingContract: permit2Contract,
920
1819
  token: tokenAddress,
921
1820
  amount: maxSourceAmount,
922
1821
  spender: sourceDefaults.escrowContract,
@@ -925,7 +1824,21 @@ var require_evm = __commonJS({
925
1824
  reserver: sourceDefaults.quoteSelector,
926
1825
  releaser: sourceDefaults.fulfillmentVerifierAccount
927
1826
  };
928
- const messagePrehash = (0, evm_escrow_encoding_1.createPermitWitnessTransferFromPrehash)(permitParams);
1827
+ if ((0, destination_js_1.usesDestinationCommitment)(sourceDefaults.depositWitnessVersion)) {
1828
+ const permitParams = {
1829
+ ...basePermit,
1830
+ // The two escrow commitments. Composed here through the shared helpers rather than
1831
+ // accepted pre-built, so this producer and the release signer cannot disagree about
1832
+ // formatting — a disagreement the escrow cannot detect, because it stores only
1833
+ // keccak256(bytes(destination)).
1834
+ depositRequestHash: (0, destination_js_1.deriveDepositRequestHash)(requestId),
1835
+ destination: (0, destination_js_1.buildEscrowDestination)(destinationAsset, destinationAccount)
1836
+ };
1837
+ const messagePrehash2 = (0, evm_escrow_encoding_1.createPermitWitnessTransferFromPrehashWithDestination)(permitParams);
1838
+ const messageHash2 = (0, evm_escrow_encoding_1.hashPermitWitnessTransferFrom)(messagePrehash2);
1839
+ return { messageScheme: "EVM_PERMIT2", messageHash: messageHash2, messagePrehash: JSON.stringify(messagePrehash2) };
1840
+ }
1841
+ const messagePrehash = (0, evm_escrow_encoding_1.createPermitWitnessTransferFromPrehash)(basePermit);
929
1842
  const messageHash = (0, evm_escrow_encoding_1.hashPermitWitnessTransferFrom)(messagePrehash);
930
1843
  return { messageScheme: "EVM_PERMIT2", messageHash, messagePrehash: JSON.stringify(messagePrehash) };
931
1844
  },
@@ -958,17 +1871,31 @@ var require_evm = __commonJS({
958
1871
  let msg;
959
1872
  try {
960
1873
  msg = JSON.parse(signed.message_prehash).message;
961
- canonical = (0, evm_escrow_encoding_1.createPermitWitnessTransferFromPrehash)({
1874
+ const base = {
962
1875
  chainId: (0, chain_id_js_1.evmChainId)(source.network),
963
- verifyingContract: evm_escrow_encoding_1.PERMIT2_CONTRACT_ADDRESS,
1876
+ // The same Permit2 buildAuthMessage signed against. Taken from the VERIFIER's
1877
+ // expectations, never from msg — the prehash is client-supplied, so reading the domain
1878
+ // out of it would let a caller nominate its own verifying contract and have the
1879
+ // signature check itself. Absent means canonical, matching the build side's default.
1880
+ verifyingContract: expected.permit2Contract ?? evm_escrow_encoding_1.PERMIT2_CONTRACT_ADDRESS,
964
1881
  token: msg.permitted.token,
965
1882
  amount: msg.permitted.amount,
966
1883
  spender: msg.spender,
967
1884
  nonce: BigInt(msg.nonce),
968
1885
  deadline: BigInt(msg.deadline),
969
- reserver: msg.witness.reserver,
970
- releaser: msg.witness.releaser
971
- });
1886
+ reserver: msg.witness?.reserver,
1887
+ releaser: msg.witness?.releaser
1888
+ };
1889
+ const hasHash = typeof msg.witness?.depositRequestHash === "string";
1890
+ const hasDestination = typeof msg.witness?.destination === "string";
1891
+ if (hasHash !== hasDestination) {
1892
+ throw new Error("half-populated deposit witness");
1893
+ }
1894
+ canonical = hasHash ? (0, evm_escrow_encoding_1.createPermitWitnessTransferFromPrehashWithDestination)({
1895
+ ...base,
1896
+ depositRequestHash: msg.witness.depositRequestHash,
1897
+ destination: msg.witness.destination
1898
+ }) : (0, evm_escrow_encoding_1.createPermitWitnessTransferFromPrehash)(base);
972
1899
  } catch {
973
1900
  throw new errors_js_1.MalformedPrehashError();
974
1901
  }
@@ -992,6 +1919,12 @@ var require_evm = __commonJS({
992
1919
  if (expected.reserver !== void 0 && expected.releaser !== void 0) {
993
1920
  (0, utils_js_1.assertWitnessRoles)(msg.witness.reserver, msg.witness.releaser, expected.reserver, expected.releaser, (a) => a);
994
1921
  }
1922
+ if (expected.destination !== void 0) {
1923
+ (0, utils_js_1.assertDestination)(msg.witness.destination, expected.destination);
1924
+ }
1925
+ if (expected.requestId !== void 0) {
1926
+ (0, utils_js_1.assertDepositRequestHash)(msg.witness.depositRequestHash, expected.requestId);
1927
+ }
995
1928
  return {
996
1929
  amount: msg.permitted.amount,
997
1930
  deadlineSec,
@@ -1002,7 +1935,11 @@ var require_evm = __commonJS({
1002
1935
  deadlineSec,
1003
1936
  reserver: msg.witness.reserver,
1004
1937
  releaser: msg.witness.releaser,
1005
- spender: msg.spender
1938
+ spender: msg.spender,
1939
+ // Surfaced whether or not the opt-in checks above ran, so a consumer binding these
1940
+ // downstream does not have to re-parse message_prehash and risk drifting from this parse.
1941
+ destination: msg.witness.destination,
1942
+ depositRequestHash: msg.witness.depositRequestHash
1006
1943
  }
1007
1944
  };
1008
1945
  }
@@ -1021,18 +1958,18 @@ var require_tron = __commonJS({
1021
1958
  var utils_js_1 = require_utils();
1022
1959
  var errors_js_1 = require_errors();
1023
1960
  var chain_id_js_1 = require_chain_id2();
1961
+ var destination_js_1 = require_destination();
1024
1962
  exports2.tronAdapter = {
1025
- async buildAuthMessage({ sourceAsset, maxSourceAmount, sourceDefaults, deadline, nonce }) {
1963
+ async buildAuthMessage({ sourceAsset, maxSourceAmount, requestId, sourceDefaults, destinationAsset, destinationAccount, deadline, nonce }) {
1026
1964
  if (nonce === void 0) {
1027
1965
  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
1966
  }
1029
1967
  if (deadline === void 0) {
1030
1968
  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
1969
  }
1032
- const sourceChainId = sourceAsset.split("/")[0];
1033
- const tokenAddress = sourceAsset.split("/")[1].split(":")[1];
1970
+ const { network: sourceChainId, asset: tokenAddress } = (0, utils_js_1.parseSourceAsset)(sourceAsset);
1034
1971
  const permit2Address = sourceDefaults.permit2Contract ?? (0, chain_id_js_1.resolveTronPermit2)(sourceChainId);
1035
- const tvmParams = {
1972
+ const baseParams = {
1036
1973
  chainId: (0, chain_id_js_1.tronNumericChainId)(sourceChainId),
1037
1974
  permit2Address,
1038
1975
  tokenAddress,
@@ -1043,7 +1980,21 @@ var require_tron = __commonJS({
1043
1980
  reserverAddress: sourceDefaults.quoteSelector,
1044
1981
  releaserAddress: sourceDefaults.fulfillmentVerifierAccount
1045
1982
  };
1046
- const messagePrehash = (0, tvm_escrow_encoding_1.createTvmPermitWitnessTransferFromPrehash)(tvmParams);
1983
+ if ((0, destination_js_1.usesDestinationCommitment)(sourceDefaults.depositWitnessVersion)) {
1984
+ const tvmParams = {
1985
+ ...baseParams,
1986
+ // The two commitments, composed through the shared helpers rather than accepted
1987
+ // pre-built, so this producer and the Go release signer cannot disagree about
1988
+ // formatting — a disagreement the escrow cannot detect, because it stores only
1989
+ // keccak256(bytes(destination)).
1990
+ depositRequestHash: (0, destination_js_1.deriveDepositRequestHash)(requestId),
1991
+ destination: (0, destination_js_1.buildEscrowDestination)(destinationAsset, destinationAccount)
1992
+ };
1993
+ const messagePrehash2 = (0, tvm_escrow_encoding_1.createTvmPermitWitnessTransferFromPrehashWithDestination)(tvmParams);
1994
+ const messageHash2 = (0, tvm_escrow_encoding_1.hashTvmPermitWitnessTransferFrom)(messagePrehash2);
1995
+ return { messageScheme: "EVM_PERMIT2", messageHash: messageHash2, messagePrehash: JSON.stringify(messagePrehash2) };
1996
+ }
1997
+ const messagePrehash = (0, tvm_escrow_encoding_1.createTvmPermitWitnessTransferFromPrehash)(baseParams);
1047
1998
  const messageHash = (0, tvm_escrow_encoding_1.hashTvmPermitWitnessTransferFrom)(messagePrehash);
1048
1999
  return { messageScheme: "EVM_PERMIT2", messageHash, messagePrehash: JSON.stringify(messagePrehash) };
1049
2000
  },
@@ -1078,17 +2029,31 @@ var require_tron = __commonJS({
1078
2029
  let digest;
1079
2030
  try {
1080
2031
  msg = JSON.parse(signed.message_prehash).message;
1081
- const canonical = (0, tvm_escrow_encoding_1.createTvmPermitWitnessTransferFromPrehash)({
2032
+ const base = {
1082
2033
  chainId: (0, chain_id_js_1.tronNumericChainId)(source.network),
1083
- permit2Address: (0, chain_id_js_1.resolveTronPermit2)(source.network),
2034
+ // The same Permit2 buildAuthMessage signed against, taken from the VERIFIER's
2035
+ // expectations rather than from msg — the prehash is payer-supplied, so reading the
2036
+ // domain out of it would let a caller nominate its own verifying contract. Absent means
2037
+ // the pinned per-chain address, matching the build side's default.
2038
+ permit2Address: expected.permit2Contract ?? (0, chain_id_js_1.resolveTronPermit2)(source.network),
1084
2039
  tokenAddress: msg.permitted.token,
1085
2040
  amount: msg.permitted.amount,
1086
2041
  spenderAddress: msg.spender,
1087
2042
  nonce: BigInt(msg.nonce),
1088
2043
  deadline: BigInt(msg.deadline),
1089
- reserverAddress: msg.witness.reserver,
1090
- releaserAddress: msg.witness.releaser
1091
- });
2044
+ reserverAddress: msg.witness?.reserver,
2045
+ releaserAddress: msg.witness?.releaser
2046
+ };
2047
+ const hasHash = typeof msg.witness?.depositRequestHash === "string";
2048
+ const hasDestination = typeof msg.witness?.destination === "string";
2049
+ if (hasHash !== hasDestination) {
2050
+ throw new Error("half-populated witness");
2051
+ }
2052
+ const canonical = hasHash ? (0, tvm_escrow_encoding_1.createTvmPermitWitnessTransferFromPrehashWithDestination)({
2053
+ ...base,
2054
+ depositRequestHash: msg.witness.depositRequestHash,
2055
+ destination: msg.witness.destination
2056
+ }) : (0, tvm_escrow_encoding_1.createTvmPermitWitnessTransferFromPrehash)(base);
1092
2057
  digest = (0, tvm_escrow_encoding_1.hashTvmPermitWitnessTransferFrom)(canonical);
1093
2058
  } catch {
1094
2059
  throw new errors_js_1.MalformedPrehashError();
@@ -1136,7 +2101,7 @@ var require_errors2 = __commonJS({
1136
2101
  "../contracts/svm/escrow-encoding/typescript/dist/errors.js"(exports2) {
1137
2102
  "use strict";
1138
2103
  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;
2104
+ 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
2105
  var EncodingError = class extends Error {
1141
2106
  constructor(message) {
1142
2107
  super(message);
@@ -1144,13 +2109,13 @@ var require_errors2 = __commonJS({
1144
2109
  }
1145
2110
  };
1146
2111
  exports2.EncodingError = EncodingError;
1147
- var ZeroPaymentIdError = class extends EncodingError {
2112
+ var ZeroDepositRequestHashError = class extends EncodingError {
1148
2113
  constructor() {
1149
- super("payment ID cannot be zero");
1150
- this.name = "ZeroPaymentIdError";
2114
+ super("deposit request hash cannot be zero");
2115
+ this.name = "ZeroDepositRequestHashError";
1151
2116
  }
1152
2117
  };
1153
- exports2.ZeroPaymentIdError = ZeroPaymentIdError;
2118
+ exports2.ZeroDepositRequestHashError = ZeroDepositRequestHashError;
1154
2119
  var ZeroDepositorError = class extends EncodingError {
1155
2120
  constructor() {
1156
2121
  super("depositor cannot be zero");
@@ -1221,6 +2186,34 @@ var require_errors2 = __commonJS({
1221
2186
  }
1222
2187
  };
1223
2188
  exports2.InvalidHexError = InvalidHexError;
2189
+ var ZeroQuoteHashError = class extends EncodingError {
2190
+ constructor() {
2191
+ super("quote hash cannot be zero");
2192
+ this.name = "ZeroQuoteHashError";
2193
+ }
2194
+ };
2195
+ exports2.ZeroQuoteHashError = ZeroQuoteHashError;
2196
+ var ZeroSourceAmountError = class extends EncodingError {
2197
+ constructor() {
2198
+ super("source amount cannot be zero");
2199
+ this.name = "ZeroSourceAmountError";
2200
+ }
2201
+ };
2202
+ exports2.ZeroSourceAmountError = ZeroSourceAmountError;
2203
+ var EmptyDestinationError = class extends EncodingError {
2204
+ constructor() {
2205
+ super("destination cannot be empty");
2206
+ this.name = "EmptyDestinationError";
2207
+ }
2208
+ };
2209
+ exports2.EmptyDestinationError = EmptyDestinationError;
2210
+ var DestinationTooLongError = class extends EncodingError {
2211
+ constructor() {
2212
+ super("destination exceeds the maximum length");
2213
+ this.name = "DestinationTooLongError";
2214
+ }
2215
+ };
2216
+ exports2.DestinationTooLongError = DestinationTooLongError;
1224
2217
  }
1225
2218
  });
1226
2219
 
@@ -1235,7 +2228,7 @@ var require_pubkey = __commonJS({
1235
2228
  exports2.Pubkey = void 0;
1236
2229
  var bs58_1 = __importDefault(require("bs58"));
1237
2230
  var errors_1 = require_errors2();
1238
- var Pubkey2 = class _Pubkey {
2231
+ var Pubkey = class _Pubkey {
1239
2232
  constructor(data) {
1240
2233
  if (data.length !== 32) {
1241
2234
  throw new errors_1.InvalidPubkeyLengthError();
@@ -1328,7 +2321,7 @@ var require_pubkey = __commonJS({
1328
2321
  return this.data.every((b, i) => b === other.data[i]);
1329
2322
  }
1330
2323
  };
1331
- exports2.Pubkey = Pubkey2;
2324
+ exports2.Pubkey = Pubkey;
1332
2325
  }
1333
2326
  });
1334
2327
 
@@ -1951,13 +2944,36 @@ var require_deposit_encoder3 = __commonJS({
1951
2944
  "../contracts/svm/escrow-encoding/typescript/dist/deposit-encoder.js"(exports2) {
1952
2945
  "use strict";
1953
2946
  Object.defineProperty(exports2, "__esModule", { value: true });
1954
- exports2.computeDepositHash = computeDepositHash2;
2947
+ exports2.MAX_DESTINATION_LEN = void 0;
2948
+ exports2.computeDepositHash = computeDepositHash;
2949
+ exports2.computeDestinationHash = computeDestinationHash;
2950
+ exports2.computeDepositHashV2 = computeDepositHashV2;
1955
2951
  var encoding_utils_1 = require_encoding_utils();
1956
2952
  var escrow_domain_1 = require_escrow_domain();
1957
2953
  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();
2954
+ function computeDepositHash(params, domain) {
2955
+ if (params.depositRequestHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositRequestHash)) {
2956
+ throw new errors_1.ZeroDepositRequestHashError();
2957
+ }
2958
+ if (params.depositor.isZero())
2959
+ throw new errors_1.ZeroDepositorError();
2960
+ if (params.mint.isZero())
2961
+ throw new errors_1.ZeroMintError();
2962
+ if (params.amount === 0n)
2963
+ throw new errors_1.ZeroAmountError();
2964
+ if (params.reserver.isZero())
2965
+ throw new errors_1.ZeroReserverError();
2966
+ if (params.releaser.isZero())
2967
+ throw new errors_1.ZeroReleaserError();
2968
+ 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));
2969
+ }
2970
+ exports2.MAX_DESTINATION_LEN = 256;
2971
+ function computeDestinationHash(destination) {
2972
+ return (0, encoding_utils_1.keccak256)((0, encoding_utils_1.stringToBytes)(destination));
2973
+ }
2974
+ function computeDepositHashV2(params, destination, domain) {
2975
+ if (params.depositRequestHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositRequestHash)) {
2976
+ throw new errors_1.ZeroDepositRequestHashError();
1961
2977
  }
1962
2978
  if (params.depositor.isZero())
1963
2979
  throw new errors_1.ZeroDepositorError();
@@ -1969,7 +2985,28 @@ var require_deposit_encoder3 = __commonJS({
1969
2985
  throw new errors_1.ZeroReserverError();
1970
2986
  if (params.releaser.isZero())
1971
2987
  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));
2988
+ if (destination.length === 0)
2989
+ throw new errors_1.EmptyDestinationError();
2990
+ if ((0, encoding_utils_1.stringToBytes)(destination).length > exports2.MAX_DESTINATION_LEN) {
2991
+ throw new errors_1.DestinationTooLongError();
2992
+ }
2993
+ return (0, encoding_utils_1.keccak256)(
2994
+ ...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain),
2995
+ (0, encoding_utils_1.stringToBytes)("deposit"),
2996
+ params.depositRequestHash,
2997
+ // Hash first: keccak256 concatenates without length prefixes, so injectivity depends on every
2998
+ // hashed field being fixed-width. Feeding the raw string would make it conditional on the
2999
+ // surrounding widths and diverge from the on-chain program, which hashes it too.
3000
+ computeDestinationHash(destination),
3001
+ params.depositor.toBytes(),
3002
+ params.mint.toBytes(),
3003
+ (0, encoding_utils_1.encodeU64LE)(params.amount),
3004
+ params.reserver.toBytes(),
3005
+ params.releaser.toBytes(),
3006
+ (0, encoding_utils_1.encodeU64LE)(params.nonce),
3007
+ (0, encoding_utils_1.encodeU64LE)(params.issuedAt),
3008
+ (0, encoding_utils_1.encodeU64LE)(params.deadline)
3009
+ );
1973
3010
  }
1974
3011
  }
1975
3012
  });
@@ -1980,6 +3017,8 @@ var require_reserve_encoder3 = __commonJS({
1980
3017
  "use strict";
1981
3018
  Object.defineProperty(exports2, "__esModule", { value: true });
1982
3019
  exports2.computeReserveHash = computeReserveHash;
3020
+ exports2.computeReserveHashV2 = computeReserveHashV2;
3021
+ exports2.computeReserveHashV3 = computeReserveHashV3;
1983
3022
  var encoding_utils_1 = require_encoding_utils();
1984
3023
  var escrow_domain_1 = require_escrow_domain();
1985
3024
  var errors_1 = require_errors2();
@@ -1991,15 +3030,38 @@ var require_reserve_encoder3 = __commonJS({
1991
3030
  throw new errors_1.ZeroRecipientError();
1992
3031
  return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("reserve"), params.recipient.toBytes(), params.depositHash);
1993
3032
  }
3033
+ function computeReserveHashV2(params, quoteHash, domain) {
3034
+ if (params.depositHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositHash)) {
3035
+ throw new errors_1.ZeroDepositHashError();
3036
+ }
3037
+ if (params.recipient.isZero())
3038
+ throw new errors_1.ZeroRecipientError();
3039
+ if (quoteHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(quoteHash))
3040
+ throw new errors_1.ZeroQuoteHashError();
3041
+ return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("reserve"), params.recipient.toBytes(), params.depositHash, quoteHash);
3042
+ }
3043
+ function computeReserveHashV3(params, quoteHash, sourceAmount, domain) {
3044
+ if (params.depositHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositHash)) {
3045
+ throw new errors_1.ZeroDepositHashError();
3046
+ }
3047
+ if (params.recipient.isZero())
3048
+ throw new errors_1.ZeroRecipientError();
3049
+ if (quoteHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(quoteHash))
3050
+ throw new errors_1.ZeroQuoteHashError();
3051
+ if (sourceAmount === 0n)
3052
+ throw new errors_1.ZeroSourceAmountError();
3053
+ 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));
3054
+ }
1994
3055
  }
1995
3056
  });
1996
3057
 
1997
3058
  // ../contracts/svm/escrow-encoding/typescript/dist/release-encoder.js
1998
- var require_release_encoder = __commonJS({
3059
+ var require_release_encoder3 = __commonJS({
1999
3060
  "../contracts/svm/escrow-encoding/typescript/dist/release-encoder.js"(exports2) {
2000
3061
  "use strict";
2001
3062
  Object.defineProperty(exports2, "__esModule", { value: true });
2002
3063
  exports2.computeReleaseHash = computeReleaseHash;
3064
+ exports2.computeReleaseHashV2 = computeReleaseHashV2;
2003
3065
  var encoding_utils_1 = require_encoding_utils();
2004
3066
  var escrow_domain_1 = require_escrow_domain();
2005
3067
  var errors_1 = require_errors2();
@@ -2009,15 +3071,22 @@ var require_release_encoder = __commonJS({
2009
3071
  }
2010
3072
  return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("release"), params.depositHash);
2011
3073
  }
3074
+ function computeReleaseHashV2(params, quoteHash, domain) {
3075
+ if (params.depositHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositHash)) {
3076
+ throw new errors_1.ZeroDepositHashError();
3077
+ }
3078
+ return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("release"), params.depositHash, quoteHash);
3079
+ }
2012
3080
  }
2013
3081
  });
2014
3082
 
2015
3083
  // ../contracts/svm/escrow-encoding/typescript/dist/refund-encoder.js
2016
- var require_refund_encoder = __commonJS({
3084
+ var require_refund_encoder3 = __commonJS({
2017
3085
  "../contracts/svm/escrow-encoding/typescript/dist/refund-encoder.js"(exports2) {
2018
3086
  "use strict";
2019
3087
  Object.defineProperty(exports2, "__esModule", { value: true });
2020
3088
  exports2.computeRefundHash = computeRefundHash;
3089
+ exports2.computeRefundHashV2 = computeRefundHashV2;
2021
3090
  var encoding_utils_1 = require_encoding_utils();
2022
3091
  var escrow_domain_1 = require_escrow_domain();
2023
3092
  var errors_1 = require_errors2();
@@ -2027,6 +3096,12 @@ var require_refund_encoder = __commonJS({
2027
3096
  }
2028
3097
  return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("refund"), params.depositHash);
2029
3098
  }
3099
+ function computeRefundHashV2(params, quoteHash, domain) {
3100
+ if (params.depositHash.length !== 32 || (0, encoding_utils_1.isZeroBytes32)(params.depositHash)) {
3101
+ throw new errors_1.ZeroDepositHashError();
3102
+ }
3103
+ return (0, encoding_utils_1.keccak256)(...(0, escrow_domain_1.escrowDomainPrefixBytes)(domain), (0, encoding_utils_1.stringToBytes)("refund"), params.depositHash, quoteHash);
3104
+ }
2030
3105
  }
2031
3106
  });
2032
3107
 
@@ -2035,16 +3110,16 @@ var require_nonce_generator2 = __commonJS({
2035
3110
  "../contracts/svm/escrow-encoding/typescript/dist/nonce-generator.js"(exports2) {
2036
3111
  "use strict";
2037
3112
  Object.defineProperty(exports2, "__esModule", { value: true });
2038
- exports2.MAX_VALID_SLOT = exports2.REPLAY_SLOTS = void 0;
3113
+ exports2.REPLAY_BUCKETS = exports2.MAX_VALID_SLOT = exports2.REPLAY_SLOTS = exports2.DEPOSIT_COMPUTE_UNIT_LIMIT = void 0;
2039
3114
  exports2.generateNonce = generateNonce2;
2040
3115
  var crypto_1 = require("crypto");
3116
+ exports2.DEPOSIT_COMPUTE_UNIT_LIMIT = 4e5;
2041
3117
  exports2.REPLAY_SLOTS = 235;
2042
3118
  exports2.MAX_VALID_SLOT = exports2.REPLAY_SLOTS - 1;
2043
- var NONCE_BUCKET_MASK = 131071;
3119
+ exports2.REPLAY_BUCKETS = 256;
2044
3120
  var NONCE_BUCKET_SHIFT = 32n;
2045
3121
  function generateNonce2() {
2046
- const bucketBytes = (0, crypto_1.randomBytes)(4);
2047
- const bucketID = bucketBytes.readUInt32LE(0) & NONCE_BUCKET_MASK;
3122
+ const bucketID = (0, crypto_1.randomBytes)(4).readUInt32LE(0) % exports2.REPLAY_BUCKETS;
2048
3123
  let slot;
2049
3124
  do {
2050
3125
  slot = (0, crypto_1.randomBytes)(1)[0];
@@ -2055,11 +3130,11 @@ var require_nonce_generator2 = __commonJS({
2055
3130
  });
2056
3131
 
2057
3132
  // ../contracts/svm/escrow-encoding/typescript/dist/index.js
2058
- var require_dist3 = __commonJS({
3133
+ var require_dist4 = __commonJS({
2059
3134
  "../contracts/svm/escrow-encoding/typescript/dist/index.js"(exports2) {
2060
3135
  "use strict";
2061
3136
  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;
3137
+ 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.ZeroDepositHashError = exports2.ZeroRecipientError = exports2.ZeroReleaserError = exports2.ZeroReserverError = exports2.ZeroAmountError = exports2.ZeroMintError = exports2.ZeroDepositorError = exports2.DestinationTooLongError = exports2.EmptyDestinationError = exports2.ZeroQuoteHashError = exports2.ZeroDepositRequestHashError = exports2.EncodingError = exports2.escrowDomainPrefixBytes = exports2.isZeroBytes32 = exports2.stringToBytes = exports2.keccak256 = exports2.encodeU64LE = exports2.Pubkey = void 0;
2063
3138
  var pubkey_1 = require_pubkey();
2064
3139
  Object.defineProperty(exports2, "Pubkey", { enumerable: true, get: function() {
2065
3140
  return pubkey_1.Pubkey;
@@ -2085,8 +3160,17 @@ var require_dist3 = __commonJS({
2085
3160
  Object.defineProperty(exports2, "EncodingError", { enumerable: true, get: function() {
2086
3161
  return errors_1.EncodingError;
2087
3162
  } });
2088
- Object.defineProperty(exports2, "ZeroPaymentIdError", { enumerable: true, get: function() {
2089
- return errors_1.ZeroPaymentIdError;
3163
+ Object.defineProperty(exports2, "ZeroDepositRequestHashError", { enumerable: true, get: function() {
3164
+ return errors_1.ZeroDepositRequestHashError;
3165
+ } });
3166
+ Object.defineProperty(exports2, "ZeroQuoteHashError", { enumerable: true, get: function() {
3167
+ return errors_1.ZeroQuoteHashError;
3168
+ } });
3169
+ Object.defineProperty(exports2, "EmptyDestinationError", { enumerable: true, get: function() {
3170
+ return errors_1.EmptyDestinationError;
3171
+ } });
3172
+ Object.defineProperty(exports2, "DestinationTooLongError", { enumerable: true, get: function() {
3173
+ return errors_1.DestinationTooLongError;
2090
3174
  } });
2091
3175
  Object.defineProperty(exports2, "ZeroDepositorError", { enumerable: true, get: function() {
2092
3176
  return errors_1.ZeroDepositorError;
@@ -2122,18 +3206,39 @@ var require_dist3 = __commonJS({
2122
3206
  Object.defineProperty(exports2, "computeDepositHash", { enumerable: true, get: function() {
2123
3207
  return deposit_encoder_1.computeDepositHash;
2124
3208
  } });
3209
+ Object.defineProperty(exports2, "computeDepositHashV2", { enumerable: true, get: function() {
3210
+ return deposit_encoder_1.computeDepositHashV2;
3211
+ } });
3212
+ Object.defineProperty(exports2, "computeDestinationHash", { enumerable: true, get: function() {
3213
+ return deposit_encoder_1.computeDestinationHash;
3214
+ } });
3215
+ Object.defineProperty(exports2, "MAX_DESTINATION_LEN", { enumerable: true, get: function() {
3216
+ return deposit_encoder_1.MAX_DESTINATION_LEN;
3217
+ } });
2125
3218
  var reserve_encoder_1 = require_reserve_encoder3();
2126
3219
  Object.defineProperty(exports2, "computeReserveHash", { enumerable: true, get: function() {
2127
3220
  return reserve_encoder_1.computeReserveHash;
2128
3221
  } });
2129
- var release_encoder_1 = require_release_encoder();
3222
+ Object.defineProperty(exports2, "computeReserveHashV2", { enumerable: true, get: function() {
3223
+ return reserve_encoder_1.computeReserveHashV2;
3224
+ } });
3225
+ Object.defineProperty(exports2, "computeReserveHashV3", { enumerable: true, get: function() {
3226
+ return reserve_encoder_1.computeReserveHashV3;
3227
+ } });
3228
+ var release_encoder_1 = require_release_encoder3();
2130
3229
  Object.defineProperty(exports2, "computeReleaseHash", { enumerable: true, get: function() {
2131
3230
  return release_encoder_1.computeReleaseHash;
2132
3231
  } });
2133
- var refund_encoder_1 = require_refund_encoder();
3232
+ Object.defineProperty(exports2, "computeReleaseHashV2", { enumerable: true, get: function() {
3233
+ return release_encoder_1.computeReleaseHashV2;
3234
+ } });
3235
+ var refund_encoder_1 = require_refund_encoder3();
2134
3236
  Object.defineProperty(exports2, "computeRefundHash", { enumerable: true, get: function() {
2135
3237
  return refund_encoder_1.computeRefundHash;
2136
3238
  } });
3239
+ Object.defineProperty(exports2, "computeRefundHashV2", { enumerable: true, get: function() {
3240
+ return refund_encoder_1.computeRefundHashV2;
3241
+ } });
2137
3242
  var nonce_generator_1 = require_nonce_generator2();
2138
3243
  Object.defineProperty(exports2, "generateNonce", { enumerable: true, get: function() {
2139
3244
  return nonce_generator_1.generateNonce;
@@ -2144,6 +3249,12 @@ var require_dist3 = __commonJS({
2144
3249
  Object.defineProperty(exports2, "MAX_VALID_SLOT", { enumerable: true, get: function() {
2145
3250
  return nonce_generator_1.MAX_VALID_SLOT;
2146
3251
  } });
3252
+ Object.defineProperty(exports2, "REPLAY_BUCKETS", { enumerable: true, get: function() {
3253
+ return nonce_generator_1.REPLAY_BUCKETS;
3254
+ } });
3255
+ Object.defineProperty(exports2, "DEPOSIT_COMPUTE_UNIT_LIMIT", { enumerable: true, get: function() {
3256
+ return nonce_generator_1.DEPOSIT_COMPUTE_UNIT_LIMIT;
3257
+ } });
2147
3258
  }
2148
3259
  });
2149
3260
 
@@ -2159,7 +3270,8 @@ var require_solana = __commonJS({
2159
3270
  var ethers_1 = require("ethers");
2160
3271
  var tweetnacl_1 = __importDefault(require("tweetnacl"));
2161
3272
  var bs58_1 = __importDefault(require("bs58"));
2162
- var solana_escrow_encoding_1 = require_dist3();
3273
+ var solana_escrow_encoding_1 = require_dist4();
3274
+ var destination_js_1 = require_destination();
2163
3275
  var utils_js_1 = require_utils();
2164
3276
  var errors_js_1 = require_errors();
2165
3277
  var chain_id_js_1 = require_chain_id2();
@@ -2169,7 +3281,8 @@ var require_solana = __commonJS({
2169
3281
  }
2170
3282
  function hashDeposit(prehash, domain) {
2171
3283
  return (0, ethers_1.hexlify)((0, solana_escrow_encoding_1.computeDepositHash)({
2172
- paymentId: (0, ethers_1.getBytes)(prehash.payment_id),
3284
+ // The encoder field was renamed for cross-VM parity; the prehash WIRE key stays payment_id.
3285
+ depositRequestHash: (0, ethers_1.getBytes)(prehash.payment_id),
2173
3286
  depositor: solana_escrow_encoding_1.Pubkey.fromBase58(prehash.depositor),
2174
3287
  mint: solana_escrow_encoding_1.Pubkey.fromBase58(prehash.mint),
2175
3288
  amount: BigInt(prehash.amount),
@@ -2180,6 +3293,26 @@ var require_solana = __commonJS({
2180
3293
  deadline: BigInt(prehash.deadline)
2181
3294
  }, domain));
2182
3295
  }
3296
+ var SVM_DESTINATION_COMMITMENT_VERSION = 4;
3297
+ function hashDepositV2(prehash, domain) {
3298
+ return (0, ethers_1.hexlify)((0, solana_escrow_encoding_1.computeDepositHashV2)(
3299
+ {
3300
+ depositRequestHash: (0, ethers_1.getBytes)(prehash.deposit_request_hash),
3301
+ depositor: solana_escrow_encoding_1.Pubkey.fromBase58(prehash.depositor),
3302
+ mint: solana_escrow_encoding_1.Pubkey.fromBase58(prehash.mint),
3303
+ amount: BigInt(prehash.amount),
3304
+ reserver: solana_escrow_encoding_1.Pubkey.fromBase58(prehash.reserver),
3305
+ releaser: solana_escrow_encoding_1.Pubkey.fromBase58(prehash.releaser),
3306
+ nonce: BigInt(prehash.nonce),
3307
+ issuedAt: BigInt(prehash.issued_at),
3308
+ deadline: BigInt(prehash.deadline)
3309
+ },
3310
+ // Plaintext, NOT pre-hashed: the encoder hashes it, and hashing an already-hashed
3311
+ // destination yields a well-formed commitment no on-chain state can satisfy.
3312
+ prehash.destination,
3313
+ domain
3314
+ ));
3315
+ }
2183
3316
  function domainFrom(defaults) {
2184
3317
  if (!defaults.escrowContract) {
2185
3318
  throw new Error("sender_auth: Solana source requires escrowContract (escrow program id) for the deposit-hash domain");
@@ -2194,12 +3327,11 @@ var require_solana = __commonJS({
2194
3327
  };
2195
3328
  }
2196
3329
  exports2.solanaAdapter = {
2197
- async buildAuthMessage({ sourceAsset, depositor, maxSourceAmount, requestId, sourceDefaults, nonce, solanaClockReader }) {
3330
+ async buildAuthMessage({ sourceAsset, depositor, maxSourceAmount, requestId, sourceDefaults, destinationAsset, destinationAccount, nonce, solanaClockReader }) {
2198
3331
  if (!requestId) {
2199
3332
  throw new Error("sender_auth: request_id is required");
2200
3333
  }
2201
- const sourceChainId = sourceAsset.split("/")[0];
2202
- const tokenMint = sourceAsset.split("/")[1].split(":")[1];
3334
+ const { network: sourceChainId, asset: tokenMint } = (0, utils_js_1.parseSourceAsset)(sourceAsset);
2203
3335
  const depositNonce = nonce !== void 0 ? BigInt(nonce) : (0, solana_escrow_encoding_1.generateNonce)();
2204
3336
  if (nonce !== void 0) {
2205
3337
  if (depositNonce < 0n || depositNonce >= 1n << 64n) {
@@ -2212,8 +3344,8 @@ var require_solana = __commonJS({
2212
3344
  const issuedAt = solanaClockReader ? await solanaClockReader(sourceChainId) : BigInt(Math.floor(Date.now() / 1e3));
2213
3345
  const deadline = issuedAt + BigInt(utils_js_1.REPLAY_HORIZON_SECS - 8);
2214
3346
  const paymentId = generateSolanaPaymentIdV3(requestId);
2215
- const prehash = {
2216
- payment_id: paymentId,
3347
+ const domain = domainFrom(sourceDefaults);
3348
+ const common = {
2217
3349
  depositor,
2218
3350
  mint: tokenMint,
2219
3351
  amount: BigInt(maxSourceAmount).toString(),
@@ -2223,7 +3355,20 @@ var require_solana = __commonJS({
2223
3355
  issued_at: issuedAt.toString(),
2224
3356
  deadline: deadline.toString()
2225
3357
  };
2226
- const depositHash = hashDeposit(prehash, domainFrom(sourceDefaults));
3358
+ if (domain.signatureDomainVersion >= SVM_DESTINATION_COMMITMENT_VERSION) {
3359
+ const prehashV2 = {
3360
+ deposit_request_hash: paymentId,
3361
+ destination: (0, destination_js_1.buildEscrowDestination)(destinationAsset, destinationAccount),
3362
+ ...common
3363
+ };
3364
+ return {
3365
+ messageScheme: "SOLANA",
3366
+ messageHash: hashDepositV2(prehashV2, domain),
3367
+ messagePrehash: JSON.stringify(prehashV2)
3368
+ };
3369
+ }
3370
+ const prehash = { payment_id: paymentId, ...common };
3371
+ const depositHash = hashDeposit(prehash, domain);
2227
3372
  return { messageScheme: "SOLANA", messageHash: depositHash, messagePrehash: JSON.stringify(prehash) };
2228
3373
  },
2229
3374
  async sign(signedMessage, privateKey) {
@@ -2269,8 +3414,18 @@ var require_solana = __commonJS({
2269
3414
  let prehash;
2270
3415
  let canonicalHash;
2271
3416
  try {
2272
- prehash = JSON.parse(signed.message_prehash);
2273
- canonicalHash = hashDeposit(prehash, domainFrom(expected));
3417
+ const domain = domainFrom(expected);
3418
+ if (domain.signatureDomainVersion >= SVM_DESTINATION_COMMITMENT_VERSION) {
3419
+ const v2 = JSON.parse(signed.message_prehash);
3420
+ if (typeof v2.deposit_request_hash !== "string" || typeof v2.destination !== "string") {
3421
+ throw new Error("pre-widening V1 prehash on a destination-committing domain");
3422
+ }
3423
+ canonicalHash = hashDepositV2(v2, domain);
3424
+ prehash = { payment_id: v2.deposit_request_hash, ...v2 };
3425
+ } else {
3426
+ prehash = JSON.parse(signed.message_prehash);
3427
+ canonicalHash = hashDeposit(prehash, domain);
3428
+ }
2274
3429
  } catch {
2275
3430
  throw new errors_js_1.MalformedPrehashError();
2276
3431
  }
@@ -2362,14 +3517,7 @@ var require_verify = __commonJS({
2362
3517
  Object.defineProperty(exports2, "__esModule", { value: true });
2363
3518
  exports2.verifyPaymentRequest = verifyPaymentRequest;
2364
3519
  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
- }
3520
+ var utils_js_1 = require_utils();
2373
3521
  function verifyPaymentRequest(request2, expected = {}) {
2374
3522
  const senderAuth = request2.sender_auth;
2375
3523
  if (!senderAuth?.signed_messages?.length) {
@@ -2378,87 +3526,473 @@ var require_verify = __commonJS({
2378
3526
  if (!request2.source) {
2379
3527
  throw new Error("sender_auth: request has no source");
2380
3528
  }
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 };
3529
+ const requestSource = (0, utils_js_1.parseSourceAsset)(request2.source.asset_identifier);
3530
+ const { sourceAsset, network: networkOverride, maxSourceAmount: amountOverride, ...scheme } = expected;
3531
+ const network = networkOverride ?? requestSource.network;
3532
+ const asset = sourceAsset ?? requestSource.asset;
3533
+ const maxSourceAmount = amountOverride ?? request2.max_source_amount ?? "0";
3534
+ const source = { network, asset, account: request2.source.account };
3535
+ const perMessage = { ...scheme, maxSourceAmount };
3536
+ const adapter = (0, index_js_1.getChainAdapter)(network);
3537
+ const results = senderAuth.signed_messages.map((m) => adapter.recoverAndVerify(m, source, perMessage));
3538
+ return { results, recoveredAccount: source.account };
3539
+ }
3540
+ }
3541
+ });
3542
+
3543
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/signer.js
3544
+ var require_signer = __commonJS({
3545
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/signer.js"(exports2) {
3546
+ "use strict";
3547
+ Object.defineProperty(exports2, "__esModule", { value: true });
3548
+ exports2.localKeySigner = localKeySigner2;
3549
+ var index_js_1 = require_adapters();
3550
+ function localKeySigner2(network, privateKey) {
3551
+ const adapter = (0, index_js_1.getChainAdapter)(network);
3552
+ return {
3553
+ async sign(signedMessage) {
3554
+ const signature = await adapter.sign(signedMessage, privateKey);
3555
+ const delegateSigner = adapter.deriveDelegateSigner?.(privateKey);
3556
+ return delegateSigner !== void 0 ? { signature, delegateSigner } : { signature };
3557
+ }
3558
+ };
3559
+ }
3560
+ }
3561
+ });
3562
+
3563
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/index.js
3564
+ var require_dist5 = __commonJS({
3565
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/sender-auth/dist/index.js"(exports2) {
3566
+ "use strict";
3567
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
3568
+ if (k2 === void 0) k2 = k;
3569
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3570
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3571
+ desc = { enumerable: true, get: function() {
3572
+ return m[k];
3573
+ } };
3574
+ }
3575
+ Object.defineProperty(o, k2, desc);
3576
+ }) : (function(o, m, k, k2) {
3577
+ if (k2 === void 0) k2 = k;
3578
+ o[k2] = m[k];
3579
+ }));
3580
+ var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
3581
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
3582
+ };
3583
+ Object.defineProperty(exports2, "__esModule", { value: true });
3584
+ 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;
3585
+ __exportStar(require_types(), exports2);
3586
+ __exportStar(require_utils(), exports2);
3587
+ __exportStar(require_chain_id2(), exports2);
3588
+ var index_js_1 = require_adapters();
3589
+ Object.defineProperty(exports2, "getChainAdapter", { enumerable: true, get: function() {
3590
+ return index_js_1.getChainAdapter;
3591
+ } });
3592
+ var destination_js_1 = require_destination();
3593
+ Object.defineProperty(exports2, "buildEscrowDestination", { enumerable: true, get: function() {
3594
+ return destination_js_1.buildEscrowDestination;
3595
+ } });
3596
+ Object.defineProperty(exports2, "deriveDepositRequestHash", { enumerable: true, get: function() {
3597
+ return destination_js_1.deriveDepositRequestHash;
3598
+ } });
3599
+ Object.defineProperty(exports2, "MAX_DESTINATION_BYTES", { enumerable: true, get: function() {
3600
+ return destination_js_1.MAX_DESTINATION_BYTES;
3601
+ } });
3602
+ Object.defineProperty(exports2, "usesDestinationCommitment", { enumerable: true, get: function() {
3603
+ return destination_js_1.usesDestinationCommitment;
3604
+ } });
3605
+ Object.defineProperty(exports2, "DESTINATION_COMMITMENT_WITNESS_VERSION", { enumerable: true, get: function() {
3606
+ return destination_js_1.DESTINATION_COMMITMENT_WITNESS_VERSION;
3607
+ } });
3608
+ var verify_js_1 = require_verify();
3609
+ Object.defineProperty(exports2, "verifyPaymentRequest", { enumerable: true, get: function() {
3610
+ return verify_js_1.verifyPaymentRequest;
3611
+ } });
3612
+ var errors_js_1 = require_errors();
3613
+ Object.defineProperty(exports2, "MalformedPrehashError", { enumerable: true, get: function() {
3614
+ return errors_js_1.MalformedPrehashError;
3615
+ } });
3616
+ Object.defineProperty(exports2, "RecoveryFailedError", { enumerable: true, get: function() {
3617
+ return errors_js_1.RecoveryFailedError;
3618
+ } });
3619
+ Object.defineProperty(exports2, "SignerMismatchError", { enumerable: true, get: function() {
3620
+ return errors_js_1.SignerMismatchError;
3621
+ } });
3622
+ var signer_js_1 = require_signer();
3623
+ Object.defineProperty(exports2, "localKeySigner", { enumerable: true, get: function() {
3624
+ return signer_js_1.localKeySigner;
3625
+ } });
3626
+ }
3627
+ });
3628
+
3629
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/allowance.js
3630
+ var require_allowance = __commonJS({
3631
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/allowance.js"(exports2) {
3632
+ "use strict";
3633
+ Object.defineProperty(exports2, "__esModule", { value: true });
3634
+ exports2.UNLIMITED_APPROVAL_FLOOR = exports2.UNLIMITED_APPROVAL = void 0;
3635
+ exports2.isAllowanceSufficient = isAllowanceSufficient;
3636
+ exports2.effectiveRequirement = effectiveRequirement;
3637
+ exports2.resolveApprovalAmount = resolveApprovalAmount;
3638
+ var ethers_1 = require("ethers");
3639
+ exports2.UNLIMITED_APPROVAL = ethers_1.MaxUint256;
3640
+ exports2.UNLIMITED_APPROVAL_FLOOR = ethers_1.MaxUint256 / 2n;
3641
+ function isAllowanceSufficient(current, requiredAllowance) {
3642
+ return requiredAllowance !== void 0 ? current >= requiredAllowance : current >= exports2.UNLIMITED_APPROVAL_FLOOR;
3643
+ }
3644
+ function effectiveRequirement(requiredAllowance, approvalAmount) {
3645
+ return requiredAllowance ?? approvalAmount;
3646
+ }
3647
+ function resolveApprovalAmount(approvalAmount, requiredAllowance) {
3648
+ if (approvalAmount === void 0)
3649
+ return exports2.UNLIMITED_APPROVAL;
3650
+ if (approvalAmount <= 0n) {
3651
+ throw new Error(`token_approval: approvalAmount must be positive, got ${approvalAmount}`);
3652
+ }
3653
+ if (requiredAllowance !== void 0 && approvalAmount < requiredAllowance) {
3654
+ 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`);
3655
+ }
3656
+ return approvalAmount;
3657
+ }
3658
+ }
3659
+ });
3660
+
3661
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/unconfirmed.js
3662
+ var require_unconfirmed = __commonJS({
3663
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/unconfirmed.js"(exports2) {
3664
+ "use strict";
3665
+ Object.defineProperty(exports2, "__esModule", { value: true });
3666
+ exports2.unconfirmed = unconfirmed;
3667
+ exports2.isUnconfirmed = isUnconfirmed2;
3668
+ function unconfirmed(message) {
3669
+ return Object.assign(new Error(message), { unconfirmed: true });
3670
+ }
3671
+ function isUnconfirmed2(error) {
3672
+ return error?.unconfirmed === true;
3673
+ }
3674
+ }
3675
+ });
3676
+
3677
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/evm.js
3678
+ var require_evm2 = __commonJS({
3679
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/evm.js"(exports2) {
3680
+ "use strict";
3681
+ Object.defineProperty(exports2, "__esModule", { value: true });
3682
+ exports2.evmAdapter = exports2.ERC20_ALLOWANCE_ABI = void 0;
3683
+ var ethers_1 = require("ethers");
3684
+ var evm_escrow_encoding_1 = require_dist3();
3685
+ var unconfirmed_js_1 = require_unconfirmed();
3686
+ exports2.ERC20_ALLOWANCE_ABI = [
3687
+ "function allowance(address owner, address spender) view returns (uint256)",
3688
+ "function approve(address spender, uint256 amount) returns (bool)"
3689
+ ];
3690
+ var DEFAULT_CONFIRMATION_TIMEOUT_MS = 6e4;
3691
+ function requireSigner(params) {
3692
+ if (!params.signer) {
3693
+ throw new Error(`token_approval: approving on ${params.network} needs an ethers signer connected to that chain (params.signer)`);
3694
+ }
3695
+ return params.signer;
3696
+ }
3697
+ function erc20(params) {
3698
+ return new ethers_1.Contract(params.token, exports2.ERC20_ALLOWANCE_ABI, requireSigner(params));
3699
+ }
3700
+ async function send(params, call, purpose) {
3701
+ const tx = await call;
3702
+ params.onSubmitted?.(tx.hash, purpose);
3703
+ const timeoutMs = params.confirmation?.timeoutMs ?? DEFAULT_CONFIRMATION_TIMEOUT_MS;
3704
+ try {
3705
+ await tx.wait(1, timeoutMs);
3706
+ } catch (error) {
3707
+ if (isTimeout(error)) {
3708
+ 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.`);
3709
+ }
3710
+ throw error;
3711
+ }
3712
+ return tx.hash;
3713
+ }
3714
+ function isTimeout(error) {
3715
+ return error?.code === "TIMEOUT";
3716
+ }
3717
+ exports2.evmAdapter = {
3718
+ applicable: true,
3719
+ resolveSpender(params) {
3720
+ return params.spender ?? evm_escrow_encoding_1.PERMIT2_CONTRACT_ADDRESS;
3721
+ },
3722
+ async senderAddress(params) {
3723
+ return await requireSigner(params).getAddress();
3724
+ },
3725
+ async readAllowance(params, spender) {
3726
+ return await erc20(params).allowance(params.owner, spender);
3727
+ },
3728
+ async approve(params, spender, amount, current) {
3729
+ const token = erc20(params);
3730
+ if (current !== 0n && await refusesOverwrite(params, token, spender, amount)) {
3731
+ const nonce = await requireSigner(params).getNonce("pending");
3732
+ const resetTxHash = await send(params, token.approve(spender, 0n, { nonce }), "reset");
3733
+ try {
3734
+ return {
3735
+ txHash: await send(params, token.approve(spender, amount, { nonce: nonce + 1 }), "approval"),
3736
+ resetTxHash
3737
+ };
3738
+ } catch (error) {
3739
+ const detail = error instanceof Error ? error.message : String(error);
3740
+ if ((0, unconfirmed_js_1.isUnconfirmed)(error)) {
3741
+ 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.`);
3742
+ }
3743
+ 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.`);
3744
+ }
3745
+ }
3746
+ return { txHash: await send(params, token.approve(spender, amount), "approval") };
3747
+ }
3748
+ };
3749
+ async function refusesOverwrite(params, token, spender, amount) {
3750
+ const data = token.interface.encodeFunctionData("approve", [spender, amount]);
3751
+ try {
3752
+ await requireSigner(params).call({ to: params.token, data });
3753
+ return false;
3754
+ } catch (error) {
3755
+ if (isRevert(error))
3756
+ return true;
3757
+ throw error;
3758
+ }
3759
+ }
3760
+ function isRevert(error) {
3761
+ return error?.code === "CALL_EXCEPTION";
3762
+ }
3763
+ }
3764
+ });
3765
+
3766
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/tron.js
3767
+ var require_tron2 = __commonJS({
3768
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/tron.js"(exports2) {
3769
+ "use strict";
3770
+ Object.defineProperty(exports2, "__esModule", { value: true });
3771
+ exports2.tronAdapter = exports2.TRC20_ALLOWANCE_ABI = void 0;
3772
+ var payment_request_sender_auth_1 = require_dist5();
3773
+ var unconfirmed_js_1 = require_unconfirmed();
3774
+ exports2.TRC20_ALLOWANCE_ABI = [
3775
+ {
3776
+ name: "allowance",
3777
+ type: "function",
3778
+ stateMutability: "View",
3779
+ inputs: [
3780
+ { name: "owner", type: "address" },
3781
+ { name: "spender", type: "address" }
3782
+ ],
3783
+ outputs: [{ type: "uint256" }]
3784
+ },
3785
+ {
3786
+ name: "approve",
3787
+ type: "function",
3788
+ stateMutability: "Nonpayable",
3789
+ inputs: [
3790
+ { name: "spender", type: "address" },
3791
+ { name: "amount", type: "uint256" }
3792
+ ],
3793
+ outputs: [{ type: "bool" }]
3794
+ }
3795
+ ];
3796
+ var DEFAULT_FEE_LIMIT = 1e8;
3797
+ var DEFAULT_CONFIRMATION_TIMEOUT_MS = 6e4;
3798
+ var DEFAULT_POLL_INTERVAL_MS2 = 1500;
3799
+ function requireTronWeb(params) {
3800
+ if (!params.tronWeb) {
3801
+ throw new Error(`token_approval: approving on ${params.network} needs a TronWeb instance configured for that chain (params.tronWeb)`);
3802
+ }
3803
+ return params.tronWeb;
3804
+ }
3805
+ function token(params) {
3806
+ return requireTronWeb(params).contract(exports2.TRC20_ALLOWANCE_ABI, params.token);
3807
+ }
3808
+ var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
3809
+ async function waitForConfirmation(tronWeb, txId, options) {
3810
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_CONFIRMATION_TIMEOUT_MS;
3811
+ const pollIntervalMs = options?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS2;
3812
+ const deadline = Date.now() + timeoutMs;
3813
+ for (; ; ) {
3814
+ let result;
3815
+ try {
3816
+ result = (await tronWeb.trx.getTransactionInfo(txId))?.receipt?.result;
3817
+ } catch {
3818
+ }
3819
+ if (result === "SUCCESS")
3820
+ return;
3821
+ if (result !== void 0) {
3822
+ throw new Error(`token_approval: Tron approval ${txId} failed on-chain (${result})`);
3823
+ }
3824
+ if (Date.now() >= deadline) {
3825
+ 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.`);
3826
+ }
3827
+ await sleep(pollIntervalMs);
3828
+ }
3829
+ }
3830
+ async function send(params, contract, spender, amount, purpose) {
3831
+ const txId = await contract.approve(spender, amount.toString()).send({ feeLimit: params.confirmation?.feeLimit ?? DEFAULT_FEE_LIMIT });
3832
+ params.onSubmitted?.(txId, purpose);
3833
+ await waitForConfirmation(requireTronWeb(params), txId, params.confirmation);
3834
+ return txId;
3835
+ }
3836
+ exports2.tronAdapter = {
3837
+ applicable: true,
3838
+ resolveSpender(params) {
3839
+ return params.spender ?? (0, payment_request_sender_auth_1.resolveTronPermit2)(params.network);
3840
+ },
3841
+ async senderAddress(params) {
3842
+ return requireTronWeb(params).defaultAddress?.base58 || void 0;
3843
+ },
3844
+ async readAllowance(params, spender) {
3845
+ const raw = await token(params).allowance(params.owner, spender).call();
3846
+ return BigInt(String(raw));
3847
+ },
3848
+ async approve(params, spender, amount, current) {
3849
+ const contract = token(params);
3850
+ try {
3851
+ return { txHash: await send(params, contract, spender, amount, "approval") };
3852
+ } catch (error) {
3853
+ if (current === 0n || (0, unconfirmed_js_1.isUnconfirmed)(error))
3854
+ throw error;
3855
+ 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.`);
3856
+ }
3857
+ }
3858
+ };
3859
+ }
3860
+ });
3861
+
3862
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/solana.js
3863
+ var require_solana2 = __commonJS({
3864
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/solana.js"(exports2) {
3865
+ "use strict";
3866
+ Object.defineProperty(exports2, "__esModule", { value: true });
3867
+ exports2.solanaAdapter = void 0;
3868
+ exports2.solanaAdapter = {
3869
+ applicable: false,
3870
+ resolveSpender() {
3871
+ throw new Error("token_approval: Solana does not use a Permit2-style allowance");
3872
+ },
3873
+ async senderAddress() {
3874
+ throw new Error("token_approval: Solana does not use a Permit2-style allowance");
3875
+ },
3876
+ async readAllowance() {
3877
+ throw new Error("token_approval: Solana does not use a Permit2-style allowance");
3878
+ },
3879
+ async approve() {
3880
+ throw new Error("token_approval: Solana does not use a Permit2-style allowance");
3881
+ }
3882
+ };
3883
+ }
3884
+ });
3885
+
3886
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/index.js
3887
+ var require_adapters2 = __commonJS({
3888
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/adapters/index.js"(exports2) {
3889
+ "use strict";
3890
+ Object.defineProperty(exports2, "__esModule", { value: true });
3891
+ exports2.approvalAdapterFor = approvalAdapterFor;
3892
+ var payment_request_sender_auth_1 = require_dist5();
3893
+ var evm_js_1 = require_evm2();
3894
+ var tron_js_1 = require_tron2();
3895
+ var solana_js_1 = require_solana2();
3896
+ var ADAPTERS = {
3897
+ eip155: evm_js_1.evmAdapter,
3898
+ tron: tron_js_1.tronAdapter,
3899
+ solana: solana_js_1.solanaAdapter
3900
+ };
3901
+ function approvalAdapterFor(network) {
3902
+ const namespace = (0, payment_request_sender_auth_1.namespaceOf)(network);
3903
+ const adapter = Object.hasOwn(ADAPTERS, namespace) ? ADAPTERS[namespace] : void 0;
3904
+ if (!adapter) {
3905
+ throw new Error(`token_approval: no approval adapter for network '${network}'`);
3906
+ }
3907
+ return adapter;
2391
3908
  }
2392
3909
  }
2393
3910
  });
2394
3911
 
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) {
3912
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/sender.js
3913
+ var require_sender = __commonJS({
3914
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/sender.js"(exports2) {
2398
3915
  "use strict";
2399
3916
  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
- };
3917
+ exports2.assertSenderIsOwner = assertSenderIsOwner;
3918
+ function assertSenderIsOwner(owner, sender) {
3919
+ if (sender === void 0 || sender.toLowerCase() === owner.toLowerCase())
3920
+ return;
3921
+ 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
3922
  }
2412
3923
  }
2413
3924
  });
2414
3925
 
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) {
3926
+ // ../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/index.js
3927
+ var require_dist6 = __commonJS({
3928
+ "../schemas/declarations/PaymentRequest/v1/bindings/typescript/token-approval/dist/index.js"(exports2) {
2418
3929
  "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
3930
  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;
3931
+ exports2.approvalAdapterFor = exports2.isUnconfirmed = exports2.assertSenderIsOwner = exports2.resolveApprovalAmount = exports2.isAllowanceSufficient = exports2.effectiveRequirement = exports2.UNLIMITED_APPROVAL_FLOOR = exports2.UNLIMITED_APPROVAL = void 0;
3932
+ exports2.needsSourceApproval = needsSourceApproval2;
3933
+ exports2.ensureSourceApproval = ensureSourceApproval2;
3934
+ var allowance_js_1 = require_allowance();
3935
+ var index_js_1 = require_adapters2();
3936
+ var sender_js_1 = require_sender();
3937
+ var allowance_js_2 = require_allowance();
3938
+ Object.defineProperty(exports2, "UNLIMITED_APPROVAL", { enumerable: true, get: function() {
3939
+ return allowance_js_2.UNLIMITED_APPROVAL;
2443
3940
  } });
2444
- var verify_js_1 = require_verify();
2445
- Object.defineProperty(exports2, "verifyPaymentRequest", { enumerable: true, get: function() {
2446
- return verify_js_1.verifyPaymentRequest;
3941
+ Object.defineProperty(exports2, "UNLIMITED_APPROVAL_FLOOR", { enumerable: true, get: function() {
3942
+ return allowance_js_2.UNLIMITED_APPROVAL_FLOOR;
2447
3943
  } });
2448
- var errors_js_1 = require_errors();
2449
- Object.defineProperty(exports2, "MalformedPrehashError", { enumerable: true, get: function() {
2450
- return errors_js_1.MalformedPrehashError;
3944
+ Object.defineProperty(exports2, "effectiveRequirement", { enumerable: true, get: function() {
3945
+ return allowance_js_2.effectiveRequirement;
2451
3946
  } });
2452
- Object.defineProperty(exports2, "RecoveryFailedError", { enumerable: true, get: function() {
2453
- return errors_js_1.RecoveryFailedError;
3947
+ Object.defineProperty(exports2, "isAllowanceSufficient", { enumerable: true, get: function() {
3948
+ return allowance_js_2.isAllowanceSufficient;
2454
3949
  } });
2455
- Object.defineProperty(exports2, "SignerMismatchError", { enumerable: true, get: function() {
2456
- return errors_js_1.SignerMismatchError;
3950
+ Object.defineProperty(exports2, "resolveApprovalAmount", { enumerable: true, get: function() {
3951
+ return allowance_js_2.resolveApprovalAmount;
2457
3952
  } });
2458
- var signer_js_1 = require_signer();
2459
- Object.defineProperty(exports2, "localKeySigner", { enumerable: true, get: function() {
2460
- return signer_js_1.localKeySigner;
3953
+ var sender_js_2 = require_sender();
3954
+ Object.defineProperty(exports2, "assertSenderIsOwner", { enumerable: true, get: function() {
3955
+ return sender_js_2.assertSenderIsOwner;
3956
+ } });
3957
+ var unconfirmed_js_1 = require_unconfirmed();
3958
+ Object.defineProperty(exports2, "isUnconfirmed", { enumerable: true, get: function() {
3959
+ return unconfirmed_js_1.isUnconfirmed;
2461
3960
  } });
3961
+ var index_js_2 = require_adapters2();
3962
+ Object.defineProperty(exports2, "approvalAdapterFor", { enumerable: true, get: function() {
3963
+ return index_js_2.approvalAdapterFor;
3964
+ } });
3965
+ async function needsSourceApproval2(params) {
3966
+ const adapter = (0, index_js_1.approvalAdapterFor)(params.network);
3967
+ if (!adapter.applicable)
3968
+ return false;
3969
+ const required = (0, allowance_js_1.effectiveRequirement)(params.requiredAllowance, params.approvalAmount);
3970
+ (0, allowance_js_1.resolveApprovalAmount)(params.approvalAmount, required);
3971
+ const spender = adapter.resolveSpender(params);
3972
+ const current = await adapter.readAllowance(params, spender);
3973
+ return !(0, allowance_js_1.isAllowanceSufficient)(current, required);
3974
+ }
3975
+ async function ensureSourceApproval2(params) {
3976
+ const adapter = (0, index_js_1.approvalAdapterFor)(params.network);
3977
+ if (!adapter.applicable)
3978
+ return { alreadySufficient: true };
3979
+ const required = (0, allowance_js_1.effectiveRequirement)(params.requiredAllowance, params.approvalAmount);
3980
+ const amount = (0, allowance_js_1.resolveApprovalAmount)(params.approvalAmount, required);
3981
+ const spender = adapter.resolveSpender(params);
3982
+ const current = await adapter.readAllowance(params, spender);
3983
+ if ((0, allowance_js_1.isAllowanceSufficient)(current, required)) {
3984
+ return { alreadySufficient: true };
3985
+ }
3986
+ (0, sender_js_1.assertSenderIsOwner)(params.owner, await adapter.senderAddress(params));
3987
+ return { alreadySufficient: false, ...await adapter.approve(params, spender, amount, current) };
3988
+ }
3989
+ }
3990
+ });
3991
+
3992
+ // src/signers/pinned-address.ts
3993
+ var init_pinned_address = __esm({
3994
+ "src/signers/pinned-address.ts"() {
3995
+ "use strict";
2462
3996
  }
2463
3997
  });
2464
3998
 
@@ -2940,7 +4474,7 @@ payment.
2940
4474
  `,
2941
4475
  413: "Payment request too large to process",
2942
4476
  500: "Internal server error",
2943
- 503: "A dependency is temporarily unavailable"
4477
+ 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
4478
  }
2945
4479
  });
2946
4480
  }
@@ -3025,6 +4559,9 @@ payment.
3025
4559
  *
3026
4560
  * The response includes everything needed to sign and submit a payment, except the signature itself.
3027
4561
  *
4562
+ * Not available on every gateway or every source chain; where it is not, this
4563
+ * returns `501`. Sign the returned request and submit it to `POST /v1/payments`.
4564
+ *
3028
4565
  * @param data The data for the request.
3029
4566
  * @param data.requestBody
3030
4567
  * @returns PreparePaymentResponse Payment request prepared successfully
@@ -3071,11 +4608,30 @@ var AuthorizationsService = class {
3071
4608
  body: data.requestBody,
3072
4609
  mediaType: "application/json",
3073
4610
  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)"
4611
+ 400: `The request was rejected before authorization was attempted, so no
4612
+ authorization outcome exists.
4613
+ `,
4614
+ 401: `The counterparty's proof was rejected (\`PROOF_INVALID\` or \`PROOF_STALE\`).
4615
+ This is an authorization outcome, so the body is an \`AuthorizationResult\`
4616
+ with \`status: error\`.
4617
+ `,
4618
+ 404: `Counterparty not found (no registration for the resolved DID). An
4619
+ authorization outcome, so the body is an \`AuthorizationResult\` with
4620
+ \`status: error\` and \`error_code: COUNTERPARTY_NOT_FOUND\`.
4621
+ `,
4622
+ 500: `Either shape, depending on where the failure happened. A failure before
4623
+ authorization was attempted returns \`ErrorResponse\`. A failure carrying an
4624
+ authorization outcome returns \`AuthorizationResult\` with \`status: error\`.
4625
+ `,
4626
+ 502: `Counterparty webhook error (HTTP error or connection failure). An
4627
+ authorization outcome, so the body is an \`AuthorizationResult\` with
4628
+ \`status: error\` and \`error_code: WEBHOOK_ERROR\` or
4629
+ \`WEBHOOK_CONNECTION_ERROR\`.
4630
+ `,
4631
+ 504: `Authorization timed out (the counterparty did not respond). An
4632
+ authorization outcome, so the body is an \`AuthorizationResult\` with
4633
+ \`status: timeout\`.
4634
+ `
3079
4635
  }
3080
4636
  });
3081
4637
  }
@@ -3102,6 +4658,31 @@ var QuoteRequestsService = class {
3102
4658
  * Collection continues server-side until the quote deadline regardless of the HTTP
3103
4659
  * connection, so quotes remain retrievable via the status endpoint in either mode.
3104
4660
  *
4661
+ * **Idempotency.** `request_id` is the idempotency key, scoped to the source account
4662
+ * and originator — the same key, and the same contract, as POST /v1/payments.
4663
+ * Submitting the same `request_id` again returns the ORIGINAL batch instead of opening
4664
+ * a second one, so a client whose request timed out or failed in transit can safely
4665
+ * re-submit and recover its `quote_request_id`.
4666
+ *
4667
+ * Because a re-submission must be admissible on its own, some fields legitimately
4668
+ * differ between attempts and are excluded from the comparison: `quote_deadline` and
4669
+ * `fulfillment_deadline` (both must be in the future, so a later attempt has to move
4670
+ * them) and the `proof` that covers them. An expired `quote_deadline` on a
4671
+ * re-submission is NOT an error — the request is resolved onto the batch that already
4672
+ * exists rather than used to open one. There is no `sender_auth` to re-sign here: this
4673
+ * endpoint rejects it, because the spend authorization belongs to the award call.
4674
+ *
4675
+ * The collection window belongs to the BATCH, not to the request. Asking again with a
4676
+ * later `quote_deadline` does not extend a window already open; `quote_deadline` in the
4677
+ * response is the batch's own, and `status` says whether collection is still running.
4678
+ *
4679
+ * What must NOT differ is the corridor's economics — source account and asset,
4680
+ * destination accounts and assets, `fulfillment_amount`, and `max_source_amount`.
4681
+ * Re-using one `request_id` for a genuinely different corridor is a client bug that
4682
+ * would otherwise be silently collapsed onto the first batch, returning quotes for a
4683
+ * corridor that was never requested. It is rejected with `409` and
4684
+ * `IDEMPOTENCY_TERMS_MISMATCH`. Use a distinct `request_id` per quote-request.
4685
+ *
3105
4686
  * @param data The data for the request.
3106
4687
  * @param data.requestBody
3107
4688
  * @param data.wait Return a handle immediately (`false`, default) or hold the connection for collected quotes (`true`).
@@ -3121,8 +4702,19 @@ var QuoteRequestsService = class {
3121
4702
  body: data.requestBody,
3122
4703
  mediaType: "application/json",
3123
4704
  errors: {
3124
- 400: "Invalid request",
3125
- 500: "Internal server error"
4705
+ 400: `Invalid request. \`QUOTE_DEADLINE_NOT_FUTURE\` is the one worth planning for: a NEW
4706
+ quote-request whose \`quote_deadline\` has already passed is refused, because there is
4707
+ no window left to collect quotes in. It does not apply to a re-submission \u2014 an
4708
+ already-used \`request_id\` resolves onto the batch that exists and its expired
4709
+ deadline is ignored, which is what makes a retry recoverable.
4710
+ `,
4711
+ 409: `The \`request_id\` has already been used for a quote-request with different
4712
+ economics (\`IDEMPOTENCY_TERMS_MISMATCH\`). Re-submitting one \`request_id\` is how a
4713
+ retry is made safe, so it must identify one batch; use a distinct \`request_id\`
4714
+ per quote-request.
4715
+ `,
4716
+ 500: "Internal server error",
4717
+ 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
4718
  }
3127
4719
  });
3128
4720
  }
@@ -3205,6 +4797,43 @@ var QuoteRequestsService = class {
3205
4797
  });
3206
4798
  }
3207
4799
  };
4800
+ var ChainDefaultsService = class {
4801
+ constructor(httpRequest) {
4802
+ this.httpRequest = httpRequest;
4803
+ }
4804
+ /**
4805
+ * Get chain defaults
4806
+ * The addresses needed to build a payment on a chain: the escrow, the accounts named
4807
+ * in the deposit authorization, and the fulfillment verifier. Fetch these rather than
4808
+ * hardcoding them - they change when a chain's contracts are redeployed.
4809
+ *
4810
+ * With `chain_id`, returns that chain. Without it, or with an empty value, returns
4811
+ * every chain the gateway serves, keyed by CAIP-2 chain id.
4812
+ *
4813
+ * A chain that is not fully configured is still returned when asked for by
4814
+ * `chain_id`, with the missing address empty, but is left out of the full listing.
4815
+ * Treat an empty address as a chain you cannot pay on.
4816
+ *
4817
+ * @param data The data for the request.
4818
+ * @param data.chainId CAIP-2 chain identifier. Omit it, or send it empty, to receive every chain the gateway serves, keyed by chain id.
4819
+ * @returns GetDefaultsResult Chain defaults. A single object when `chain_id` was supplied, otherwise an object keyed by CAIP-2 chain id.
4820
+ * @throws ApiError
4821
+ */
4822
+ getDefaults(data = {}) {
4823
+ return this.httpRequest.request({
4824
+ method: "GET",
4825
+ url: "/v1/defaults",
4826
+ query: {
4827
+ chain_id: data.chainId
4828
+ },
4829
+ errors: {
4830
+ 400: "The `chain_id` is not a valid CAIP-2 chain identifier",
4831
+ 404: "The requested chain is not served by this gateway, or - when `chain_id` was omitted - no chain could be resolved at all",
4832
+ 503: "A dependency is temporarily unavailable"
4833
+ }
4834
+ });
4835
+ }
4836
+ };
3208
4837
  var HealthService = class {
3209
4838
  constructor(httpRequest) {
3210
4839
  this.httpRequest = httpRequest;
@@ -3242,19 +4871,126 @@ var PaymentGatewayClient = class {
3242
4871
  }
3243
4872
  });
3244
4873
  this.authorizations = new AuthorizationsService(this.request);
4874
+ this.chainDefaults = new ChainDefaultsService(this.request);
3245
4875
  this.health = new HealthService(this.request);
3246
4876
  this.payments = new PaymentsService(this.request);
3247
4877
  this.quoteRequests = new QuoteRequestsService(this.request);
3248
4878
  }
3249
4879
  };
3250
4880
 
4881
+ // src/errors.ts
4882
+ var GatewayTimeoutError = class extends Error {
4883
+ constructor(baseUrl, timeoutMs) {
4884
+ super(
4885
+ `Gateway at ${baseUrl || "(same origin)"} did not respond within ${formatSeconds(timeoutMs)}`
4886
+ );
4887
+ this.baseUrl = baseUrl;
4888
+ this.timeoutMs = timeoutMs;
4889
+ this.name = "GatewayTimeoutError";
4890
+ }
4891
+ };
4892
+ function formatSeconds(ms) {
4893
+ const seconds = ms / 1e3;
4894
+ return `${Number.isInteger(seconds) ? seconds : seconds.toFixed(1)}s`;
4895
+ }
4896
+ function isGatewayTimeoutError(err) {
4897
+ return err instanceof GatewayTimeoutError;
4898
+ }
4899
+ function isApiError(err) {
4900
+ return err instanceof ApiError;
4901
+ }
4902
+
4903
+ // src/request-timeout.ts
4904
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
4905
+ var DEFAULT_SYNC_WAIT_TIMEOUT_MS = 12e4;
4906
+ var SYNC_HOLD_PATHS = ["/v1/payments", "/v1/payments/awards"];
4907
+ function pathOf(url) {
4908
+ if (!url) return "";
4909
+ const path = url.split("?")[0];
4910
+ const scheme = path.indexOf("://");
4911
+ if (scheme === -1) return path;
4912
+ const host = path.indexOf("/", scheme + 3);
4913
+ return host === -1 ? "" : path.slice(host);
4914
+ }
4915
+ function hasWaitTrueQuery(url) {
4916
+ const query = url?.indexOf("?") ?? -1;
4917
+ if (query === -1) return false;
4918
+ return new URLSearchParams(url.slice(query + 1)).get("wait") === "true";
4919
+ }
4920
+ function isSyncWaitRequest({ method, url, wait }) {
4921
+ if (wait === true || wait === "true" || hasWaitTrueQuery(url)) return true;
4922
+ if (method?.toUpperCase() !== "POST") return false;
4923
+ const path = pathOf(url);
4924
+ return SYNC_HOLD_PATHS.some((held) => path === held || path.endsWith(held));
4925
+ }
4926
+ function ordinaryTimeout(timeouts = {}) {
4927
+ return timeouts.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
4928
+ }
4929
+ function timeoutForRequest(request2, timeouts = {}) {
4930
+ return isSyncWaitRequest(request2) ? timeouts.syncWaitTimeoutMs ?? DEFAULT_SYNC_WAIT_TIMEOUT_MS : ordinaryTimeout(timeouts);
4931
+ }
4932
+ function applyRequestTimeout(timeouts = {}) {
4933
+ return (config2) => ({
4934
+ ...config2,
4935
+ timeout: config2.timeout ?? timeoutForRequest({ method: config2.method, url: config2.url }, timeouts)
4936
+ });
4937
+ }
4938
+ function isAxiosTimeout(error) {
4939
+ const failure = error;
4940
+ if (!failure) return false;
4941
+ if (failure.code === "ECONNABORTED" || failure.code === "ETIMEDOUT") return true;
4942
+ return failure.code === "ERR_BAD_RESPONSE" && /stream has been aborted/i.test(failure.message ?? "");
4943
+ }
4944
+ function translateTimeout(error, baseUrl, fallbackTimeoutMs) {
4945
+ if (!isAxiosTimeout(error)) return error;
4946
+ const configured = error.config?.timeout;
4947
+ return new GatewayTimeoutError(baseUrl, configured ?? fallbackTimeoutMs);
4948
+ }
4949
+
4950
+ // src/timeout-http-request.ts
4951
+ function withRequestTimeout(config2, timeouts) {
4952
+ const request2 = new Interceptors();
4953
+ for (const fn of config2?.interceptors?.request?._fns ?? []) request2.use(fn);
4954
+ request2.use(applyRequestTimeout(timeouts));
4955
+ return {
4956
+ interceptors: { request: request2, response: config2?.interceptors?.response ?? new Interceptors() }
4957
+ };
4958
+ }
4959
+ var TimeoutHttpRequest = class extends AxiosHttpRequest {
4960
+ constructor(config2, timeouts = {}) {
4961
+ super(config2);
4962
+ this.timeouts = timeouts;
4963
+ }
4964
+ request(options) {
4965
+ return new CancelablePromise((resolve2, reject, onCancel) => {
4966
+ const pending = super.request(options);
4967
+ onCancel(() => pending.cancel());
4968
+ pending.then(resolve2, (error) => {
4969
+ const request2 = { method: options.method, url: options.url, wait: options.query?.wait };
4970
+ reject(
4971
+ translateTimeout(error, this.config.BASE, timeoutForRequest(request2, this.timeouts))
4972
+ );
4973
+ });
4974
+ });
4975
+ }
4976
+ };
4977
+ function timeoutHttpRequest(timeouts) {
4978
+ return class extends TimeoutHttpRequest {
4979
+ constructor(config2) {
4980
+ super(config2, timeouts);
4981
+ }
4982
+ };
4983
+ }
4984
+
3251
4985
  // src/chain-adapters/evm.ts
3252
4986
  var import_ethers = require("ethers");
3253
4987
 
3254
4988
  // src/chain-adapters/types.ts
3255
4989
  function assertKeyMatchesSender(matches, sender, derived) {
3256
4990
  if (!matches) {
3257
- throw new Error(`The private key derives ${derived}, which does not match the sender address ${sender}`);
4991
+ throw new Error(
4992
+ `The private key derives ${derived}, which does not match the sender address ${sender}`
4993
+ );
3258
4994
  }
3259
4995
  }
3260
4996
 
@@ -3306,10 +5042,9 @@ var tronAdapter = {
3306
5042
  throw new Error("Invalid private key");
3307
5043
  }
3308
5044
  },
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.
5045
+ // Tron addresses are the same secp256k1-derived 20 bytes as EVM. The derived
5046
+ // address is already canonical 20-byte hex, so only the sender side — which
5047
+ // arrives in whichever spelling the caller chose — needs normalizing.
3313
5048
  verifyAddressMatchesKey(privateKey, address) {
3314
5049
  const key = privateKey.startsWith("0x") ? privateKey : "0x" + privateKey;
3315
5050
  const derived = new import_ethers2.ethers.Wallet(key).address;
@@ -3348,22 +5083,133 @@ function secretKeyFromPrivate(privateKey) {
3348
5083
  if (decoded.length === 32) {
3349
5084
  return import_tweetnacl.default.sign.keyPair.fromSeed(decoded).secretKey;
3350
5085
  }
3351
- throw new Error(`Invalid Solana private key length: expected 32 or 64 bytes, got ${decoded.length}`);
5086
+ throw new Error(
5087
+ `Invalid Solana private key length: expected 32 or 64 bytes, got ${decoded.length}`
5088
+ );
3352
5089
  }
3353
5090
 
3354
5091
  // src/chain-adapters/index.ts
3355
5092
  var adapters = {
3356
- "eip155": evmAdapter,
3357
- "tron": tronAdapter,
3358
- "solana": solanaAdapter
5093
+ eip155: evmAdapter,
5094
+ tron: tronAdapter,
5095
+ solana: solanaAdapter
3359
5096
  };
3360
5097
  function getChainAdapter(sourceChainId) {
3361
- const prefix = sourceChainId.split(":")[0];
5098
+ const prefix = sourceChainId.split(":")[0]?.toLowerCase() ?? "";
3362
5099
  const adapter = adapters[prefix];
3363
5100
  if (!adapter) throw new Error(`Unsupported source chain: ${sourceChainId}`);
3364
5101
  return adapter;
3365
5102
  }
3366
5103
 
5104
+ // src/asset-identifier.ts
5105
+ var import_ethers3 = require("ethers");
5106
+ var SHAPE_EXAMPLE = "eip155:421614/erc20:0x...";
5107
+ var NAMESPACE = /^[a-z0-9]+$/;
5108
+ var CHAIN_REFERENCE = /^[a-zA-Z0-9_-]+$/;
5109
+ var ASSET_NAMESPACE = /^[a-z0-9-]{3,8}$/;
5110
+ var ASSET_REFERENCE = /^[-.%a-zA-Z0-9]{1,128}$/;
5111
+ var TOKEN_ID = /^[-.%a-zA-Z0-9]{1,78}$/;
5112
+ var EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
5113
+ var EIP155_REFERENCE = /^[0-9]+$/;
5114
+ var HEX_REFERENCE = /^0[xX][0-9a-fA-F]{1,16}$/;
5115
+ var MAX_ECHO = 120;
5116
+ var MAX_REFERENCE_ECHO = 32;
5117
+ function parseAssetIdentifier(value) {
5118
+ if (typeof value !== "string" || value === "") {
5119
+ throw new Error(shapeError(value));
5120
+ }
5121
+ const firstSlash = value.indexOf("/");
5122
+ if (firstSlash === -1) {
5123
+ throw new Error(shapeError(value));
5124
+ }
5125
+ const chainSegments = value.slice(0, firstSlash).split(":");
5126
+ if (chainSegments.length !== 2) {
5127
+ throw new Error(shapeError(value));
5128
+ }
5129
+ const namespace = chainSegments[0].toLowerCase();
5130
+ const reference = namespace === "tron" ? chainSegments[1].toLowerCase() : chainSegments[1];
5131
+ if (!NAMESPACE.test(namespace) || !CHAIN_REFERENCE.test(reference)) {
5132
+ throw new Error(shapeError(value));
5133
+ }
5134
+ if (namespace === "eip155" && !EIP155_REFERENCE.test(reference)) {
5135
+ throw new Error(eip155ReferenceError(reference, value));
5136
+ }
5137
+ const assetPart = value.slice(firstSlash + 1);
5138
+ const separator = assetPart.indexOf(":");
5139
+ if (separator === -1) {
5140
+ throw new Error(tokenAddressError(value));
5141
+ }
5142
+ const assetNamespace = assetPart.slice(0, separator).toLowerCase();
5143
+ const rest = assetPart.slice(separator + 1);
5144
+ const referenceSlash = rest.indexOf("/");
5145
+ const tokenAddress = referenceSlash === -1 ? rest : rest.slice(0, referenceSlash);
5146
+ const tokenId = referenceSlash === -1 ? void 0 : rest.slice(referenceSlash + 1);
5147
+ if (!ASSET_NAMESPACE.test(assetNamespace)) {
5148
+ throw new Error(tokenAddressError(value));
5149
+ }
5150
+ if (assetNamespace === "slip44") {
5151
+ throw new Error(nativeAssetError(value));
5152
+ }
5153
+ if (!ASSET_REFERENCE.test(tokenAddress)) {
5154
+ throw new Error(tokenAddressError(value));
5155
+ }
5156
+ if (tokenId !== void 0 && !TOKEN_ID.test(tokenId)) {
5157
+ throw new Error(tokenAddressError(value));
5158
+ }
5159
+ assertTokenAddress(namespace, tokenAddress, value);
5160
+ const chainId = `${namespace}:${reference}`;
5161
+ return {
5162
+ chainId,
5163
+ namespace,
5164
+ reference,
5165
+ assetNamespace,
5166
+ tokenAddress,
5167
+ ...tokenId === void 0 ? {} : { tokenId },
5168
+ normalized: `${chainId}/${assetNamespace}:${tokenAddress}${tokenId === void 0 ? "" : `/${tokenId}`}`
5169
+ };
5170
+ }
5171
+ function assetChainId(value) {
5172
+ return parseAssetIdentifier(value).chainId;
5173
+ }
5174
+ function echo(value, limit = MAX_ECHO) {
5175
+ const shown = typeof value === "string" ? value : String(value);
5176
+ return shown.length > limit ? `${shown.slice(0, limit)}\u2026` : shown;
5177
+ }
5178
+ function shapeError(value) {
5179
+ return `Invalid asset identifier "${echo(value)}": expected CAIP-19 "<chain>/<type>:<address>", e.g. ${SHAPE_EXAMPLE}`;
5180
+ }
5181
+ function tokenAddressError(value) {
5182
+ return `Invalid token address in asset "${echo(value)}".`;
5183
+ }
5184
+ function eip155ReferenceError(reference, value) {
5185
+ const prefix = `Invalid eip155 chain id "${echo(reference, MAX_REFERENCE_ECHO)}" in asset "${echo(value)}"`;
5186
+ if (HEX_REFERENCE.test(reference)) {
5187
+ return `${prefix}: use the decimal chain id (${BigInt(reference)}), not hex.`;
5188
+ }
5189
+ return `${prefix}: an eip155 chain id is decimal, e.g. 421614.`;
5190
+ }
5191
+ function nativeAssetError(value) {
5192
+ return `Asset "${echo(value)}" is a native asset (slip44) and has no contract to deposit. Use the wrapped token's erc20 identifier.`;
5193
+ }
5194
+ function assertTokenAddress(namespace, tokenAddress, value) {
5195
+ if (namespace !== "eip155") return;
5196
+ if (!EVM_ADDRESS.test(tokenAddress)) {
5197
+ throw new Error(tokenAddressError(value));
5198
+ }
5199
+ const body = tokenAddress.slice(2);
5200
+ if (body === body.toLowerCase() || body === body.toUpperCase()) return;
5201
+ try {
5202
+ (0, import_ethers3.getAddress)(tokenAddress);
5203
+ } catch {
5204
+ throw new Error(
5205
+ `Token address "${tokenAddress}" has an invalid checksum. Fix the capitalization or use the all-lowercase form.`
5206
+ );
5207
+ }
5208
+ }
5209
+
5210
+ // src/index.ts
5211
+ var import_chain_address = __toESM(require_dist2());
5212
+
3367
5213
  // src/chain-adapters/solana-clock.ts
3368
5214
  var DEFAULT_SOLANA_RPC_URLS = {
3369
5215
  "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "https://api.mainnet-beta.solana.com",
@@ -3432,22 +5278,39 @@ async function resolveSolanaIssuedAt(opts) {
3432
5278
  }
3433
5279
 
3434
5280
  // src/index.ts
3435
- var import_payment_request_sender_auth2 = __toESM(require_dist4());
5281
+ var import_payment_request_sender_auth2 = __toESM(require_dist5());
5282
+ var import_chain_address2 = __toESM(require_dist2());
5283
+
5284
+ // src/payment-tracking.ts
5285
+ var DEFAULT_WAIT_SECONDS = 60;
5286
+ var DEFAULT_WAIT_BUDGET_MS = DEFAULT_WAIT_SECONDS * 1e3;
5287
+
5288
+ // src/index.ts
5289
+ var import_payment_request_token_approval = __toESM(require_dist6());
3436
5290
 
3437
5291
  // src/sender_auth_schemes/evm_permit2.ts
3438
- var import_ethers3 = require("ethers");
3439
- var import_evm_escrow_encoding = __toESM(require_dist2());
5292
+ var import_ethers4 = require("ethers");
5293
+ var import_evm_escrow_encoding = __toESM(require_dist3());
3440
5294
 
3441
5295
  // src/sender_auth_schemes/solana.ts
3442
- var import_ethers4 = require("ethers");
5296
+ var import_ethers5 = require("ethers");
3443
5297
  var import_bs582 = __toESM(require("bs58"));
3444
- var import_solana_escrow_encoding = __toESM(require_dist3());
5298
+ var import_solana_escrow_encoding = __toESM(require_dist4());
5299
+
5300
+ // src/signers/index.ts
5301
+ init_pinned_address();
3445
5302
 
3446
5303
  // src/signers/raw.ts
3447
- var import_payment_request_sender_auth = __toESM(require_dist4());
5304
+ var import_payment_request_sender_auth = __toESM(require_dist5());
5305
+
5306
+ // src/signers/turnkey.ts
5307
+ init_pinned_address();
3448
5308
 
3449
5309
  // src/index.ts
3450
5310
  var PAYMENT_REQUEST_VERSION = "1.0";
5311
+ function assertPayableAccount(assetIdentifier, account) {
5312
+ (0, import_chain_address.validate)(assetChainId(assetIdentifier), account);
5313
+ }
3451
5314
  var defaultGateway = "https://payment-gw.production-testnet.atum.xyz";
3452
5315
  var OpenAPI2 = { ...OpenAPI, BASE: defaultGateway };
3453
5316
  var DEFAULT_QUOTE_DEADLINE_SECONDS = 5;
@@ -3464,10 +5327,14 @@ function resolveDeadlines(params, defaultQuoteSeconds) {
3464
5327
  const quoteDeadlineSeconds = params.quoteDeadlineSeconds ?? defaultQuoteSeconds;
3465
5328
  const fulfillmentDeadlineSeconds = params.fulfillmentDeadlineSeconds ?? DEFAULT_FULFILLMENT_DEADLINE_SECONDS;
3466
5329
  if (!Number.isFinite(quoteDeadlineSeconds) || !Number.isFinite(fulfillmentDeadlineSeconds)) {
3467
- throw new Error("quoteDeadlineSeconds and fulfillmentDeadlineSeconds must be finite numbers of seconds.");
5330
+ throw new Error(
5331
+ "quoteDeadlineSeconds and fulfillmentDeadlineSeconds must be finite numbers of seconds."
5332
+ );
3468
5333
  }
3469
5334
  if (quoteDeadlineSeconds <= 0 || fulfillmentDeadlineSeconds <= 0) {
3470
- throw new Error("quoteDeadlineSeconds and fulfillmentDeadlineSeconds must be positive numbers of seconds.");
5335
+ throw new Error(
5336
+ "quoteDeadlineSeconds and fulfillmentDeadlineSeconds must be positive numbers of seconds."
5337
+ );
3471
5338
  }
3472
5339
  if (quoteDeadlineSeconds >= fulfillmentDeadlineSeconds) {
3473
5340
  throw new Error(
@@ -3480,18 +5347,67 @@ function resolveDeadlines(params, defaultQuoteSeconds) {
3480
5347
  fulfillment_deadline: new Date(now + fulfillmentDeadlineSeconds * 1e3).toISOString()
3481
5348
  };
3482
5349
  }
5350
+ function defaultsErrorDetail(error) {
5351
+ if (!isApiError(error)) {
5352
+ return error instanceof Error ? error.message : String(error);
5353
+ }
5354
+ const body = error.body;
5355
+ const parts = [];
5356
+ if (typeof body?.code === "string" && body.code.trim() !== "") parts.push(body.code);
5357
+ if (typeof body?.message === "string" && body.message.trim() !== "") parts.push(body.message);
5358
+ const requestId = typeof body?.request_id === "string" && body.request_id.trim() !== "" ? body.request_id : "";
5359
+ if (parts.length > 0) {
5360
+ return `${parts.join(": ")}${requestId === "" ? "" : ` (request_id=${requestId})`}`;
5361
+ }
5362
+ return error.statusText || `HTTP ${error.status}`;
5363
+ }
5364
+ function singleChainOf(response, chainId) {
5365
+ if (typeof response !== "object" || response === null) {
5366
+ throw new Error(
5367
+ `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.`
5368
+ );
5369
+ }
5370
+ const single = response;
5371
+ if (typeof single.chain_id !== "string") {
5372
+ throw new Error(
5373
+ `Failed to fetch defaults for chain ${chainId}: the gateway answered with defaults for every chain rather than the one requested`
5374
+ );
5375
+ }
5376
+ if (single.chain_id.toLowerCase() !== chainId.toLowerCase()) {
5377
+ throw new Error(
5378
+ `Failed to fetch defaults for chain ${chainId}: the gateway answered with defaults for ` + single.chain_id
5379
+ );
5380
+ }
5381
+ return single;
5382
+ }
3483
5383
  async function assemblePaymentRequest(params) {
3484
- const sourceChainId = params.sourceAsset.split("/")[0];
3485
- const namespace = sourceChainId.split(":")[0];
5384
+ const source = parseAssetIdentifier(params.sourceAsset);
5385
+ const destination = parseAssetIdentifier(params.destinationAsset);
5386
+ const { chainId: sourceChainId, namespace } = source;
3486
5387
  const adapter = getChainAdapter(sourceChainId);
3487
5388
  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
5389
  const auth = await (0, import_payment_request_sender_auth2.getChainAdapter)(sourceChainId).buildAuthMessage({
3489
- sourceAsset: params.sourceAsset,
5390
+ // Canonicalized: the Tron adapter resolves its Permit2 address by exact chain-id key, so an
5391
+ // uppercase namespace would miss the lookup and fail inside the SDK.
5392
+ sourceAsset: source.normalized,
3490
5393
  depositor: params.depositor,
3491
5394
  // The gateway pins the signed deposit amount to max_source_amount (the cap).
3492
5395
  maxSourceAmount: params.maxSourceAmount,
3493
5396
  requestId: params.requestId,
3494
5397
  sourceDefaults: params.sourceDefaults,
5398
+ // The payee the deposit commits to. Passed as CAIP components, not a composed string:
5399
+ // the adapter composes it through the shared buildEscrowDestination so this producer
5400
+ // and the release signer cannot disagree by a byte. These are the SAME two values that
5401
+ // become paymentRequest.destination[0] below, so the signed commitment and the request
5402
+ // body cannot describe different payees.
5403
+ // Canonicalized for the same reason `sourceAsset` is, and additionally because the claim
5404
+ // three lines up has to be TRUE: destination[0] below carries `destination.normalized`, so
5405
+ // passing the raw string here would sign a commitment over different bytes than the request
5406
+ // body names whenever a caller supplies a non-canonical namespace (e.g. "EIP155:42220").
5407
+ // `normalized` lowercases only the namespaces and the asset namespace — the chain reference
5408
+ // and token address keep their case, so base58 (Solana genesis reference, SPL mint) survives.
5409
+ destinationAsset: destination.normalized,
5410
+ destinationAccount: params.destinationAccount,
3495
5411
  deadline: params.deadline,
3496
5412
  nonce,
3497
5413
  ...namespace === "solana" ? {
@@ -3507,13 +5423,15 @@ async function assemblePaymentRequest(params) {
3507
5423
  version: params.version ?? PAYMENT_REQUEST_VERSION,
3508
5424
  request_id: params.requestId,
3509
5425
  source: {
3510
- asset_identifier: params.sourceAsset,
5426
+ asset_identifier: source.normalized,
3511
5427
  account: params.depositor
3512
5428
  },
3513
- destination: [{
3514
- asset_identifier: params.destinationAsset,
3515
- account: params.destinationAccount
3516
- }],
5429
+ destination: [
5430
+ {
5431
+ asset_identifier: destination.normalized,
5432
+ account: params.destinationAccount
5433
+ }
5434
+ ],
3517
5435
  fulfillment_amount: params.fulfillmentAmount,
3518
5436
  max_source_amount: params.maxSourceAmount,
3519
5437
  quote_deadline: params.quoteDeadline,
@@ -3528,43 +5446,58 @@ async function assemblePaymentRequest(params) {
3528
5446
  ...params.settlerRequirements ? { settler_requirements: params.settlerRequirements } : {},
3529
5447
  sender_auth: {
3530
5448
  message_scheme: auth.messageScheme,
3531
- signed_messages: [{
3532
- message: auth.messageHash,
3533
- message_prehash: auth.messagePrehash,
3534
- signature: ""
3535
- }]
5449
+ signed_messages: [
5450
+ {
5451
+ message: auth.messageHash,
5452
+ message_prehash: auth.messagePrehash,
5453
+ signature: ""
5454
+ }
5455
+ ]
3536
5456
  }
3537
5457
  };
3538
5458
  }
3539
5459
  var PaymentGatewayClient2 = class extends PaymentGatewayClient {
3540
- constructor(config2, HttpRequest = AxiosHttpRequest) {
5460
+ constructor(config2, HttpRequest) {
3541
5461
  const envBase = (typeof process !== "undefined" ? process.env.GATEWAY_URL : void 0)?.trim();
3542
5462
  const base = config2?.BASE ?? (envBase || defaultGateway);
3543
- super({ ...config2, BASE: base }, HttpRequest);
3544
- this.baseUrl = base;
5463
+ const timeouts = {
5464
+ timeoutMs: config2?.timeoutMs,
5465
+ syncWaitTimeoutMs: config2?.syncWaitTimeoutMs
5466
+ };
5467
+ super(
5468
+ { ...config2, BASE: base, ...withRequestTimeout(config2, timeouts) },
5469
+ HttpRequest ?? timeoutHttpRequest(timeouts)
5470
+ );
3545
5471
  }
3546
5472
  /**
3547
5473
  * Fetches chain defaults from the payment gateway.
3548
- *
5474
+ *
5475
+ * Goes through the generated typed client, so the request shares the payment calls'
5476
+ * transport: one base URL, one timeout policy, and `/v1/defaults` is described by the
5477
+ * OpenAPI contract rather than assembled by hand here.
5478
+ *
3549
5479
  * @param chainId The CAIP-2 chain identifier (e.g., "eip155:42161")
3550
5480
  * @returns The chain defaults including escrow, quote selector, and fulfillment verifier
3551
5481
  */
3552
5482
  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();
5483
+ if (chainId.trim() === "") {
5484
+ throw new Error(
5485
+ 'payment-gateway-client: fetchChainDefaults requires a CAIP-2 chain id, for example "eip155:8453"'
5486
+ );
5487
+ }
5488
+ let response;
5489
+ try {
5490
+ response = await this.chainDefaults.getDefaults({ chainId });
5491
+ } catch (error) {
5492
+ if (isGatewayTimeoutError(error)) throw error;
5493
+ throw new Error(
5494
+ `Failed to fetch defaults for chain ${chainId}: ${defaultsErrorDetail(error)}`,
5495
+ {
5496
+ cause: error
3560
5497
  }
3561
- } catch {
3562
- }
3563
- const error = new Error(`Failed to fetch defaults for chain ${chainId}: ${response.statusText}`);
3564
- error.availableDefaults = availableDefaults;
3565
- throw error;
5498
+ );
3566
5499
  }
3567
- const data = await response.json();
5500
+ const data = singleChainOf(response, chainId);
3568
5501
  if (!data.escrow_contract) {
3569
5502
  throw new Error("defaults missing escrow_contract");
3570
5503
  }
@@ -3583,23 +5516,34 @@ var PaymentGatewayClient2 = class extends PaymentGatewayClient {
3583
5516
  if (!data.fulfillment_verifier.endpoint) {
3584
5517
  throw new Error("defaults missing fulfillment_verifier.endpoint");
3585
5518
  }
5519
+ if (typeof data.permit2_contract === "string" && data.permit2_contract.trim() === "") {
5520
+ throw new Error("defaults returned an empty permit2_contract");
5521
+ }
3586
5522
  return {
3587
5523
  escrowContract: data.escrow_contract,
3588
5524
  quoteSelector: data.quote_selector,
3589
5525
  fulfillmentVerifierAccount: data.fulfillment_verifier.account,
3590
5526
  fulfillmentVerifierEndpoint: data.fulfillment_verifier.endpoint,
3591
5527
  fulfillmentProxy: data.fulfillment_proxy,
3592
- permit2Contract: data.permit2_contract,
5528
+ // `?? undefined` normalises a JSON null at the boundary. The declared type is
5529
+ // `string | undefined`, and a consumer testing `!== undefined` or `in` - both
5530
+ // reasonable against that type - would otherwise build an EIP-712 domain around a
5531
+ // null verifyingContract.
5532
+ permit2Contract: data.permit2_contract ?? void 0,
5533
+ // Which deposit witness the escrow on this chain pins (CORE-2033). Absent means the
5534
+ // four-member CORE-2120 witness — see ChainDefaults.depositWitnessVersion for why
5535
+ // absence is the permissive default. EVM/Tron only; Solana uses the svm_* fields below.
5536
+ depositWitnessVersion: data.deposit_witness_version ?? void 0,
3593
5537
  // V3 Solana escrow domain separation. Present only for Solana
3594
5538
  // 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
5539
+ svmSignatureClusterId: data.svm_signature_cluster_id ?? void 0,
5540
+ svmSignatureDomainVersion: data.svm_signature_domain_version ?? void 0
3597
5541
  };
3598
5542
  }
3599
5543
  /**
3600
5544
  * Prepares a payment request with defaults, ready for signing.
3601
5545
  *
3602
- * By default this resolves the corridor addresses from the gateway `/defaults`
5546
+ * By default this resolves the corridor addresses from the gateway `/v1/defaults`
3603
5547
  * endpoint. It reaches the gateway only for what the caller has NOT already
3604
5548
  * supplied via `resolvedDefaults`: supply `resolvedDefaults.source` to skip the
3605
5549
  * source-chain fetch and `resolvedDefaults.destination` to skip the destination
@@ -3629,10 +5573,14 @@ var PaymentGatewayClient2 = class extends PaymentGatewayClient {
3629
5573
  * @returns A complete PaymentRequest object without the signature
3630
5574
  */
3631
5575
  async preparePaymentRequest(params) {
5576
+ assertPayableAccount(params.destinationAsset, params.destinationAccount);
3632
5577
  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];
5578
+ const { quote_deadline, fulfillment_deadline } = resolveDeadlines(
5579
+ { ...params, now: () => now },
5580
+ DEFAULT_PAYMENT_QUOTE_DEADLINE_SECONDS
5581
+ );
5582
+ const sourceChainId = assetChainId(params.sourceAsset);
5583
+ const destChainId = assetChainId(params.destinationAsset);
3636
5584
  const [sourceDefaults, fulfillmentProxy] = await Promise.all([
3637
5585
  params.resolvedDefaults?.source ?? this.fetchChainDefaults(sourceChainId),
3638
5586
  params.resolvedDefaults?.destination?.fulfillmentProxy ?? this.fetchChainDefaults(destChainId).then((d) => d.fulfillmentProxy)
@@ -3702,7 +5650,7 @@ var PaymentGatewayClient2 = class extends PaymentGatewayClient {
3702
5650
  * defaults and populates the SAME contract fields (`escrow_contract_address`,
3703
5651
  * `quote_selector`, `fulfillment_verifier`, `fulfillment_proxy`). These are not
3704
5652
  * optional in practice: the gateway requires `fulfillment_verifier` to build the
3705
- * QuoteRequested event it broadcasts to settlers, so the quote-request body
5653
+ * request event it broadcasts to settlers, so the quote-request body
3706
5654
  * must carry the identical contract fields the payment flow does. The ONLY
3707
5655
  * field this drops relative to `preparePaymentRequest` is `sender_auth`, which
3708
5656
  * is supplied at award time (quote-time is unauthenticated — no signing, no
@@ -3712,26 +5660,38 @@ var PaymentGatewayClient2 = class extends PaymentGatewayClient {
3712
5660
  * @returns A complete `CreateQuoteRequest` body (no signature step needed)
3713
5661
  */
3714
5662
  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];
5663
+ assertPayableAccount(params.destinationAsset, params.destinationAccount);
5664
+ if (!params.requestId) {
5665
+ throw new Error(
5666
+ "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"
5667
+ );
5668
+ }
5669
+ const { quote_deadline, fulfillment_deadline } = resolveDeadlines(
5670
+ params,
5671
+ DEFAULT_QUOTE_DEADLINE_SECONDS
5672
+ );
5673
+ const source = parseAssetIdentifier(params.sourceAsset);
5674
+ const destination = parseAssetIdentifier(params.destinationAsset);
5675
+ const sourceChainId = source.chainId;
5676
+ const destChainId = destination.chainId;
3718
5677
  const [sourceDefaults, destDefaults] = await Promise.all([
3719
5678
  this.fetchChainDefaults(sourceChainId),
3720
5679
  this.fetchChainDefaults(destChainId)
3721
5680
  ]);
3722
5681
  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
5682
  return {
3725
5683
  version: PAYMENT_REQUEST_VERSION,
3726
- request_id: requestId,
5684
+ request_id: params.requestId,
3727
5685
  source: {
3728
- asset_identifier: params.sourceAsset,
5686
+ asset_identifier: source.normalized,
3729
5687
  account: params.depositor
3730
5688
  },
3731
- destination: [{
3732
- asset_identifier: params.destinationAsset,
3733
- account: params.destinationAccount
3734
- }],
5689
+ destination: [
5690
+ {
5691
+ asset_identifier: destination.normalized,
5692
+ account: params.destinationAccount
5693
+ }
5694
+ ],
3735
5695
  fulfillment_amount: params.fulfillmentAmount,
3736
5696
  max_source_amount: params.maxSourceAmount ?? defaultMaxSourceAmount(params.fulfillmentAmount),
3737
5697
  // Required + originator-supplied: the gateway injects no default and never
@@ -3757,7 +5717,7 @@ var PaymentGatewayClient2 = class extends PaymentGatewayClient {
3757
5717
  };
3758
5718
 
3759
5719
  // src/version.ts
3760
- var PACKAGE_VERSION = true ? "2.2.0" : "0.0.0-dev";
5720
+ var PACKAGE_VERSION = true ? "3.0.0" : "0.0.0-dev";
3761
5721
 
3762
5722
  // src/cli/load-env.ts
3763
5723
  var import_dotenv = require("dotenv");
@@ -3765,6 +5725,25 @@ function loadCliEnv() {
3765
5725
  (0, import_dotenv.config)({ override: false, quiet: true });
3766
5726
  }
3767
5727
 
5728
+ // src/cli/cli-input-error.ts
5729
+ var CliInputError = class extends Error {
5730
+ constructor(message) {
5731
+ super(message);
5732
+ this.name = "CliInputError";
5733
+ }
5734
+ };
5735
+
5736
+ // src/cli/run-cli.ts
5737
+ function runCli(program2, ...parseArgs) {
5738
+ try {
5739
+ program2.parse(...parseArgs);
5740
+ } catch (error) {
5741
+ if (!(error instanceof CliInputError)) throw error;
5742
+ console.error("\n\u274C Error:", error.message);
5743
+ process.exit(1);
5744
+ }
5745
+ }
5746
+
3768
5747
  // src/cli/payment-outcome.ts
3769
5748
  var EXIT_COMPLETED = 0;
3770
5749
  var EXIT_PENDING = 2;
@@ -3796,7 +5775,12 @@ function describePaymentOutcome(input) {
3796
5775
  // src/cli/payment-status.ts
3797
5776
  loadCliEnv();
3798
5777
  var program = new import_commander.Command();
3799
- program.name("payment-status").description("Fetch the status of a payment (no signing required)").version(PACKAGE_VERSION).argument("<paymentId>", "The payment_id returned by send-payment (or a Quote-API award)").option("--gateway <url>", "Payment gateway URL (overrides GATEWAY_URL env; default: production-testnet)").addHelpText("after", `
5778
+ program.name("payment-status").description("Fetch the status of a payment (no signing required)").version(PACKAGE_VERSION).argument("<paymentId>", "The payment_id returned by send-payment (or a Quote-API award)").option(
5779
+ "--gateway <url>",
5780
+ "Payment gateway URL (overrides GATEWAY_URL env; default: production-testnet)"
5781
+ ).addHelpText(
5782
+ "after",
5783
+ `
3800
5784
  Example:
3801
5785
  payment-status --gateway http://localhost:8080 0x<payment_id>
3802
5786
 
@@ -3807,7 +5791,8 @@ Output:
3807
5791
  What it means -> stderr
3808
5792
 
3809
5793
  Exit code reports whether the lookup worked (0) or not (1), not the payment's
3810
- outcome \u2014 read \`status\` for that, or use send-payment's exit code.`).action(async (paymentId, options) => {
5794
+ outcome \u2014 read \`status\` for that, or use send-payment's exit code.`
5795
+ ).action(async (paymentId, options) => {
3811
5796
  try {
3812
5797
  const client = new PaymentGatewayClient2({ BASE: options.gateway });
3813
5798
  const response = await client.payments.getPaymentStatus({ paymentId });
@@ -3829,7 +5814,7 @@ outcome \u2014 read \`status\` for that, or use send-payment's exit code.`).acti
3829
5814
  process.exit(1);
3830
5815
  }
3831
5816
  });
3832
- program.parse();
5817
+ runCli(program);
3833
5818
  /*! Bundled license information:
3834
5819
 
3835
5820
  @noble/hashes/utils.js: