Tiny Adventure Anchor Program - Part Two
In this tutorial, we will rebuild the Tiny Adventure game and introduce a chest with a reward of 0.1 SOL. The chest will “spawn” at a specific position, and when the player reaches that position, they will receive the reward. The goal of this program is to demonstrate how to store SOL within a program account and distribute it to players. The Tiny Adventure Two Program consists of 3 instructions:initialize_level_one- This instruction initializes two onchain accounts: one for recording the player’s position and another for holding the SOL reward that represents the “reward chest”.reset_level_and_spawn_chest- This instruction resets the player’s position to zero and “respawns” a reward chest by transferring SOL from the user invoking the instruction to the reward chest account.move_right- This instruction allows the player to move their position to the right and collect the SOL in the reward chest once they reach a specific position.
Getting Started
This tutorial uses the Anchor CLI on your computer. If you haven’t installed the Solana development tools yet, follow the installation guide. It installs Rust, the Solana CLI, the Anchor CLI, Surfpool, Node.js, and Yarn. This tutorial was tested with Anchor CLI 1.1.2, Solana CLI 3.1.10 (the pair the installer sets up through AVM), and Surfpool 1.7.0. 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
lives in programs/tiny-adventure-two/src/lib.rs. The TypeScript test in
tests/tiny-adventure-two.ts is where you’ll write the client.
The initialize_level_one instruction uses Anchor’s init_if_needed
constraint, which needs the init-if-needed feature. In
programs/tiny-adventure-two/Cargo.toml, replace the anchor-lang line under
[dependencies] with:
programs/tiny-adventure-two/Cargo.toml
programs/tiny-adventure-two/src/lib.rs with
the code below:
programs/tiny-adventure-two/src/lib.rs
Defining the Chest Vault Account
Add theCHEST_REWARD constant at the beginning of the program. The
CHEST_REWARD represents the amount of lamports that will be put into the chest
and given out as rewards. Lamports are the smallest fractions of a SOL, with 1
billion lamports being equal to 1 SOL. The LAMPORTS_PER_SOL constant at the
top of the file holds that conversion.
To store the SOL reward, we will define a new ChestVaultAccount struct. This
is an empty struct because we will be directly updating the lamports in the
account. The account will hold the SOL reward and does not need to store any
additional data.
Defining the Game Data Account
To keep track of the player’s position within the game, we need to define a structure for the onchain account that will store the player’s position. TheGameDataAccount struct contains a single field, player_position, which
stores the player’s current position as an unsigned 8-bit integer.
GameDataAccount struct defined, you can now use it to store and
update the player’s position as they interact with the game. As the player moves
right and progresses through the game, their position will be updated within the
GameDataAccount, allowing you to track their progress towards the chest
containing the SOL reward.
Initialize Level One Instruction
With theGameDataAccount and ChestVaultAccount defined, let’s implement the
initialize_level_one instruction. This instruction initializes both the
GameDataAccount and ChestVaultAccount, sets the player’s position to 0, and
displays the starting message.
The initialize_level_one instruction requires 4 accounts:
new_game_data_account- theGameDataAccountwe are initializing to store the player’s positionchest_vault- theChestVaultAccountwe are initializing to store the SOL rewardsigner- the player paying for the initialization of the accountssystem_program- a required account when creating a new account
GameDataAccount and ChestVaultAccount are created using a Program
Derived Address (PDA) as the address of the account, allowing us to
deterministically locate the address later. The init_if_needed constraint
ensures that the accounts are only initialized if they don’t already exist.
Since the PDAs for both accounts in this instruction use a single fixed seed,
our program can only create one of each type of account. In effect, the
instruction would only ever need to be invoked one time.
It’s worth noting that the current implementation does not have any restrictions
on who can modify the GameDataAccount, effectively turning the game into a
multiplayer experience where everyone can control the player’s movement.
Alternatively, you can use the signer’s address as an extra seed in the
initialize_level_one instruction, allowing each player to create their own
GameDataAccount.
Reset Level and Spawn Chest Instruction
Next, let’s implement thereset_level_and_spawn_chest instruction, which
resets the player’s position to the start and fills up the chest with a reward
of 0.1 SOL.
The reset_level_and_spawn_chest instruction requires 4 accounts:
payer- the player providing the SOL reward for the chestchest_vault- theChestVaultAccountstoring the SOL rewardgame_data_account- theGameDataAccountstoring the player’s positionsystem_program- the program we’ll be invoking to transfer SOL using a cross-program invocation (CPI), more on this shortly
ChestVaultAccount. A cross-program invocation is when one
program invokes an instruction on another program. In this case, we use a CPI to
invoke the Transfer instruction from the system_program to transfer SOL from
the payer to the ChestVaultAccount. CpiContext::new takes the address of the
program to invoke, here the System Program’s, and the accounts its instruction
expects.
Cross-program invocations are a key concept in the Solana programming model,
enabling programs to directly interact with instructions from other programs.
For a deeper dive into CPIs, feel free to explore the
CPI guide.
Move Right Instruction
Finally, let’s implement themove_right instruction which includes the logic
for collecting the chest reward. When a player reaches position 3 and inputs the
correct “password”, the reward is transferred from the ChestVaultAccount
to the player’s account. If an incorrect password is entered, a custom Anchor
Error is returned. If the player is already at position 3, a message will be
logged. Otherwise, the position will be incremented by 1 to represent moving to
the right.
The main purpose of this “password” functionality is to demonstrate how to
incorporate parameters into an instruction and the implementation of custom
Anchor Errors for improved error handling. In this example, the correct password
will be “gib”.
The move_right instruction requires 3 accounts:
chest_vault- theChestVaultAccountstoring the SOL rewardgame_data_account- theGameDataAccountstoring the player’s positionplayer- the wallet of the player invoking the instruction and the potential recipient of SOL reward
ChestVaultAccount isn’t owned by the System Program. Instead, we directly
modify the lamports within the accounts by using try_borrow_mut_lamports.
The program can subtract lamports from ChestVaultAccount because the program
owns that account: the runtime only lets an account’s owner program debit it,
and no signature is involved. Any program can add lamports to a writable
account, so crediting the player works too. After each instruction, the runtime
also checks that the total balance across all accounts is unchanged (see the
account modification rules).
PDA signing (invoke_signed, or CpiContext::new_with_signer in Anchor) is
only needed when a CPI requires the PDA as a signer, for example a System
Program transfer out of a PDA that the System Program owns. Here, the PDA gives
the chest a deterministic address that every client can derive from the
chestVault seed.
Build the program
You’ve now completed part two of the Tiny Adventure program. Your final program should look like this:programs/tiny-adventure-two/src/lib.rs
declare_id! at your project’s program address, then build the program:
Terminal
anchor keys sync reads the program keypair that anchor init created in
target/deploy/tiny_adventure_two-keypair.json and writes its address into
declare_id! and Anchor.toml. anchor build compiles the program to
target/deploy/tiny_adventure_two.so and writes its IDL to
target/idl/tiny_adventure_two.json and the TypeScript types the client imports
to target/types/tiny_adventure_two.ts.
anchor build fails with Platform tools v1.52 is incompatible with SBPFv3?
That happens with Anchor 1.1.x on Solana CLI 4.3 or later, without AVM. Build
the program for SBPF v0 without the IDL, then build the IDL and the
TypeScript types on their own:Terminal
anchor test --skip-build, so it doesn’t rebuild. For other Anchor and
Solana CLI versions, see
Build your first program.Write the client
In this section, we’ll walk through a simple client for interacting with the game. The client is the Mocha test thatanchor init created, and anchor test
runs it against a local validator. We will break down the code and provide
detailed explanations for each step.
Replace the contents of tests/tiny-adventure-two.ts with the code below, then
add the code snippets from the following sections, in order, inside the it
block:
tests/tiny-adventure-two.ts
program is the client for your program, built from the IDL and types that
anchor build wrote to target. player is the wallet set in Anchor.toml,
which pays for and signs every transaction the test sends. printProgramLogs
fetches a transaction and prints the lines your program logged with msg!, so
you can follow the program’s side of the game in the test output.
First, let’s derive the PDAs (program-derived addresses) for the
GameDataAccount and ChestVaultAccount. A PDA is a unique address in the
format of a public key, derived using the program’s ID and additional seeds.
initializeLevelOne instruction to set up the
GameDataAccount and ChestVaultAccount.
accountsPartial lets you pass every account the instruction requires, as this
client does. With .accounts() instead, the client fills in the accounts it
can work out itself: PDAs whose seeds are in the IDL, the System Program, and
signers, which default to your wallet. .rpc() signs the transaction with your
wallet, sends it, and waits for the confirmed commitment, so
printProgramLogs can fetch it.
After that, we’ll use the resetLevelAndSpawnChest instruction to set the
player’s position to 0 and fill the ChestVaultAccount with 0.1 SOL.
moveRight instruction. In
this example, we’ll loop through this instruction until the player reaches the
position to collect the reward from the ChestVaultAccount.
Run the client
Run the test:Terminal
anchor test builds the program, starts a local validator (Surfpool, the
default in Anchor CLI 1.1.2), deploys the program to it, and runs the test. The
validator funds your wallet, so you don’t need devnet SOL, and it stops when the
test finishes. If Surfpool isn’t installed, anchor test fails with
Failed to spawn `surfpool`; run anchor test --validator legacy to use
solana-test-validator instead.
The output should resemble the following. Your transaction signatures and
balances will differ:
Output
moveRight to anything other than
“gib”, the third moveRight call fails when the player tries to claim the
chest, and the test fails with this error: