transferSol.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import * as anchor from '@coral-xyz/anchor';
  2. import { Program } from '@coral-xyz/anchor';
  3. import { Keypair, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js';
  4. import { TransferSol } from '../target/types/transfer_sol';
  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(user.publicKey, 5 * LAMPORTS_PER_SOL);
  19. await provider.connection.confirmTransaction({
  20. blockhash: latestBlockHash.blockhash,
  21. lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
  22. signature: airdropUser,
  23. });
  24. });
  25. it('Transfer SOL with CPI', async () => {
  26. await getBalances(user.publicKey, receiver.publicKey, '\n Beginning');
  27. // Transfer SOL instruction invoked from the program
  28. await program.methods
  29. .transferSolWithCpi(new anchor.BN(transferAmount))
  30. .accountsPartial({
  31. payer: user.publicKey,
  32. recipient: receiver.publicKey,
  33. })
  34. .signers([user])
  35. .rpc();
  36. await getBalances(user.publicKey, receiver.publicKey, '\n Resulting');
  37. });
  38. // Helper function to display balance of the accounts
  39. async function getBalances(payerPubkey: PublicKey, recipientPubkey: PublicKey, timeframe: string) {
  40. const payerBalance = await provider.connection.getBalance(payerPubkey);
  41. const recipientBalance = await provider.connection.getBalance(recipientPubkey);
  42. console.log(`${timeframe} balances:`);
  43. console.log(` Payer: ${payerBalance / LAMPORTS_PER_SOL}`);
  44. console.log(` Recipient: ${recipientBalance / LAMPORTS_PER_SOL}`);
  45. }
  46. });