Deploy Your First Solana Program

Build, deploy, and test your first program to the Solana Blockchain using the Anchor framework. This guide will help you become more familiar with the Solana Playground and prepare you to use program derived addresses (PDA) and cross-program invocation (CPI).

Create Anchor Project

  1. Open the Solana Playground in your web browser
  2. On the left panel, click + Create a new project
  3. Enter a Project name
  4. Select Anchor (Rust) as the framework
  5. Click Create

New ProjectNew Project

The src/lib.rs source file will open. It contains one struct called Initialize, which does the following:

  • Receives a required parameter called data: u64
  • Creates a new account
  • Saves the value of data: u64 to the new account
  • Adds a message to the transaction's program logs
lib.rs
use anchor_lang::prelude::*;
// This is your program's public key and it will update
// automatically when you build the project.
declare_id!("11111111111111111111111111111111");
#[program]
mod hello_anchor {
use super::*;
pub fn initialize(ctx: Context<Initialize>, data: u64) -> Result<()> {
ctx.accounts.new_account.data = data;
msg!("Changed data to: {}!", data); // Message will show up in the tx logs
Ok(())
}
}
#[derive(Accounts)]
pub struct Initialize<'info> {
// We must specify the space in order to initialize an account.
// First 8 bytes are default account discriminator,
// next 8 bytes come from NewAccount.data being type u64.
// (u64 = 64 bits unsigned integer = 8 bytes)
#[account(
init,
payer = signer,
space = 8 + 8
)]
pub new_account: Account<'info, NewAccount>,
#[account(mut)]
pub signer: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct NewAccount {
data: u64
}

Build and Deploy the Program

  1. Compile the program code
Terminal
$
build

Your program ID, defined in declare_id!(), will now be updated.

  1. Add SOL to your wallet (Optional)

Deploying a program requires SOL in the program's on-chain account. If necessary, add SOL to your wallet before proceeding to step 3.

  1. Deploy the program to the network
Terminal
$
deploy

When deployed, the program's bytecode is stored in an executable program account.

Note: If preferred, you can use the Build and Deploy buttons on the left-side panel, as shown in the screenshot below.

Build and DeployBuild and Deploy

Test the Program

  1. Open the test file called tests/anchor.test.ts. This file demonstrates how to invoke the program's initialize struct from the client.
anchor.test.ts
// No imports needed: web3, anchor, pg and more are globally available
describe("Test", () => {
it("initialize", async () => {
// Generate keypair for the new account
const newAccountKp = new web3.Keypair();
// Send transaction
const data = new BN(42);
const txHash = await pg.program.methods
.initialize(data)
.accounts({
newAccount: newAccountKp.publicKey,
signer: pg.wallet.publicKey,
systemProgram: web3.SystemProgram.programId
})
.signers([newAccountKp])
.rpc();
console.log(`Use 'solana confirm -v ${txHash}' to see the logs`);
// Confirm transaction
await pg.connection.confirmTransaction(txHash);
// Fetch the created account
const newAccount = await pg.program.account.newAccount.fetch(
newAccountKp.publicKey
);
console.log("On-chain data is:", newAccount.data.toString());
// Check whether the data on-chain is equal to local 'data'
assert(data.eq(newAccount.data));
});
});
  1. Run the test file
Terminal
$
test
  1. Store the transaction hash (TxHash) included in the output

(In the example above, the transaction hash is 3TewJtiUz1EgtT88pLJHvKFzqrzDNuHVi8CfD2mWmHEBAaMfC5NAaHdmr19qQYfTiBace6XUmADvR4Qrhe8gH5uc.)

Note: If preferred, you can use the Test button on the left-side panel.

Run TestRun Test

  1. Run solana confirm -v [TxHash] to view the transaction logs
Terminal
$
solana confirm -v 3TewJtiUz1EgtT88pLJHvKFzqrzDNuHVi8CfD2mWmHEBAaMfC5NAaHdmr19qQYfTiBace6XUmADvR4Qrhe8gH5uc
  1. View the transaction details

Open either SolanaFM or Solana Explorer and search for the transaction hash.

Solana Explorer: Set the network cluster to devnet, to match that of the Solana Playground.

Close the Program

Close the program to recover the SOL allocated to the on-chain program. To do so, run solana program close [ProgramID], using the program address stored in the declare_id!() macro.

Terminal
$
solana program close 2VvQ11q8xrn5tkPNyeraRsPaATdiPx8weLAD8aD4dn2r

Programs can only be closed or updated by an account with upgrade authority. Your Playground wallet automatically becomes the upgrade authority for each program when it is deployed. If the upgrade authority is revoked, the program becomes immutable.

Congratulations! You built and deployed your first Solana program using Anchor.

Next steps

Now that you have deployed your first program, you are ready to explore program-derived addresses and cross-program invocation.

Is this page helpful?

सामग्री तालिका

पृष्ठ संपादित करें
Deploy Your First Solana Program | Solana