Skip to content

Commit bbe6a8d

Browse files
authored
Merge pull request #51 from ZYJLiu/main
update anchor basics examples
2 parents bbe74ee + 1f38abb commit bbe6a8d

File tree

56 files changed

+801
-625
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+801
-625
lines changed

.github/workflows/anchor.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ jobs:
3030
"basics/pda-rent-payer/anchor"
3131
"basics/processing-instructions/anchor"
3232
"basics/program-derived-addresses/anchor"
33+
"basics/realloc/anchor"
3334
"basics/rent/anchor"
3435
"basics/repository-layout/anchor"
3536
"basics/transfer-sol/anchor"

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: 36 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,51 @@
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 } 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,
2237
})
23-
.signers([payer.payer])
24-
.rpc();
25-
});
38+
.signers([addressInfoAccount])
39+
.rpc()
40+
})
2641

2742
it("Read the new account's data", async () => {
2843
const addressInfo = await program.account.addressInfo.fetch(
2944
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-
});
45+
)
46+
console.log(`Name : ${addressInfo.name}`)
47+
console.log(`House Num: ${addressInfo.houseNumber}`)
48+
console.log(`Street : ${addressInfo.street}`)
49+
console.log(`City : ${addressInfo.city}`)
50+
})
51+
})

basics/checking-accounts/anchor/programs/anchor-program-example/src/lib.rs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,25 @@ declare_id!("ECWPhR3rJbaPfyNFgphnjxSEexbTArc7vxD8fnW6tgKw");
88
pub mod anchor_program_example {
99
use super::*;
1010

11-
#[allow(clippy::result_large_err)]
1211
pub fn check_accounts(_ctx: Context<CheckingAccounts>) -> Result<()> {
1312
Ok(())
1413
}
1514
}
1615

16+
// Account validation in Anchor is done using the types and constraints specified in the #[derive(Accounts)] structs
17+
// This is a simple example and does not include all possible constraints and types
1718
#[derive(Accounts)]
1819
pub struct CheckingAccounts<'info> {
19-
payer: Signer<'info>,
20-
#[account(mut)]
21-
/// CHECK: This account's data is empty
22-
account_to_create: AccountInfo<'info>,
20+
payer: Signer<'info>, // checks account is signer
21+
22+
/// CHECK: No checks performed, example of an unchecked account
2323
#[account(mut)]
24-
/// CHECK: This account's data is empty
25-
account_to_change: AccountInfo<'info>,
26-
system_program: Program<'info, System>,
24+
account_to_create: UncheckedAccount<'info>,
25+
/// CHECK: Perform owner check using constraint
26+
#[account(
27+
mut,
28+
owner = id()
29+
)]
30+
account_to_change: UncheckedAccount<'info>,
31+
system_program: Program<'info, System>, // checks account is executable, and is the system program
2732
}
Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,50 @@
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 {
4+
Keypair,
5+
SystemProgram,
6+
Transaction,
7+
sendAndConfirmTransaction,
8+
} from "@solana/web3.js"
39

410
describe("Anchor example", () => {
5-
const provider = anchor.AnchorProvider.env();
6-
anchor.setProvider(provider);
11+
const provider = anchor.AnchorProvider.env()
12+
anchor.setProvider(provider)
713
const program = anchor.workspace
8-
.AnchorProgramExample as anchor.Program<AnchorProgramExample>;
9-
const payer = provider.wallet as anchor.Wallet;
14+
.AnchorProgramExample as anchor.Program<AnchorProgramExample>
15+
const wallet = provider.wallet as anchor.Wallet
1016

1117
// We'll create this ahead of time.
1218
// Our program will try to modify it.
13-
const accountToChange = anchor.web3.Keypair.generate();
19+
const accountToChange = new Keypair()
1420
// Our program will create this.
15-
const accountToCreate = anchor.web3.Keypair.generate();
21+
const accountToCreate = new Keypair()
1622

1723
it("Create an account owned by our program", async () => {
18-
let ix = anchor.web3.SystemProgram.createAccount({
24+
let instruction = SystemProgram.createAccount({
1925
fromPubkey: provider.wallet.publicKey,
2026
newAccountPubkey: accountToChange.publicKey,
2127
lamports: await provider.connection.getMinimumBalanceForRentExemption(0),
2228
space: 0,
2329
programId: program.programId, // Our program
24-
});
30+
})
2531

26-
await anchor.web3.sendAndConfirmTransaction(
27-
provider.connection,
28-
new anchor.web3.Transaction().add(ix),
29-
[payer.payer, accountToChange]
30-
);
31-
});
32+
const transaction = new Transaction().add(instruction)
33+
34+
await sendAndConfirmTransaction(provider.connection, transaction, [
35+
wallet.payer,
36+
accountToChange,
37+
])
38+
})
3239

3340
it("Check accounts", async () => {
3441
await program.methods
3542
.checkAccounts()
3643
.accounts({
37-
payer: provider.wallet.publicKey,
44+
payer: wallet.publicKey,
3845
accountToCreate: accountToCreate.publicKey,
3946
accountToChange: accountToChange.publicKey,
40-
systemProgram: anchor.web3.SystemProgram.programId,
4147
})
42-
.signers([payer.payer])
43-
.rpc();
44-
});
45-
});
48+
.rpc()
49+
})
50+
})

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]

0 commit comments

Comments
 (0)