Attribute Macro anchor_attribute_account::account

source ·
Expand description

An attribute for a data structure representing a Solana account.

#[account] generates trait implementations for the following traits:

When implementing account serialization traits the first 8 bytes are reserved for a unique account discriminator, self described by the first 8 bytes of the SHA256 of the account’s Rust ident.

As a result, any calls to AccountDeserialize’s try_deserialize will check this discriminator. If it doesn’t match, an invalid account was given, and the account deserialization will exit with an error.

Zero Copy Deserialization

WARNING: Zero copy deserialization is an experimental feature. It’s recommended to use it only when necessary, i.e., when you have extremely large accounts that cannot be Borsh deserialized without hitting stack or heap limits.


To enable zero-copy-deserialization, one can pass in the zero_copy argument to the macro as follows:


This can be used to conveniently implement ZeroCopy so that the account can be used with AccountLoader.

Other than being more efficient, the most salient benefit this provides is the ability to define account types larger than the max stack or heap size. When using borsh, the account has to be copied and deserialized into a new data structure and thus is constrained by stack and heap limits imposed by the BPF VM. With zero copy deserialization, all bytes from the account’s backing RefCell<&mut [u8]> are simply re-interpreted as a reference to the data structure. No allocations or copies necessary. Hence the ability to get around stack and heap limitations.

To facilitate this, all fields in an account must be constrained to be “plain old data”, i.e., they must implement Pod. Please review the safety section before using.

Using zero_copy requires adding the following to your cargo.toml file: bytemuck = { version = "1.4.0", features = ["derive", "min_const_generics"]}