Skip to content

Commit d54727e

Browse files
committed
update anchor basics examples
1 parent f004003 commit d54727e

File tree

38 files changed

+489
-570
lines changed

38 files changed

+489
-570
lines changed

basics/account-data/anchor/Anchor.toml

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
[features]
22
seeds = false
3+
skip-lint = false
4+
35
[programs.localnet]
4-
anchor_program_example = "FFKtnYFyzPj1qFjE9epkrfYHJwZMdh8CvJrB6XsKeFVz"
6+
anchor_program_example = "GpVcgWdgVErgLqsn8VYUch6EqDerMgNqoLSmGyKrd6MR"
57

68
[registry]
7-
url = "https://anchor.projectserum.com"
9+
url = "https://api.apr.dev"
810

911
[provider]
10-
cluster = "localnet"
12+
cluster = "Localnet"
1113
wallet = "~/.config/solana/id.json"
1214

1315
[scripts]
Lines changed: 20 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,32 @@
1+
use crate::state::AddressInfo;
12
use anchor_lang::prelude::*;
2-
use anchor_lang::system_program;
33

4-
use crate::state::AddressInfo;
4+
#[derive(Accounts)]
5+
pub struct CreateAddressInfo<'info> {
6+
#[account(mut)]
7+
payer: Signer<'info>,
8+
9+
#[account(
10+
init,
11+
payer = payer,
12+
space = 8 + AddressInfo::INIT_SPACE,
13+
)]
14+
address_info: Account<'info, AddressInfo>,
15+
system_program: Program<'info, System>,
16+
}
517

6-
#[allow(clippy::result_large_err)]
718
pub fn create_address_info(
819
ctx: Context<CreateAddressInfo>,
920
name: String,
1021
house_number: u8,
1122
street: String,
1223
city: String,
1324
) -> Result<()> {
14-
let address_info = AddressInfo::new(name, house_number, street, city);
15-
16-
let account_span = (address_info.try_to_vec()?).len();
17-
let lamports_required = (Rent::get()?).minimum_balance(account_span);
18-
19-
system_program::create_account(
20-
CpiContext::new(
21-
ctx.accounts.system_program.to_account_info(),
22-
system_program::CreateAccount {
23-
from: ctx.accounts.payer.to_account_info(),
24-
to: ctx.accounts.address_info.to_account_info(),
25-
},
26-
),
27-
lamports_required,
28-
account_span as u64,
29-
&ctx.accounts.system_program.key(),
30-
)?;
31-
32-
let address_info_account = &mut ctx.accounts.address_info;
33-
address_info_account.set_inner(address_info);
25+
*ctx.accounts.address_info = AddressInfo {
26+
name,
27+
house_number,
28+
street,
29+
city,
30+
};
3431
Ok(())
3532
}
36-
37-
#[derive(Accounts)]
38-
pub struct CreateAddressInfo<'info> {
39-
#[account(mut)]
40-
address_info: Account<'info, AddressInfo>,
41-
#[account(mut)]
42-
payer: Signer<'info>,
43-
system_program: Program<'info, System>,
44-
}
Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
pub mod create;
2-
32
pub use create::*;
Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,23 @@
11
#![allow(clippy::result_large_err)]
2-
32
use anchor_lang::prelude::*;
4-
53
use instructions::*;
64

75
pub mod instructions;
86
pub mod state;
97

10-
declare_id!("FFKtnYFyzPj1qFjE9epkrfYHJwZMdh8CvJrB6XsKeFVz");
8+
declare_id!("GpVcgWdgVErgLqsn8VYUch6EqDerMgNqoLSmGyKrd6MR");
119

1210
#[program]
1311
pub mod anchor_program_example {
1412
use super::*;
1513

16-
#[allow(clippy::result_large_err)]
1714
pub fn create_address_info(
1815
ctx: Context<CreateAddressInfo>,
1916
name: String,
2017
house_number: u8,
2118
street: String,
2219
city: String,
2320
) -> Result<()> {
24-
instructions::create::create_address_info(ctx, name, house_number, street, city)
21+
create::create_address_info(ctx, name, house_number, street, city)
2522
}
2623
}
Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,13 @@
11
use anchor_lang::prelude::*;
22

