use anchor_lang::prelude::*;
use crate::state::*;
use crate::constants::*;
use crate::utils::realloc_slot;
pub fn send_regular_message(ctx: Context<SendRegularMessage>, message: String, to: Pubkey) -> Result<()> {
let slot = &mut ctx.accounts.slot;
slot.to = to;
slot.message = message;
let inbox = &mut ctx.accounts.inbox;
inbox.latest_free_slot += 1;
msg!("Message {:?} sent to: {:?}. New free slot: {:?}", slot.message, slot.to, inbox.latest_free_slot);
Ok(())
}
pub fn send_whitelisted_message(ctx: Context<SendWhitelistedMessage>, message: String, to: Pubkey) -> Result<()> {
let inbox = &mut ctx.accounts.inbox;
realloc_slot(
&ctx.accounts.slot.to_account_info(),
&message,
inbox,
&ctx.accounts.sender.to_account_info(),
&ctx.accounts.system_program.to_account_info(),
)?;
let slot = &mut ctx.accounts.slot;
slot.to = to;
slot.message = message;
inbox.latest_whitelisted_slot += 1;
msg!("Whitelisted message {:?} sent to: {:?}. New whitelisted slot: {:?}", slot.message, slot.to, inbox.latest_whitelisted_slot);
Ok(())
}
pub fn reclaim_slot(ctx: Context<ReclaimSlot>) -> Result<()> {
msg!("Slot reclaimed: {:?}", ctx.accounts.slot.key());
Ok(())
}
#[derive(Accounts)]
#[instruction(message: String)]
pub struct SendRegularMessage<'info> {
#[account(mut)]
pub inbox: Account<'info, Inbox>,
#[account(
init,
seeds=[&inbox.latest_free_slot.to_le_bytes()],
bump,
payer = sender,
space = SLOT_BASE_SPACE + message.len()
)]
pub slot: Account<'info, Slot>,
#[account(mut)]
pub sender: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct SendWhitelistedMessage<'info> {
#[account(mut)]
pub inbox: Account<'info, Inbox>,
#[account(
mut,
seeds=[&inbox.latest_whitelisted_slot.to_le_bytes()],
bump,
constraint = inbox.latest_whitelisted_slot < inbox.latest_free_slot,
)]
pub slot: Account<'info, Slot>,
#[account(seeds=[sender.key().as_ref()], bump)]
pub whitelist: Account<'info, Whitelist>,
#[account(mut)]
pub sender: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct ReclaimSlot<'info> {
#[account(mut, has_one = admin)]
pub inbox: Account<'info, Inbox>,
#[account(mut, close = admin)]
pub slot: Account<'info, Slot>,
#[account(mut)]
pub admin: Signer<'info>,
}