-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathDepositAddressHandler.ts
More file actions
1330 lines (1171 loc) · 57.1 KB
/
Copy pathDepositAddressHandler.ts
File metadata and controls
1330 lines (1171 loc) · 57.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sinon from "sinon";
import { expect } from "chai";
import {
CHAIN_IDs,
EvmAddress,
getCurrentTime,
HttpError,
Signer,
toAddressType,
toBN,
TransactionReceipt,
utils,
winston,
} from "../src/utils";
import { DepositAddressMessage, DepositAddressMessageV3 } from "../src/interfaces/DepositAddress";
import { AcrossApiHttpError, DepositAddressExecuteResponse, DepositAddressSignWithdrawResponse } from "../src/clients";
import { DepositAddressHandler } from "../src/deposit-address/DepositAddressHandler";
import { DepositAddressHandlerConfig } from "../src/deposit-address/DepositAddressHandlerConfig";
import { ERC20_TRANSFER_TOPIC } from "../src/deposit-address/withdrawPayload";
import { getDepositKey, NATIVE_TOKEN_SENTINEL_ADDRESS } from "../src/utils/DepositAddressUtils";
// EIP-55 checksummed: the handler round-trips the signer through `toAddressType().toNative()`,
// which returns the checksummed form, so an un-checksummed literal fails the request-shape compares.
const SIGNER = "0x000000000000000000000000000000000000bEEF";
const DEPOSIT_ADDRESS = "0x000000000000000000000000000000000000C0DE";
const REFUND_ADDRESS = "0x0000000000000000000000000000000000002222";
const TOKEN = "0x000000000000000000000000000000000000DEAD";
const OUTPUT_TOKEN = "0x0000000000000000000000000000000000005678";
const RECIPIENT = "0x0000000000000000000000000000000000001111";
const IMPL = "0x000000000000000000000000000000000000A4A4";
// Tron-origin v3 sample fields (indexer verbatim: base58 addresses, un-prefixed tx hash).
const TRON_DEPOSIT_ADDRESS = "TRhLhFckPaeCtFyrUBJRK6p9LhRtbS7Pa5";
const TRON_REFUND_ADDRESS = "TQ4T4DgHoezYBTRoZPCspsSgRw38Ni9prA";
const TRON_TOKEN = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
const TRON_TX_HASH = "3b699036b64d765dea6a9103c33793d343381bab361b3e96051e56de2d174247";
const TRON_FACTORY = "0xce892B16B4D486e26c869bCb8475b087f4469A48";
// The 12 params the deposit-execute quote sent before executionFee support — the legacy request shape.
const BASE_PARAM_KEYS = [
"originChainId",
"destinationChainId",
"inputToken",
"outputToken",
"tradeType",
"amount",
"depositor",
"recipient",
"refundAddress",
"depositAddress",
"executionFeeRecipient",
"shouldSponsorAccountCreation",
];
/**
* EVM-origin correct_transfer message; `materials` overrides the counterfactualMaterials leaves and
* `integrator` overrides the optional integrator projection (omitted entirely when not provided).
*/
function depositMessage(
materials: DepositAddressMessage["counterfactualMaterials"],
integrator?: DepositAddressMessage["integrator"]
): DepositAddressMessage {
return {
...(integrator !== undefined ? { integrator } : {}),
depositAddress: DEPOSIT_ADDRESS,
paramsHash: "0x" + "0".repeat(64),
salt: "0x" + "0".repeat(64),
counterfactualDepositContractAddress: "0x000000000000000000000000000000000000A1A1",
counterfactualFactoryContractAddress: "0x000000000000000000000000000000000000A2A2",
adminWithdrawManagerContractAddress: "0x000000000000000000000000000000000000A3A3",
shouldSponsorAccountCreation: false,
counterfactualMaterials: materials,
routeParams: {
inputToken: TOKEN,
outputToken: OUTPUT_TOKEN,
originChainId: "1",
destinationChainId: "10",
recipient: RECIPIENT,
refundAddress: REFUND_ADDRESS,
},
erc20Transfer: {
chainId: "1",
blockNumber: 1_000_000,
logIndex: 4,
from: REFUND_ADDRESS,
to: DEPOSIT_ADDRESS,
amount: "5000",
contractAddress: TOKEN,
transactionHash: "0x" + "1".repeat(64),
transferClassification: "correct_transfer",
},
};
}
const withdrawLeaf = {
leafHash: "0x" + "0".repeat(64),
merkleProof: [],
encodedParams: "0x",
implementationAddress: IMPL,
};
const WITHDRAW_IMPL = "0x000000000000000000000000000000000000B4B4";
/** v3 withdraw leaf as projected by the indexer (`kind === "withdraw"`). */
const v3WithdrawLeaf = {
kind: "withdraw",
implementationAddress: WITHDRAW_IMPL,
encodedParams: "0x",
leafHash: "0x" + "4".repeat(64),
merkleProof: ["0x" + "5".repeat(64), "0x" + "6".repeat(64)],
};
/** v3 mis_route message carrying a withdraw leaf, ready for the refund-withdraw path. */
function withdrawMessageV3(overrides: Partial<DepositAddressMessageV3> = {}): DepositAddressMessageV3 {
const message = depositMessageV3({
counterfactualMaterials: [v3WithdrawLeaf],
...overrides,
});
message.erc20Transfer.transferClassification = "mis_route";
return message;
}
/** v3 correct_transfer message mirroring the indexer's DepositAddressTransferItemV3 projection. */
function depositMessageV3(overrides: Partial<DepositAddressMessageV3> = {}): DepositAddressMessageV3 {
return {
depositAddress: DEPOSIT_ADDRESS,
version: 3,
salt: "0x" + "0".repeat(64),
initialRoot: "0x" + "2".repeat(64),
counterfactualBeaconContractAddress: "0x000000000000000000000000000000000000B1B1",
counterfactualFactoryContractAddress: "0x000000000000000000000000000000000000B2B2",
adminWithdrawManagerContractAddress: "0x000000000000000000000000000000000000B3B3",
shouldSponsorAccountCreation: false,
counterfactualMaterials: [
{
kind: "vanilla-cctp",
implementationAddress: IMPL,
encodedParams: "0x",
leafHash: "0x" + "0".repeat(64),
merkleProof: [],
},
],
routeParams: {
outputToken: OUTPUT_TOKEN,
destinationChainId: "1337",
recipient: { namespace: "evm", address: RECIPIENT },
},
refundAddress: { namespace: "evm", address: REFUND_ADDRESS },
depositAddressNamespace: "evm",
integrator: { name: "test-integrator", integratorId: "0xdead" },
erc20Transfer: {
chainId: "42161",
blockNumber: 1_000_000,
logIndex: 4,
from: REFUND_ADDRESS,
to: DEPOSIT_ADDRESS,
amount: "5000",
contractAddress: TOKEN,
transactionHash: "0x" + "3".repeat(64),
transferClassification: "correct_transfer",
},
...overrides,
};
}
/**
* v3 Tron-origin correct_transfer message mirroring the indexer sample: base58 addresses,
* un-prefixed transaction hash, `tron` namespaces, EVM destination.
*/
function tronDepositMessageV3(overrides: Partial<DepositAddressMessageV3> = {}): DepositAddressMessageV3 {
return depositMessageV3({
depositAddress: TRON_DEPOSIT_ADDRESS,
routeParams: {
outputToken: OUTPUT_TOKEN,
destinationChainId: String(CHAIN_IDs.BASE),
recipient: { namespace: "evm", address: RECIPIENT },
},
refundAddress: { namespace: "tron", address: TRON_REFUND_ADDRESS },
depositAddressNamespace: "tron",
integrator: { name: "test-integrator", integratorId: "0x00e6" },
erc20Transfer: {
chainId: String(CHAIN_IDs.TRON),
blockNumber: 84_665_484,
logIndex: 55,
from: TRON_REFUND_ADDRESS,
to: TRON_DEPOSIT_ADDRESS,
amount: "25000000",
contractAddress: TRON_TOKEN,
transactionHash: TRON_TX_HASH,
transferClassification: "correct_transfer",
},
...overrides,
});
}
describe("DepositAddressHandler._getSwapApiQuote params", function () {
let handler: DepositAddressHandler;
let getStub: sinon.SinonStub;
beforeEach(function () {
const config = {} as unknown as DepositAddressHandlerConfig;
handler = new DepositAddressHandler(undefined as unknown as winston.Logger, config, {} as unknown as Signer, []);
// _signerAddress is normally set by initialize(); set it directly for this unit test.
(handler as unknown as { _signerAddress: EvmAddress })._signerAddress = EvmAddress.from(SIGNER);
// Replace the swap API client with a stub that captures the params and returns a successful quote.
getStub = sinon.stub().resolves({ swapTx: { simulationSuccess: true, to: TOKEN, data: "0x", value: "0" } });
(handler as unknown as { api: { getCounterfactualDepositQuote: sinon.SinonStub } }).api = {
getCounterfactualDepositQuote: getStub,
};
});
afterEach(() => sinon.restore());
async function capturedParams(message: DepositAddressMessage): Promise<Record<string, unknown>> {
await (handler as unknown as { _getSwapApiQuote: (m: DepositAddressMessage) => Promise<unknown> })._getSwapApiQuote(
message
);
expect(getStub.calledOnce).to.equal(true);
return getStub.firstCall.args[0] as Record<string, unknown>;
}
it("forwards both committed fees verbatim when both leaves carry params", async function () {
const params = await capturedParams(
depositMessage({
withdrawLeaf,
cctpLeaf: { ...withdrawLeaf, params: { executionFee: "777" } },
spokePoolLeaf: { ...withdrawLeaf, params: { executionFee: "12345" } },
})
);
expect(params.cctpExecutionFee).to.equal("777");
expect(params.spokePoolExecutionFee).to.equal("12345");
});
it("leaves the fee param undefined for the leaves whose params are absent", async function () {
const params = await capturedParams(
depositMessage({ withdrawLeaf, spokePoolLeaf: { ...withdrawLeaf, params: { executionFee: "12345" } } })
);
// Undefined values are dropped at query-string serialization, so the absent leaf contributes no fee.
expect(params.cctpExecutionFee).to.equal(undefined);
expect(params.spokePoolExecutionFee).to.equal("12345");
});
it("leaves both fee params undefined when no fee leaves are present", async function () {
const params = await capturedParams(depositMessage({ withdrawLeaf }));
// No fee leaves => both fees undefined and dropped at serialization, yielding the legacy request shape.
expect(params.cctpExecutionFee).to.equal(undefined);
expect(params.spokePoolExecutionFee).to.equal(undefined);
expect(BASE_PARAM_KEYS.every((key) => key in params)).to.equal(true);
});
it("forwards integratorId verbatim when the message carries one", async function () {
const params = await capturedParams(
depositMessage({ withdrawLeaf }, { name: "test-integrator", integratorId: "0x1234" })
);
expect(params.integratorId).to.equal("0x1234");
});
it("leaves integratorId undefined when the message has no integrator", async function () {
const params = await capturedParams(depositMessage({ withdrawLeaf }));
// Undefined is dropped at query-string serialization, so the request keeps its legacy shape.
expect(params.integratorId).to.equal(undefined);
});
it("leaves integratorId undefined when the integrator id is null", async function () {
const params = await capturedParams(
depositMessage({ withdrawLeaf }, { name: "test-integrator", integratorId: null })
);
// `?? undefined` collapses an explicit null id so it too is dropped at serialization.
expect(params.integratorId).to.equal(undefined);
});
});
describe("DepositAddressHandler._queryIndexerApi version filtering", function () {
let handler: DepositAddressHandler;
let getStub: sinon.SinonStub;
let warnStub: sinon.SinonStub;
type Internals = { _queryIndexerApi: () => Promise<DepositAddressMessage[]> };
beforeEach(function () {
const config = {} as unknown as DepositAddressHandlerConfig;
warnStub = sinon.stub();
const logger = { debug: sinon.stub(), warn: warnStub } as unknown as winston.Logger;
handler = new DepositAddressHandler(logger, config, {} as unknown as Signer, []);
getStub = sinon.stub();
(handler as unknown as { indexerApi: { get: sinon.SinonStub } }).indexerApi = { get: getStub };
});
afterEach(() => sinon.restore());
async function query(messages: unknown[]): Promise<DepositAddressMessage[]> {
getStub.resolves(messages);
return (handler as unknown as Internals)._queryIndexerApi();
}
it("drops v2 messages and keeps v1 + legacy + v3 in the same batch", async function () {
const v1 = { ...depositMessage({ withdrawLeaf }), version: 1 };
const legacy = depositMessage({ withdrawLeaf });
// v2 payloads do NOT carry the v1 shape — only v1/legacy messages should ever reach
// normalizeDepositAddressMessage, so v2 must be filtered out before the map.
const v2 = { version: 2, depositAddress: DEPOSIT_ADDRESS, paramsHash: "0x" + "0".repeat(64) };
const v3 = depositMessageV3();
const result = await query([v2, v1, v3, legacy]);
expect(result).to.have.length(3);
expect(result.map((m) => m.version)).to.deep.equal([1, 3, undefined]);
});
it("passes v3 messages through un-normalized", async function () {
// normalizeDepositAddressMessage dereferences v1-only fields; a v3 item reaching it would
// throw. The v3 shape must be returned verbatim.
const v3 = depositMessageV3();
const result = await query([v3]);
expect(result).to.deep.equal([v3]);
});
it("does not throw when a v2 message lacks the v1 shape", async function () {
// A bare v2 payload would make normalizeDepositAddressMessage throw if it reached the map;
// filtering before normalization must keep the poll alive.
const result = await query([{ version: 2 }]);
expect(result).to.deep.equal([]);
});
it("keeps a v1 message whose counterfactualMaterials are absent", async function () {
// Pre-V2-backfill deposit addresses are served with `counterfactualMaterials: undefined`;
// they must survive normalization (the withdraw path guards on the leaf downstream).
const v1 = { ...depositMessage(undefined), version: 1 };
const result = await query([v1]);
expect(result).to.have.length(1);
expect(result[0].counterfactualMaterials).to.equal(undefined);
expect(warnStub.called).to.equal(false);
});
it("drops a malformed supported-version message with a warn and keeps the rest of the batch", async function () {
// A supported-version message can still be malformed (missing routeParams here). It must be
// dropped individually — not sink the batch — or a redelivered poison message starves every
// other message for the indexer's whole redelivery window (2026-07-15 incident).
const poison = { ...depositMessage({ withdrawLeaf }), version: 1, routeParams: undefined };
const healthyV1 = { ...depositMessage({ withdrawLeaf }), version: 1 };
const v3 = depositMessageV3();
const result = await query([poison, healthyV1, v3]);
expect(result).to.have.length(2);
expect(result.map((m) => m.version)).to.deep.equal([1, 3]);
expect(warnStub.calledOnce).to.equal(true);
expect(warnStub.firstCall.args[0].message).to.equal(
"deposit-address transfer dropped: message failed normalization"
);
});
});
describe("DepositAddressHandler.processExecution v3 routing", function () {
let handler: DepositAddressHandler;
let v3Stub: sinon.SinonStub;
let v1Stub: sinon.SinonStub;
let withdrawStub: sinon.SinonStub;
let withdrawV3Stub: sinon.SinonStub;
let logger: winston.Logger;
type Internals = { processExecution: (m: unknown) => Promise<void> };
beforeEach(function () {
const config = {} as unknown as DepositAddressHandlerConfig;
logger = { debug: sinon.stub() } as unknown as winston.Logger;
handler = new DepositAddressHandler(logger, config, {} as unknown as Signer, []);
v3Stub = sinon.stub().resolves();
v1Stub = sinon.stub().resolves();
withdrawStub = sinon.stub().resolves();
withdrawV3Stub = sinon.stub().resolves();
Object.assign(handler, {
initiateDepositV3: v3Stub,
initiateDeposit: v1Stub,
initiateWithdraw: withdrawStub,
initiateWithdrawV3: withdrawV3Stub,
});
});
afterEach(() => sinon.restore());
it("routes v3 correct_transfer to the v3 execute path", async function () {
const message = depositMessageV3();
await (handler as unknown as Internals).processExecution(message);
expect(v3Stub.calledOnceWithExactly(message)).to.equal(true);
expect(v1Stub.notCalled).to.equal(true);
expect(withdrawStub.notCalled).to.equal(true);
expect(withdrawV3Stub.notCalled).to.equal(true);
});
it("routes v3 mis_route to the v3 withdraw path", async function () {
const message = depositMessageV3();
message.erc20Transfer.transferClassification = "mis_route";
await (handler as unknown as Internals).processExecution(message);
expect(withdrawV3Stub.calledOnceWithExactly(message)).to.equal(true);
expect(v3Stub.notCalled).to.equal(true);
expect(v1Stub.notCalled).to.equal(true);
expect(withdrawStub.notCalled).to.equal(true);
});
it("routes a v3 correct_transfer marked refund-only to the v3 withdraw path", async function () {
const message = depositMessageV3();
(handler as unknown as { refundOnlyDepositKeys: Set<string> }).refundOnlyDepositKeys.add(getDepositKey(message));
await (handler as unknown as Internals).processExecution(message);
expect(withdrawV3Stub.calledOnceWithExactly(message)).to.equal(true);
expect(v3Stub.notCalled).to.equal(true);
});
it("routes v3 intent_refund to the v3 withdraw path", async function () {
const message = depositMessageV3();
message.erc20Transfer.transferClassification = "intent_refund";
await (handler as unknown as Internals).processExecution(message);
expect(withdrawV3Stub.calledOnceWithExactly(message)).to.equal(true);
expect(v3Stub.notCalled).to.equal(true);
expect(v1Stub.notCalled).to.equal(true);
expect(withdrawStub.notCalled).to.equal(true);
});
it("keeps routing v1 messages to the v1 paths", async function () {
const deposit = depositMessage({ withdrawLeaf });
await (handler as unknown as Internals).processExecution(deposit);
expect(v1Stub.calledOnceWithExactly(deposit)).to.equal(true);
const refund = depositMessage({ withdrawLeaf });
refund.erc20Transfer.transferClassification = "mis_route";
await (handler as unknown as Internals).processExecution(refund);
expect(withdrawStub.calledOnceWithExactly(refund)).to.equal(true);
expect(v3Stub.notCalled).to.equal(true);
expect(withdrawV3Stub.notCalled).to.equal(true);
});
});
describe("DepositAddressHandler._getExecuteTx request mapping", function () {
let handler: DepositAddressHandler;
let executeStub: sinon.SinonStub;
type Internals = {
_getExecuteTx: (m: DepositAddressMessageV3) => Promise<DepositAddressExecuteResponse | undefined>;
};
beforeEach(function () {
const config = {} as unknown as DepositAddressHandlerConfig;
handler = new DepositAddressHandler(undefined as unknown as winston.Logger, config, {} as unknown as Signer, []);
// _signerAddress is normally set by initialize(); set it directly for this unit test.
(handler as unknown as { _signerAddress: EvmAddress })._signerAddress = EvmAddress.from(SIGNER);
executeStub = sinon.stub().resolves({ depositAddress: DEPOSIT_ADDRESS });
(handler as unknown as { api: { executeDepositAddress: sinon.SinonStub } }).api = {
executeDepositAddress: executeStub,
};
});
afterEach(() => sinon.restore());
it("relays funding context, depositAddress, inputToken and integratorId, with executionFee omitted", async function () {
await (handler as unknown as Internals)._getExecuteTx(depositMessageV3());
expect(executeStub.calledOnce).to.equal(true);
// Exact request body in the default / production shape: the execute endpoint re-derives the
// materials from this identity, and its superstruct schema rejects unknown or missing keys.
// `depositAddress` and `inputToken` are always sent; only `erc20Transfer` remains gated.
expect(executeStub.firstCall.args[0]).to.deep.equal({
destination: {
token: { chainId: 1337, address: OUTPUT_TOKEN },
recipient: RECIPIENT,
},
originChainId: 42161,
depositAddress: DEPOSIT_ADDRESS,
inputToken: { chainId: 42161, address: TOKEN },
userAddress: REFUND_ADDRESS,
amount: "5000",
executionFeeRecipient: SIGNER,
integratorId: "0xdead",
});
});
it("relays erc20Transfer provenance when ENABLE_EXECUTE_ERC20_TRANSFER_METADATA is on", async function () {
(handler as unknown as { config: { enableExecuteErc20Transfer: boolean } }).config.enableExecuteErc20Transfer =
true;
await (handler as unknown as Internals)._getExecuteTx(depositMessageV3());
expect(executeStub.calledOnce).to.equal(true);
expect(executeStub.firstCall.args[0]).to.deep.equal({
destination: {
token: { chainId: 1337, address: OUTPUT_TOKEN },
recipient: RECIPIENT,
},
originChainId: 42161,
depositAddress: DEPOSIT_ADDRESS,
inputToken: { chainId: 42161, address: TOKEN },
userAddress: REFUND_ADDRESS,
amount: "5000",
executionFeeRecipient: SIGNER,
integratorId: "0xdead",
// chainId coerced from the fixture's "42161" string; Number() is a no-op on a numeric value.
erc20Transfer: {
chainId: 42161,
blockNumber: 1_000_000,
transactionHash: "0x" + "3".repeat(64),
logIndex: 4,
},
});
});
it("retries on undefined responses and gives up after exhausting retries", async function () {
executeStub.resolves(undefined);
const result = await (handler as unknown as Internals)._getExecuteTx(depositMessageV3());
expect(result).to.equal(undefined);
expect(executeStub.callCount).to.equal(4); // initial attempt + 3 retries
});
it("sends origin-native Tron encodings: base58 identity fields verbatim, base58 executionFeeRecipient", async function () {
await (handler as unknown as Internals)._getExecuteTx(tronDepositMessageV3());
expect(executeStub.calledOnce).to.equal(true);
const expectedFeeRecipient = toAddressType(SIGNER, CHAIN_IDs.TRON).toNative();
// Sanity: the fee recipient really is re-encoded, not the signer's 0x form.
expect(expectedFeeRecipient).to.not.equal(SIGNER);
expect(executeStub.firstCall.args[0]).to.deep.equal({
destination: {
token: { chainId: CHAIN_IDs.BASE, address: OUTPUT_TOKEN },
recipient: RECIPIENT,
},
originChainId: CHAIN_IDs.TRON,
depositAddress: TRON_DEPOSIT_ADDRESS,
inputToken: { chainId: CHAIN_IDs.TRON, address: TRON_TOKEN },
userAddress: TRON_REFUND_ADDRESS,
amount: "25000000",
executionFeeRecipient: expectedFeeRecipient,
integratorId: "0x00e6",
});
});
it("relays the un-prefixed Tron provenance hash verbatim when the erc20Transfer gate is on", async function () {
(handler as unknown as { config: { enableExecuteErc20Transfer: boolean } }).config.enableExecuteErc20Transfer =
true;
await (handler as unknown as Internals)._getExecuteTx(tronDepositMessageV3());
expect(executeStub.calledOnce).to.equal(true);
const request = executeStub.firstCall.args[0] as Record<string, unknown>;
expect(request.erc20Transfer).to.deep.equal({
chainId: CHAIN_IDs.TRON,
blockNumber: 84_665_484,
transactionHash: TRON_TX_HASH,
logIndex: 55,
});
});
});
describe("DepositAddressHandler._getExecuteTx terminal-code handling", function () {
let handler: DepositAddressHandler;
let executeStub: sinon.SinonStub;
let redisSetStub: sinon.SinonStub;
let warnStub: sinon.SinonStub;
const depositKey = getDepositKey(depositMessageV3());
type Internals = {
_getExecuteTx: (m: DepositAddressMessageV3) => Promise<DepositAddressExecuteResponse | undefined>;
refundOnlyDepositKeys: Set<string>;
};
function internals(): Internals {
return handler as unknown as Internals;
}
beforeEach(function () {
const config = {} as unknown as DepositAddressHandlerConfig;
warnStub = sinon.stub();
const logger = { warn: warnStub, debug: sinon.stub() } as unknown as winston.Logger;
handler = new DepositAddressHandler(logger, config, {} as unknown as Signer, []);
(handler as unknown as { _signerAddress: EvmAddress })._signerAddress = EvmAddress.from(SIGNER);
executeStub = sinon.stub();
(handler as unknown as { api: { executeDepositAddress: sinon.SinonStub } }).api = {
executeDepositAddress: executeStub,
};
redisSetStub = sinon.stub().resolves();
(handler as unknown as { redisCache: { set: sinon.SinonStub } }).redisCache = { set: redisSetStub };
});
afterEach(() => sinon.restore());
it("treats AMOUNT_BELOW_MINIMUM as terminal: no retry, persists the refund-only key", async function () {
executeStub.rejects(new AcrossApiHttpError(422, "amount must be >= 5000000", "AMOUNT_BELOW_MINIMUM", "amount"));
const result = await internals()._getExecuteTx(depositMessageV3());
expect(result).to.equal(undefined);
expect(executeStub.callCount).to.equal(1); // no retries on a terminal rejection
expect(internals().refundOnlyDepositKeys.has(depositKey)).to.equal(true);
expect(redisSetStub.calledOnce).to.equal(true);
expect(redisSetStub.firstCall.args[1]).to.equal(JSON.stringify([depositKey]));
});
it("keys on the error code, not the status, so a status change does not silently re-enable retries", async function () {
executeStub.rejects(new AcrossApiHttpError(400, "amount must be >= 5000000", "AMOUNT_BELOW_MINIMUM", "amount"));
await internals()._getExecuteTx(depositMessageV3());
expect(executeStub.callCount).to.equal(1);
expect(internals().refundOnlyDepositKeys.has(depositKey)).to.equal(true);
});
it("treats AMOUNT_TEMPORARILY_UNSWEEPABLE (400) as terminal: no retry, persists the refund-only key", async function () {
executeStub.rejects(
new AcrossApiHttpError(400, "maxFeeCctp 419883 exceeds the on-chain cap 250000", "AMOUNT_TEMPORARILY_UNSWEEPABLE")
);
const result = await internals()._getExecuteTx(depositMessageV3());
expect(result).to.equal(undefined);
expect(executeStub.callCount).to.equal(1);
expect(internals().refundOnlyDepositKeys.has(depositKey)).to.equal(true);
expect(redisSetStub.calledOnce).to.equal(true);
expect(redisSetStub.firstCall.args[1]).to.equal(JSON.stringify([depositKey]));
});
it("retries other terminal-looking 422s and persists no refund-only key", async function () {
executeStub.rejects(new AcrossApiHttpError(422, "cannot price token", "UNPRICEABLE_TOKEN"));
const result = await internals()._getExecuteTx(depositMessageV3());
expect(result).to.equal(undefined);
expect(executeStub.callCount).to.equal(4); // initial attempt + 3 retries
expect(internals().refundOnlyDepositKeys.size).to.equal(0);
expect(redisSetStub.notCalled).to.equal(true);
});
it("retries a plain HttpError carrying no code", async function () {
executeStub.rejects(new HttpError(500, "HTTP 500: Internal Server Error"));
await internals()._getExecuteTx(depositMessageV3());
expect(executeStub.callCount).to.equal(4);
expect(internals().refundOnlyDepositKeys.size).to.equal(0);
});
});
describe("DepositAddressHandler.initiateDepositV3 below-minimum refund fallback", function () {
let handler: DepositAddressHandler;
let executeStub: sinon.SinonStub;
let withdrawV3Stub: sinon.SinonStub;
let warnStub: sinon.SinonStub;
const originChainId = 42161;
const depositKey = getDepositKey(depositMessageV3());
type Internals = {
initiateDepositV3: (m: DepositAddressMessageV3) => Promise<void>;
refundOnlyDepositKeys: Set<string>;
observedExecutedDeposits: Record<number, Set<string>>;
};
function internals(): Internals {
return handler as unknown as Internals;
}
beforeEach(function () {
const config = { relayerOriginChains: [originChainId] } as unknown as DepositAddressHandlerConfig;
warnStub = sinon.stub();
const logger = { warn: warnStub, debug: sinon.stub() } as unknown as winston.Logger;
handler = new DepositAddressHandler(logger, config, {} as unknown as Signer, []);
(handler as unknown as { _signerAddress: EvmAddress })._signerAddress = EvmAddress.from(SIGNER);
executeStub = sinon.stub();
(handler as unknown as { api: { executeDepositAddress: sinon.SinonStub } }).api = {
executeDepositAddress: executeStub,
};
(handler as unknown as { redisCache: { set: sinon.SinonStub } }).redisCache = { set: sinon.stub().resolves() };
(handler as unknown as { observedExecutedDeposits: Record<number, Set<string>> }).observedExecutedDeposits = {
[originChainId]: new Set<string>(),
};
(handler as unknown as { getDepositAddressBalance: sinon.SinonStub }).getDepositAddressBalance = sinon
.stub()
.resolves(toBN("5000"));
withdrawV3Stub = sinon.stub().resolves();
Object.assign(handler, { initiateWithdrawV3: withdrawV3Stub });
});
afterEach(() => sinon.restore());
it("refunds in the same tick when the execute is rejected as below minimum", async function () {
executeStub.rejects(new AcrossApiHttpError(422, "amount must be >= 5000000", "AMOUNT_BELOW_MINIMUM", "amount"));
const message = depositMessageV3();
await internals().initiateDepositV3(message);
expect(executeStub.callCount).to.equal(1);
expect(withdrawV3Stub.calledOnceWithExactly(message)).to.equal(true);
// No execute happened, so the deposit in-flight lock must be released for the next poll.
expect(internals().observedExecutedDeposits[originChainId].has(depositKey)).to.equal(false);
expect(internals().refundOnlyDepositKeys.has(depositKey)).to.equal(true);
});
it("warns and does not refund when the execute failed for any other reason", async function () {
executeStub.rejects(new AcrossApiHttpError(500, "boom", "UNEXPECTED_ERROR"));
await internals().initiateDepositV3(depositMessageV3());
expect(withdrawV3Stub.notCalled).to.equal(true);
expect(warnStub.called).to.equal(true);
expect(internals().refundOnlyDepositKeys.size).to.equal(0);
});
});
describe("DepositAddressHandler.initiateDepositV3 namespace guard", function () {
let handler: DepositAddressHandler;
let executeStub: sinon.SinonStub;
let warnStub: sinon.SinonStub;
type Internals = { initiateDepositV3: (m: DepositAddressMessageV3) => Promise<void> };
function makeHandler(originChainId: number): void {
const config = { relayerOriginChains: [originChainId] } as unknown as DepositAddressHandlerConfig;
warnStub = sinon.stub();
const logger = { warn: warnStub, debug: sinon.stub() } as unknown as winston.Logger;
handler = new DepositAddressHandler(logger, config, {} as unknown as Signer, []);
(handler as unknown as { _signerAddress: EvmAddress })._signerAddress = EvmAddress.from(SIGNER);
// Resolving undefined makes _getExecuteTx retry then bail with a warn — reaching the endpoint
// at all is the proof that the namespace guard opened.
executeStub = sinon.stub().resolves(undefined);
(handler as unknown as { api: { executeDepositAddress: sinon.SinonStub } }).api = {
executeDepositAddress: executeStub,
};
(handler as unknown as { observedExecutedDeposits: Record<number, Set<string>> }).observedExecutedDeposits = {
[originChainId]: new Set<string>(),
};
// The balance check sits between the namespace guard and the API call; make it pass.
(handler as unknown as { getDepositAddressBalance: sinon.SinonStub }).getDepositAddressBalance = sinon
.stub()
.resolves(toBN("25000000"));
}
afterEach(() => sinon.restore());
it("skips an svm-namespaced message without calling the execute endpoint", async function () {
makeHandler(42161);
await (handler as unknown as Internals).initiateDepositV3(depositMessageV3({ depositAddressNamespace: "svm" }));
expect(executeStub.notCalled).to.equal(true);
expect(warnStub.calledOnce).to.equal(true);
});
it("skips a tron-namespaced message on an EVM origin chain (cross-family anomaly)", async function () {
makeHandler(42161);
await (handler as unknown as Internals).initiateDepositV3(depositMessageV3({ depositAddressNamespace: "tron" }));
expect(executeStub.notCalled).to.equal(true);
expect(warnStub.calledOnce).to.equal(true);
});
it("skips a Tron-origin message whose refund namespace does not match the chain family", async function () {
makeHandler(CHAIN_IDs.TRON);
await (handler as unknown as Internals).initiateDepositV3(
tronDepositMessageV3({ refundAddress: { namespace: "evm", address: REFUND_ADDRESS } })
);
expect(executeStub.notCalled).to.equal(true);
expect(warnStub.calledOnce).to.equal(true);
});
it("lets a tron-namespaced message on the Tron chain through to the execute endpoint", async function () {
makeHandler(CHAIN_IDs.TRON);
await (handler as unknown as Internals).initiateDepositV3(tronDepositMessageV3());
expect(executeStub.called).to.equal(true);
});
});
describe("DepositAddressHandler.initiateDepositV3 integratorId guard", function () {
let handler: DepositAddressHandler;
let executeStub: sinon.SinonStub;
let warnStub: sinon.SinonStub;
const originChainId = 42161;
type Internals = { initiateDepositV3: (m: DepositAddressMessageV3) => Promise<void> };
beforeEach(function () {
const config = { relayerOriginChains: [originChainId] } as unknown as DepositAddressHandlerConfig;
warnStub = sinon.stub();
const logger = { warn: warnStub, debug: sinon.stub() } as unknown as winston.Logger;
handler = new DepositAddressHandler(logger, config, {} as unknown as Signer, []);
executeStub = sinon.stub().resolves({ depositAddress: DEPOSIT_ADDRESS });
(handler as unknown as { api: { executeDepositAddress: sinon.SinonStub } }).api = {
executeDepositAddress: executeStub,
};
// initiateDepositV3 adds/removes the depositKey from this set; seed it so the path runs.
(handler as unknown as { observedExecutedDeposits: Record<number, Set<string>> }).observedExecutedDeposits = {
[originChainId]: new Set<string>(),
};
});
afterEach(() => sinon.restore());
// Each case reaches the guard (evm namespace, origin chain allowed, not yet executed) and must
// skip before calling the execute endpoint, since a missing/malformed integratorId would only
// derive a different, unfunded address.
const skipCases: { name: string; integrator: DepositAddressMessageV3["integrator"] }[] = [
{ name: "integrator is null", integrator: null },
{ name: "integratorId is null", integrator: { name: "x", integratorId: null } },
{ name: "integratorId is non-hex", integrator: { name: "x", integratorId: "0xZZZZ" } },
{ name: "integratorId is wrong length", integrator: { name: "x", integratorId: "0xdeadbeef" } },
];
skipCases.forEach(({ name, integrator }) => {
it(`skips without calling the execute endpoint when ${name}`, async function () {
await (handler as unknown as Internals).initiateDepositV3(depositMessageV3({ integrator }));
expect(executeStub.notCalled).to.equal(true);
expect(warnStub.calledOnce).to.equal(true);
});
});
});
describe("DepositAddressHandler._validateExecuteResponse guards", function () {
let handler: DepositAddressHandler;
let warnStub: sinon.SinonStub;
type Internals = {
_validateExecuteResponse: (
r: DepositAddressExecuteResponse,
m: DepositAddressMessageV3,
originChainId: number,
depositKey: string
) => boolean;
};
const message = depositMessageV3();
const originChainId = Number(message.erc20Transfer.chainId);
function executeResponse(overrides: Partial<DepositAddressExecuteResponse> = {}): DepositAddressExecuteResponse {
return {
depositAddress: DEPOSIT_ADDRESS,
executeTx: { ecosystem: "evm", chainId: originChainId, to: TOKEN, data: "0x", value: "0" },
signer: SIGNER,
signatureDeadline: getCurrentTime() + 600,
isPlaceholder: false,
...overrides,
};
}
function validate(response: DepositAddressExecuteResponse): boolean {
return (handler as unknown as Internals)._validateExecuteResponse(response, message, originChainId, "key");
}
beforeEach(function () {
const config = {} as unknown as DepositAddressHandlerConfig;
warnStub = sinon.stub();
const logger = { warn: warnStub } as unknown as winston.Logger;
handler = new DepositAddressHandler(logger, config, {} as unknown as Signer, []);
});
afterEach(() => sinon.restore());
it("accepts a well-formed response (case-insensitive address match)", function () {
expect(validate(executeResponse({ depositAddress: DEPOSIT_ADDRESS.toLowerCase() }))).to.equal(true);
expect(warnStub.notCalled).to.equal(true);
});
it("rejects when the API-derived deposit address does not match the funded address", function () {
expect(validate(executeResponse({ depositAddress: RECIPIENT }))).to.equal(false);
expect(warnStub.calledOnce).to.equal(true);
});
it("rejects when the execute tx targets the wrong chain", function () {
const response = executeResponse();
response.executeTx.chainId = 1;
expect(validate(response)).to.equal(false);
});
it("rejects placeholder derivations", function () {
expect(validate(executeResponse({ isPlaceholder: true }))).to.equal(false);
});
it("rejects responses whose signature deadline is too close to expiry", function () {
expect(validate(executeResponse({ signatureDeadline: getCurrentTime() + 30 }))).to.equal(false);
});
it("rejects a tvm-ecosystem response for an EVM origin", function () {
const response = executeResponse();
response.executeTx.ecosystem = "tvm";
expect(validate(response)).to.equal(false);
expect(warnStub.calledOnce).to.equal(true);
});
});
describe("DepositAddressHandler._validateExecuteResponse for Tron origins", function () {
let handler: DepositAddressHandler;
let warnStub: sinon.SinonStub;
type Internals = {
_validateExecuteResponse: (
r: DepositAddressExecuteResponse,
m: DepositAddressMessageV3,
originChainId: number,
depositKey: string
) => boolean;
};
const message = tronDepositMessageV3();
const originChainId = Number(message.erc20Transfer.chainId);
/** Mirrors the live quote-api Tron response: base58 depositAddress echo, "tvm", 0x-hex `to`. */
function executeResponse(overrides: Partial<DepositAddressExecuteResponse> = {}): DepositAddressExecuteResponse {
return {
depositAddress: TRON_DEPOSIT_ADDRESS,
executeTx: { ecosystem: "tvm", chainId: originChainId, to: TRON_FACTORY, data: "0x", value: "0" },
signer: SIGNER,
signatureDeadline: getCurrentTime() + 600,
isPlaceholder: false,
...overrides,
};
}
function validate(response: DepositAddressExecuteResponse): boolean {
return (handler as unknown as Internals)._validateExecuteResponse(response, message, originChainId, "key");
}
beforeEach(function () {
const config = {} as unknown as DepositAddressHandlerConfig;
warnStub = sinon.stub();
const logger = { warn: warnStub } as unknown as winston.Logger;
handler = new DepositAddressHandler(logger, config, {} as unknown as Signer, []);
});
afterEach(() => sinon.restore());
it("accepts a base58 depositAddress echo", function () {
expect(validate(executeResponse())).to.equal(true);
expect(warnStub.notCalled).to.equal(true);
});
it("accepts the 0x-hex encoding of the funded base58 address", function () {
const hexDepositAddress = toAddressType(TRON_DEPOSIT_ADDRESS, originChainId).toEvmAddress();
expect(validate(executeResponse({ depositAddress: hexDepositAddress }))).to.equal(true);
expect(warnStub.notCalled).to.equal(true);
});
it("rejects a different base58 depositAddress", function () {
expect(validate(executeResponse({ depositAddress: TRON_REFUND_ADDRESS }))).to.equal(false);
expect(warnStub.calledOnce).to.equal(true);
});
it("rejects an evm-ecosystem response for a Tron origin", function () {
const response = executeResponse();
response.executeTx.ecosystem = "evm";
expect(validate(response)).to.equal(false);
expect(warnStub.calledOnce).to.equal(true);
});
});
describe("DepositAddressHandler._getSignedWithdrawV3", function () {
let handler: DepositAddressHandler;
let signWithdrawStub: sinon.SinonStub;
let redisSetStub: sinon.SinonStub;
let publishStub: sinon.SinonStub;
type Internals = {
_getSignedWithdrawV3: (
m: DepositAddressMessageV3,
leaf: typeof v3WithdrawLeaf,
retriesRemaining?: number
) => Promise<DepositAddressSignWithdrawResponse | undefined>;
terminallySkippedWithdrawKeys: Set<string>;
};
function internals(): Internals {
return handler as unknown as Internals;
}
beforeEach(function () {
// A terminal 422 publishes withdraw_failed; the gate must be on to observe it.
const config = { enableDepositAddressWithdrawPublisher: true } as unknown as DepositAddressHandlerConfig;
const logger = { warn: sinon.stub(), debug: sinon.stub() } as unknown as winston.Logger;
handler = new DepositAddressHandler(logger, config, {} as unknown as Signer, []);
signWithdrawStub = sinon.stub();
(handler as unknown as { api: { signWithdrawDepositAddressV3: sinon.SinonStub } }).api = {
signWithdrawDepositAddressV3: signWithdrawStub,
};
redisSetStub = sinon.stub().resolves();
(handler as unknown as { redisCache: { set: sinon.SinonStub } }).redisCache = { set: redisSetStub };
publishStub = sinon.stub().resolves("msg-id");
(handler as unknown as { executionPublisher: { publishJson: sinon.SinonStub } }).executionPublisher = {
publishJson: publishStub,
};
});
afterEach(() => sinon.restore());
it("builds the sign-withdraw request from the message + withdraw leaf, with gas deduction on", async function () {
signWithdrawStub.resolves({ signedWithdrawTx: { chainId: 42161 } });
const message = withdrawMessageV3();
await internals()._getSignedWithdrawV3(message, v3WithdrawLeaf);
expect(signWithdrawStub.calledOnce).to.equal(true);
expect(signWithdrawStub.firstCall.args[0]).to.deep.equal({
chainId: 42161,
depositAddress: DEPOSIT_ADDRESS,
initialRoot: "0x" + "2".repeat(64),
salt: "0x" + "0".repeat(64),
token: TOKEN,
amount: "5000",
user: REFUND_ADDRESS,
proof: v3WithdrawLeaf.merkleProof,
counterfactualDepositFactory: "0x000000000000000000000000000000000000B2B2",
counterfactualBeacon: "0x000000000000000000000000000000000000B1B1",
adminWithdrawManager: "0x000000000000000000000000000000000000B3B3",
withdrawImplementation: WITHDRAW_IMPL,
deductGasFromRefund: true,
});
});
it("does not deduct gas from an intent_refund: the user is made whole at our expense", async function () {
signWithdrawStub.resolves({ signedWithdrawTx: { chainId: 42161 } });
const message = withdrawMessageV3();
message.erc20Transfer.transferClassification = "intent_refund";
await internals()._getSignedWithdrawV3(message, v3WithdrawLeaf);
expect(signWithdrawStub.firstCall.args[0].deductGasFromRefund).to.equal(false);
});
it("retries transient failures, then gives up without persisting a skip", async function () {
signWithdrawStub.rejects(new HttpError(400, "GAS_FEE_TEMPORARILY_UNAVAILABLE"));
const message = withdrawMessageV3();
const result = await internals()._getSignedWithdrawV3(message, v3WithdrawLeaf);
expect(result).to.equal(undefined);
expect(signWithdrawStub.callCount).to.equal(4); // initial attempt + 3 retries
expect(internals().terminallySkippedWithdrawKeys.size).to.equal(0);
expect(redisSetStub.notCalled).to.equal(true);