3

Looking through examples like Soldev, one sees PDAs sizes calculated using code like:

pub fn get_account_size(title: String, description: String) -> usize {
    return (4 + MovieAccountState::DISCRIMINATOR.len())
        + 1
        + 1
        + (4 + title.len())
        + (4 + description.len());
}

Where do these magic numbers come from? I have seen these values in the anchor account space docs

Type: String

Space in bytes: 4 + length of string in bytes

Details: Account size is fixed so account should be initialized with sufficient space from the beginning

but where are these standards defined? Are they from Solana, borsh, Anchor or something else? Where is the definitive reference for the size of different types?

2 Answers 2

7

Note that anchor now has InitSpace to calculate sizes, meaning you don't need to manually calculate the sizes.

These sizes depend on how you do serialization. Anchor uses Borsh for serialisation/deserialisation, and you can see the Borsh spec for these values.

Once you know how things are serialized its about knowing the type sizes. Most are known and platform independent, others may not be. For rust, you can find sizes in the rust docs or the function to find the size for platform specific types.

1

@tiago's answer is good (and you should use InitSpace), I just wanted to paste the constants.rs I use in case you have an app that uses magic numbers and wanted to work out what the magic numbers may mean (and hopefully remove the magic numbers and just use InitSpace).

pub const ANCHOR_DISCRIMINATOR_SIZE: usize = 8;
pub const U8_SIZE: usize = 1;
pub const U64_SIZE: usize = 8;
pub const PUBKEY_SIZE: usize = 32;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.