当前位置:网站首页>155 Solana storage array

155 Solana storage array

2022-06-21 06:39:00 Lich Howger

Today, let's try storing arrays

Save the data as an array to account In the account

Let's define a struct

#[repr(C)]
#[derive(Clone, BorshSerialize, BorshDeserialize, Debug)]
pub struct GameConfig {
    pub array: [u8; 5],
}

In this case, we have saved a size of 5 Of u8 Array

Then we write a create Array instructions

pub fn process_create_array(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
) -> ProgramResult {
    let account_info_iter = &mut accounts.iter();
    let signer_info = next_account_info(account_info_iter)?;
    let rent_info = next_account_info(account_info_iter)?;
    let system_info = next_account_info(account_info_iter)?;
    let game_config_info = next_account_info(account_info_iter)?;

    assert_signer(&signer_info)?;

    msg!("Create Game Config");
    let bump_seed = assert_derivation(
        program_id,
        game_config_info,
        &[
            SEED_GAME_CONFIG.as_bytes(),
            program_id.as_ref(),
        ],
    )?;
    let game_config_seeds = &[
        SEED_GAME_CONFIG.as_bytes(),
        program_id.as_ref(),
        &[bump_seed],
    ];
    create_or_allocate_account_raw(
        *program_id,
        game_config_info,
        rent_info,
        system_info,
        signer_info,
        MAX_GAME_CONFIG_LENGTH,
        game_config_seeds,
    )?;

    let array = [1, 2, 3, 4, 5];
    let mut game_config = GameConfig::from_account_info(game_config_info)?;
    game_config.array = array;
    game_config.serialize(&mut *game_config_info.try_borrow_mut_data()?)?;

    Ok(())
}

Here we created an account

Then the initialization array is saved 1,2,3,4,5

Then let's write a update Instructions

pub fn process_update_array(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
) -> ProgramResult {
    let account_info_iter = &mut accounts.iter();
    let game_config_info = next_account_info(account_info_iter)?;

    let mut game_config = GameConfig::from_account_info(game_config_info)?;
    let mut array = game_config.array.clone();

    for i in 0..array.len() {
        array[i] += 1;
    }

    game_config.array = array;
    game_config.serialize(&mut *game_config_info.try_borrow_mut_data()?)?;

    Ok(())
}

When called , Just add the numbers in the array 1

Then we call on the front end

const test08 = async () => {
    const connection = new Connection(
        clusterApiUrl('devnet'),
        'confirmed',
    );

    const derivePath = `m/44'/501'/1'/0'`;
    const text = key_words;
    const seed = bip39.mnemonicToSeedSync(text).toString('hex');
    const derivedSeed = ed25519.derivePath(derivePath, seed).key;
    const wallet = web3.Keypair.fromSeed(derivedSeed);
    console.log(wallet.publicKey.toBase58());

    const programId = new PublicKey('51ueUQ1y9ZBkMsGy56Zspw9ECBZH6xLY3Z33UGdWG6c9');
    const token_program_info = new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
    const system_info = new PublicKey("11111111111111111111111111111111");
    const [game_config_info] = await PublicKey.findProgramAddress(
        [
            Buffer.from("game_config"),
            programId.toBuffer(),
        ],
        programId
    );
    console.log("game_config:::", game_config_info.toBase58());

    const keys = [
        {
            pubkey: wallet.publicKey,
            isSigner: true,
            isWritable: true,
        },
        {
            pubkey: SYSVAR_RENT_PUBKEY,
            isSigner: false,
            isWritable: false,
        },
        {
            pubkey: SystemProgram.programId,
            isSigner: false,
            isWritable: false,
        },
        {
            pubkey: game_config_info,
            isSigner: false,
            isWritable: true,
        },
    ];

    const data = Buffer.from([11]);
    const initIX = new TransactionInstruction({
        keys: keys,
        programId: programId,
        data,
    })
    const initTX = new Transaction()
    initTX.add(initIX)
    const signature = await sendAndConfirmTransaction(
        connection,
        initTX,
        [wallet],
    )
    console.log("signature::::", signature)
}

This side is create

then update once

const test09 = async () => {
    const connection = new Connection(
        clusterApiUrl('devnet'),
        'confirmed',
    );

    const derivePath = `m/44'/501'/1'/0'`;
    const text = key_words;
    const seed = bip39.mnemonicToSeedSync(text).toString('hex');
    const derivedSeed = ed25519.derivePath(derivePath, seed).key;
    const wallet = web3.Keypair.fromSeed(derivedSeed);
    console.log(wallet.publicKey.toBase58());

    const programId = new PublicKey('51ueUQ1y9ZBkMsGy56Zspw9ECBZH6xLY3Z33UGdWG6c9');
    const token_program_info = new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
    const system_info = new PublicKey("11111111111111111111111111111111");
    const [game_config_info] = await PublicKey.findProgramAddress(
        [
            Buffer.from("game_config"),
            programId.toBuffer(),
        ],
        programId
    );
    console.log("game_config:::", game_config_info.toBase58());

    const keys = [
        {
            pubkey: game_config_info,
            isSigner: false,
            isWritable: true,
        },
    ];

    const data = Buffer.from([12]);
    const initIX = new TransactionInstruction({
        keys: keys,
        programId: programId,
        data,
    })
    const initTX = new Transaction()
    initTX.add(initIX)
    const signature = await sendAndConfirmTransaction(
        connection,
        initTX,
        [wallet],
    )
    console.log("signature::::", signature)
}

Then we'll get it again account The array data inside

const test10 = async () => {
    const connection = new Connection(
        clusterApiUrl('devnet'),
        'confirmed',
    );
    let publicKey = new PublicKey("25hZjqSZAwdeUBitm3SsC1hM2LnZVNU2FAN7E63yiLkr");
    const accountInfo = await connection.getAccountInfo(publicKey);
    console.log(accountInfo.data)
    for (let i = 0; i < accountInfo.data.length; i++) {
        console.log(accountInfo.data[i])
    }
}

Let's write a two-dimensional array

原网站

版权声明
本文为[Lich Howger]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210626160504.html