|
1 | | -# Destroy an Account |
| 1 | +# Close Account |
2 | 2 |
|
3 | | -1. A `PDA` is created using the [create_user.rs](programs/destroy-an-account/src/instructions/create_user.rs) instruction. |
| 3 | +Two instruction handlers: `create_user` initializes a PDA `UserState` account, and `close_user` closes it and returns the rent to the user. |
| 4 | + |
| 5 | +1. `create_user` initializes the PDA with Anchor's `init` constraint: |
4 | 6 |
|
5 | 7 | ```rust |
6 | 8 | #[account( |
7 | 9 | init, |
8 | | - seeds = [User::PREFIX.as_bytes(), user.key().as_ref()], |
9 | 10 | payer = user, |
10 | | - space = User::SIZE, |
| 11 | + space = UserState::DISCRIMINATOR.len() + UserState::INIT_SPACE, |
| 12 | + seeds = [b"USER", user.key().as_ref()], |
11 | 13 | bump, |
12 | 14 | )] |
13 | | - pub user_account: Box<Account<'info, User>>, |
| 15 | + pub user_account: Account<'info, UserState>, |
14 | 16 | ``` |
15 | 17 |
|
16 | | -2. The account is closed in [destroy_user.rs](programs/destroy-an-account/src/instructions/destroy_user.rs), using Anchor's `close` helper on the account info: |
| 18 | + See [`programs/close-account/src/instructions/create_user.rs`](programs/close-account/src/instructions/create_user.rs). |
| 19 | + |
| 20 | +2. `close_user` closes the account using Anchor's `close` constraint, which returns lamports to the given account: |
17 | 21 |
|
18 | 22 | ```rust |
19 | | - user_account.close(user.to_account_info())?; |
| 23 | + #[account( |
| 24 | + mut, |
| 25 | + seeds = [b"USER", user.key().as_ref()], |
| 26 | + bump = user_account.bump, |
| 27 | + close = user, // close account and return lamports to user |
| 28 | + )] |
| 29 | + pub user_account: Account<'info, UserState>, |
20 | 30 | ``` |
21 | 31 |
|
22 | | -3. The test [destroy-an-account.ts](tests/destroy-an-account.ts) verifies that the account is null both before creation and after closing, via `fetchNullable`: |
| 32 | + See [`programs/close-account/src/instructions/close_user.rs`](programs/close-account/src/instructions/close_user.rs). |
23 | 33 |
|
24 | | - ```typescript |
25 | | - const userAccountBefore = await program.account.user.fetchNullable(userAccountAddress, "processed"); |
26 | | - assert.equal(userAccountBefore, null); |
27 | | - // ... |
28 | | - const userAccountAfter = await program.account.user.fetchNullable(userAccountAddress, "processed"); |
29 | | - assert.notEqual(userAccountAfter, null); |
30 | | - ``` |
| 34 | +## Tests |
| 35 | + |
| 36 | +Tests live in [`programs/close-account/tests/test_close_account.rs`](programs/close-account/tests/test_close_account.rs) and run against litesvm. `Anchor.toml`'s `scripts.test` is `cargo test`, so `anchor test` builds the program and runs the Rust tests: |
| 37 | + |
| 38 | +```bash |
| 39 | +anchor test |
| 40 | +``` |
0 commit comments