Skip to content

Commit

Permalink
update anchor basics examples
Browse files Browse the repository at this point in the history
  • Loading branch information
ZYJLiu committed Sep 12, 2023
1 parent f004003 commit d54727e
Show file tree
Hide file tree
Showing 38 changed files with 489 additions and 570 deletions.
8 changes: 5 additions & 3 deletions basics/account-data/anchor/Anchor.toml
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
[features]
seeds = false
skip-lint = false

[programs.localnet]
anchor_program_example = "FFKtnYFyzPj1qFjE9epkrfYHJwZMdh8CvJrB6XsKeFVz"
anchor_program_example = "GpVcgWdgVErgLqsn8VYUch6EqDerMgNqoLSmGyKrd6MR"

[registry]
url = "https://anchor.projectserum.com"
url = "https://api.apr.dev"

[provider]
cluster = "localnet"
cluster = "Localnet"
wallet = "~/.config/solana/id.json"

[scripts]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,44 +1,32 @@
use crate::state::AddressInfo;
use anchor_lang::prelude::*;
use anchor_lang::system_program;

use crate::state::AddressInfo;
#[derive(Accounts)]
pub struct CreateAddressInfo<'info> {
#[account(mut)]
payer: Signer<'info>,

#[account(
init,
payer = payer,
space = 8 + AddressInfo::INIT_SPACE,
)]
address_info: Account<'info, AddressInfo>,
system_program: Program<'info, System>,
}

#[allow(clippy::result_large_err)]
pub fn create_address_info(
ctx: Context<CreateAddressInfo>,
name: String,
house_number: u8,
street: String,
city: String,
) -> Result<()> {
let address_info = AddressInfo::new(name, house_number, street, city);

let account_span = (address_info.try_to_vec()?).len();
let lamports_required = (Rent::get()?).minimum_balance(account_span);

system_program::create_account(
CpiContext::new(
ctx.accounts.system_program.to_account_info(),
system_program::CreateAccount {
from: ctx.accounts.payer.to_account_info(),
to: ctx.accounts.address_info.to_account_info(),
},
),
lamports_required,
account_span as u64,
&ctx.accounts.system_program.key(),
)?;

let address_info_account = &mut ctx.accounts.address_info;
address_info_account.set_inner(address_info);
*ctx.accounts.address_info = AddressInfo {
name,
house_number,
street,
city,
};
Ok(())
}

#[derive(Accounts)]
pub struct CreateAddressInfo<'info> {
#[account(mut)]
address_info: Account<'info, AddressInfo>,
#[account(mut)]
payer: Signer<'info>,
system_program: Program<'info, System>,
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
pub mod create;

pub use create::*;
Original file line number Diff line number Diff line change
@@ -1,26 +1,23 @@
#![allow(clippy::result_large_err)]

use anchor_lang::prelude::*;

use instructions::*;

pub mod instructions;
pub mod state;

declare_id!("FFKtnYFyzPj1qFjE9epkrfYHJwZMdh8CvJrB6XsKeFVz");
declare_id!("GpVcgWdgVErgLqsn8VYUch6EqDerMgNqoLSmGyKrd6MR");

