SolMeet
Search…
Introduction to Anchor
Author: @ironaddicteddog
[Updated at 2022.3.31]
You can find the full code base here

What is Anchor?

There is a comprehensive explanation on the official website. Let me just quote relative paragraphs here:
Anchor is a framework for Solana's Sealevel runtime providing several convenient developer tools.
If you're familiar with developing in Ethereum's Solidity, Truffle, web3.js, then the experience will be familiar. Although the DSL syntax and semantics are targeted at Solana, the high level flow of writing RPC request handlers, emitting an IDL, and generating clients from IDL is the same.
In short, Anchor gives you the following handy tools for developing Solana programs:
  • Rust crates and eDSL for writing Solana programs
  • IDL specification
  • TypeScript package for generating clients from IDL
  • CLI and workspace management for developing complete applications
You can watch this awesome talk given by Armani Ferrante at Breakpoint 2021 to feel the power of Anchor.

Workflow

  1. 1.
    Develop the program (Smart Contract)
  2. 2.
    Build the program and export the IDL
  3. 3.
    Generate the client representation of program from the IDL to interact with the program

Why Anchor?

  • Productivity
    • Make Solana program more intuitive to understand
    • More clear buisness Logic
    • Remove a ton of biolderplate code
  • Security
    • Customized Account Validation
      • Singer
      • Mut
      • ...
    • Discriminator
      • Discriminator is generated and inserted into the first 8 bytes of account data. Ex: sha256("account:<MyAccountName>")[..8] || borsh(account_struct)
      • Used for more secure account validation and function dispatch
      • See this Twitter thread for more details
      • See here and here for the actual implementation

Before We Start

Why Rust? Why Solana?

You can refer to this doc for the motivations.

Prerequisites

Installation

Install avm:
1
$ cargo install --git https://github.com/project-serum/anchor avm --locked --force
2
...
Copied!
Install latest anchor version:
1
$ avm install latest
2
...
3
$ avm use latest
4
...
Copied!
If you haven't installed cargo, please refer to this doc for installation steps.

Extra Dependencies on Linux (Optional)

You may have to install some extra dependencies on Linux (ex. Ubuntu):
1
$ sudo apt-get update && sudo apt-get upgrade && sudo apt-get install -y pkg-config build-essential libudev-dev
2
...
Copied!

Verify the Installation

Check if Anchor is successfully installed:
1
$ anchor --version
2
anchor-cli 0.22.0
Copied!

Escrow Program

Reminder: you can find the full code base for this example here. However, I would strongly recommend you to go through the copy-paste with me to get familiar with the flow.
Next, let's develop an escrow program using Anchor. I strongly recommend you to go through this tutorial if you are not familiar with escrow program yet.

Overview

Since this program is extended from the original Escrow Program, I assumed you have gone through the original blog post at least once.
However, there is one major difference between this exmaple and the original Escrow program: Instead of letting initializer create a token account to be reset to a PDA authority, we create a token account Vault that has both a PDA key and a PDA authority.

Initialize

Initializer can send a transaction to the escrow program to initialize the Vault. In this transaction, two new accounts: Vault and EscrowAccount, will be created and tokens (Token A) to be exchanged will be transfered from Initializer to Vault.

Cancel

Initializer can also send a transaction to the escrow program to cancel the demand of escrow. The tokens will be transfered back to the Initialzer and both Vault and EscrowAccount will be closed in this case.

Exchange

Taker can send a transaction to the escrow to exchange Token B for Token A. First, tokens (Token B) will be transfered from Taker to Initializer. Afterward, the tokens (Token A) kept in the Vault will be transfered to Taker. Finally, both Vault and EscrowAccount will be closed.

Initialize the Program

First, let's start a fresh Anchor project:
1
$ anchor init anchor-escrow
2
...
Copied!
This handy command will populate a project folder including the following files:
  • Cargo.toml
  • Anchor.toml
  • package.json
  • tsconfig.json
  • ...

Program Architecture

There are 3 main parts in the program:
  • Processor: Main buisiness logic locates in processor
  • Account Context (Instructions): Instruction data packing/unpacking and account constraints and access control locate in Instruction handling part
  • Account: Declaration of account owned by program locates in account part

Dependencies

Before we dive into the program, we need add the missing dependencies in Cargo.toml:
1
# Cargo.toml
2
3
...
4
[dependencies]
5
anchor-lang = "0.20.1"
6
anchor-spl = {version = "0.20.1"}
7
spl-token = {version = "3.3.0", features = ["no-entrypoint"]}
Copied!

Update program_id (Optional)

There is a default program_id defined by declare_id! macro in lib.rs:
1
// lib.rs
2
3
...
4
5
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
6
7
...
Copied!
Although we can use the default value just fine, I would strongly recommend to replace this with the actual program_id, which is the public key of the deploy key.
Get the public key of the deploy key:
1
$ anchor keys list
2
anchor_escrow: Hfd7V12kj9AENQjLpTozaPW6aT2rhPm3LSyjXZ5AbWH
Copied!
Replace the default value of program_id with this new value:
1
# Anchor.toml
2
3
[programs.localnet]
4
anchor_escrow = "Hfd7V12kj9AENQjLpTozaPW6aT2rhPm3LSyjXZ5AbWH"
5
6
...
Copied!
1
// lib.rs
2
3
...
4
5
declare_id!("Hfd7V12kj9AENQjLpTozaPW6aT2rhPm3LSyjXZ5AbWH");
6
7
...
Copied!

