Account Model
In Solana, especially when using Anchor, an account model refers to the way data is stored on-chain. Unlike traditional databases, Solana doesn’t use tables—it uses accounts, and each account stores structured binary data
🔹 What is an Account in Solana?
A Solana account is a piece of memory on-chain that:
-
Has a public key
-
Holds data (if it’s not executable)
-
May be owned by a program (smart contract)
-
Can be mutable or immutable
-
May be rent-exempt or rent-paying
🔹 Account Model in Anchor
With Anchor, you define account structures using the #[account]
macro. These are your on-chain models.
Example:
```#[account]
pub struct VoteAccount {
pub voter: Pubkey,
pub choice: u8,
pub timestamp: i64,
}```
🔹 #[derive(Accounts)]
→ Instruction Context
This is used to define the context (i.e., required accounts) for a program instruction.
```#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(init, payer = user, space = 8 + 8)]
pub my_account: Account<'info, MyAccount>,
#[account(mut)]
pub user: Signer<'info>,
pub system_program: Program<'info, System>,
} ```
💡 What it does:
-
Tells Anchor which accounts are needed to run the instruction.
-
Validates the accounts automatically (e.g., signer, ownership, mutability).
-
Helps Anchor generate the client IDL and JavaScript/TypeScript code.
🔹 #[account]
→ On-chain Data Structure
This is used to define a custom struct that will be stored in an account.
```#[account]
pub struct MyAccount {
pub counter: u64,
}```
💡 What it does:
-
Marks the struct as an on-chain account.
-
Adds an 8-byte discriminator automatically.
-
Makes it serializable via Borsh for storage and retrieval.
Example:
```// On-chain model
#[account]
pub struct Counter {
pub value: u64,
}
// Instruction context
#[derive(Accounts)]
pub struct Increment<'info> {
#[account(mut)]
pub counter: Account<'info, Counter>,
pub user: Signer<'info>,
}```
Comments
Post a Comment