What you will learn
- Setting up your environment
- Using
npx create-solana-dapp - Anchor program development
- Anchor PDAs and accounts
- Deploying a Solana program
- Generating a TypeScript client from the program’s IDL
- Connecting an onchain program to a React UI
Prerequisites
For this guide, you will need to have your local development environment setup with a few tools: This guide was tested withcreate-solana-dapp 4.8.5 and its nextjs-anchor
template, Anchor CLI 1.1.2, and Solana CLI 3.1.10 (the pair the installer sets
up through AVM).
Setting up the project
nextjs-anchor template and
installs its dependencies. You can find the source code of the CLI
here and of the
template
here.
The template has three parts you will change in this guide:
anchor/: an Anchor workspace with an examplevaultprogram inanchor/programs/vaultapp/: a Next.js app built on@solana/kit, with a wallet connector, a cluster selector, and a client for the vault program inapp/generated/vaultcodama.json: tells Codama which IDL to read and where to write the generated client
Writing a Solana program with Anchor
If you’re new to Anchor, The Anchor Book and Anchor Examples are great references to help you learn. We’ll add ajournal program next to the template’s vault program. Create its
folder in the Anchor workspace:
anchor/programs/journal/Cargo.toml:
anchor/programs/journal/Cargo.toml
anchor new journal also adds a program, but the manifest it writes inherits
edition and rust-version from a [workspace.package] table this template
doesn’t have, so the build fails until you edit it. Writing the manifest
yourself avoids that.Define your Anchor program
Createanchor/programs/journal/src/lib.rs and start with the program module:
anchor/programs/journal/src/lib.rs
declare_id! is a placeholder. You’ll replace it with your
program’s real address before you build.
Define your program state
The state is the data structure used to define the information you want to save to the account. Since Solana onchain programs do not have storage, the data is stored in accounts that live on the blockchain. When using Anchor, the#[account] attribute macro is used to define your
program state.
- the journal’s owner
- the title of each journal entry, and
- the message of each journal entry
InitSpace macro
used in the above code will help calculate the space needed when initializing an
account. For more information on space, read
here.
Each entry’s title is also a seed of its address (see below), and a seed can be
at most 32 bytes, so the title is capped at 32 bytes. Add the errors the program
returns when a title or message is too long:
Create a journal entry
Now, let’s add an instruction handler to this program that creates a new journal entry. To do this, we will update the#[program] code that we already defined earlier to include an instruction for
create_journal_entry.
When creating a journal entry, the user will need to provide the title and
message of the journal entry. So we need to add those two variables as
additional arguments.
When calling this instruction handler function, we want to check the lengths,
then save the owner of the account, the journal entry title, and the journal
entry message to the account’s JournalEntryState.
Context type as its first
argument. The Context macro is used to define a struct that encapsulates
accounts that will be passed to a given instruction handler. Therefore, each
Context must have a specified type with respect to the instruction handler. In
our case, we need to define a data structure for CreateEntry:
#[derive(Accounts)]macro is used to deserialize and validate the list of accounts specified within the struct#[instruction(...)]attribute macro is used to access the instruction data passed into the instruction handler#[account(...)]attribute macro then specifies additional constraints on the accounts
init constraint. init fails if
the account already exists, so creating a second entry with the same title
returns an error instead of overwriting the first one.
With Anchor, a PDA is initialized with the seeds, bump, and init
constraints. The init constraint also requires the payer and space
constraints to define who is paying the
rent to hold this account’s data onchain
and how much space needs to be allocated for that data.
Note: By using the InitSpace macro in the JournalEntryState, we are able to
calculate space by using the INIT_SPACE constant and adding 8 to the space
constraint for Anchor’s internal discriminator.
Updating a journal entry
Now that we can create a new journal entry, let’s add anupdate_journal_entry
instruction handler with a context that has an UpdateEntry type.
To do this, the instruction will need to rewrite/update the data for a specific
PDA that was saved to the JournalEntryState of the account when the owner of
the journal entry calls the update_journal_entry instruction.
update_journal_entry is editing an already existing PDA, we do not need to
initialize it. However, the message being passed to the instruction handler
could have a different space size required to store it (i.e. the message could
be shorter or longer), so we will need to use a few specific realloc
constraints to reallocate the space for the account onchain:
realloc- sets the new space required: 8 bytes for the discriminator, 32 for the owner, and a 4-byte length prefix plus the bytes of the title and of the messagerealloc::payer- defines the account that will either pay or be refunded based on the newly required lamportsrealloc::zero- defines that the account may be updated multiple times when set totrue
seeds and bump constraints are still needed to be able to find the
specific PDA we want to update.
The mut constraints allows us to mutate/change the data within the account.
Because how the Solana blockchain handles reading from accounts and writing to
accounts differently, we must explicitly define which accounts will be mutable
so the Solana runtime can correctly process them.
Note: In Solana, when you perform a reallocation, which changes the account’s
size, the transaction must cover the rent for the new account size. The
realloc::payer = owner attribute indicates that the owner account will pay for
the rent. For an account to be able to cover the rent, it typically needs to be
a signer (to authorize the deduction of funds), and in Anchor, it also needs to
be mutable so that the runtime can deduct the lamports to cover the rent from
the account.
Delete a journal entry
Lastly, we will add adelete_journal_entry instruction handler with a context
that has a DeleteEntry type.
To do this, we will simply need to close the account for the specified journal
entry.
close constraint to close out the account
onchain and refund the rent back to the journal entry’s owner.
The seeds and bump constraints are needed to validate the account.
The complete program
Put together,anchor/programs/journal/src/lib.rs looks like this:
anchor/programs/journal/src/lib.rs
Build and deploy your Anchor program
From theanchor folder, give the program its address, then build the
workspace:
anchor keys sync creates the program’s keypair,
target/deploy/journal-keypair.json, and writes its address into
declare_id!. anchor build compiles the vault and journal programs into
target/deploy and writes their IDLs to target/idl.
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, for example when
Anchor isn’t managed by AVM (AVM pairs Anchor 1.1.2 with Solana CLI 3.1.10).
Build the programs for SBPF v0 without the IDL, then build the journal IDL on
its own (tested with Anchor 1.1.2 and Solana CLI 4.3.2):--no-deploy stops it from deploying the workspace on its own, since
you’ll deploy the program yourself:
~/.config/solana/id.json, the deployer in
Anchor.toml) on the local network and deploy the journal program:
solana address
prints it) from the Solana Faucet. Deploying needs
about 2.5 SOL: about 1.25 SOL stays in the program account, and the rest comes
back when the deploy closes its temporary buffer. Then run:
Connecting a Solana program to a UI
create-solana-dapp already sets up a UI with a wallet connector for you. All
we need to do is simply modify it to fit your newly created program.
Since this journal program has the three instructions, we will need components
in the UI that will be able to call each of these instructions:
- create entry
- update entry
- delete entry
Generate a TypeScript client
The template turns the program’s IDL into a TypeScript client with Codama. Pointcodama.json, in the project root, at the journal IDL:
codama.json
app/generated/journal. It includes an instruction
builder for each instruction, such as getCreateJournalEntryInstructionAsync,
which derives the entry’s PDA from the title and the owner, and fetchers for
the entry accounts, such as fetchAllJournalEntryState.
Add a journal component
Createapp/components/journal-card.tsx. It reads the connected wallet’s
entries, and builds and sends the create, update and delete instructions with
the template’s useSendTransaction hook, which has the wallet sign each
transaction:
app/components/journal-card.tsx
getProgramAccounts: every
journal entry account stores its owner right after Anchor’s 8-byte
discriminator, so a memcmp filter at offset 8 returns only the connected
wallet’s entries. The title input is capped at 32 bytes, the same limit the
program enforces.
Show the journal on the page
Inapp/page.tsx, replace the vault card with the journal card:
app/page.tsx
VaultCard import and the <VaultCard /> element it replaces.
Run the app
http://localhost:3000, pick the cluster you deployed to in the cluster
menu (localnet for Surfpool), and connect a wallet. On localnet, use the
Airdrop button to fund the wallet; on devnet, use the
Solana Faucet. Then create, update and delete
journal entries.
Resources
nextjs-anchortemplate: solana-foundation/templates- Anchor account constraints
- Codama