Solana is a decentralized blockchain ecosystem designed to overcome the scalability and congestion issues that plague older blockchain networks. Capable of processing up to 710,000 transactions per second on a standard gigabit network, Solana offers exceptional speed and efficiency, making it a popular choice for developers and businesses alike.
Often referred to as an "Ethereum Killer," Solana has rapidly grown in prominence. Its Total Value Locked (TVL) surged dramatically in a short span, reflecting the expanding ecosystem of decentralized applications and the increasing adoption of Solana for token and smart contract development.
With its robust capabilities and innovative features, Solana presents a significant opportunity to transform various business sectors. This guide provides a comprehensive overview of how to build and deploy smart contracts on the Solana blockchain.
Understanding the Solana Blockchain
At its core, Solana is an open-source blockchain focused on delivering high scalability. It achieves this through a unique architecture that enables a high number of transactions per second (TPS) and extremely fast confirmation times. The project leverages groundbreaking technologies from industry leaders, ensuring it maintains high-performance standards.
Beyond offering fast and cost-effective transactions, Solana supports smart contract development using popular programming languages like Rust, C++, and C. This flexibility opens the door for a wide range of developers to build on its network.
How Solana Smart Contracts Work
Solana’s smart contract model differs significantly from traditional Ethereum Virtual Machine (EVM) based blockchains. On EVM networks, a smart contract typically bundles both its logic (the code) and its state (the data) into a single on-chain contract.
On Solana, this model is separated. Smart contracts, known as programs, are stateless and contain only the program logic. Once deployed, these programs are accessed by external accounts that interact with them. These accounts are then responsible for storing the data generated from these interactions. This separation of logic and state is a fundamental architectural difference.
Furthermore, accounts on Solana serve a different purpose. While Ethereum accounts are primarily references for user wallets, Solana accounts are designed to store data. This design, combined with a Command Line Interface (CLI) and a JSON RPC API, facilitates smoother interactions for decentralized applications (dApps) within the ecosystem.
The Solana Development Workflow
Building on Solana involves two primary components that work in tandem:
- The Program (Smart Contract): This refers to the development and deployment of custom programs written in Rust, C, or C++ onto the Solana blockchain. Once deployed, these programs are available for anyone to use.
- The Client (dApp): This involves building dApps—such as crypto wallets, decentralized exchanges, and more—that communicate with the deployed programs. These client applications use Software Development Kits (SDKs) to submit transactions to the programs via the JSON RPC API.
Together, the Program and the Client form a complete network of interactive applications and services on the blockchain.
Prerequisites for Solana Smart Contract Development
Before you begin building, you need to set up your development environment. Ensure you have the following tools installed:
- NodeJS version 14 or higher and NPM
- The latest stable version of the Rust build
- Solana Command Line Interface (CLI) version 1.7.11 or later
- Git
A Step-by-Step Guide to Building a Smart Contract
We will walk through creating and deploying a simple "HelloWorld" smart contract written in Rust. This program will log a message to the console and keep track of how many times it has been called by storing a count on-chain.
1. Setting Up the Development Environment
For developers using Windows, it is recommended to use the Windows Subsystem for Linux (WSL) with an Ubuntu distribution. This environment simplifies the process of compiling Rust code into the required .so file format.
Run the following commands in your WSL terminal to set up the necessary environment:
sudo apt upgrade && sudo apt update
sudo apt install nodejs npm python3-pip
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
sh -c "$(curl -sSfL https://release.solana.com/v1.5.7/install)"
source $HOME/.cargo/env
export PATH="/root/.local/share/solana/install/active_release/bin:$PATH"
export RUST_LOG=solana_runtime::system_instruction_processor=trace,solana_runtime::message_processor=debug,solana_bpf_loader=debug,solana_rbpf=debug
solana-test-validator --logAfter setting up, test the environment by cloning and running the Hello World example:
git clone https://github.com/solana-labs/example-helloworld.git
cd example-helloworld/
npm install
npm run build:program-rust2. Writing the Smart Contract Code
The HelloWorld program uses the BORSH serializer for handling parameters. The code is structured into key functions.
First, the entry point and data structure are defined:
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint,
entrypoint::ProgramResult,
msg,
program_error::ProgramError,
pubkey::Pubkey,
};
#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub struct GreetingAccount {
pub counter: u32,
}
entrypoint!(process_instruction);The process_instruction function is the program's entry point:
pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
_instruction_data: &[u8],
) -> ProgramResult {
msg!("Hello World Rust program entrypoint");
let accounts_iter = &mut accounts.iter();
let account = next_account_info(accounts_iter)?;
if account.owner != program_id {
msg!("Greeted account does not have the correct program id");
return Err(ProgramError::IncorrectProgramId);
}
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(())
}This function retrieves the target account, checks its permissions, deserializes its data, increments the counter, and then logs the result.
3. Deploying the Smart Contract
With the code written, the next step is deployment to the Solana Devnet, a test network for developers.
Clone the example repository and configure the CLI to use Devnet:
git clone https://github.com/solana-labs/example-helloworld
cd example-helloworld
solana config set --url https://api.devnet.solana.comGenerate a new keypair for your account and request test SOL tokens via an airdrop:
solana-keygen new --force
solana airdrop 5Build the Rust program:
npm run build:program-rustFinally, deploy the compiled program to Devnet. The build output will provide the exact deploy command, which will look similar to:
solana program deploy dist/program/helloworld.soUpon successful deployment, you will receive a program ID. You can use this ID to verify your program on the Solana Devnet explorer.
Frequently Asked Questions
What programming languages can I use for Solana smart contracts?
Solana smart contracts, known as programs, can be written in Rust, C, or C++. Rust is the most commonly used and recommended language due to its performance and safety features, which are ideal for blockchain development.
What is the difference between an account and a program on Solana?
On Solana, a program is the stateless smart contract that contains the executable logic. An account is a data storage entity that holds the state or information related to interactions with a program. This separation of logic and state is a key architectural feature.
Why is Solana considered highly scalable?
Solana achieves high scalability through its innovative consensus mechanism, Proof of History (PoH), which creates a historical record of events. Combined with its high throughput capacity, this allows the network to process tens of thousands of transactions per second very efficiently.
Do I need real SOL to deploy on Devnet?
No, you do not need real SOL tokens for development and testing on the Devnet. You can obtain test SOL through the solana airdrop command, which provides tokens that have no real-world value.
How do I interact with my deployed smart contract?
You interact with a deployed program by building a client-side dApp using Solana's JavaScript SDK or other available client SDKs. This dApp submits transactions to your program's endpoint using the JSON RPC API. For a comprehensive suite of tools to manage your assets, you can explore more strategies.
What kinds of applications can I build on Solana?
Solana's high speed and low transaction costs make it suitable for a wide array of applications, including decentralized finance (DeFi) platforms, non-fungible token (NFT) marketplaces, decentralized exchanges (DEXs), Web3 applications, and more. To bring your project idea to life, you can get advanced methods.