Processor (Part 1)

Let's scaffold the processor first. There should be 3 functions corresponding 3 tasks listed above:
1
// Processor (unimplemented)
2
3
#[program]
4
pub mod anchor_escrow {
5
use super::*;
6
7
pub fn initialize(
8
ctx: Context<Initialize>,
9
_vault_account_bump: u8,
10
initializer_amount: u64,
11
taker_amount: u64,
12
) -> ProgramResult {
13
// TODO
14
Ok(())
15
}
16
17
pub fn cancel(ctx: Context<Cancel>) -> ProgramResult {
18
// TODO
19
Ok(())
20
}
21
22
pub fn exchange(ctx: Context<Exchange>) -> ProgramResult {
23
// TODO
24
Ok(())
25
}
26
}
Copied!
The #[program] keyword is what makes the magic happen. In argument ctx, notice that we have to use a type Initialize for Context<T> generic. Initialize can be considered as a wrapper for instructions. This wrapper is enhanced by Anchor via derived macro (#[derive(account)]). We will see how it works real quick.
Each function has a corresponding instruction. As a result, there will be 3 instruction wrappers.

Instructions (Part 1)

From the processor section, we know that each function defined needs a corresponding instruction. So let's define those in instruction section:
1
// Instructions (unimplemented)
2
3
#[derive(Accounts)]
4
pub struct Initialize<'info> {
5
// TODO
6
}
7
8
#[derive(Accounts)]
9
pub struct Exchange<'info> {
10
// TODO
11
}
12
13
#[derive(Accounts)]
14
pub struct Cancel<'info> {
15
// TODO
16
}
Copied!
Depending on the program functions, the instructions should bring in the accounts that are needed for operations.
To see what are accounts needed for initializing escrow account, we have to consider what data stored in escrow account first.

Program Account

Accounts that are owned and managed by the program are defined in the #[account] section.

EscrowAccount

Field
Type
Description
initializer_key
Pubkey
To authorize the actions properly
initializer_deposit_token_account
Pubkey
To record the deposit account of initialzer
initializer_receive_token_account
Pubkey
To record the receiving account of initializer
initializer_amount
u64
To record how much token should the initializer transfer to taker
taker_amount
u64
To record how much token should the initializer receive from the taker
As a result, we should design an account that stores the minimum information to validate the escrow state and keep the integrity of the program:
1
// Program Account (fully implemented)
2
3
#[account]
4
pub struct EscrowAccount {
5
pub initializer_key: Pubkey,
6
pub initializer_deposit_token_account: Pubkey,
7
pub initializer_receive_token_account: Pubkey,
8
pub initializer_amount: u64,
9
pub taker_amount: u64,
10
}
Copied!

Instructions (Part 2)

According to what we have in EscrowAccount, we need the following accounts to initialize it.

Initialize

Field
Type
Description
initializer
AccountInfo
Signer of InitialEscrow instruction. To be stored in EscrowAccount
initializer_deposit_token_account
Account<TokenAccount>
The account of token account for token exchange. To be stored in EscrowAccount
initializer_receive_token_account
Account<TokenAccount>
The account of token account for token exchange. To be stored in EscrowAccount
token_program
AccountInfo
The account of TokenProgram
escrow_account
Box<Account<EscrowAccount>>
The account of EscrowAccount
vault_account
Account<TokenAccount>
The account of Vault, which is created by Anchor via constraints. (Will be explained in part 3)
mint
Account<Mint>
-
system_program
AccountInfo
-
rent
Sysvar<Rent>
-

Cancel

Field
Type
Description
initializer
AccountInfo
The initializer of EscrowAccount
initializer_deposit_token_account
Account<TokenAccount>
The address of token account for token exchange
vault_account
Account<TokenAccount>
The program derived address
vault_authority
AccountInfo
The program derived address
escrow_account
Box<Account<EscrowAccount>>
The address of EscrowAccount. Have to check if the EscrowAccount follows certain constraints.
token_program
AccountInfo
The address of TokenProgram

Exchange

