Skip to content

Commit 354afb7

Browse files
committed
feat: add PDA size derivation in anchor
use InitSpace macro to derive PDA account size
1 parent 4af1e6c commit 354afb7

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

skill/references/programs-anchor.md

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,9 @@ pub account: Account<'info, CustomAccount>,
9494
pub account: Account<'info, CustomAccount>,
9595
```
9696

97-
## Account Discriminators
97+
## PDA Management
98+
99+
### Account Discriminators
98100

99101
Default discriminators use `sha256("account:<StructName>")[0..8]`. Custom discriminators (Anchor 0.31+):
100102

@@ -108,6 +110,35 @@ pub struct Escrow { ... }
108110
- Using `[1]` prevents using `[1, 2, ...]` which also start with `1`
109111
- `[0]` conflicts with uninitialized accounts
110112

113+
### Account Size
114+
115+
Should use `#[derive(InitSpace)]` to derive PDA data size instead of calculating it manually.
116+
It usually is combined with the macro `#[max_len(...)]` if you want to use variable-length data types
117+
(e.g. Vec, HashMap, String, etc.) in the PDA struct.
118+
It will generate a const member `INIT_SPACE` for the PDA struct.
119+
The total space required for the account will be `INIT_SPACE` plus the account discriminator size, which is 8 bytes.
120+
121+
```rust
122+
#[account]
123+
#[derive(InitSpace)]
124+
pub struct AgreementState {
125+
pub authority: Pubkey,
126+
#[max_len(MAX_TITLE_LEN)]
127+
pub title: String,
128+
#[max_len(MAX_PARTIES)]
129+
pub parties: Vec<Pubkey>,
130+
pub bump: u8,
131+
}
132+
133+
// must add the discriminator size to the account space
134+
#[account(
135+
init,
136+
payer = payer,
137+
space = 8 + AgreementState::INIT_SPACE
138+
)]
139+
pub account: Account<'info, AgreementState>,
140+
```
141+
111142
## Instruction Patterns
112143

113144
### Basic Structure

0 commit comments

Comments
 (0)