transferSol.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import * as anchor from "@coral-xyz/anchor";
  2. import { Program } from "@coral-xyz/anchor";
  3. import { TransferSol } from "../target/types/transfer_sol";
  4. import { Keypair, LAMPORTS_PER_SOL, PublicKey } from "@solana/web3.js";
  5. describe("transfer-sol", () => {
  6. // Configure the client to use the local cluster.
  7. const provider = anchor.AnchorProvider.env();
  8. anchor.setProvider(provider);
  9. const program = anchor.workspace.TransferSol as Program<TransferSol>;
  10. // Generate new user keypairs for testing
  11. const user = Keypair.generate();
  12. const receiver = Keypair.generate();
  13. // Set the transfer amount to 1 SOL
  14. const transferAmount = 1 * LAMPORTS_PER_SOL;
  15. before(async () => {
  16. const latestBlockHash = await provider.connection.getLatestBlockhash();
  17. // Airdrop 5 SOL to the user that will send SOL to the other user
  18. const airdropUser = await provider.connection.requestAirdrop(
  19. user.publicKey,
  20. 5 * LAMPORTS_PER_SOL
  21. );
  22. await provider.connection.confirmTransaction({
  23. blockhash: latestBlockHash.blockhash,
  24. lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
  25. signature: airdropUser,
  26. });
  27. });
  28. it("Transfer SOL with CPI", async () => {
  29. await getBalances(user.publicKey, receiver.publicKey, "\n Beginning");
  30. // Transfer SOL instruction invoked from the program
  31. await program.methods
  32. .transferSolWithCpi(new anchor.BN(transferAmount))
  33. .accountsPartial({
  34. payer: user.publicKey,
  35. recipient: receiver.publicKey,
  36. })
  37. .signers([user])
  38. .rpc();
  39. await getBalances(user.publicKey, receiver.publicKey, "\n Resulting");
  40. });
  41. // Helper function to display balance of the accounts
  42. async function getBalances(
  43. payerPubkey: PublicKey,
  44. recipientPubkey: PublicKey,
  45. timeframe: string
  46. ) {
  47. const payerBalance = await provider.connection.getBalance(payerPubkey);
  48. const recipientBalance = await provider.connection.getBalance(
  49. recipientPubkey
  50. );
  51. console.log(`${timeframe} balances:`);
  52. console.log(` Payer: ${payerBalance / LAMPORTS_PER_SOL}`);
  53. console.log(` Recipient: ${recipientBalance / LAMPORTS_PER_SOL}`);
  54. }
  55. });