Field
Type
Description
taker
AccountInfo
Singer of Exchange instruction
taker_deposit_token_account
Account<TokenAccount>
Token account for token exchange
taker_receive_token_account
Account<TokenAccount>
Token account for token exchange
initializer_deposit_token_account
Account<TokenAccount>
Token account for token exchange
initializer_receive_token_account
Account<TokenAccount>
Token account for token exchange
initializer
AccountInfo
To be used in constraints. (Will explain in part 3)
escrow_account
Box<Account<EscrowAccount>>
The address of EscrowAccount. Have to check if the EscrowAccount follows certain constraints.
vault_account
Account<TokenAccount>
The program derived address
vault_authority
AccountInfo
The program derived address
token_program
AccountInfo
The address of TokenProgram
You can tell this is a very long list of inputs since Solana programs are stateless.
1
// Instructions (partially implemented)
2
3
use anchor_spl::token::{self, CloseAccount, Mint, SetAuthority, TokenAccount, Transfer};
4
use spl_token::instruction::AuthorityType;
5
...
6
7
#[derive(Accounts)]
8
pub struct Initialize<'info> {
9
pub initializer: AccountInfo<'info>,
10
pub mint: Account<'info, Mint>,
11
pub vault_account: Account<'info, TokenAccount>,
12
pub initializer_deposit_token_account: Account<'info, TokenAccount>,
13
pub initializer_receive_token_account: Account<'info, TokenAccount>,
14
pub escrow_account: Box<Account<'info, EscrowAccount>>,
15
pub system_program: AccountInfo<'info>,
16
pub rent: Sysvar<'info, Rent>,
17
pub token_program: AccountInfo<'info>,
18
}
19
20
#[derive(Accounts)]
21
pub struct Cancel<'info> {
22
pub initializer: AccountInfo<'info>,
23
pub initializer_deposit_token_account: Account<'info, TokenAccount>,
24
pub vault_account: Account<'info, TokenAccount>,
25
pub vault_authority: AccountInfo<'info>,
26
pub escrow_account: Box<Account<'info, EscrowAccount>>,
27
pub token_program: AccountInfo<'info>,
28
}
29
30
#[derive(Accounts)]
31
pub struct Exchange<'info> {
32
pub taker: AccountInfo<'info>,
33
pub taker_deposit_token_account: Account<'info, TokenAccount>,
34
pub taker_receive_token_account: Account<'info, TokenAccount>,
35
pub initializer_deposit_token_account: Account<'info, TokenAccount>,
36
pub initializer_receive_token_account: Account<'info, TokenAccount>,
37
pub initializer: AccountInfo<'info>,
38
pub escrow_account: Box<Account<'info, EscrowAccount>>,
39
pub vault_account: Account<'info, TokenAccount>,
40
pub vault_authority: AccountInfo<'info>,
41
pub token_program: AccountInfo<'info>,
42
}
Copied!
Notice the lifetime anotation used in generic
You can see there are 2 different types for account: AccountInfo and Account. So what is the difference? I suppose it's proper to use Account over AccountInfo when you want Anchor to deserialize the data for convenience. In that case, you can access the account data via a trivial method call. For example: ctx.accounts.vault_account.mint

Processor (Part 2)

With necessary accounts, we can implement the business logic inside processor without bothering:
1
// Processor (fully implenmented)
2
3
#[program]
4
pub mod anchor_escrow {
5
use super::*;
6
7
const ESCROW_PDA_SEED: &[u8] = b"escrow";
8
9
pub fn initialize(
10
ctx: Context<Initialize>,
11
_vault_account_bump: u8,
12
initializer_amount: u64,
13
taker_amount: u64,
14
) -> ProgramResult {
15
ctx.accounts.escrow_account.initializer_key = *ctx.accounts.initializer.key;
16
ctx.accounts
17
.escrow_account
18
.initializer_deposit_token_account = *ctx
19
.accounts
20
.initializer_deposit_token_account
21
.to_account_info()
22
.key;
23
ctx.accounts
24
.escrow_account
25
.initializer_receive_token_account = *ctx
26
.accounts
27
.initializer_receive_token_account
28
.to_account_info()
29
.key;
30
ctx.accounts.escrow_account.initializer_amount = initializer_amount;
31
ctx.accounts.escrow_account.taker_amount = taker_amount;
32
33
let (vault_authority, _vault_authority_bump) =
34
Pubkey::find_program_address(&[ESCROW_PDA_SEED], ctx.program_id);
35
token::set_authority(
36
ctx.accounts.into_set_authority_context(),
37
AuthorityType::AccountOwner,
38
Some(vault_authority),
39
)?;
40
41
token::transfer(
42
ctx.accounts.into_transfer_to_pda_context(),
43
ctx.accounts.escrow_account.initializer_amount,
44
)?;
45
46
Ok(())
47
}
48
49
pub fn cancel(ctx: Context<Cancel>) -> ProgramResult {
50
let (_vault_authority, vault_authority_bump) =
51
Pubkey::find_program_address(&[ESCROW_PDA_SEED], ctx.program_id);
52
let authority_seeds = &[&ESCROW_PDA_SEED[..], &[vault_authority_bump]];
53
54
token::transfer(
55
ctx.accounts
56
.into_transfer_to_initializer_context()
57
.with_signer(&[&authority_seeds[..]]),
58
ctx.accounts.escrow_account.initializer_amount,
59
)?;
60
61
token::close_account(
62
ctx.accounts
63
.into_close_context()
64
.with_signer(&[&authority_seeds[..]]),
65
)?;
66
67
Ok(())
68
}
69
70
pub fn exchange(ctx: Context<Exchange>) -> ProgramResult {
71
let (_vault_authority, vault_authority_bump) =
72
Pubkey::find_program_address(&[ESCROW_PDA_SEED], ctx.program_id);
73
let authority_seeds = &[&ESCROW_PDA_SEED[..], &[vault_authority_bump]];
74
75
token::transfer(
76
ctx.accounts.into_transfer_to_initializer_context(),
77
ctx.accounts.escrow_account.taker_amount,
78
)?;
79
80
token::transfer(
81
ctx.accounts
82
.into_transfer_to_taker_context()
83
.with_signer(&[&authority_seeds[..]]),
84
ctx.accounts.escrow_account.initializer_amount,
85
)?;
86
87
token::close_account(
88
ctx.accounts
89
.into_close_context()
90
.with_signer(&[&authority_seeds[..]]),
91
)?;
92
93
Ok(())
94
}
95
}
Copied!
Now the business logic is simple, straightforward, and clear to understand.
  • In initialize, what happens is that the input accounts are assigned to EscrowAccount fields one by one. Then, a program derived address, or PDA, is derived to be going to become new authority of initializer_deposit_token_account.
  • In cancel, it just simply reset the authority from PDA back to the initializer.
  • In exchange, 3 things happen:
    • First, token A gets transfered from pda_deposit_token_account to taker_receive_token_account.
    • Next, token B gets transfered from taker_deposit_token_account to initializer_receive_token_account.
    • Finally, the authority of pda_deposit_token_account gets set back to the initializer.

