lib.rs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. use anchor_lang::prelude::*;
  2. declare_id!("Lamports11111111111111111111111111111111111");
  3. #[program]
  4. pub mod lamports {
  5. use super::*;
  6. pub fn test_lamports_trait(ctx: Context<TestLamportsTrait>, amount: u64) -> Result<()> {
  7. let pda = &ctx.accounts.pda;
  8. let signer = &ctx.accounts.signer;
  9. // Transfer **to** PDA
  10. {
  11. // Get the balance of the PDA **before** the transfer to PDA
  12. let pda_balance_before = pda.get_lamports();
  13. // Transfer to the PDA
  14. anchor_lang::system_program::transfer(
  15. CpiContext::new(
  16. ctx.accounts.system_program.to_account_info(),
  17. anchor_lang::system_program::Transfer {
  18. from: signer.to_account_info(),
  19. to: pda.to_account_info(),
  20. },
  21. ),
  22. amount,
  23. )?;
  24. // Get the balance of the PDA **after** the transfer to PDA
  25. let pda_balance_after = pda.get_lamports();
  26. // Validate balance
  27. require_eq!(pda_balance_after, pda_balance_before + amount);
  28. }
  29. // Transfer **from** PDA
  30. {
  31. // Get the balance of the PDA **before** the transfer from PDA
  32. let pda_balance_before = pda.get_lamports();
  33. // Transfer from the PDA
  34. pda.sub_lamports(amount)?;
  35. signer.add_lamports(amount)?;
  36. // Get the balance of the PDA **after** the transfer from PDA
  37. let pda_balance_after = pda.get_lamports();
  38. // Validate balance
  39. require_eq!(pda_balance_after, pda_balance_before - amount);
  40. }
  41. Ok(())
  42. }
  43. }
  44. #[derive(Accounts)]
  45. pub struct TestLamportsTrait<'info> {
  46. #[account(mut)]
  47. pub signer: Signer<'info>,
  48. #[account(
  49. init,
  50. payer = signer,
  51. space = 8,
  52. seeds = [b"lamports"],
  53. bump
  54. )]
  55. pub pda: Account<'info, LamportsPda>,
  56. pub system_program: Program<'info, System>,
  57. }
  58. #[account]
  59. pub struct LamportsPda {}