Solana Smart Contract Building – An Introduction

Illustration of code meant for Solana smart contract development.
Table of Contents

Are you looking to develop dapps or other Web3 projects for the Solana network? If so, you are in the right place, as this tutorial will delve deep into Solana smart contract building and demonstrate how to create your own contract! Along with writing an actual Solana smart contract, this “Solana Smart Contract Building” tutorial will also showcase how to deploy and call the contract using a simple testing application. Creating the smart contract testing application is relatively straightforward, thanks to Moralis‘ Ethereum boilerplate, which is Solana compatible. All you need to do is clone the template and make a few simple configurations! 

The accessibility of setting up the dapp partly originates from Moralis’ Web3 template. However, Moralis does not only enable you to develop projects for Ethereum and Solana but features additional boilerplates alike. As such, if you are interested in developing dapps for other networks, you can, for example, check out the Avalanche boilerplate or Cronos boilerplate. Thanks to the boilerplates – and other tools – Moralis presents the fastest way to build a Web3 app for any network! 

So, if you want to write smart contracts or build Web3 dapps, sign up with Moralis right now entirely for free!

Exploring the Solana Network

Solana is an open-source, programable blockchain focusing on speed and scalability, allowing the network to facilitate transactions quickly and at low costs. Moreover, the “programable” characteristic of the blockchain indicates that Solana supports smart contracts. Solana smart contracts are programs running on the Solana blockchain, and they are crucial components of the network’s ecosystem since they mediate agreements between network participants. Consequently, smart contracts make it possible for developers to build sophisticated dapps (decentralized applications) and other Web3 projects powered by Solana. 

Now, before we dive deeper into the main topic of this article, let’s explore Solana and the network’s smart contracts a bit further!

What are Solana Smart Contracts? 

Let’s now return to the basics. To simplify the explanation, we will break down the concept (Solana smart contracts) into two parts: the Solana network and smart contracts, and begin by explaining these components separately!

Solana Labs – the organization behind the network – first launched Solana’s programmable, open-source blockchain in 2017. The fact that Solana is programmable means that the network features smart contracts, allowing developers to build Web3 projects and dapps powered by the Solana blockchain. 

Black letters stating "Solana" on a white background.

Solana implements a hybrid consensus mechanism combining PoH (proof-of-history) and PoS (proof-of-stake). Using the two mechanisms enables Solana to keep the transaction speed high and costs minimal. Furthermore, the emphasis on speed and scalability makes Solana programming faster and more economically friendly than some competitors. 

With a quick introduction to Solana, we will now take a closer look at smart contracts. In short, smart contracts – also referred to as Web3 contracts – are programs built and stored on a blockchain network. Furthermore, smart contracts have predefined conditions along with predefined actions. Consequently, when these conditions meet, the actions defined within the contract autonomously execute. Based on this, it suggests that smart contracts are perfect for automating agreements without the need for unnecessary intermediaries taking a cut for facilitating transactions. 

So, in the context of Solana, a smart contract is basically a program stored on the Solana blockchain! 

With a somewhat better understanding of a Solana smart contract, it is now time to explore the intricacies of Solana smart contract building. As such, the following sections will demonstrate how to build a Solana smart contract easily! 

Solana Smart Contract Building – Step-by-Step Process on How to Build a Smart Contract

In the following sections, we’ll delve deep into Solana smart contract building and show you how to create your own Solana smart contract. We will additionally demonstrate how to deploy and call the contract. However, to call the contract, you must set up a testing dapp. To make this entire process more understandable, we will divide the Solana smart contract building process into the following three steps: 

  1. Rust and Solana CLI Setup
  2. Write and Deploy the Solana Smart Contract
  3. Create the Testing Application

Following the three steps above will allow you to create, deploy, and call the Solana smart contract using a testing application. To show what you are working towards, this will be the landing page for the app: 

The landing page of our dapp showing a "Hello World" title and a "Run Program" button.

As the above image illustrates, you can click on the ”Run Program” button. This will prompt your Solana Web3 wallet, allowing you to sign a message and call the smart contract. Once called, the app will display the data log from the contract, which, in this case, is a ”Hello World!!” message: 

Message stating "Program log: Hello World!!" on the dapp's page.

