test.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import * as anchor from "@project-serum/anchor";
  2. import { TransferSol } from "../target/types/transfer_sol";
  3. describe("transfer-sol", () => {
  4. const provider = anchor.AnchorProvider.env();
  5. anchor.setProvider(provider);
  6. const payer = provider.wallet as anchor.Wallet;
  7. const program = anchor.workspace.TransferSol as anchor.Program<TransferSol>;
  8. const transferAmount = 1 * anchor.web3.LAMPORTS_PER_SOL;
  9. const test1Recipient = anchor.web3.Keypair.generate();
  10. const test2Recipient1 = anchor.web3.Keypair.generate();
  11. const test2Recipient2 = anchor.web3.Keypair.generate();
  12. it("Transfer between accounts using the system program", async () => {
  13. await getBalances(payer.publicKey, test1Recipient.publicKey, "Beginning");
  14. await program.methods.transferSolWithCpi(new anchor.BN(transferAmount))
  15. .accounts({
  16. payer: payer.publicKey,
  17. recipient: test1Recipient.publicKey,
  18. systemProgram: anchor.web3.SystemProgram.programId,
  19. })
  20. .signers([payer.payer])
  21. .rpc();
  22. await getBalances(payer.publicKey, test1Recipient.publicKey, "Resulting");
  23. });
  24. it("Create two accounts for the following test", async () => {
  25. const ix = (pubkey: anchor.web3.PublicKey) => {
  26. return anchor.web3.SystemProgram.createAccount({
  27. fromPubkey: payer.publicKey,
  28. newAccountPubkey: pubkey,
  29. space: 0,
  30. lamports: 2 * anchor.web3.LAMPORTS_PER_SOL,
  31. programId: program.programId,
  32. })
  33. };
  34. await anchor.web3.sendAndConfirmTransaction(
  35. provider.connection,
  36. new anchor.web3.Transaction()
  37. .add(ix(test2Recipient1.publicKey))
  38. .add(ix(test2Recipient2.publicKey))
  39. ,
  40. [payer.payer, test2Recipient1, test2Recipient2]
  41. );
  42. });
  43. it("Transfer between accounts using our program", async () => {
  44. await getBalances(test2Recipient1.publicKey, test2Recipient2.publicKey, "Beginning");
  45. await program.methods.transferSolWithProgram(new anchor.BN(transferAmount))
  46. .accounts({
  47. payer: test2Recipient1.publicKey,
  48. recipient: test2Recipient2.publicKey,
  49. systemProgram: anchor.web3.SystemProgram.programId,
  50. })
  51. .rpc();
  52. await getBalances(test2Recipient1.publicKey, test2Recipient2.publicKey, "Resulting");
  53. });
  54. async function getBalances(
  55. payerPubkey: anchor.web3.PublicKey,
  56. recipientPubkey: anchor.web3.PublicKey,
  57. timeframe: string
  58. ) {
  59. let payerBalance = await provider.connection.getBalance(payerPubkey);
  60. let recipientBalance = await provider.connection.getBalance(recipientPubkey);
  61. console.log(`${timeframe} balances:`);
  62. console.log(` Payer: ${payerBalance}`);
  63. console.log(` Recipient: ${recipientBalance}`);
  64. };
  65. });