#[program]
pub mod anchor_program_example {
use super::*;

#[allow(clippy::result_large_err)]
pub fn create_address_info(
ctx: Context<CreateAddressInfo>,
name: String,
house_number: u8,
street: String,
city: String,
) -> Result<()> {
instructions::create::create_address_info(ctx, name, house_number, street, city)
create::create_address_info(ctx, name, house_number, street, city)
}
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
use anchor_lang::prelude::*;

#[account]
#[derive(InitSpace)] // automatically calculate the space required for the struct
pub struct AddressInfo {
pub name: String,
pub house_number: u8,
pub street: String,
pub city: String,
}

impl AddressInfo {
pub fn new(name: String, house_number: u8, street: String, city: String) -> Self {
AddressInfo {
name,
house_number,
street,
city,
}
}
#[max_len(50)] // set a max length for the string
pub name: String, // 4 bytes + 50 bytes
pub house_number: u8, // 1 byte
#[max_len(50)]
pub street: String, // 4 bytes + 50 bytes
#[max_len(50)]
pub city: String, // 4 bytes + 50 bytes
}
58 changes: 37 additions & 21 deletions basics/account-data/anchor/tests/test.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,52 @@
import * as anchor from "@coral-xyz/anchor";
import { AnchorProgramExample } from "../target/types/anchor_program_example";
import * as anchor from "@coral-xyz/anchor"
import { AnchorProgramExample } from "../target/types/anchor_program_example"
import { Keypair, SystemProgram } from "@solana/web3.js"

describe("Account Data!", () => {
const provider = anchor.AnchorProvider.env();
anchor.setProvider(provider);
const payer = provider.wallet as anchor.Wallet;
const provider = anchor.AnchorProvider.env()
anchor.setProvider(provider)
const payer = provider.wallet as anchor.Wallet
const program = anchor.workspace
.AnchorProgramExample as anchor.Program<AnchorProgramExample>;
.AnchorProgramExample as anchor.Program<AnchorProgramExample>

const addressInfoAccount = anchor.web3.Keypair.generate();
// Generate a new keypair for the addressInfo account
const addressInfoAccount = new Keypair()

it("Create the address info account", async () => {
console.log(`Payer Address : ${payer.publicKey}`);
console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`);
console.log(`Payer Address : ${payer.publicKey}`)
console.log(`Address Info Acct : ${addressInfoAccount.publicKey}`)

// Instruction data
const addressInfo = {
name: "Joe C",
houseNumber: 136,
street: "Mile High Dr.",
city: "Solana Beach",
}

await program.methods
.createAddressInfo("Joe C", 136, "Mile High Dr.", "Solana Beach")
.createAddressInfo(
addressInfo.name,
addressInfo.houseNumber,
addressInfo.street,
addressInfo.city
)
.accounts({
addressInfo: addressInfoAccount.publicKey,
payer: payer.publicKey,
systemProgram: anchor.web3.SystemProgram.programId,
systemProgram: SystemProgram.programId,
})
.signers([payer.payer])
.rpc();
});
.signers([addressInfoAccount])
.rpc()
})

it("Read the new account's data", async () => {
const addressInfo = await program.account.addressInfo.fetch(
addressInfoAccount.publicKey
);
console.log(`Name : ${addressInfo.name}`);
console.log(`House Num: ${addressInfo.houseNumber}`);
console.log(`Street : ${addressInfo.street}`);
console.log(`City : ${addressInfo.city}`);
});
});
)
console.log(`Name : ${addressInfo.name}`)
console.log(`House Num: ${addressInfo.houseNumber}`)
console.log(`Street : ${addressInfo.street}`)
console.log(`City : ${addressInfo.city}`)
})
})
5 changes: 3 additions & 2 deletions basics/close-account/anchor/Anchor.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
[features]
seeds = false
skip-lint = false

[programs.localnet]
close_account_program = "9SWqhEABWnKXTPvSLc4aQAJyESVxtRvYBvwF2WuBy7jf"
close_account_program = "99TQtoDdQ5NS2v5Ppha93aqEmv3vV9VZVfHTP5rGST3c"

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

[provider]
cluster = "localnet"
cluster = "Localnet"
wallet = "~/.config/solana/id.json"

[scripts]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,29 +1,23 @@
use anchor_lang::prelude::*;
use anchor_lang::AccountsClose;

use crate::state::*;
use anchor_lang::prelude::*;

#[derive(Accounts)]
pub struct CloseUserContext<'info> {
#[account(mut)]
pub user: Signer<'info>,

#[account(
mut,
seeds = [
User::PREFIX.as_bytes(),
b"USER",
user.key().as_ref(),
],
has_one = user,
bump = user_account.bump
bump = user_account.bump,
close = user, // close account and return lamports to user
)]
pub user_account: Account<'info, User>,
#[account(mut)]
pub user: Signer<'info>,
pub system_program: Program<'info, System>,
pub rent: Sysvar<'info, Rent>,
pub user_account: Account<'info, UserState>,
}

pub fn close_user(ctx: Context<CloseUserContext>) -> Result<()> {
let user = &mut ctx.accounts.user;
let user_account = &mut ctx.accounts.user_account;
user_account.close(user.to_account_info())?;
pub fn close_user(_ctx: Context<CloseUserContext>) -> Result<()> {
Ok(())
}
Original file line number Diff line number Diff line change
@@ -1,41 +1,31 @@
use anchor_lang::prelude::*;

use crate::state::*;

#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct CreateUserArgs {
pub name: String,
}
use anchor_lang::prelude::*;

#[derive(Accounts)]
#[instruction(args: CreateUserArgs)]
pub struct CreateUserContext<'info> {
#[account(mut)]
pub user: Signer<'info>,

#[account(
init,
space = User::SIZE,
payer = payer,
payer = user,
space = UserState::INIT_SPACE,
seeds = [
User::PREFIX.as_bytes(),
payer.key().as_ref(),
b"USER",
user.key().as_ref(),
],
bump
)]
pub user_account: Account<'info, User>,
#[account(mut)]
pub payer: Signer<'info>,
pub user_account: Account<'info, UserState>,
pub system_program: Program<'info, System>,
pub rent: Sysvar<'info, Rent>,
}

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

msg!("{:#?}", ctx.bumps);

user_account.bump = *ctx.bumps.get("user_account").expect("Bump not found.");
user_account.user = payer.key();
user_account.name = args.name;
user_account.bump = *ctx.bumps.get("user_account").unwrap();
user_account.user = ctx.accounts.user.key();
user_account.name = name;

Ok(())
}
7 changes: 3 additions & 4 deletions basics/close-account/anchor/programs/close-account/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
#![allow(clippy::result_large_err)]

use anchor_lang::prelude::*;

mod instructions;
mod state;
use instructions::*;

declare_id!("9SWqhEABWnKXTPvSLc4aQAJyESVxtRvYBvwF2WuBy7jf");
declare_id!("99TQtoDdQ5NS2v5Ppha93aqEmv3vV9VZVfHTP5rGST3c");

#[program]
pub mod close_account_program {
use super::*;

pub fn create_user(ctx: Context<CreateUserContext>, args: CreateUserArgs) -> Result<()> {
create_user::create_user(ctx, args)
pub fn create_user(ctx: Context<CreateUserContext>, name: String) -> Result<()> {
create_user::create_user(ctx, name)
}

pub fn close_user(ctx: Context<CloseUserContext>) -> Result<()> {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
pub mod user;

pub use user::*;
pub mod user_state;
pub use user_state::*;

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use anchor_lang::prelude::*;

#[account]
#[derive(InitSpace)] // automatically calculate the space required for the struct
pub struct UserState {
pub bump: u8, // 1 byte
pub user: Pubkey, // 32 bytes
#[max_len(50)] // set a max length for the string
pub name: String, // 4 bytes + 50 bytes
}
Loading

0 comments on commit d54727e

Please sign in to comment.