lib.rs 1.7 KB

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