Search code examples
rustblockchainsolanaanchor-solana

Nested Accounts in Solana Anchor (Maybe a custom data types in account)


I would like to achieve a linked list type data structure in my anchor program. However I can't bring myself to understand how I can use nested account. Following is the code I am using:

#[derive(Accounts)]
pub struct Create<'info> {
    #[account(init, payer = user, space = 8 + 32 + 8 + 8 + 32 )]
    pub endpoint: Account<'info, Endpoint>,
    #[account(mut)]
    pub user: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct Update<'info> {
    pub authority: Signer<'info>,
    #[account(mut, has_one = authority)]
    pub endpoint: Account<'info, Endpoint>,
}

#[account]
pub struct Endpoint {
    pub authority: Pubkey,
    pub data: u64,
    pub len: u64,
    pub next: Endpoint
}

impl Endpoint {
    pub fn push(&mut self, data:u64){
        if self.len  == 0 {
            self.data = data;
        } else {
            // Recursion to push data into the next node
        }
        self.len += 1;
    }
}

What I want to achieve is that an account named Endpoint has a parameter named 'next' which stores another Endpoint account.


Solution

  • No, you can't do that.

    You can't query an account in the on-chain. You can only read an account only if you put the account inside your instruction. In Anchor, the account you can interact with is the Account inside the Context.

    Another way, you can allocate a data account that stores an array of struct. So you can read all those structs inside the array. Don't forget that the data account size can't be adjusted, so make sure you allocate it as much as you need.