Search code examples
javascriptsolana

Solana token ownership


is there any way to check that user A owns spl token B inside solana contract? Maybe there is safe method to check it outside.

I need it to give some privileges to users, which own mine nfts. Users would write data to program only when they have nft.


Solution

  • To check the owner of an SPL token account from within a program, you'll have to deserialize it and check the owner field, ie:

    use solana_program::{
        account_info::next_account_info, account_info::AccountInfo, entrypoint,
        entrypoint::ProgramResult, pubkey::Pubkey, program_pack::Pack,
    };
    use spl_token::state::Account;
    
    entrypoint!(process_instruction);
    
    const EXPECTED_OWNER: Pubkey = Pubkey::new_from_array([1; 32]);
    
    fn process_instruction(
        program_id: &Pubkey,
        accounts: &[AccountInfo], 
        instruction_data: &[u8],
    ) -> ProgramResult {
        let account_info_iter = &mut accounts.iter();
    
        let spl_token_account_info = next_account_info(account_info_iter)?;
        let spl_token_account_data = spl_token_account_info.try_borrow_data()?;
        let spl_token_account = Account::unpack(&spl_token_account_data)?;
        if spl_token_account.owner == EXPECTED_OWNER {
            // your logic here
        }
    }
    

    Note that I haven't tried to compile this, so use with caution!