0

What's the solidity equivalent to implement a mapping(address => bool) in anchor for solana? I figured out the way to go is PDA, but I was only able to figure out how to generate a PDA using find_program_address and create a PDA account using system_instruction::create_account. I wanna know how to store and to retrieve value using the generated PDA with a variable like is_early_sale,

#[account]
pub struct IsEarlySale
{
    pub is_early_sale: bool
}


#[derive(Accounts)] 
#[instruction(user: Pubkey)]
pub struct EarlySaleContext<'info> 
{
    #[account(
        init,
        payer = caller,
        seeds = [user.key().as_ref()], 
        bump,
        space = size_of::<IsEarlySale>() + 16
    )]
    pub set_pda_account: Account<'info, IsEarlySale>, 

    #[account(mut)]
    pub caller: Signer<'info>,
    pub system_program: Program<'info,System>,

    #[account(mut)]
    /// CHECK: This account is used to receive SOL.
    pub program_account: AccountInfo<'info>
}

2 Answers 2

1

As mentioned by this SE answer, you may want to use a PDA for your operation.

Given the size limitations of Solana accounts (10kibibytes) per account, it might make more sense to associate each user address with the data, in your case is_early_sale as you've done.

The EarlySaleContext ix initializes the IsEarlySale account. If you want to make use of it, you might need to create a new #[derive(Accounts)] to check/use the account to separate the account initialization logic from it's usage.

#[derive(Accounts)]
pub struct CheckSaleContext<'info> {
    #[account(mut)]
    pub caller: Signer<'info>,

    #[account(mut)]
    pub pda_account: Account<'info, IsEarlySale>,

    #[account(mut)]
    /// CHECK: This account is used to receive SOL.
    pub program_account: AccountInfo<'info>,

    pub system_program: Program<'info, System>,
}

The EarlySaleContext will err out if you try to re-initialize an already existing account and CheckSaleContext will err out if you try to read from an uninitialized account.

If you don't want to use the accounts struct and would just want to read data from the PDA account to check if it contains is_early_sale or is initialized,

let data = ctx.accounts.asset.data.try_borrow_mut().unwrap();
let data = IsEarlySale::deserialize(&mut data.as_ref());

if let Ok(pda_data) = data { /*pda is initialized*/ } else { /*pda not initialized */ }
0

Since Anchor is just based on Rust, you can simply use Hashmap.

use std::collections::HashMap;

let mut my_map = HashMap::new();
 my_map.insert("first", 1);
my_map.insert("second", 2);

for (key, value) in &my_map{
        println!("{}: {}", key, value);
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.