test.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. const transferAmount = 1 * LAMPORTS_PER_SOL
  17. // Generate a new keypair for the recipient
  18. const recipient = new Keypair()
  19. // Generate a new keypair to create an account owned by our program
  20. const programOwnedAccount = new Keypair()
  21. it("Transfer SOL with CPI", async () => {
  22. await getBalances(payer.publicKey, recipient.publicKey, "Beginning")
  23. await program.methods
  24. .transferSolWithCpi(new anchor.BN(transferAmount))
  25. .accounts({
  26. payer: payer.publicKey,
  27. recipient: recipient.publicKey,
  28. })
  29. .rpc()
  30. await getBalances(payer.publicKey, recipient.publicKey, "Resulting")
  31. })
  32. it("Create and fund account owned by our program", async () => {
  33. const instruction = SystemProgram.createAccount({
  34. fromPubkey: payer.publicKey,
  35. newAccountPubkey: programOwnedAccount.publicKey,
  36. space: 0,
  37. lamports: 1 * LAMPORTS_PER_SOL, // 1 SOL
  38. programId: program.programId, // Program Owner, our program's address
  39. })
  40. const transaction = new Transaction().add(instruction)
  41. await sendAndConfirmTransaction(provider.connection, transaction, [
  42. payer.payer,
  43. programOwnedAccount,
  44. ])
  45. })
  46. it("Transfer SOL with Program", async () => {
  47. await getBalances(
  48. programOwnedAccount.publicKey,
  49. payer.publicKey,
  50. "Beginning"
  51. )
  52. await program.methods
  53. .transferSolWithProgram(new anchor.BN(transferAmount))
  54. .accounts({
  55. payer: programOwnedAccount.publicKey,
  56. recipient: payer.publicKey,
  57. })
  58. .rpc()
  59. await getBalances(
  60. programOwnedAccount.publicKey,
  61. payer.publicKey,
  62. "Resulting"
  63. )
  64. })
  65. async function getBalances(
  66. payerPubkey: PublicKey,
  67. recipientPubkey: PublicKey,
  68. timeframe: string
  69. ) {
  70. let payerBalance = await provider.connection.getBalance(payerPubkey)
  71. let recipientBalance = await provider.connection.getBalance(recipientPubkey)
  72. console.log(`${timeframe} balances:`)
  73. console.log(` Payer: ${payerBalance / LAMPORTS_PER_SOL}`)
  74. console.log(` Recipient: ${recipientBalance / LAMPORTS_PER_SOL}`)
  75. }
  76. })