Program Derived Address
In this section, we'll walk through how to build a basic CRUD (Create, Read, Update, Delete) program. The program will store a user's message using a Program Derived Address (PDA) as the account's address.
The purpose of this section is to guide you through the steps for building and testing a Solana program using the Anchor framework and demonstrating how to use PDAs within a program. For more details, refer to the Programs Derived Address page.
For reference, here is the final code after completing both the PDA and CPI sections.
Starter Code
Begin by opening this Solana Playground link with the starter code. Then click the "Import" button, which will add the program to your list of projects on Solana Playground.
Import
In the lib.rs
file, you'll find a program scaffolded with the create
,
update
, and delete
instructions we'll implement in the following steps.
Before we begin, run build
in the Playground terminal to check the starter
program builds successfully.
Define Message Account Type
First, let's define the structure for the message account that our program will create. This is the data that we'll store in the account created by the program.
In lib.rs
, update the MessageAccount
struct with the following:
Build the program again by running build
in the terminal.
We've defined what our message account will look like. Next, we'll implement the program instructions.
Implement Create Instruction
Now, let's implement the create
instruction to create and initialize the
MessageAccount
.
Start by defining the accounts required for the instruction by updating the
Create
struct with the following:
Next, implement the business logic for the create
instruction by updating the
create
function with the following:
Rebuild the program.
Implement Update Instruction
Next, implement the update
instruction to update the MessageAccount
with a
new message.
Just as before, the first step is to specify the accounts required by the
update
instruction.
Update the Update
struct with the following:
Next, implement the logic for the update
instruction.
Rebuild the program
Implement Delete Instruction
Next, implement the delete
instruction to close the MessageAccount
.
Update the Delete
struct with the following:
Next, implement the logic for the delete
instruction.
Rebuild the program.
Deploy Program
The basic CRUD program is now complete. Deploy the program by running deploy
in the Playground terminal.
Set Up Test File
Included with the starter code is also a test file in anchor.test.ts
.
Add the code below inside describe
, but before the it
sections.
Run the test file by running test
in the Playground terminal to check the file
runs as expected. We will implement the tests in the following steps.
Last updated on