use anchor_lang::prelude::*;
use crate::constants::*;
use crate::events::{UserAuthorityChanged, UserDeleted, UserNew};
use crate::state::User;
#[derive(Accounts)]
#[instruction(random_hash: [u8;32])]
pub struct CreateUser<'info> {
#[account(
init,
seeds = [
USER_PREFIX_SEED.as_bytes(),
random_hash.as_ref(),
],
bump,
payer = authority,
space = User::LEN
)]
pub user: Account<'info, User>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
pub fn create_user_handler(ctx: Context<CreateUser>, random_hash: [u8; 32]) -> Result<()> {
let user = &mut ctx.accounts.user;
user.random_hash = random_hash;
user.authority = *ctx.accounts.authority.key;
emit!(UserNew {
user: *user.to_account_info().key,
random_hash: random_hash,
authority: *ctx.accounts.authority.key,
timestamp: Clock::get()?.unix_timestamp,
});
Ok(())
}
#[derive(Accounts)]
pub struct UpdateUser<'info> {
#[account(
mut,
seeds = [
USER_PREFIX_SEED.as_bytes(),
user.random_hash.as_ref(),
],
bump,
has_one = authority,
)]
pub user: Account<'info, User>,
pub new_authority: SystemAccount<'info>,
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
pub fn update_user_handler(ctx: Context<UpdateUser>) -> Result<()> {
let user = &mut ctx.accounts.user;
user.authority = *ctx.accounts.new_authority.key;
emit!(UserAuthorityChanged {
user: *user.to_account_info().key,
old_authority: *ctx.accounts.authority.key,
new_authority: *ctx.accounts.new_authority.key,
timestamp: Clock::get()?.unix_timestamp,
});
Ok(())
}
#[derive(Accounts)]
pub struct DeleteUser<'info> {
#[account(
mut,
seeds = [
USER_PREFIX_SEED.as_bytes(),
user.random_hash.as_ref(),
],
bump,
has_one = authority,
close = authority
)]
pub user: Account<'info, User>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
pub fn delete_user_handler(ctx: Context<DeleteUser>) -> Result<()> {
emit!(UserDeleted {
user: *ctx.accounts.user.to_account_info().key,
authority: *ctx.accounts.authority.key,
timestamp: Clock::get()?.unix_timestamp,
});
Ok(())
}