Utils

There are some util functions used for wrapping the data to be passed in tokens::transfer, token::close_account and token::set_authority. It might look a bit overwhelmed in the first place. However, the purpose behind these functions are clear and simple:
1
// Utils (fully implemented)
2
3
impl<'info> Initialize<'info> {
4
fn into_transfer_to_pda_context(&self) -> CpiContext<'_, '_, '_, 'info, Transfer<'info>> {
5
let cpi_accounts = Transfer {
6
from: self
7
.initializer_deposit_token_account
8
.to_account_info()
9
.clone(),
10
to: self.vault_account.to_account_info().clone(),
11
authority: self.initializer.clone(),
12
};
13
CpiContext::new(self.token_program.clone(), cpi_accounts)
14
}
15
16
fn into_set_authority_context(&self) -> CpiContext<'_, '_, '_, 'info, SetAuthority<'info>> {
17
let cpi_accounts = SetAuthority {
18
account_or_mint: self.vault_account.to_account_info().clone(),
19
current_authority: self.initializer.clone(),
20
};
21
CpiContext::new(self.token_program.clone(), cpi_accounts)
22
}
23
}
24
25
impl<'info> Cancel<'info> {
26
fn into_transfer_to_initializer_context(
27
&self,
28
) -> CpiContext<'_, '_, '_, 'info, Transfer<'info>> {
29
let cpi_accounts = Transfer {
30
from: self.vault_account.to_account_info().clone(),
31
to: self
32
.initializer_deposit_token_account
33
.to_account_info()
34
.clone(),
35
authority: self.vault_authority.clone(),
36
};
37
CpiContext::new(self.token_program.clone(), cpi_accounts)
38
}
39
40
fn into_close_context(&self) -> CpiContext<'_, '_, '_, 'info, CloseAccount<'info>> {
41
let cpi_accounts = CloseAccount {
42
account: self.vault_account.to_account_info().clone(),
43
destination: self.initializer.clone(),
44
authority: self.vault_authority.clone(),
45
};
46
CpiContext::new(self.token_program.clone(), cpi_accounts)
47
}
48
}
49
50
impl<'info> Exchange<'info> {
51
fn into_transfer_to_initializer_context(
52
&self,
53
) -> CpiContext<'_, '_, '_, 'info, Transfer<'info>> {
54
let cpi_accounts = Transfer {
55
from: self.taker_deposit_token_account.to_account_info().clone(),
56
to: self
57
.initializer_receive_token_account
58
.to_account_info()
59
.clone(),
60
authority: self.taker.clone(),
61
};
62
CpiContext::new(self.token_program.clone(), cpi_accounts)
63
}
64
65
fn into_transfer_to_taker_context(&self) -> CpiContext<'_, '_, '_, 'info, Transfer<'info>> {
66
let cpi_accounts = Transfer {
67
from: self.vault_account.to_account_info().clone(),
68
to: self.taker_receive_token_account.to_account_info().clone(),
69
authority: self.vault_authority.clone(),
70
};
71
CpiContext::new(self.token_program.clone(), cpi_accounts)
72
}
73
74
fn into_close_context(&self) -> CpiContext<'_, '_, '_, 'info, CloseAccount<'info>> {
75
let cpi_accounts = CloseAccount {
76
account: self.vault_account.to_account_info().clone(),
77
destination: self.initializer.clone(),
78
authority: self.vault_authority.clone(),
79
};
80
CpiContext::new(self.token_program.clone(), cpi_accounts)
81
}
82
}
Copied!

Instructions (Part 3)

