test.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import * as anchor from "@coral-xyz/anchor"
  2. import { TransferSol } from "../target/types/transfer_sol"
  3. import {
  4. Keypair,
  5. PublicKey,
  6. LAMPORTS_PER_SOL,
  7. SystemProgram,
  8. Transaction,
  9. sendAndConfirmTransaction,
  10. } from "@solana/web3.js"
  11. describe("transfer-sol", () => {
  12. const provider = anchor.AnchorProvider.env()
  13. anchor.setProvider(provider)
  14. const payer = provider.wallet as anchor.Wallet
  15. const program = anchor.workspace.TransferSol as anchor.Program<TransferSol>
  16. // 1 SOL
  17. const transferAmount = 1 * LAMPORTS_PER_SOL
  18. // Generate a new keypair for the recipient
  19. const recipient = new Keypair()
  20. // Generate a new keypair to create an account owned by our program
  21. const programOwnedAccount = new Keypair()
  22. it("Transfer SOL with CPI", async () => {
  23. await getBalances(payer.publicKey, recipient.publicKey, "Beginning")
  24. await program.methods
  25. .transferSolWithCpi(new anchor.BN(transferAmount))
  26. .accounts({
  27. payer: payer.publicKey,
  28. recipient: recipient.publicKey,
  29. })
  30. .rpc()
  31. await getBalances(payer.publicKey, recipient.publicKey, "Resulting")
  32. })
  33. it("Create and fund account owned by our program", async () => {
  34. const instruction = SystemProgram.createAccount({
  35. fromPubkey: payer.publicKey,
  36. newAccountPubkey: programOwnedAccount.publicKey,
  37. space: 0,
  38. lamports: 1 * LAMPORTS_PER_SOL, // 1 SOL
  39. programId: program.programId, // Program Owner, our program's address
  40. })
  41. const transaction = new Transaction().add(instruction)
  42. await sendAndConfirmTransaction(provider.connection, transaction, [
  43. payer.payer,
  44. programOwnedAccount,
  45. ])
  46. })
  47. it("Transfer SOL with Program", async () => {
  48. await getBalances(
  49. programOwnedAccount.publicKey,
  50. payer.publicKey,
  51. "Beginning"
  52. )
  53. await program.methods
  54. .transferSolWithProgram(new anchor.BN(transferAmount))
  55. .accounts({
  56. payer: programOwnedAccount.publicKey,
  57. recipient: payer.publicKey,
  58. })
  59. .rpc()
  60. await getBalances(
  61. programOwnedAccount.publicKey,
  62. payer.publicKey,
  63. "Resulting"
  64. )
  65. })
  66. async function getBalances(
  67. payerPubkey: PublicKey,
  68. recipientPubkey: PublicKey,
  69. timeframe: string
  70. ) {
  71. let payerBalance = await provider.connection.getBalance(payerPubkey)
  72. let recipientBalance = await provider.connection.getBalance(recipientPubkey)
  73. console.log(`${timeframe} balances:`)
  74. console.log(` Payer: ${payerBalance / LAMPORTS_PER_SOL}`)
  75. console.log(` Recipient: ${recipientBalance / LAMPORTS_PER_SOL}`)
  76. }
  77. })