-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathSvmSpoke.Deposit.ts
818 lines (691 loc) · 33.2 KB
/
SvmSpoke.Deposit.ts
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
import * as anchor from "@coral-xyz/anchor";
import { BN } from "@coral-xyz/anchor";
import { getApproveCheckedInstruction } from "@solana-program/token";
import {
address,
airdropFactory,
appendTransactionMessageInstruction,
createKeyPairFromBytes,
createSignerFromKeyPair,
getProgramDerivedAddress,
lamports,
pipe,
} from "@solana/kit";
import {
ASSOCIATED_TOKEN_PROGRAM_ID,
ExtensionType,
NATIVE_MINT,
TOKEN_2022_PROGRAM_ID,
TOKEN_PROGRAM_ID,
createApproveCheckedInstruction,
createAssociatedTokenAccountIdempotentInstruction,
createCloseAccountInstruction,
createEnableCpiGuardInstruction,
createMint,
createReallocateInstruction,
createSyncNativeInstruction,
getAccount,
getAssociatedTokenAddressSync,
getMinimumBalanceForRentExemptAccount,
getOrCreateAssociatedTokenAccount,
mintTo,
} from "@solana/spl-token";
import { Keypair, PublicKey, SystemProgram, Transaction, sendAndConfirmTransaction } from "@solana/web3.js";
import { BigNumber, ethers } from "ethers";
import { SvmSpokeClient } from "../../src/svm";
import { DepositInput } from "../../src/svm/clients/SvmSpoke";
import { intToU8Array32, readEventsUntilFound, u8Array32ToBigNumber, u8Array32ToInt } from "../../src/svm/web3-v1";
import { DepositDataValues } from "../../src/types/svm";
import { MAX_EXCLUSIVITY_OFFSET_SECONDS } from "../../test-utils";
import { common } from "./SvmSpoke.common";
import { createDefaultSolanaClient, createDefaultTransaction, signAndSendTransaction } from "./utils";
const { provider, connection, program, owner, seedBalance, initializeState, depositData } = common;
const { getOrCreateVaultAta, assertSE, assert, getCurrentTime, depositQuoteTimeBuffer, fillDeadlineBuffer } = common;
const maxExclusivityOffsetSeconds = new BN(MAX_EXCLUSIVITY_OFFSET_SECONDS); // 1 year in seconds
describe("svm_spoke.deposit", () => {
anchor.setProvider(provider);
const depositor = Keypair.generate();
const payer = (anchor.AnchorProvider.env().wallet as anchor.Wallet).payer;
const tokenDecimals = 6;
let state: PublicKey, inputToken: PublicKey, depositorTA: PublicKey, vault: PublicKey, tokenProgram: PublicKey;
// Re-used between tests to simplify props.
type DepositAccounts = {
state: PublicKey;
signer: PublicKey;
depositorTokenAccount: PublicKey;
vault: PublicKey;
mint: PublicKey;
tokenProgram: PublicKey;
program: PublicKey;
};
let depositAccounts: DepositAccounts;
const setupInputToken = async () => {
inputToken = await createMint(connection, payer, owner, owner, tokenDecimals, undefined, undefined, tokenProgram);
depositorTA = (
await getOrCreateAssociatedTokenAccount(
connection,
payer,
inputToken,
depositor.publicKey,
undefined,
undefined,
undefined,
tokenProgram
)
).address;
await mintTo(connection, payer, inputToken, depositorTA, owner, seedBalance, undefined, undefined, tokenProgram);
};
const createVault = async () => {
vault = await getOrCreateVaultAta(payer, inputToken, state);
// Set known fields in the depositData.
depositData.depositor = depositor.publicKey;
depositData.inputToken = inputToken;
depositAccounts = {
state,
signer: depositor.publicKey,
depositorTokenAccount: depositorTA,
vault,
mint: inputToken,
tokenProgram: tokenProgram ?? TOKEN_PROGRAM_ID,
program: program.programId,
};
};
const approvedDeposit = async (
depositDataValues: DepositDataValues,
calledDepositAccounts: DepositAccounts = depositAccounts
) => {
// Delegate state PDA to pull depositor tokens.
const approveIx = await createApproveCheckedInstruction(
calledDepositAccounts.depositorTokenAccount,
calledDepositAccounts.mint,
calledDepositAccounts.state,
depositor.publicKey,
BigInt(depositData.inputAmount.toString()),
tokenDecimals,
undefined,
tokenProgram
);
const depositIx = await program.methods
.deposit(...depositDataValues)
.accounts(calledDepositAccounts)
.instruction();
const depositTx = new Transaction().add(approveIx, depositIx);
const tx = await sendAndConfirmTransaction(connection, depositTx, [depositor]);
return tx;
};
before(async () => {
await connection.requestAirdrop(depositor.publicKey, 10_000_000_000); // 10 SOL
});
beforeEach(async () => {
({ state } = await initializeState());
tokenProgram = TOKEN_PROGRAM_ID; // Some tests might override this.
await setupInputToken();
await createVault();
});
it("Deposits tokens via deposit function and checks balances", async () => {
// Verify vault balance is zero before the deposit
let vaultAccount = await getAccount(connection, vault);
assertSE(vaultAccount.amount, "0", "Vault balance should be zero before the deposit");
// Execute the deposit call
let depositDataValues = Object.values(depositData) as DepositDataValues;
await approvedDeposit(depositDataValues);
// Verify tokens leave the depositor's account
let depositorAccount = await getAccount(connection, depositorTA);
assertSE(
depositorAccount.amount,
seedBalance - depositData.inputAmount.toNumber(),
"Depositor's balance should be reduced by the deposited amount"
);
// Verify tokens are credited into the vault
vaultAccount = await getAccount(connection, vault);
assertSE(vaultAccount.amount, depositData.inputAmount, "Vault balance should be increased by the deposited amount");
// Modify depositData for the second deposit
const secondInputAmount = new BN(300000);
// Execute the second deposit call
depositDataValues = Object.values({ ...depositData, inputAmount: secondInputAmount }) as DepositDataValues;
await approvedDeposit(depositDataValues);
// Verify tokens leave the depositor's account again
depositorAccount = await getAccount(connection, depositorTA);
assertSE(
depositorAccount.amount,
seedBalance - depositData.inputAmount.toNumber() - secondInputAmount.toNumber(),
"Depositor's balance should be reduced by the total deposited amount"
);
// Verify tokens are credited into the vault again
vaultAccount = await getAccount(connection, vault);
assertSE(
vaultAccount.amount,
depositData.inputAmount.add(secondInputAmount),
"Vault balance should be increased by the total deposited amount"
);
});
it("Verifies FundsDeposited after deposits", async () => {
depositData.inputAmount = depositData.inputAmount.add(new BN(69));
// Execute the first deposit call
let depositDataValues = Object.values(depositData) as DepositDataValues;
const tx = await approvedDeposit(depositDataValues);
let events = await readEventsUntilFound(connection, tx, [program]);
let event = events[0].data; // 0th event is the latest event
const expectedValues1 = { ...depositData, depositId: intToU8Array32(1) }; // Verify the event props emitted match the depositData.
for (let [key, value] of Object.entries(expectedValues1)) {
if (key === "exclusivityParameter") key = "exclusivityDeadline"; // the prop and the event names differ on this key.
assertSE(event[key], value, `${key} should match`);
}
// Test the id recovery with the conversion utils
assertSE(u8Array32ToInt(event.depositId), 1, `depositId should recover to 1`);
assertSE(u8Array32ToBigNumber(event.depositId), BigNumber.from(1), `depositId should recover to 1`);
// Execute the second deposit_v3 call
const tx2 = await approvedDeposit(depositDataValues);
events = await readEventsUntilFound(connection, tx2, [program]);
event = events[0].data; // 0th event is the latest event.
const expectedValues2 = { ...expectedValues1, depositId: intToU8Array32(2) }; // Verify the event props emitted match the depositData.
for (let [key, value] of Object.entries(expectedValues2)) {
if (key === "exclusivityParameter") key = "exclusivityDeadline"; // the prop and the event names differ on this key.
assertSE(event[key], value, `${key} should match`);
}
// Test the id recovery with the conversion utils
assertSE(u8Array32ToInt(event.depositId), 2, `depositId should recover to 2`);
assertSE(u8Array32ToBigNumber(event.depositId), BigNumber.from(2), `depositId should recover to 2`);
});
it("Deposit with deadline before current time succeeds", async () => {
const currentTime = await getCurrentTime(program, state);
// Fill deadline is before current time on the contract
let fillDeadline = currentTime - 1; // 1 second before current time on the contract.
depositData.fillDeadline = new BN(fillDeadline);
depositData.quoteTimestamp = new BN(currentTime - 1); // 1 second before current time on the contract to reset.
const depositDataValues = Object.values(depositData) as DepositDataValues;
const tx = await approvedDeposit(depositDataValues);
const events = await readEventsUntilFound(connection, tx, [program]);
const event = events[0].data; // 0th event is the latest event.
assertSE(event.fillDeadline, fillDeadline, "Fill deadline should match");
});
it("Fails to process deposit when deposits are paused", async () => {
// Pause deposits
const pauseDepositsAccounts = { state, signer: owner, program: program.programId };
await program.methods.pauseDeposits(true).accounts(pauseDepositsAccounts).rpc();
const stateAccountData = await program.account.state.fetch(state);
assert.isTrue(stateAccountData.pausedDeposits, "Deposits should be paused");
// Try to deposit. This should fail because deposits are paused.
try {
const depositDataValues = Object.values(depositData) as DepositDataValues;
await approvedDeposit(depositDataValues);
assert.fail("Should not be able to process deposit when deposits are paused");
} catch (err: any) {
assert.include(err.toString(), "Error Code: DepositsArePaused", "Expected DepositsArePaused error");
}
});
it("Fails to deposit tokens with InvalidQuoteTimestamp when quote timestamp is in the future", async () => {
const currentTime = await getCurrentTime(program, state);
const futureQuoteTimestamp = new BN(currentTime + 10); // 10 seconds in the future
depositData.quoteTimestamp = futureQuoteTimestamp;
try {
const depositDataValues = Object.values(depositData) as DepositDataValues;
await approvedDeposit(depositDataValues);
assert.fail("Deposit should have failed due to InvalidQuoteTimestamp");
} catch (err: any) {
assert.include(err.toString(), "Error Code: InvalidQuoteTimestamp", "Expected InvalidQuoteTimestamp error");
}
});
it("Fails to deposit tokens with quoteTimestamp is too old", async () => {
const currentTime = await getCurrentTime(program, state);
const futureQuoteTimestamp = new BN(currentTime - depositQuoteTimeBuffer.toNumber() - 1); // older than buffer.
depositData.quoteTimestamp = futureQuoteTimestamp;
try {
const depositDataValues = Object.values(depositData) as DepositDataValues;
await approvedDeposit(depositDataValues);
assert.fail("Deposit should have failed due to InvalidQuoteTimestamp");
} catch (err: any) {
assert.include(err.toString(), "Error Code: InvalidQuoteTimestamp", "Expected InvalidQuoteTimestamp error");
}
});
it("Fails to deposit tokens with InvalidFillDeadline when fill deadline is invalid", async () => {
const currentTime = await getCurrentTime(program, state);
// Fill deadline is too far ahead (longer than fill_deadline_buffer + currentTime)
const invalidFillDeadline = currentTime + fillDeadlineBuffer.toNumber() + 1; // 1 seconds beyond the buffer
depositData.fillDeadline = new BN(invalidFillDeadline);
depositData.quoteTimestamp = new BN(currentTime);
try {
const depositDataValues = Object.values(depositData) as DepositDataValues;
await approvedDeposit(depositDataValues);
assert.fail("Deposit should have failed due to InvalidFillDeadline (future deadline)");
} catch (err: any) {
assert.include(err.toString(), "InvalidFillDeadline", "Expected InvalidFillDeadline error for future deadline");
}
});
it("Fails to process deposit for mint inconsistent input_token", async () => {
// Save the correct data from global scope before changing it when creating a new input token.
const firstInputToken = inputToken;
// Create a new input token and the vault.
await setupInputToken();
await createVault();
// Try to execute the deposit call with malformed inputs where the first input token is passed combined with mint,
// vault and user token account from the second input token.
const malformedDepositData = { ...depositData, inputToken: firstInputToken };
const malformedDepositAccounts = { ...depositAccounts };
try {
const depositDataValues = Object.values(malformedDepositData) as DepositDataValues;
await approvedDeposit(depositDataValues, malformedDepositAccounts);
assert.fail("Should not be able to process deposit for inconsistent mint");
} catch (err: any) {
assert.include(err.toString(), "Error Code: InvalidMint", "Expected InvalidMint error");
}
});
it("depositV3Now behaves as deposit but forces the quote timestamp as expected", async () => {
// Set up initial deposit data. Note that this method has a slightly different interface to deposit, using
// fillDeadlineOffset rather than fillDeadline. current chain time is added to fillDeadlineOffset to set the
// fillDeadline for the deposit. exclusivityPeriod operates the same as in standard deposit.
// Equally, depositV3Now does not have `quoteTimestamp`. this is set to the current time from the program.
const fillDeadlineOffset = 60; // 60 seconds offset
// Delegate state PDA to pull depositor tokens.
const approveIx = await createApproveCheckedInstruction(
depositAccounts.depositorTokenAccount,
depositAccounts.mint,
depositAccounts.state,
depositor.publicKey,
BigInt(depositData.inputAmount.toString()),
tokenDecimals,
undefined,
tokenProgram
);
// Execute the deposit_now call. Remove the quoteTimestamp from the depositData as not needed for this method.
const depositIx = await program.methods
.depositNow(
depositData.depositor!,
depositData.recipient!,
depositData.inputToken!,
depositData.outputToken!,
depositData.inputAmount,
depositData.outputAmount,
depositData.destinationChainId,
depositData.exclusiveRelayer!,
fillDeadlineOffset,
0,
depositData.message
)
.accounts(depositAccounts)
.instruction();
const depositTx = new Transaction().add(approveIx, depositIx);
const tx = await sendAndConfirmTransaction(connection, depositTx, [payer, depositor]);
const events = await readEventsUntilFound(connection, tx, [program]);
const event = events[0].data; // 0th event is the latest event.
// Verify the event props emitted match the expected values
const currentTime = await getCurrentTime(program, state);
const expectedValues = {
...depositData,
quoteTimestamp: currentTime,
fillDeadline: currentTime + fillDeadlineOffset,
depositId: intToU8Array32(1),
};
for (let [key, value] of Object.entries(expectedValues)) {
if (key === "exclusivityParameter") key = "exclusivityDeadline"; // the prop and the event names differ on this key.
assertSE(event[key], value, `${key} should match`);
}
});
it("Fails with invalid exclusivity params", async () => {
const currentTime = new BN(await getCurrentTime(program, state));
depositData.quoteTimestamp = currentTime;
// If exclusivityParameter is not zero, then exclusiveRelayer must be set.
depositData.exclusiveRelayer = new PublicKey("11111111111111111111111111111111");
depositData.exclusivityParameter = new BN(1);
try {
const depositDataValues = Object.values(depositData) as DepositDataValues;
await approvedDeposit(depositDataValues);
assert.fail("Should have failed due to InvalidExclusiveRelayer");
} catch (err: any) {
assert.include(err.toString(), "InvalidExclusiveRelayer");
}
// Test with other invalid exclusivityDeadline values
const invalidExclusivityDeadlines = [
maxExclusivityOffsetSeconds,
maxExclusivityOffsetSeconds.add(new BN(1)),
currentTime.sub(new BN(1)),
currentTime.add(new BN(1)),
];
for (const exclusivityDeadline of invalidExclusivityDeadlines) {
depositData.exclusivityParameter = exclusivityDeadline;
try {
const depositDataValues = Object.values(depositData) as DepositDataValues;
await approvedDeposit(depositDataValues);
assert.fail("Should have failed due to InvalidExclusiveRelayer");
} catch (err: any) {
assert.include(err.toString(), "InvalidExclusiveRelayer");
}
}
// Test with exclusivityDeadline set to 0
depositData.exclusivityParameter = new BN(0);
const depositDataValues = Object.values(depositData) as DepositDataValues;
await approvedDeposit(depositDataValues);
});
it("Exclusivity param is used as an offset", async () => {
const currentTime = new BN(await getCurrentTime(program, state));
depositData.quoteTimestamp = currentTime;
depositData.exclusiveRelayer = depositor.publicKey;
depositData.exclusivityParameter = maxExclusivityOffsetSeconds;
const depositDataValues = Object.values(depositData) as DepositDataValues;
const tx = await approvedDeposit(depositDataValues);
const events = await readEventsUntilFound(connection, tx, [program]);
const event = events[0].data; // 0th event is the latest event
assertSE(
event.exclusivityDeadline,
currentTime.add(maxExclusivityOffsetSeconds),
"exclusivityDeadline should be current time + offset"
);
});
it("Exclusivity param is used as a timestamp", async () => {
const currentTime = new BN(await getCurrentTime(program, state));
depositData.quoteTimestamp = currentTime;
const exclusivityDeadlineTimestamp = maxExclusivityOffsetSeconds.add(new BN(1)); // 1 year + 1 second
depositData.exclusiveRelayer = depositor.publicKey;
depositData.exclusivityParameter = exclusivityDeadlineTimestamp;
const depositDataValues = Object.values(depositData) as DepositDataValues;
const tx = await approvedDeposit(depositDataValues);
const events = await readEventsUntilFound(connection, tx, [program]);
const event = events[0].data; // 0th event is the latest event;
assertSE(event.exclusivityDeadline, exclusivityDeadlineTimestamp, "exclusivityDeadline should be passed in time");
});
it("Exclusivity param is set to 0", async () => {
const currentTime = new BN(await getCurrentTime(program, state));
depositData.quoteTimestamp = currentTime;
const zeroExclusivity = new BN(0);
depositData.exclusiveRelayer = depositor.publicKey;
depositData.exclusivityParameter = zeroExclusivity;
const depositDataValues = Object.values(depositData) as DepositDataValues;
const tx = await approvedDeposit(depositDataValues);
const events = await readEventsUntilFound(connection, tx, [program]);
const event = events[0].data; // 0th event is the latest event;
assertSE(event.exclusivityDeadline, zeroExclusivity, "Exclusivity deadline should always be 0");
});
it("unsafe deposit ID", async () => {
const forcedDepositId = new BN(99);
// Convert the inputs to byte arrays
const msgSenderBytes = ethers.utils.arrayify(depositAccounts.signer.toBytes());
const depositorBytes = ethers.utils.arrayify(depositData.depositor!.toBytes());
const depositNonceBytes = ethers.utils.zeroPad(forcedDepositId.toArrayLike(Buffer, "le", 8), 8);
const data = ethers.utils.concat([msgSenderBytes, depositorBytes, depositNonceBytes]); // Concatenate the byte arrays
const expectedDepositId = ethers.utils.keccak256(data); // Hash the concatenated data using keccak256
const expectedDepositIdArray = ethers.utils.arrayify(expectedDepositId);
// Call the method to get the unsafe deposit ID
const unsafeDepositIdTx = await program.methods
.getUnsafeDepositId(depositAccounts.signer, depositData.depositor!, forcedDepositId)
.view();
assert.strictEqual(
expectedDepositIdArray.toString(),
unsafeDepositIdTx.toString(),
"Deposit ID should match the expected hash"
);
// Delegate state PDA to pull depositor tokens.
const approveIx = await createApproveCheckedInstruction(
depositAccounts.depositorTokenAccount,
depositAccounts.mint,
depositAccounts.state,
depositor.publicKey,
BigInt(depositData.inputAmount.toString()),
tokenDecimals,
undefined,
tokenProgram
);
// Create the transaction for unsafeDepositV3
const unsafeDepositIx = await program.methods
.unsafeDeposit(
depositData.depositor!,
depositData.recipient!,
depositData.inputToken!,
depositData.outputToken!,
depositData.inputAmount!,
depositData.outputAmount!,
depositData.destinationChainId!,
depositData.exclusiveRelayer!,
forcedDepositId, // deposit nonce
depositData.quoteTimestamp.toNumber(),
depositData.fillDeadline.toNumber(),
depositData.exclusivityParameter.toNumber(),
depositData.message!
)
.accounts(depositAccounts) // Assuming depositAccounts is already set up correctly
.instruction();
const unsafeDepositTx = new Transaction().add(approveIx, unsafeDepositIx);
const tx = await sendAndConfirmTransaction(connection, unsafeDepositTx, [payer, depositor]);
// Wait for a short period to ensure the event is emitted
// Read and verify the event
const events = await readEventsUntilFound(connection, tx, [program]);
const event = events[0].data; // Assuming the latest event is the one we want
const expectedValues = { ...depositData, depositId: expectedDepositIdArray };
for (let [key, value] of Object.entries(expectedValues)) {
if (key === "exclusivityParameter") key = "exclusivityDeadline"; // Adjust for any key differences
assertSE(event[key], value, `${key} should match`);
}
});
it("Deposit with enabled CPI-guard", async () => {
// CPI-guard is available only for the 2022 token program.
tokenProgram = TOKEN_2022_PROGRAM_ID;
await setupInputToken();
await createVault();
// Enable CPI-guard for the depositor (requires TA reallocation).
const enableCpiGuardTx = new Transaction().add(
createReallocateInstruction(depositorTA, payer.publicKey, [ExtensionType.CpiGuard], depositor.publicKey),
createEnableCpiGuardInstruction(depositorTA, depositor.publicKey)
);
await sendAndConfirmTransaction(connection, enableCpiGuardTx, [payer, depositor]);
// Verify vault balance is zero before the deposit
let vaultAccount = await getAccount(connection, vault, undefined, tokenProgram);
assertSE(vaultAccount.amount, "0", "Vault balance should be zero before the deposit");
// Execute the deposit call
const depositDataValues = Object.values(depositData) as DepositDataValues;
await approvedDeposit(depositDataValues);
// Verify tokens leave the depositor's account
const depositorAccount = await getAccount(connection, depositorTA, undefined, tokenProgram);
assertSE(
depositorAccount.amount,
seedBalance - depositData.inputAmount.toNumber(),
"Depositor's balance should be reduced by the deposited amount"
);
// Verify tokens are credited into the vault
vaultAccount = await getAccount(connection, vault, undefined, tokenProgram);
assertSE(vaultAccount.amount, depositData.inputAmount, "Vault balance should be increased by the deposited amount");
});
it("Deposit without approval fails", async () => {
const depositDataValues = Object.values(depositData) as DepositDataValues;
try {
await program.methods
.deposit(...depositDataValues)
.accounts(depositAccounts)
.signers([depositor])
.rpc();
assert.fail("Deposit should have failed due to missing approval");
} catch (err: any) {
assert.include(err.toString(), "owner does not match");
}
});
it("Deposit native token, new token account", async () => {
// Fund depositor account with SOL.
const nativeAmount = 1_000_000_000; // 1 SOL
await connection.requestAirdrop(depositor.publicKey, nativeAmount * 2); // Add buffer for transaction fees.
// Setup wSOL as the input token.
inputToken = NATIVE_MINT;
const nativeDecimals = 9;
depositorTA = getAssociatedTokenAddressSync(inputToken, depositor.publicKey);
await createVault();
// Will need to add rent exemption to the deposit amount, will recover it at the end of the transaction.
const rentExempt = await getMinimumBalanceForRentExemptAccount(connection);
const transferIx = SystemProgram.transfer({
fromPubkey: depositor.publicKey,
toPubkey: depositorTA,
lamports: BigInt(nativeAmount) + BigInt(rentExempt),
});
// Create wSOL user account.
const createIx = createAssociatedTokenAccountIdempotentInstruction(
depositor.publicKey,
depositorTA,
depositor.publicKey,
inputToken
);
const approveIx = await createApproveCheckedInstruction(
depositAccounts.depositorTokenAccount,
depositAccounts.mint,
depositAccounts.state,
depositor.publicKey,
BigInt(nativeAmount),
nativeDecimals,
undefined,
tokenProgram
);
const nativeDepositData = { ...depositData, inputAmount: new BN(nativeAmount), outputAmount: new BN(nativeAmount) };
const depositDataValues = Object.values(nativeDepositData) as DepositDataValues;
const depositIx = await program.methods
.deposit(...depositDataValues)
.accounts(depositAccounts)
.instruction();
const closeIx = createCloseAccountInstruction(depositorTA, depositor.publicKey, depositor.publicKey);
const iVaultAmount = (await getAccount(connection, vault, undefined, tokenProgram)).amount;
const depositTx = new Transaction().add(transferIx, createIx, approveIx, depositIx, closeIx);
const tx = await sendAndConfirmTransaction(connection, depositTx, [depositor]);
const fVaultAmount = (await getAccount(connection, vault, undefined, tokenProgram)).amount;
assertSE(
fVaultAmount,
iVaultAmount + BigInt(nativeAmount),
"Vault balance should be increased by the deposited amount"
);
});
it("Deposit native token, existing token account", async () => {
// Fund depositor account with SOL.
const nativeAmount = 1_000_000_000; // 1 SOL
await connection.requestAirdrop(depositor.publicKey, nativeAmount * 2); // Add buffer for transaction fees.
// Setup wSOL as the input token, creating the associated token account for the user.
inputToken = NATIVE_MINT;
const nativeDecimals = 9;
depositorTA = (await getOrCreateAssociatedTokenAccount(connection, payer, inputToken, depositor.publicKey)).address;
await createVault();
// Transfer SOL to the user token account.
const transferIx = SystemProgram.transfer({
fromPubkey: depositor.publicKey,
toPubkey: depositorTA,
lamports: nativeAmount,
});
// Sync the user token account with the native balance.
const syncIx = createSyncNativeInstruction(depositorTA);
const approveIx = await createApproveCheckedInstruction(
depositAccounts.depositorTokenAccount,
depositAccounts.mint,
depositAccounts.state,
depositor.publicKey,
BigInt(nativeAmount),
nativeDecimals,
undefined,
tokenProgram
);
const nativeDepositData = { ...depositData, inputAmount: new BN(nativeAmount), outputAmount: new BN(nativeAmount) };
const depositDataValues = Object.values(nativeDepositData) as DepositDataValues;
const depositIx = await program.methods
.deposit(...depositDataValues)
.accounts(depositAccounts)
.instruction();
const iVaultAmount = (await getAccount(connection, vault, undefined, tokenProgram)).amount;
const depositTx = new Transaction().add(transferIx, syncIx, approveIx, depositIx);
const tx = await sendAndConfirmTransaction(connection, depositTx, [depositor]);
const fVaultAmount = (await getAccount(connection, vault, undefined, tokenProgram)).amount;
assertSE(
fVaultAmount,
iVaultAmount + BigInt(nativeAmount),
"Vault balance should be increased by the deposited amount"
);
});
it("Deposits tokens to a new vault", async () => {
// Create new input token without creating a new vault for it.
await setupInputToken();
const inputTokenAccount = await provider.connection.getAccountInfo(inputToken);
if (inputTokenAccount === null) throw new Error("Input mint account not found");
vault = getAssociatedTokenAddressSync(
inputToken,
state,
true,
inputTokenAccount.owner,
ASSOCIATED_TOKEN_PROGRAM_ID
);
// Update global variables using the new input token.
depositData.inputToken = inputToken;
depositAccounts.depositorTokenAccount = depositorTA;
depositAccounts.vault = vault;
depositAccounts.mint = inputToken;
// Verify there is no vault account before the deposit.
assert.isNull(await provider.connection.getAccountInfo(vault), "Vault should not exist before the deposit");
// Execute the deposit call
const depositDataValues = Object.values(depositData) as DepositDataValues;
await approvedDeposit(depositDataValues);
// Verify tokens leave the depositor's account
const depositorAccount = await getAccount(connection, depositorTA);
assertSE(
depositorAccount.amount,
seedBalance - depositData.inputAmount.toNumber(),
"Depositor's balance should be reduced by the deposited amount"
);
// Verify tokens are credited into the new vault
const vaultAccount = await getAccount(connection, vault);
assertSE(vaultAccount.amount, depositData.inputAmount, "Vault balance should equal the deposited amount");
});
describe("codama client and solana kit", () => {
it("Deposit with with solana kit and codama client", async () => {
// typescript is not happy with the depositData object
if (!depositData.inputToken || !depositData.depositor) {
throw new Error("Input token or depositor is null");
}
const rpcClient = createDefaultSolanaClient();
const signer = await createSignerFromKeyPair(await createKeyPairFromBytes(depositor.secretKey));
await airdropFactory(rpcClient)({
recipientAddress: signer.address,
lamports: lamports(100000000000000n),
commitment: "confirmed",
});
const [eventAuthority] = await getProgramDerivedAddress({
programAddress: address(program.programId.toString()),
seeds: ["__event_authority"],
});
// note that we are using getApproveCheckedInstruction from @solana-program/token
const approveIx = getApproveCheckedInstruction({
source: address(depositAccounts.depositorTokenAccount.toString()),
mint: address(depositAccounts.mint.toString()),
delegate: address(depositAccounts.state.toString()),
owner: address(depositor.publicKey.toString()),
amount: BigInt(depositData.inputAmount.toString()),
decimals: tokenDecimals,
});
const formattedDepositData = {
depositor: address(depositData.depositor.toString()),
recipient: address(depositData.recipient.toString()),
inputToken: address(depositData.inputToken.toString()),
outputToken: address(depositData.outputToken.toString()),
inputAmount: BigInt(depositData.inputAmount.toString()),
outputAmount: BigInt(depositData.outputAmount.toString()),
destinationChainId: depositData.destinationChainId.toNumber(),
exclusiveRelayer: address(depositData.exclusiveRelayer.toString()),
quoteTimestamp: depositData.quoteTimestamp.toNumber(),
fillDeadline: depositData.fillDeadline.toNumber(),
exclusivityParameter: depositData.exclusivityParameter.toNumber(),
message: depositData.message,
};
const formattedAccounts = {
state: address(depositAccounts.state.toString()),
depositorTokenAccount: address(depositAccounts.depositorTokenAccount.toString()),
mint: address(depositAccounts.mint.toString()),
tokenProgram: address(tokenProgram.toString()),
program: address(program.programId.toString()),
vault: address(vault.toString()),
};
const depositInput: DepositInput = {
...formattedDepositData,
...formattedAccounts,
eventAuthority,
signer,
};
const depositIx = await SvmSpokeClient.getDepositInstructionAsync(depositInput);
const tx = await pipe(
await createDefaultTransaction(rpcClient, signer),
(tx) => appendTransactionMessageInstruction(approveIx, tx),
(tx) => appendTransactionMessageInstruction(depositIx, tx),
(tx) => signAndSendTransaction(rpcClient, tx)
);
const events = await readEventsUntilFound(connection, tx, [program]);
const event = events[0].data; // 0th event is the latest event;
assertSE(event.depositId, intToU8Array32(1), "Deposit ID should match the expected hash");
});
});
});