Finally, let's talk about the account constraints. Here comes a very handy funcionality that Anchor provides: Account Constraints.
Constraints are useful for basic checkings such as whether the initializer is the signer of instruction.
If you are familiar of Solidity, you can map this concept to solidity modifier.
1
// Instructions (fully implementated)
2
3
#[derive(Accounts)]
4
#[instruction(vault_account_bump: u8, initializer_amount: u64)]
5
pub struct Initialize<'info> {
6
#[account(mut, signer)]
7
pub initializer: AccountInfo<'info>,
8
pub mint: Account<'info, Mint>,
9
#[account(
10
init,
11
seeds = [b"token-seed".as_ref()],
12
bump = vault_account_bump,
13
payer = initializer,
14
token::mint = mint,
15
token::authority = initializer,
16
)]
17
pub vault_account: Account<'info, TokenAccount>,
18
#[account(
19
mut,
20
constraint = initializer_deposit_token_account.amount >= initializer_amount
21
)]
22
pub initializer_deposit_token_account: Account<'info, TokenAccount>,
23
pub initializer_receive_token_account: Account<'info, TokenAccount>,
24
#[account(zero)]
25
pub escrow_account: Box<Account<'info, EscrowAccount>>,
26
pub system_program: AccountInfo<'info>,
27
pub rent: Sysvar<'info, Rent>,
28
pub token_program: AccountInfo<'info>,
29
}
30
31
#[derive(Accounts)]
32
pub struct Cancel<'info> {
33
#[account(mut, signer)]
34
pub initializer: AccountInfo<'info>,
35
#[account(mut)]
36
pub vault_account: Account<'info, TokenAccount>,
37
pub vault_authority: AccountInfo<'info>,
38
#[account(mut)]
39
pub initializer_deposit_token_account: Account<'info, TokenAccount>,
40
#[account(
41
mut,
42
constraint = escrow_account.initializer_key == *initializer.key,
43
constraint = escrow_account.initializer_deposit_token_account == *initializer_deposit_token_account.to_account_info().key,
44
close = initializer
45
)]
46
pub escrow_account: Box<Account<'info, EscrowAccount>>,
47
pub token_program: AccountInfo<'info>,
48
}
49
50
#[derive(Accounts)]
51
pub struct Exchange<'info> {
52
#[account(signer)]
53
pub taker: AccountInfo<'info>,
54
#[account(mut)]
55
pub taker_deposit_token_account: Account<'info, TokenAccount>,
56
#[account(mut)]
57
pub taker_receive_token_account: Account<'info, TokenAccount>,
58
#[account(mut)]
59
pub initializer_deposit_token_account: Account<'info, TokenAccount>,
60
#[account(mut)]
61
pub initializer_receive_token_account: Account<'info, TokenAccount>,
62
#[account(mut)]
63
pub initializer: AccountInfo<'info>,
64
#[account(
65
mut,
66
constraint = escrow_account.taker_amount <= taker_deposit_token_account.amount,
67
constraint = escrow_account.initializer_deposit_token_account == *initializer_deposit_token_account.to_account_info().key,
68
constraint = escrow_account.initializer_receive_token_account == *initializer_receive_token_account.to_account_info().key,
69
constraint = escrow_account.initializer_key == *initializer.key,
70
close = initializer
71
)]
72
pub escrow_account: Box<Account<'info, EscrowAccount>>,
73
#[account(mut)]
74
pub vault_account: Account<'info, TokenAccount>,
75
pub vault_authority: AccountInfo<'info>,
76
pub token_program: AccountInfo<'info>,
77
}
Copied!
Here, we can see a few new attributes, such as:
Attribute
Description
#[account(signer)]
Checks the given account signed the transaction
#[account(mut)]
Marks the account as mutable and persists the state transition
#[account(constraint = <expression\>)]
Executes the given code as a constraint. The expression should evaluate to a boolean
#[account(close = <target\>)]
Marks the account as being closed at the end of the instruction’s execution, sending the rent exemption lamports to the specified
Notice that we used a rather complex constraint to create an token account that has a PDA key (See this code snippet for more details). Let's take a closer look of it:
1
#[derive(Accounts)]
2
#[instruction(token_bump: u8)]
3
pub struct TestTokenSeedsInit<'info> {
4
#[account(
5
init,
6
seeds = [b"my-token-seed".as_ref()],
7
bump = token_bump,
8
payer = authority,
9
token::mint = mint,
10
token::authority = authority,
11
)]
12
pub my_pda: Account<'info, TokenAccount>,
13
pub mint: Account<'info, Mint>,
14
pub authority: AccountInfo<'info>,
15
pub system_program: AccountInfo<'info>,
16
pub rent: Sysvar<'info, Rent>,
17
pub token_program: AccountInfo<'info>,
18
}
Copied!
Check the official document for more constraints.
Now, the program should compile again successfully:
1
$ anchor build
2
...
Copied!

Build and Test

So far we have only accomplished the first part of the workflow. Let's write some client side test for it.

Interface Description Language (IDL)

