|
@@ -12,6 +12,8 @@ so there the `C` layout applies.
|
|
|
|
|
|
In addition to the space for the account data, you have to add `8` to the `space` constraint for Anchor's internal discriminator (see the example).
|
|
|
|
|
|
+## Type chart
|
|
|
+
|
|
|
| Types | Space in bytes | Details/Example |
|
|
|
| ---------- | ----------------------------- | ----------------------------------------------------------------------------------------------- |
|
|
|
| bool | 1 | would only require 1 bit but still uses 1 byte |
|
|
@@ -29,7 +31,7 @@ In addition to the space for the account data, you have to add `8` to the `space
|
|
|
| f32 | 4 | serialization will fail for NaN |
|
|
|
| f64 | 8 | serialization will fail for NaN |
|
|
|
|
|
|
-# Example
|
|
|
+## Example
|
|
|
|
|
|
```rust
|
|
|
#[account]
|
|
@@ -59,3 +61,33 @@ pub struct InitializeMyData<'info> {
|
|
|
pub system_program: Program<'info, System>
|
|
|
}
|
|
|
```
|
|
|
+
|
|
|
+## The InitSpace macro
|
|
|
+
|
|
|
+Sometimes it can be difficult to calculate the initial space of an account. This macro will add an `INIT_SPACE` constant to the structure. It is not necessary for the structure to contain the `#[account]` macro to generate the constant. Here's an example:
|
|
|
+
|
|
|
+```rust
|
|
|
+#[account]
|
|
|
+#[derive(InitSpace)]
|
|
|
+pub struct ExampleAccount {
|
|
|
+ pub data: u64,
|
|
|
+ #[max_len(50)]
|
|
|
+ pub string_one: String,
|
|
|
+ #[max_len(10, 5)]
|
|
|
+ pub nested: Vec<Vec<u8>>,
|
|
|
+}
|
|
|
+
|
|
|
+#[derive(Accounts)]
|
|
|
+pub struct Initialize<'info> {
|
|
|
+ #[account(mut)]
|
|
|
+ pub payer: Signer<'info>,
|
|
|
+ pub system_program: Program<'info, System>,
|
|
|
+ #[account(init, payer = payer, space = 8 + ExampleAccount::INIT_SPACE)]
|
|
|
+ pub data: Account<'info, ExampleAccount>,
|
|
|
+}
|
|
|
+```
|
|
|
+
|
|
|
+A few important things to know:
|
|
|
+
|
|
|
+- Don't forget the discriminator when defining `space`
|
|
|
+- The `max_len` length represents the length of the structure, not the total length. (ie: the `max_len` of a Vec<u32> will be `max_len` \* 4)
|