Nevertheless, if you like watching videos to learn instead of reading, you can instead check out the video below covering the aforementioned steps. Also, the clip provides a more detailed breakdown of the app’s code if this interests you! 

Step 1: Rust and Solana CLI Setup

To begin with, the first step of this tutorial on Solana smart contract building revolves around setting up Rust and the Solana CLI. If you are already familiar with these two components, feel free to skip this initial step and jump straight into the process of building and deploying the Solana smart contract. However, if you are new to Rust and Solana, worry not; this section provides a complete breakdown of the setup processes, starting with Rust! 

The first part of this initial step is to open a Unix terminal. With the terminal open, you can initiate the installation process for Rust by inputting the following command:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

The terminal will present a few installation options as soon as you run this command. For this tutorial, you want to pick the ”default” option by inputting a ”1” and pressing enter. This is what it should look like in your terminal: 

Three lines with three different messages in the terminal: Proceed with installation, Customize installation, and Cancel installation.

Once you select the installation option, it should begin installing Rust for you. When the installation finalizes, the next part of this initial step is to install the Solana CLI. To install the CLI, input the following into your terminal: 

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

Running the command above will install the Solana CLI, and you will need to set the ”env path” when it finalizes. This will be displayed in the terminal and should look something like this: 

Message in the terminal stating: "Rust is installed".

With the path set, you now need to set up a new local file system and Solana wallet key-pair using these two commands: 

mkdir ~/my-solana-wallet
solana-keygen new --outfile ~/my-solana-wallet/my-keypair.json

With a local Solana wallet at your disposal, it is time to set a target cluster. In this instance, we will target the devnet cluster with the following command: 

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

Finally, once you have specified the devnet cluster, this last command will add some test SOL to your wallet: 

solana airdrop 1

Step 2: Write and Deploy the Solana Smart Contract

With Rust and the Solana CLI all set up, it is time to delve deeper into Solana smart contract building. Hence, this part outlines the process of writing and deploying Solana smart contracts. Further, you must first open your preferred IDE or ”integrated development environment” to do so. 

For this tutorial, we are using VSC (Visual Studio Code). If you use another IDE, note that the process might occasionally differ. Nevertheless, once your IDE is open, the next step is to set up a new folder and open a new terminal. If you are using VSC, click on the ”Terminal” tab at the top and hit ”New Terminal”: 

The terminal showing the "New terminal" button to start exploring Solana smart contract building.

With a terminal open, you can create a new project using Cargo by running the following command in the terminal: 

cargo init hello_world --lib

Running the command above will set up a new Cargo library in your local directory with all the files you need for Solana smart contract building: 

The "hello_world" file inside the IDE.

Next up, progress by navigating to the ”hello_world” project folder using the command below: 

cd hello_world

Following this, you can go ahead and open the ”Cargo.toml” file and add the following code snippet at the end of the file: 

[lib]
name = "hello_world"
crate-type = ["cdylib", "lib"]

This is what it should look like: 

The editor showing code inside the "Cargo.toml" file.

Now, before writing the actual contract, go ahead and add the Solana program package by running the command below in the terminal:

cargo add solana_program

Lastly, it is now time to write the Solana smart contract itself. To do so, navigate to the ”src/lib.rs” file and remove all the code. First up, import the Solana program by adding this code snippet to the file: 

use solana_program::{
    account_info::AccountInfo,
    entrypoint,
    entrypoint::ProgramResult,
    pubkey::Pubkey,
    msg,
};

Following this, specify the “entrypoint” using the ”process_instruction” function: 

entrypoint!(process_instruction);

Finally, add the ”process_instruction” function: 

pub fn process_instruction(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    instruction_data: &[u8]
) -> ProgramResult {

    msg!("Hello, world!");

    Ok(())
}

Nevertheless, this should be the final version of the ”src/lib.rs” file: 

use solana_program::{
    account_info::AccountInfo,
    entrypoint,
    entrypoint::ProgramResult,
    pubkey::Pubkey,
    msg,
};

entrypoint!(process_instruction);

pub fn process_instruction(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    instruction_data: &[u8]
) -> ProgramResult {

    msg!("Hello, world!");

    Ok(())
}

Deploying the Contract

With the contract written, you can go ahead and build the Solana smart contract by inputting this command into the terminal and hitting enter: 

cargo build-bpf

