Soldev

Getting started with Anchor

Last updated:

To start developing on Anchor we'll need the Solana CLI.

sh -c "$(curl -sSfL https://release.anza.xyz/stable/install)"

You'll then need to add the CLI to your $PATH.

First open the local zsh config with nvim ~/.zshenv.local

Then add this line: export PATH="$HOME/.local/share/solana/install/active_release/bin:$PATH"

Close and re-open your terminal, and run solana --version and you should see the correct version output, meaning it's now found in the PATH.

Anchor CLI

To install Anchor we'll use the Anchor Version Manager which is a cargo package:

cargo install --git https://github.com/coral-xyz/anchor avm --force

After this is done installing, check that it worked by running avm --version.

Now we'll use AVM to install the Anchor CLI. We'll install the latest version:

avm install latest
avm use latest

Now run anchor --version to check if it installed correctly. If it doesn't you'll need to install the dependencies mentioned here.

Making your first project

Navigate to a directory where you'd like to place your project.

The default anchor template is written in TypeScript, so we'll use the Rust template instead and give it a name:

anchor init --test-template rust 

Setting up a test environment

Now we have a rust project, but we'll want to configure it so that we are only testing on localhost:

solana config set --url localhost

This will set the RPC URL and WebSocket URL to source to http://localhost:8899 and ws://localhost:8900/ respectively.

We'll now build and test our Anchor project:

anchor build

This will compile your Rust code into an executable. This executable is what will be stored in your Account on Solana when we're live. It'll exist now at /target/deploy/my_project.so

Now if you run the Rust tests with anchor test, you'll notice it complains: Error: Unable to read keypair file (/home/andrewd/.config/solana/id.json)

We'll need to create a wallet and give it a keypair. Since we've set up our solana config to use localhost, we're safe to generate our keys:

solana-keygen new

You'll be prompted to enter a BIP39 passphrase, you can skip it.

Then note down your seed phrase somewhere, and now you can run anchor test.

If the test passed, congrats, you have a working basic Anchor setup.