First, you can access the IDL via the following path:
1
$ cat ./target/idl/anchor_escrow.json
2
...
Copied!
This will print the full IDL on the terminal:
1
// anchor_escrow.json
2
3
{
4
"version": "0.0.0",
5
"name": "anchor_escrow",
6
"instructions": [
7
{
8
"name": "initialize",
9
"accounts": [
10
{
11
"name": "initializer",
12
"isMut": true,
13
"isSigner": true
14
},
15
{
16
"name": "mint",
17
"isMut": false,
18
"isSigner": false
19
},
20
{
21
"name": "vaultAccount",
22
"isMut": true,
23
"isSigner": false
24
},
25
{
26
"name": "initializerDepositTokenAccount",
27
"isMut": true,
28
"isSigner": false
29
},
30
{
31
"name": "initializerReceiveTokenAccount",
32
"isMut": false,
33
"isSigner": false
34
},
35
{
36
"name": "escrowAccount",
37
"isMut": true,
38
"isSigner": false
39
},
40
{
41
"name": "systemProgram",
42
"isMut": false,
43
"isSigner": false
44
},
45
{
46
"name": "rent",
47
"isMut": false,
48
"isSigner": false
49
},
50
{
51
"name": "tokenProgram",
52
"isMut": false,
53
"isSigner": false
54
}
55
],
56
"args": [
57
{
58
"name": "vaultAccountBump",
59
"type": "u8"
60
},
61
{
62
"name": "initializerAmount",
63
"type": "u64"
64
},
65
{
66
"name": "takerAmount",
67
"type": "u64"
68
}
69
]
70
},
71
{
72
"name": "cancel",
73
"accounts": [
74
{
75
"name": "initializer",
76
"isMut": true,
77
"isSigner": true
78
},
79
{
80
"name": "vaultAccount",
81
"isMut": true,
82
"isSigner": false
83
},
84
{
85
"name": "vaultAuthority",
86
"isMut": false,
87
"isSigner": false
88
},
89
{
90
"name": "initializerDepositTokenAccount",
91
"isMut": true,
92
"isSigner": false
93
},
94
{
95
"name": "escrowAccount",
96
"isMut": true,
97
"isSigner": false
98
},
99
{
100
"name": "tokenProgram",
101
"isMut": false,
102
"isSigner": false
103
}
104
],
105
"args": []
106
},
107
{
108
"name": "exchange",
109
"accounts": [
110
{
111
"name": "taker",
112
"isMut": false,
113
"isSigner": true
114
},
115
{
116
"name": "takerDepositTokenAccount",
117
"isMut": true,
118
"isSigner": false
119
},
120
{
121
"name": "takerReceiveTokenAccount",
122
"isMut": true,
123
"isSigner": false
124
},
125
{
126
"name": "initializerDepositTokenAccount",
127
"isMut": true,
128
"isSigner": false
129
},
130
{
131
"name": "initializerReceiveTokenAccount",
132
"isMut": true,
133
"isSigner": false
134
},
135
{
136
"name": "initializer",
137
"isMut": true,
138
"isSigner": false
139
},
140
{
141
"name": "escrowAccount",
142
"isMut": true,
143
"isSigner": false
144
},
145
{
146
"name": "vaultAccount",
147
"isMut": true,
148
"isSigner": false
149
},
150
{
151
"name": "vaultAuthority",
152
"isMut": false,
153
"isSigner": false
154
},
155
{
156
"name": "tokenProgram",
157
"isMut": false,
158
"isSigner": false
159
}
160
],
161
"args": []
162
}
163
],
164
"accounts": [
165
{
166
"name": "EscrowAccount",
167
"type": {
168
"kind": "struct",
169
"fields": [
170
{
171
"name": "initializerKey",
172
"type": "publicKey"
173
},
174
{
175
"name": "initializerDepositTokenAccount",
176
"type": "publicKey"
177
},
178
{
179
"name": "initializerReceiveTokenAccount",
180
"type": "publicKey"
181
},
182
{
183
"name": "initializerAmount",
184
"type": "u64"
185
},
186
{
187
"name": "takerAmount",
188
"type": "u64"
189
}
190
]
191
}
192
}
193
]
194
}
Copied!
As you can see, the IDL basically defines everything needed for a client representation.
You can think of IDL as ABI if you are familiar with Ethereum and Solidity.
Next, lets move to tests/anchor-escrow.ts to implement the tests.

Setup

