Overview
In this tutorial, we will build a game using Anchor to introduce the basics of interacting with the Token Program on Solana. The game will be structured around four main actions: creating a new token mint, initializing player accounts, rewarding players for defeating enemies, and allowing players to heal by burning tokens. The program consists of 4 instructions:create_mint- this instruction creates a new token mint with a program-derived address (PDA) as the mint authority and creates the metadata account for the mint. We will add a constraint that allows only an “admin” to invoke this instructioninit_player- this instruction initializes a new player account with a starting health of 100kill_enemy- this instruction deducts 10 health points from the player account upon “defeating an enemy” and mints 1 token as a reward for the playerheal- this instruction allows a player to burn 1 token to restore their health back to 100
This example uses some external tools and program, created by Metaplex, for working with tokens. For a high-level overview of the relationship among user wallets, token mints, token accounts, and token metadata accounts, consider exploring this portion of the Metaplex documentation.
Getting Started
You’ll build the program and run its client on your machine with the Anchor CLI. Before you start, install the Solana development tools. The installer sets up the Anchor CLI 1.1.2, the Solana CLI, Surfpool, Node.js, and Yarn, which this tutorial uses.1
Create the project
Create a project with a single-file program and a Mocha test:
Terminal
--package-manager yarn sets the project up with Yarn. Without it,
anchor init uses the first of pnpm, Yarn, and npm that it finds. The program
is in programs/anchor-token/src/lib.rs, and the client you’ll write is the
test file, tests/anchor-token.ts.2
Add the dependencies
In The client uses the
programs/anchor-token/Cargo.toml, add anchor-spl with its metadata
feature, enable Anchor’s init-if-needed feature (the init_if_needed
constraint needs it), and add anchor-spl/idl-build to the idl-build
feature. Keep the other [features] entries that anchor init created:programs/anchor-token/Cargo.toml
@solana/spl-token library. Add it with Yarn:Terminal
3
Load the Token Metadata program
anchor test runs the client against a local Surfpool
validator. The create_mint instruction calls the Token Metadata program,
which the local validator doesn’t have. Add this section to Anchor.toml:Anchor.toml
anchor test starts Surfpool offline unless online is true. Online,
Surfpool loads accounts that a transaction uses but the local validator doesn’t
have, such as the Token Metadata program, from mainnet. Without this setting,
create_mint fails with InvalidProgramExecutable.To use
solana-test-validator instead of Surfpool, add this to Anchor.toml
to clone the Token Metadata program from mainnet, then run
anchor test --validator legacy wherever this tutorial runs anchor test:Anchor.toml
programs/anchor-token/src/lib.rs with the
code below:
lib.rs
anchor_spl crate to
interact with the SPL Token program, and its metadata module, which re-exports
Metaplex’s mpl_token_metadata crate, to interact with the Token Metadata
program. You’ll replace the declare_id! placeholder with your program’s
address when you build the program.
Create Mint instruction
First, let’s implement an instruction to create a new token mint and its metadata account. The onchain token metadata, including the name, symbol, and URI, will be provided as parameters to the instruction. Additionally, we’ll only allow an “admin” to invoke this instruction by defining anADMIN_PUBKEY constant and using it as a constraint. Be sure to replace
REPLACE_WITH_YOUR_WALLET_PUBKEY in the ADMIN_PUBKEY line with the address of
the wallet that signs the client’s transactions. That’s the wallet in
Anchor.toml, ~/.config/solana/id.json by default. Print its address with:
Terminal
create_mint instruction requires the following accounts:
admin- theADMIN_PUBKEYthat signs the transaction and pays for the initialization of the accountsreward_token_mint- the new token mint we are initializing, using a PDA as both the mint account’s address and its mint authoritymetadata_account- the metadata account we are initializing for the token minttoken_program- required for interacting with instructions on the Token programtoken_metadata_program- required account for interacting with instructions on the Token Metadata programsystem_program- a required account when creating a new accountrent- Sysvar Rent, a required account when creating the metadata account
lib.rs
create_mint instruction creates a new token mint, using a Program Derived
Address (PDA) as both the address of the token mint and its mint authority. The
instruction takes a URI (offchain metadata), name, and symbol as parameters.
This instruction then creates a metadata account for the token mint through a
Cross-Program Invocation (CPI) calling the
create_metadata_accounts_v3 instruction from the Token Metadata program.
CpiContext::new_with_signer takes the address of the program to call
(ctx.accounts.token_metadata_program.key()), the accounts that instruction
needs, and the seeds the program signs with.
The PDA is used to “sign” the CPI since it is the mint authority, which is a
required signer when creating the metadata account for a mint. The instruction
data (URI, name, symbol) is included in the DataV2 struct to specify the new
token mint’s metadata.
We also verify that the address of the admin account signing the transaction
matches the value of the ADMIN_PUBKEY constant to ensure only the intended
wallet can invoke this instruction.
Init Player Instruction
Next, let’s implement theinit_player instruction which creates a new player
account with an initial health of 100. The constant MAX_HEALTH is set to 100
to represent the starting health.
The init_player instruction requires the following accounts:
player_data- the new player account we are initializing, which will store the player’s healthplayer- the user who signs the transaction and pays for the initialization of the accountsystem_program- a required account when creating a new account
lib.rs
player_data account is initialized using a program-derived address (PDA)
with the player public key as one of the seeds. This ensures that each
player_data account is unique and associated with the player, allowing every
player to create their own player_data account.
Kill Enemy Instruction
Next, let’s implement thekill_enemy instruction which reduces the player’s
health by 10 and mints 1 token to the player’s token account as a reward.
The kill_enemy instruction requires the following accounts:
player- the player receiving the tokenplayer_data- the player data account storing the player’s current healthplayer_token_account- the player’s associated token account where tokens will be mintedreward_token_mint- the token mint account, specifying the type of token that will be mintedtoken_program- required for interacting with instructions on the token programassociated_token_program- required when working with associated token accountssystem_program- a required account when creating a new account
lib.rs
mint_to
instruction from the Token program and mints 1 token of the reward_token_mint
to the player_token_account as a reward for killing the enemy.
Since the mint authority for the token mint is a program-derived address (PDA),
we can mint tokens directly by calling this instruction without additional
signers. The program can “sign” on behalf of the PDA, allowing token minting
without explicitly requiring extra signers.
Heal Instruction
Next, let’s implement theheal instruction which allows a player to burn 1
token and restore their health to its maximum value.
The heal instruction requires the following accounts:
player- the player executing the healing actionplayer_data- the player data account storing the player’s current healthplayer_token_account- the player’s associated token account where the tokens will be burnedreward_token_mint- the token mint account, specifying the type of token that will be burnedtoken_program- required for interacting with instructions on the token programassociated_token_program- required when working with associated token accounts
lib.rs
heal
instruction. The instruction then uses a cross-program invocation (CPI) to call
the burn instruction from the Token program, which burns 1 token from the
player_token_account to heal the player.
Build the Program
You’ve now completed the program. Your final program should look like this:lib.rs
declare_id! to your project’s program address, then build
the program:
Terminal
anchor keys sync writes the address of the program keypair that anchor init
created into declare_id!. Without it, anchor build only warns
Program ID mismatch detected, and the client fails with
DeclaredProgramIdMismatch.
If anchor build fails, see
Build your first program
for the workarounds that apply to your Anchor and Solana CLI versions.
Get Started with the Client
In this section, we’ll walk you through a simple client-side implementation for interacting with the program. The client is the project’s Mocha test:anchor test builds the program, starts a local validator, deploys the program
to it, and runs tests/anchor-token.ts. To get started, open
tests/anchor-token.ts, remove the placeholder code, and add the code snippets
from the following sections.
Start by adding the following code for the setup.
tests/anchor-token.ts
@anchor-lang/core is Anchor’s TypeScript client. anchor.workspace.anchorToken
creates a client for the program from the IDL that anchor build writes to
target/idl/anchor_token.json, typed with target/types/anchor_token.ts. The
provider connects to the local validator that anchor test starts and signs
with the wallet in Anchor.toml.
Next, add the following two helper functions. These functions will be used to
log transaction signatures and fetch account data.
createMint instruction to create a new token mint if it does
not already exist:
rpc() sends the transaction and waits for the validator to confirm it. The
client fills in every account that it can work out from the IDL: fixed
addresses such as admin and the program accounts, PDAs whose seeds the IDL
describes, such as rewardTokenMint, and signers, which default to the
provider’s wallet. accounts() takes only the rest, here metadataAccount,
because the program checks its address with a function call that the IDL can’t
describe. Listing an account that the client resolves is a TypeScript error;
use accountsPartial() instead to set such accounts yourself.
Next, call the initPlayer instruction to create a new player account if one
does not already exist.
killEnemy instruction:
heal instruction:
Terminal
anchor test builds the program, starts Surfpool, deploys the program, runs
the client, then stops the validator. The output should be similar to the
following, with your own addresses and signatures. Before it, recent Node.js
releases print a MODULE_TYPELESS_PACKAGE_JSON warning about
tests/anchor-token.ts, which doesn’t affect the client.
Output
anchor test run starts a new local validator, so the client creates the
mint and the player account every time. The Mint Already Exists and
Player Already Exists branches only run against a validator that already has
those accounts.
To inspect the transactions and accounts after the client runs, use
anchor test --detach, which keeps the validator running until you press
Ctrl+C. Print a transaction’s logs, including the Token Metadata program’s
IX: Create Metadata Accounts v3 from createMint, with
solana confirm -v <SIGNATURE> --url localhost. To look up the token mint
address, open
Solana Explorer
connected to the local validator.