Lastly, all that remains is to deploy the smart contract using the Solana deploy command: 

solana program deploy ./target/deploy/hello_world.so

Once you run the command, it should provide a program ID in return. Make sure to keep this ID close at hand since you will need this in the following section: 

The Solana smart contract building command: solana program deploy ./target/deploy/hello_world.so.

That concludes the step of writing and deploying the contract! In the following section, you will learn how to set up the testing application from which you can call the Solana smart contract. In turn, it will allow you to ensure that the contract works as intended! 

Step 3: Create the Testing Application

With the contract written and deployed, it is time to create an application you can use to call and test the Solana smart contract. To make the process as accessible as possible, you can clone a template based on Moralis’ Ethereum boilerplate, allowing you to build the application in no time! 

Solana Smart Contract Testing App – https://github.com/johnvsnagendra/solana-smart-contract-helloWorld 

To clone the testing application, open the project’s GitHub repository with the link above. From there, click on the ”Code” button and copy the repo URL: 

Cloning the code for the "Solana smart contract building" project on GitHub.

Next up, open your IDE once again, create a new folder for the project, and open a new terminal. You can then clone the project using the following command with the repository URL: 

git clone “REPOSITORY_URL”

Running the command above will clone the project to your local device. However, you must make two configurations before launching and testing the app. First, open the ”.env.local.example” file and rename the file ”.env.local”. From there, you must add your Moralis Web3 API key to the ”MORALIS_API_KEY” variable. 

If you have not already, you must create a Moralis account to get the key. To get going, click on the ”Start for Free” button at the top of the Moralis website and follow the instructions: 

Moralis' homepage showing the "Start for Free" button.

Once you log in, navigate to the ”Account” tab, click on ”Keys”, and copy the Web3 API key: 

Account Settings page after logging in to Moralis.

Now that you have added the API key to the environment variables, open the ”/src/components/templates/helloWorld/HelloWorld.tsx” file. You can then scroll down to the nineteenth line and add the program ID you received when deploying your contract: 

The programID variable where you need to enter in your ID.

Call the Smart Contract

Adding the Moralis Web3 API key and program ID covers the necessary configurations to the code. Now, all that remains is to launch the application, call the smart contract, and ensure that everything works as intended. 

As such, you should now be able to launch the app in your browser, click on the ”Run Program” button, and sign the message to run the smart contract. This should return the ”Hello World!!” message: 

The result of finalizing this "Smart contract building" tutorial: a page displaying the "Hello World!!" message.

If the testing app returns the message, you know that the smart contract works as it should! However, if you experienced trouble during the process, check out the video we linked earlier. You can also join Moralis’ Discord channel to ask our talented community engineers any questions you might have!

Summary – Solana Smart Contract Building

This article explores the intricacies of Solana smart contract building. Accordingly, the article explains how to write, deploy, and test a Solana smart contract. Moreover, to make the process more straightforward, the tutorial was divided into the following three steps: 

  1. Rust and Solana CLI Setup
  2. Write and Deploy the Solana Smart Contract
  3. Create the Testing Application

The accessibility of this ”Solana Smart Contract Building” guide originates from Moralis. For example, you can set up the testing application easily thanks to Moralis’ Ethereum boilerplate. That template utilizes various Moralis Web3 APIs, including the Web3 Auth API. This API allows you to integrate authentication mechanisms into any of your Web3 projects easily. If this sounds interesting, you can, for example, learn how to add Coinbase Wallet login functionality

Moreover, if you found this guide helpful, check out more content here at Moralis’ Web3 blog. For instance, learn how to build a Solana NFT explorer or create your own Solana NFT

Nevertheless, it does not matter if you want to develop Solana projects or build dapps; Moralis makes all development endeavors feel like a breeze! As such, sign up with Moralis immediately and increase your efficiency for all future development endeavors!

October 19, 2022
Join the Moralis Community
Get the latest Moralis Web3 news and updates via email.
Search
Generic filters
MOralis launched
Streams API
Real-Time blockchain data delivered to your backend via webhooks. Used by the biggest dapps.
Real-Time blockchain data delivered to your backend via webhooks. Used by the biggest dapps.
Follow us on Twitter
Real-Time blockchain data delivered to your backend via webhooks. Used by the biggest dapps.
Related Articles