Getting Started
This guide uses the Anchor CLI, the Solana CLI, and Node.js. If you haven’t installed them yet, install the Solana development tools. The installer sets up Rust, the Solana CLI, the Anchor CLI, Node.js, and Yarn. This guide was tested with Anchor CLI 1.1.2 and Solana CLI 3.1.10, the pair the installer sets up through AVM.Create the project
Create a project with a single-file program and a TypeScript setup:Terminal
--template single puts the whole program in one file,
programs/tiny-adventure/src/lib.rs. --test-template mocha sets up a
TypeScript project with Anchor’s TypeScript client, @anchor-lang/core, which
the client in this guide uses. --package-manager yarn installs it with Yarn.
Without the flag, anchor init uses the first of pnpm, Yarn, and npm that it
finds. You won’t use the starter test, which is written for the template’s
counter program, so delete it:
Terminal
Initial Program Code
Replace the contents ofprograms/tiny-adventure/src/lib.rs with the code
below:
lib.rs
declare_id! placeholder is replaced with your program’s address in
Build and Deploy.
Defining the Game Data Account
The first step in building the game is 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.
lib.rs
Program Instructions
Our Tiny Adventure program consists of only 3 instruction handlers:initialize- sets up an onchain account to store the player’s positionmove_left- lets the player move their position to the leftmove_right- lets the player move their position to the right
Initialize Instruction
Ourinitialize instruction initializes the GameDataAccount if it does not
already exist, sets the player_position to 0, and prints some message logs.
The initialize instruction requires 3 accounts:
new_game_data_account- theGameDataAccountwe are initializingsigner- the player paying for the initialization of theGameDataAccountsystem_program- a required account when creating a new account
lib.rs
GameDataAccount address. This enables us to deterministically locate the
address later on. It is important to note that the PDA in this example is
generated with a single fixed value as the seed (level1), limiting our program
to creating only one GameDataAccount. The init_if_needed constraint then
ensures that the GameDataAccount is initialized only if it doesn’t already
exist.
init_if_needed is behind an Anchor Cargo feature because it can open a program
to re-initialization attacks: the instruction also runs when the account already
exists, so it must not reset data that you want to keep. Enable the feature in
programs/tiny-adventure/Cargo.toml by replacing the anchor-lang line under
[dependencies] with:
programs/tiny-adventure/Cargo.toml
anchor build fails with
init_if_needed requires that anchor-lang be imported with the init-if-needed cargo feature enabled.
It is worth noting that the current implementation does not have any
restrictions on who can modify the GameDataAccount. This effectively
transforms the game into a multiplayer experience where everyone can control the
player’s movement. Calling initialize again also sets the position back to 0.
Alternatively, you can use the signer’s address as an extra seed in the
initialize instruction, which would enable each player to create their own
GameDataAccount.
Move Left Instruction
Now that we can initialize aGameDataAccount account, let’s implement the
move_left instruction which allows a player to update their player_position.
In this example, moving left simply means decrementing the player_position
by 1. We’ll also set the minimum position to 0. The only account needed for this
instruction is the GameDataAccount.
lib.rs
Move Right Instruction
Lastly, let’s implement themove_right instruction. Similarly, moving right
will simply mean incrementing the player_position by 1. We’ll also limit the
maximum position to 3.
Just like before, the only account needed for this instruction is the
GameDataAccount.
lib.rs
Build and Deploy
We’ve now completed the Tiny Adventure program. Your finalprograms/tiny-adventure/src/lib.rs should resemble the following:
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-keypair.json and writes its address into
declare_id!. anchor build compiles the program to
target/deploy/tiny_adventure.so, and writes its IDL to
target/idl/tiny_adventure.json and the TypeScript types the client imports to
target/types/tiny_adventure.ts.
Next, start a local validator in a second terminal, and leave it running:
Terminal
solana-test-validator runs a single-node Solana network on your computer, with
its RPC endpoint at http://127.0.0.1:8899. When it starts, it gives
500,000,000 SOL to your Solana CLI wallet, ~/.config/solana/id.json, the same
wallet Anchor.toml uses, so you don’t need devnet SOL. It keeps its state in a
test-ledger folder in the directory you start it from, so your program and the
game state survive a restart. To start over, stop it and run
solana-test-validator --reset, which also removes your program, so deploy it
again.
Back in the first terminal, deploy the program to the local validator:
Terminal
anchor program deploy deploys the program that anchor build wrote to
target/deploy to the cluster set in Anchor.toml, which is localnet, the
local validator. The output shows your program’s address:
Output
anchor build or anchor program deploy fails? Anchor 1.1 builds SBPF
v0 programs. The test validator in Solana CLI 4.1 and later rejects deploying
them, so anchor program deploy fails with
Detected sbpf_version required by the executable which are not enabled.
Without AVM, on Solana CLI 4.3 or later, anchor build already fails with
Platform tools v1.52 is incompatible with SBPFv3.Run solana --version to see your active Solana CLI. To switch, install
Anchor 1.1.2 with AVM, as the installer and
Install dependencies
set it up: when you run anchor, AVM makes Solana CLI 3.1.10 your active
release, and its test validator runs v0 programs. Then stop
solana-test-validator and start it again. Anchor CLI 1.2 and later build
SBPF v3 programs, which the newer test validators run.Get Started with the Client
This next section will guide you through a simple client-side implementation for interacting with the game. We’ll break down the code and provide detailed explanations for each step. Create aclient.ts file in the project’s root folder, next to Anchor.toml,
with the code below. Then add the code snippets from the following sections, in
order, inside the main function:
client.ts
Connect to the Program
First, let’s create a client for the program and print the wallet that plays the game.client.ts
AnchorProvider.env() connects to the cluster and loads the wallet that
anchor run passes to the script in the ANCHOR_PROVIDER_URL and
ANCHOR_WALLET environment variables, which come from Anchor.toml: the local
validator and ~/.config/solana/id.json. That wallet pays for and signs every
transaction the client sends. anchor.workspace.tinyAdventure creates a client
for your program from the IDL that anchor build wrote to target/idl, and the
TinyAdventure type from target/types gives you typed instructions and
accounts.
Derive the GameDataAccount Account Address
Next, let’s derive the PDA for theGameDataAccount using the
findProgramAddressSync function.
A program-derived address (PDA) is a unique address in the format of a public key, derived using the program’s ID and additional seeds.
client.ts
Initialize the Game State
Next, let’s try to fetch the game data account using the PDA from the previous step. If the account doesn’t exist, we’ll create it by invoking theinitialize
instruction from our program.
client.ts
accountsPartial lets you pass every account the instruction requires, as the
program’s Initialize struct lists them. With .accounts() instead, the client
fills in the accounts it can work out from the IDL itself: the PDA, whose seeds
are in the IDL, the System Program, and the signer, which defaults to your
wallet. .rpc() signs the transaction with your wallet, sends it, and waits for
the validator to process it.
Move Left and Right
Now we are ready to interact with the game by moving left or right. This is done by invoking themoveLeft or moveRight instructions from the program by
submitting a transaction to the Solana network.
You can repeat this step as many times as you like. Each time, the move logic
runs onchain and updates the player’s state.
client.ts
MoveLeft and MoveRight structs don’t give the GameDataAccount any
seeds, so the client can’t work out its address from the IDL, and you pass it in
.accounts().
Logging the Player’s Position
Lastly, let’s use aswitch statement to log the character’s position based on
the playerPosition value stored in the gameDataAccount. We’ll use this as a
visual representation of the character’s movement in the game.
client.ts
Run the Client Program
Yourclient.ts should now look like this:
client.ts
client script to the [scripts] section of Anchor.toml,
below the test line that anchor init created:
Anchor.toml
solana-test-validator still running, run the client:
Terminal
anchor run client runs the script with ANCHOR_PROVIDER_URL and
ANCHOR_WALLET set from Anchor.toml. Running npx tsx client.ts on its own
fails with ANCHOR_PROVIDER_URL is not defined. The first time, npx downloads
tsx, which runs TypeScript files directly. The output
should be similar to the following. Your address, balance, and transaction
signatures will differ:
Output
GameDataAccount, then moves the player right. Run
anchor run client again, and the player moves to position 2, then 3. At
position 3, move_right logs You have reached the end! Super! and the player
stays where it is. To move left instead, comment out .moveRight() and
uncomment .moveLeft().
To see the messages the program logged, run the solana confirm command that
the client printed for the move. The end of its output lists the logs:
Output (excerpt)
What’s Next?
With the basic game complete, unleash your creativity and practice building independently by implementing your own ideas to enrich the game experience. Here are a few suggestions:- Modify the in-game texts to create an intriguing story. To let a friend play through your custom narrative, deploy the program to devnet (Deploy Program shows how) and observe the onchain transactions as they happen.
- Add a chest that rewards players with SOL Rewards or let the player collect coins and interact with tokens as they progress through the game.
- Create a grid that allows the player to move up, down, left, and right, and introduce multiple players for a more dynamic experience.