lib.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. use anchor_lang::prelude::*;
  2. declare_id!("Fod47xKXjdHVQDzkFPBvfdWLm8gEAV4iMSXkfUzCHiSD");
  3. #[program]
  4. pub mod anchor_realloc {
  5. use super::*;
  6. pub fn initialize(ctx: Context<Initialize>, input: String) -> Result<()> {
  7. ctx.accounts.message_account.message = input;
  8. Ok(())
  9. }
  10. pub fn update(ctx: Context<Update>, input: String) -> Result<()> {
  11. ctx.accounts.message_account.message = input;
  12. Ok(())
  13. }
  14. }
  15. #[derive(Accounts)]
  16. #[instruction(input: String)]
  17. pub struct Initialize<'info> {
  18. #[account(mut)]
  19. pub payer: Signer<'info>,
  20. #[account(
  21. init,
  22. payer = payer,
  23. space = Message::required_space(input.len()),
  24. )]
  25. pub message_account: Account<'info, Message>,
  26. pub system_program: Program<'info, System>,
  27. }
  28. #[derive(Accounts)]
  29. #[instruction(input: String)]
  30. pub struct Update<'info> {
  31. #[account(mut)]
  32. pub payer: Signer<'info>,
  33. #[account(
  34. mut,
  35. realloc = Message::required_space(input.len()),
  36. realloc::payer = payer,
  37. realloc::zero = true,
  38. )]
  39. pub message_account: Account<'info, Message>,
  40. pub system_program: Program<'info, System>,
  41. }
  42. #[account]
  43. pub struct Message {
  44. pub message: String,
  45. }
  46. impl Message {
  47. pub fn required_space(input_len: usize) -> usize {
  48. 8 + // 8 byte discriminator
  49. 4 + // 4 byte for length of string
  50. input_len
  51. }
  52. }