lib.rs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. use anchor_lang::prelude::*;
  2. use anchor_lang::system_program;
  3. declare_id!("ED6f4gweAE7hWPQPXMt4kWxzDJne8VQEm9zkb1tMpFNB");
  4. #[program]
  5. pub mod rent_example {
  6. use super::*;
  7. pub fn create_system_account(ctx: Context<CreateSystemAccount>, address_data: AddressData) -> Result<()> {
  8. msg!("Program invoked. Creating a system account...");
  9. msg!(" New public key will be: {}", &ctx.accounts.new_account.key().to_string());
  10. // Determine the necessary minimum rent by calculating the account's size
  11. //
  12. let account_span = (address_data.try_to_vec()?).len();
  13. let lamports_required = (Rent::get()?).minimum_balance(account_span);
  14. msg!("Account span: {}", &account_span);
  15. msg!("Lamports required: {}", &lamports_required);
  16. system_program::create_account(
  17. CpiContext::new(
  18. ctx.accounts.system_program.to_account_info(),
  19. system_program::CreateAccount {
  20. from: ctx.accounts.payer.to_account_info(),
  21. to: ctx.accounts.new_account.to_account_info(),
  22. },
  23. ),
  24. lamports_required,
  25. account_span as u64,
  26. &ctx.accounts.system_program.key(),
  27. )?;
  28. msg!("Account created succesfully.");
  29. Ok(())
  30. }
  31. }
  32. #[derive(Accounts)]
  33. pub struct CreateSystemAccount<'info> {
  34. #[account(mut)]
  35. pub payer: Signer<'info>,
  36. #[account(mut)]
  37. pub new_account: Signer<'info>,
  38. pub system_program: Program<'info, System>,
  39. }
  40. #[derive(AnchorSerialize, AnchorDeserialize, Debug)]
  41. pub struct AddressData {
  42. name: String,
  43. address: String,
  44. }