Intermediate

How to Build and Deploy a Solana Smart Contract

Welcome to this tutorial on how to build and deploy a Solana smart contract. In this tutorial, we will guide you through the process of creating a simple “Hello World” program in Rust, and deploying it to the Solana devnet. This tutorial assumes that you have a basic understanding of programming and the Solana blockchain. It is also assumed that you have NodeJS, NPM, Rust, the Solana CLI, and Git installed on your machine. Follow along with the tutorial to learn how to deploy your own smart contracts on the Solana blockchain.

Requirements

The following should be installed before proceeding:

NodeJS v14 or greater & NPM

The latest stable Rust build

Solana CLI v1.7.11 or later

Git

The HelloWorld Program

The first section defines some standard Solana program parameters and defines an entry point for the program (the ‘process_instruction’ function). In addition to this, it uses borsh for serializing and deserializing parameters being passed to and from the deployed program.

use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint,
entrypoint::ProgramResult,
msg,
program_error::ProgramError,
pubkey::Pubkey,
};

 

/// Define the type of state stored in accounts
#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub struct GreetingAccount {
/// number of greetings
pub counter: u32,
}

// Declare and export the program's entrypoint
entrypoint!(process_instruction);

 

The process_instruction function accepts the program_id, which is the public key where the program is deployed to, and accountInfo, which is the account to say hello to.

pub fn process_instruction(
program_id: &Pubkey, // Public key of the account the hello world program was loaded into
accounts: &[AccountInfo], // The account to say hello to
_instruction_data: &[u8], // Ignored, all helloworld instructions are hellos

 

The ProgramResult is where the main logic of the program resides. In this case, it simply prints a message, then selects the accounts by looping through ‘accounts’. However, in our example there will only be one account.

) -> ProgramResult {
msg!("Hello World Rust program entrypoint");

// Iterating accounts is safer then indexing
let accounts_iter = &mut accounts.iter();

// Get the account to say hello to
let account = next_account_info(accounts_iter)?;

 

Next, the program checks to see if the account has permission to modify the data for the specified account.

// The account must be owned by the program in order to modify its data
if account.owner != program_id {
msg!("Greeted account does not have the correct program id");
return Err(ProgramError::IncorrectProgramId);
}

 

Finally, the function takes the existing account’s stored number, increases the value by one, writes the result back, and displays a message

// Increment and store the number of times the account has been greeted
let mut greeting_account = GreetingAccount::try_from_slice(&account.data.borrow())?;
greeting_account.counter += 1;
greeting_account.serialize(&mut &mut account.data.borrow_mut()[..])?;

msg!("Greeted {} time(s)!", greeting_account.counter);

Ok(())

 

Deploying the Program

The first step is to clone the repository.

git clone https://github.com/solana-labs/example-helloworld
cd example-helloworld

Once this is done, you can then set your current environment to devnet. This is the test network for Solana developers writing and testing smart contracts.

solana config set --url https://api.devnet.solana.com

 

 
Next, you need to create a new keypair for your account. This is required to interact with deployed programs (smart contracts) on the Solana devnet. Take note: this is an insecure method for storing keys and should only be used for demo purposes. You will be prompted to enter in a passphrase for security reasons.
solana-keygen new --force

 

 

Now that you’ve created an account, you can use the airdrop program to obtain some SOL tokens. You will need some lamports (fractions of SOL tokens) to deploy your smart contract. This command requests SOL tokens into your newly generated account:

solana airdrop 2

 

 

You’re now ready to build the hello world program. You can build it by running the following command

npm run build:program-rust

 

It will take some time depending on your internet speed, Once the program has been built, you can then deploy it to devnet. The previous command’s output will give you the command that you need to run, but it should look something similar to the following:

solana program deploy dist/program/helloworld.so

 

The end result is that you have successfully deployed the hello world program to devnet with an assigned program Id. This can then be checked on the Solana Devnet explorer.

Interacting With the Deployed Program

Running the Client

Before you can run the client to read data from your deployed program, you need to install the client dependencies.

 
npm install

 

Once this is done, you can start the client.

 

npm run start

 

You should see output showing your program successfully being executed, and it should display the number of times the account has been greeted. Subsequent runs should increase this number.

Congratulations, you’ve deployed and interacted with a Solana smart contract on the devnet network!