33
#[account]
4+
#[derive(InitSpace)] // automatically calculate the space required for the struct
45
pub struct AddressInfo {
5-
pub name: String,
6-
pub house_number: u8,
7-
pub street: String,
8-
pub city: String,
9-
}
10-
11-
impl AddressInfo {
12-
pub fn new(name: String, house_number: u8, street: String, city: String) -> Self {
13-
AddressInfo {
14-
name,
15-
house_number,
16-
street,
17-
city,
18-
}
19-
}
6+
#[max_len(50)] // set a max length for the string
7+
pub name: String, // 4 bytes + 50 bytes
8+
pub house_number: u8, // 1 byte
9+
#[max_len(50)]
10+
pub street: String, // 4 bytes + 50 bytes
11+
#[max_len(50)]
12+
pub city: String, // 4 bytes + 50 bytes
2013
}
Lines changed: 37 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,52 @@
1-
import * as anchor from "@coral-xyz/anchor";
2-
import { AnchorProgramExample } from "../target/types/anchor_program_example";
1+
import * as anchor from "@coral-xyz/anchor"
2+
import { AnchorProgramExample } from "../target/types/anchor_program_example"
3+
import { Keypair, SystemProgram } from "@solana/web3.js"
34

45
describe("Account Data!", () => {
5-
const provider = anchor.AnchorProvider.env();
6-
anchor.setProvider(provider);
7-
const payer = provider.wallet as anchor.Wallet;
6+
const provider = anchor.AnchorProvider.env()
7+
anchor.setProvider(provider)
8+
const payer = provider.wallet as anchor.Wallet
89
const program = anchor.workspace
9-
.AnchorProgramExample as anchor.Program<AnchorProgramExample>;
10+
.AnchorProgramExample as anchor.Program<AnchorProgramExample>
1011

11-
const addressInfoAccount = anchor.web3.Keypair.generate();
12+
// Generate a new keypair for the addressInfo account
13+
const addressInfoAccount = new Keypair()
1214

1315
it("Create the address info account", async () => {
14-
console.log(`Payer Address : ${payer.publicKey}`);
15-
console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`);
16+
console.log(`Payer Address : ${payer.publicKey}`)
17+
console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`)
18+
19+
// Instruction data
20+
const addressInfo = {
21+
name: "Joe C",
22+
houseNumber: 136,
23+
street: "Mile High Dr.",
24+
city: "Solana Beach",
25+
}
26+
1627
await program.methods
17-
.createAddressInfo("Joe C", 136, "Mile High Dr.", "Solana Beach")
28+
.createAddressInfo(
29+
addressInfo.name,
30+
addressInfo.houseNumber,
31+
addressInfo.street,
32+
addressInfo.city
33+
)
1834
.accounts({
1935
addressInfo: addressInfoAccount.publicKey,
2036
payer: payer.publicKey,
21-
systemProgram: anchor.web3.SystemProgram.programId,
37+
systemProgram: SystemProgram.programId,
2238
})
23-
.signers([payer.payer])
24-
.rpc();
25-
});
39+
.signers([addressInfoAccount])
40+
.rpc()
41+
})
2642

2743
it("Read the new account's data", async () => {
2844
const addressInfo = await program.account.addressInfo.fetch(
2945
addressInfoAccount.publicKey
30-
);
31-
console.log(`Name : ${addressInfo.name}`);
32-
console.log(`House Num: ${addressInfo.houseNumber}`);
33-
console.log(`Street : ${addressInfo.street}`);
34-
console.log(`City : ${addressInfo.city}`);
35-
});
36-
});
46+
)
47+
console.log(`Name : ${addressInfo.name}`)
48+
console.log(`House Num: ${addressInfo.houseNumber}`)
49+
console.log(`Street : ${addressInfo.street}`)
50+
console.log(`City : ${addressInfo.city}`)
51+
})
52+
})

basics/close-account/anchor/Anchor.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
[features]
22
seeds = false
33
skip-lint = false
4+
45
[programs.localnet]
5-
close_account_program = "9SWqhEABWnKXTPvSLc4aQAJyESVxtRvYBvwF2WuBy7jf"
6+
close_account_program = "99TQtoDdQ5NS2v5Ppha93aqEmv3vV9VZVfHTP5rGST3c"
67

78
[registry]
89
url = "https://api.apr.dev"
910

1011
[provider]
11-
cluster = "localnet"
12+
cluster = "Localnet"
1213
wallet = "~/.config/solana/id.json"
1314

