lib.rs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. use anchor_lang::prelude::*;
  2. declare_id!("Lamports11111111111111111111111111111111111");
  3. #[program]
  4. pub mod lamports {
  5. use super::*;
  6. pub fn transfer(ctx: Context<Transfer>, 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. // Return overflow error in the case of overflow (instead of panicking)
  44. pub fn overflow(ctx: Context<Overflow>) -> Result<()> {
  45. let pda = &ctx.accounts.pda;
  46. match pda.add_lamports(u64::MAX) {
  47. Err(e) => assert_eq!(e, ProgramError::ArithmeticOverflow.into()),
  48. _ => unreachable!(),
  49. }
  50. match pda.sub_lamports(u64::MAX) {
  51. Err(e) => assert_eq!(e, ProgramError::ArithmeticOverflow.into()),
  52. _ => unreachable!(),
  53. }
  54. Ok(())
  55. }
  56. }
  57. #[derive(Accounts)]
  58. pub struct Transfer<'info> {
  59. #[account(mut)]
  60. pub signer: Signer<'info>,
  61. #[account(
  62. init,
  63. payer = signer,
  64. space = 8,
  65. seeds = [b"lamports"],
  66. bump
  67. )]
  68. pub pda: Account<'info, LamportsPda>,
  69. pub system_program: Program<'info, System>,
  70. }
  71. #[derive(Accounts)]
  72. pub struct Overflow<'info> {
  73. #[account(seeds = [b"lamports"], bump)]
  74. pub pda: Account<'info, LamportsPda>,
  75. }
  76. #[account]
  77. pub struct LamportsPda {}