Before we dive into the actual test cases, let's first setup the boilerlate for the tests:
1
$ npm install --save @solana/spl-token
Copied!
1
// anchor-escrow.ts
2
3
import * as anchor from '@project-serum/anchor';
4
import { Program } from '@project-serum/anchor';
5
import { AnchorEscrow } from '../target/types/anchor_escrow';
6
import { PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
7
import { TOKEN_PROGRAM_ID, Token } from "@solana/spl-token";
8
import { assert } from "chai";
9
10
describe('anchor-escrow', () => {
11
12
// Configure the client to use the local cluster.
13
const provider = anchor.Provider.env();
14
anchor.setProvider(provider);
15
16
const program = anchor.workspace.AnchorEscrow as Program<AnchorEscrow>;
17
18
let mintA = null;
19
let mintB = null;
20
let initializerTokenAccountA = null;
21
let initializerTokenAccountB = null;
22
let takerTokenAccountA = null;
23
let takerTokenAccountB = null;
24
let vault_account_pda = null;
25
let vault_account_bump = null;
26
let vault_authority_pda = null;
27
28
const takerAmount = 1000;
29
const initializerAmount = 500;
30
31
const escrowAccount = anchor.web3.Keypair.generate();
32
const payer = anchor.web3.Keypair.generate();
33
const mintAuthority = anchor.web3.Keypair.generate();
34
const initializerMainAccount = anchor.web3.Keypair.generate();
35
const takerMainAccount = anchor.web3.Keypair.generate();
36
37
it("Initialize program state", async () => {
38
// TODO
39
});
40
41
it("Initialize escrow", async () => {
42
// TODO
43
});
44
45
it("Exchange escrow state", async () => {
46
// TODO
47
});
48
49
it("Initialize escrow and cancel escrow", async () => {
50
// TODO
51
});
52
});
Copied!
Note: target/types/anchor_escrow is generated by running anchor build. Make sure you build the program first.
You can see there are 4 test cases to be completed. However, the first test case Initialize program state is used for program state setup such as minting tokens. As a result, there should be only 3 test cases corresponding to 3 functions of the program.
Let's finish the program state initialization:
1
// anchor-escrow.ts
2
3
...
4
5
describe('anchor-escrow', () => {
6
it("Initialize program state", async () => {
7
// Airdropping tokens to a payer.
8
await provider.connection.confirmTransaction(
9
await provider.connection.requestAirdrop(payer.publicKey, 10000000000),
10
"confirmed"
11
);
12
13
// Fund Main Accounts
14
await provider.send(
15
(() => {
16
const tx = new Transaction();
17
tx.add(
18
SystemProgram.transfer({
19
fromPubkey: payer.publicKey,
20
toPubkey: initializerMainAccount.publicKey,
21
lamports: 1000000000,
22
}),
23
SystemProgram.transfer({
24
fromPubkey: payer.publicKey,
25
toPubkey: takerMainAccount.publicKey,
26
lamports: 1000000000,
27
})
28
);
29
return tx;
30
})(),
31
[payer]
32
);
33
34
mintA = await Token.createMint(
35
provider.connection,
36
payer,
37
mintAuthority.publicKey,
38
null,
39
0,
40
TOKEN_PROGRAM_ID
41
);
42
43
mintB = await Token.createMint(
44
provider.connection,
45
payer,
46
mintAuthority.publicKey,
47
null,
48
0,
49
TOKEN_PROGRAM_ID
50
);
51
52
initializerTokenAccountA = await mintA.createAccount(initializerMainAccount.publicKey);
53
takerTokenAccountA = await mintA.createAccount(takerMainAccount.publicKey);
54
55
initializerTokenAccountB = await mintB.createAccount(initializerMainAccount.publicKey);
56
takerTokenAccountB = await mintB.createAccount(takerMainAccount.publicKey);
57
58
await mintA.mintTo(
59
initializerTokenAccountA,
60
mintAuthority.publicKey,
61
[mintAuthority],
62
initializerAmount
63
);
64
65
await mintB.mintTo(
66
takerTokenAccountB,
67
mintAuthority.publicKey,
68
[mintAuthority],
69
takerAmount
70
);
71
72
let _initializerTokenAccountA = await mintA.getAccountInfo(initializerTokenAccountA);
73
let _takerTokenAccountB = await mintB.getAccountInfo(takerTokenAccountB);
74
75
assert.ok(_initializerTokenAccountA.amount.toNumber() == initializerAmount);
76
assert.ok(_takerTokenAccountB.amount.toNumber() == takerAmount);
77
});
78
...
79
80
}
Copied!
We should be able to pass the first test case at this point:
1
$ anchor test
2
...
3
4
anchor-escrow
5
✔ Initialize program state (4814ms)
6
✔ Initialize escrow
7
✔ Exchange escrow state
8
✔ Initialize escrow and cancel escrow
9
10
11
4 passing (5s)
12
13
✨ Done in 10.89s.
Copied!

Implement Tests for initialize, exchange and cancel

Next, we add the test case for initialize:
1
// anchor-escrow.ts
2
3
...
4
5
describe('anchor-escrow', () => {
6
...
7
8
it("Initialize escrow", async () => {
9
const [_vault_account_pda, _vault_account_bump] = await PublicKey.findProgramAddress(
10
[Buffer.from(anchor.utils.bytes.utf8.encode("token-seed"))],
11
program.programId
12
);
13
vault_account_pda = _vault_account_pda;
14
vault_account_bump = _vault_account_bump;
15
16
const [_vault_authority_pda, _vault_authority_bump] = await PublicKey.findProgramAddress(
17
[Buffer.from(anchor.utils.bytes.utf8.encode("escrow"))],
18
program.programId
19
);
20
vault_authority_pda = _vault_authority_pda;
21
22
await program.rpc.initialize(
23
vault_account_bump,
24
new anchor.BN(initializerAmount),
25
new anchor.BN(takerAmount),
26
{
27
accounts: {
28
initializer: initializerMainAccount.publicKey,
29
vaultAccount: vault_account_pda,
30
mint: mintA.publicKey,
31
initializerDepositTokenAccount: initializerTokenAccountA,
32
initializerReceiveTokenAccount: initializerTokenAccountB,
33
escrowAccount: escrowAccount.publicKey,
34
systemProgram: anchor.web3.SystemProgram.programId,
35
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
36
tokenProgram: TOKEN_PROGRAM_ID,
37
},
38
instructions: [
39
await program.account.escrowAccount.createInstruction(escrowAccount),
40
],
41
signers: [escrowAccount, initializerMainAccount],
42
}
43
);
44
45
let _vault = await mintA.getAccountInfo(vault_account_pda);
46
47
let _escrowAccount = await program.account.escrowAccount.fetch(
48
escrowAccount.publicKey
49
);
50
51
// Check that the new owner is the PDA.
52
assert.ok(_vault.owner.equals(vault_authority_pda));
53
54
// Check that the values in the escrow account match what we expect.
55
assert.ok(_escrowAccount.initializerKey.equals(initializerMainAccount.publicKey));
56
assert.ok(_escrowAccount.initializerAmount.toNumber() == initializerAmount);
57
assert.ok(_escrowAccount.takerAmount.toNumber() == takerAmount);
58
assert.ok(
59
_escrowAccount.initializerDepositTokenAccount.equals(initializerTokenAccountA)
60
);
61
assert.ok(
62
_escrowAccount.initializerReceiveTokenAccount.equals(initializerTokenAccountB)
63
);
64
});
65
...
66
67
}
Copied!
We should see 2 implemented test cases passed at this point:
1
$ anchor test
2
...
3
4
anchor-escrow
5
✔ Initialize program state (5035ms)
6
✔ Initialize escrow (499ms)
7
✔ Exchange escrow state
8
✔ Initialize escrow and cancel escrow
9
10
11
4 passing (6s)
12
13
✨ Done in 11.39s.
Copied!
Similarly, let's implement the rest of the tests real quick:
1
// anchor-escrow.ts
2
3
...
4
5
describe('anchor-escrow', () => {
6
...
7
8
it("Exchange escrow state", async () => {
9
await program.rpc.exchange({
10
accounts: {
11
taker: takerMainAccount.publicKey,
12
takerDepositTokenAccount: takerTokenAccountB,
13
takerReceiveTokenAccount: takerTokenAccountA,
14
initializerDepositTokenAccount: initializerTokenAccountA,
15
initializerReceiveTokenAccount: initializerTokenAccountB,
16
initializer: initializerMainAccount.publicKey,
17
escrowAccount: escrowAccount.publicKey,
18
vaultAccount: vault_account_pda,
19
vaultAuthority: vault_authority_pda,
20
tokenProgram: TOKEN_PROGRAM_ID,
21
},
22
signers: [takerMainAccount]
23
});
24
25
let _takerTokenAccountA = await mintA.getAccountInfo(takerTokenAccountA);
26
let _takerTokenAccountB = await mintB.getAccountInfo(takerTokenAccountB);
27
let _initializerTokenAccountA = await mintA.getAccountInfo(initializerTokenAccountA);
28
let _initializerTokenAccountB = await mintB.getAccountInfo(initializerTokenAccountB);
29
30
assert.ok(_takerTokenAccountA.amount.toNumber() == initializerAmount);
31
assert.ok(_initializerTokenAccountA.amount.toNumber() == 0);
32
assert.ok(_initializerTokenAccountB.amount.toNumber() == takerAmount);
33
assert.ok(_takerTokenAccountB.amount.toNumber() == 0);
34
});
35
36
it("Initialize escrow and cancel escrow", async () => {
37
// Put back tokens into initializer token A account.
38
await mintA.mintTo(
39
initializerTokenAccountA,
40
mintAuthority.publicKey,
41
[mintAuthority],
42
initializerAmount
43
);
44
45
await program.rpc.initialize(
46
vault_account_bump,
47
new anchor.BN(initializerAmount),
48
new anchor.BN(takerAmount),
49
{
50
accounts: {
51
initializer: initializerMainAccount.publicKey,
52
vaultAccount: vault_account_pda,
53
mint: mintA.publicKey,
54
initializerDepositTokenAccount: initializerTokenAccountA,
55
initializerReceiveTokenAccount: initializerTokenAccountB,
56
escrowAccount: escrowAccount.publicKey,
57
systemProgram: anchor.web3.SystemProgram.programId,
58
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
59
tokenProgram: TOKEN_PROGRAM_ID,
60
},
61
instructions: [
62
await program.account.escrowAccount.createInstruction(escrowAccount),
63
],
64
signers: [escrowAccount, initializerMainAccount],
65
}
66
);
67
68
// Cancel the escrow.
69