1415
[scripts]
Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,23 @@
1-
use anchor_lang::prelude::*;
2-
use anchor_lang::AccountsClose;
3-
41
use crate::state::*;
2+
use anchor_lang::prelude::*;
53

64
#[derive(Accounts)]
75
pub struct CloseUserContext<'info> {
6+
#[account(mut)]
7+
pub user: Signer<'info>,
8+
89
#[account(
910
mut,
1011
seeds = [
11-
User::PREFIX.as_bytes(),
12+
b"USER",
1213
user.key().as_ref(),
1314
],
14-
has_one = user,
15-
bump = user_account.bump
15+
bump = user_account.bump,
16+
close = user, // close account and return lamports to user
1617
)]
17-
pub user_account: Account<'info, User>,
18-
#[account(mut)]
19-
pub user: Signer<'info>,
20-
pub system_program: Program<'info, System>,
21-
pub rent: Sysvar<'info, Rent>,
18+
pub user_account: Account<'info, UserState>,
2219
}
2320

24-
pub fn close_user(ctx: Context<CloseUserContext>) -> Result<()> {
25-
let user = &mut ctx.accounts.user;
26-
let user_account = &mut ctx.accounts.user_account;
27-
user_account.close(user.to_account_info())?;
21+
pub fn close_user(_ctx: Context<CloseUserContext>) -> Result<()> {
2822
Ok(())
2923
}
Lines changed: 13 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,31 @@
1-
use anchor_lang::prelude::*;
2-
31
use crate::state::*;
4-
5-
#[derive(AnchorSerialize, AnchorDeserialize)]
6-
pub struct CreateUserArgs {
7-
pub name: String,
8-
}
2+
use anchor_lang::prelude::*;
93

104
#[derive(Accounts)]
11-
#[instruction(args: CreateUserArgs)]
125
pub struct CreateUserContext<'info> {
6+
#[account(mut)]
7+
pub user: Signer<'info>,
8+
139
#[account(
1410
init,
15-
space = User::SIZE,
16-
payer = payer,
11+
payer = user,
12+
space = UserState::INIT_SPACE,
1713
seeds = [
18-
User::PREFIX.as_bytes(),
19-
payer.key().as_ref(),
14+
b"USER",
15+
user.key().as_ref(),
2016
],
2117
bump
2218
)]
23-
pub user_account: Account<'info, User>,
24-
#[account(mut)]
25-
pub payer: Signer<'info>,
19+
pub user_account: Account<'info, UserState>,
2620
pub system_program: Program<'info, System>,
27-
pub rent: Sysvar<'info, Rent>,
2821
}
2922

30-
pub fn create_user(ctx: Context<CreateUserContext>, args: CreateUserArgs) -> Result<()> {
31-
let payer = &ctx.accounts.payer;
23+
pub fn create_user(ctx: Context<CreateUserContext>, name: String) -> Result<()> {
3224
let user_account = &mut ctx.accounts.user_account;
3325

34-
msg!("{:#?}", ctx.bumps);
35-
36-
user_account.bump = *ctx.bumps.get("user_account").expect("Bump not found.");
37-
user_account.user = payer.key();
38-
user_account.name = args.name;
26+
user_account.bump = *ctx.bumps.get("user_account").unwrap();
27+
user_account.user = ctx.accounts.user.key();
28+
user_account.name = name;
3929

4030
Ok(())
4131
}

basics/close-account/anchor/programs/close-account/src/lib.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
11
#![allow(clippy::result_large_err)]
22

33
use anchor_lang::prelude::*;
4-
54
mod instructions;
65
mod state;
76
use instructions::*;
87

9-
declare_id!("9SWqhEABWnKXTPvSLc4aQAJyESVxtRvYBvwF2WuBy7jf");
8+
declare_id!("99TQtoDdQ5NS2v5Ppha93aqEmv3vV9VZVfHTP5rGST3c");
109

1110
#[program]
1211
pub mod close_account_program {
1312
use super::*;
1413

15-
pub fn create_user(ctx: Context<CreateUserContext>, args: CreateUserArgs) -> Result<()> {
16-
create_user::create_user(ctx, args)
14+
pub fn create_user(ctx: Context<CreateUserContext>, name: String) -> Result<()> {
15+
create_user::create_user(ctx, name)
1716
}
1817

1918
pub fn close_user(ctx: Context<CloseUserContext>) -> Result<()> {

0 commit comments

Comments
 (0)