Getting Started with Solana Smart Contracts from Scratch

·

Solana has emerged as one of the most high-performance blockchain platforms, offering fast transaction speeds, low fees, and robust support for decentralized applications (dApps). At the heart of these dApps are smart contracts—called programs in Solana—written in Rust and deployed on-chain to enable trustless interactions. This guide walks you through setting up your development environment, writing your first Solana program, and deploying it locally or on Devnet.

Whether you're new to blockchain or expanding your expertise into Solana development, this step-by-step tutorial provides everything you need to get started building on Solana.


Understanding the Solana CLI

The Solana Command Line Interface (CLI) is a powerful tool that allows developers to interact directly with the Solana network. It enables you to configure your environment, manage accounts, deploy programs, and monitor on-chain activity—all from your terminal.

To view all available commands, run:

solana --help

This will display a full list of operations supported by the CLI.

Configuring the Solana CLI

The CLI stores configuration settings that determine how it interacts with the network. You can check your current setup using:

solana config get

This returns key information such as:

You can update any setting using solana config set. For example, to switch between clusters:

solana config set --url localhost
solana config set --url devnet
solana config set --url mainnet-beta

Similarly, set a custom keypair:

solana config set --keypair ~/your-keypair.json

👉 Discover how to securely manage your keys and interact with Solana programs using advanced tools.


Setting Up a Local Test Validator

For efficient testing and debugging, running a local test validator is often more effective than deploying directly to Devnet. The local validator simulates the Solana network on your machine.

Start it with:

solana-test-validator

This command launches a local cluster in a separate terminal window. It runs continuously and allows you to deploy and test programs without consuming real funds.

Ensure your CLI is configured to use localhost:

solana config set --url localhost

Streaming Program Logs

Monitoring logs is essential during development. Open another terminal and run:

solana logs

This streams real-time log output from the connected cluster. When working locally, it shows logs from your test validator.

On public clusters like Devnet, specify a program ID to filter logs:

solana logs <PROGRAM_ID>

Alternatively, use grep to isolate specific calls:

solana logs | grep "<PROGRAM_ID> invoke" -A 5

This helps track function invocations and debug execution flow.


Managing Keys and Balances

Secure account management is critical in blockchain development.

Generate a new keypair:

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

Check your public address:

solana address

View your current balance:

solana balance

Request test SOL tokens (airdrops) on Devnet or localhost:

solana airdrop 5

Note: Airdrops on Devnet are limited to 5 SOL per request.

Common issues during development include:

Using the above commands regularly helps avoid these pitfalls.


Building Your First Solana Program

While online playgrounds are useful, a local development environment offers greater flexibility—especially when integrating with client-side applications.

Creating a New Rust Project

Solana programs are written in Rust. Start by creating a new library project:

cargo new --lib solana-hello-world-local

Then update Cargo.toml to include Solana dependencies:

[package]
name = "solana-hello-world-local"
version = "0.1.0"
edition = "2021"

[dependencies]
solana-program = "~1.8.14"

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

Add the [lib] section to ensure proper compilation for BPF (Berkeley Packet Filter), Solana’s runtime environment.


Writing the Smart Contract

Edit src/lib.rs with the following code—a simple "Hello World" program:

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(())
}

This program uses the msg! macro to print a message to the program log whenever it's invoked.


Compiling and Deploying

Build the program for Solana’s BPF runtime:

cargo build-bpf

The output includes a deployment command like:

solana program deploy /path/to/program.so

Deploy it using:

solana program deploy target/deploy/solana_hello_world_local.so

The CLI returns the Program ID, which you can use to interact with your deployed contract.

👉 Learn how to analyze deployed programs and verify their behavior securely.


Full Walkthrough: Deploying Locally

Let’s walk through deploying the "Hello World" program step by step.

  1. Set CLI to Localhost

    solana config set --url localhost
  2. Launch Test Validator
    In a new terminal:

    solana-test-validator
  3. Build the Program

    cargo build-bpf
  4. Deploy the Program
    Use the path from the build output:

    solana program deploy target/deploy/solana_hello_world_local.so
  5. Monitor Logs
    In another terminal:

    solana logs <PROGRAM_ID>
  6. Invoke the Program
    Use a client script (e.g., Node.js with @solana/web3.js) to call the program. Replace <PROGRAM_ID> in your script and run:

    npm install && npm start
  7. Verify Output
    Check the transaction on Solana Explorer by pasting the URL returned by the client. Confirm that “Hello, world!” appears in the logs.

Congratulations—you’ve built, deployed, and executed your first Solana smart contract!


Challenge: Deploy to Devnet

Now try deploying your program to Devnet:

  1. Update your CLI:

    solana config set --url devnet
  2. Airdrop test SOL:

    solana airdrop 5
  3. Rebuild and redeploy:

    cargo build-bpf
    solana program deploy target/deploy/solana_hello_world_local.so
  4. Update your client script to connect to Devnet:

    let connection = new web3.Connection(web3.clusterApiUrl("devnet"));
  5. Adjust explorer links:

    console.log(`Transaction: https://explorer.solana.com/tx/${tx}?cluster=devnet`);

Use filtered logs to monitor your program:

solana logs <PROGRAM_ID>

Frequently Asked Questions (FAQ)

What is a Solana program?

A Solana program is equivalent to a smart contract on other blockchains. It's a stateless, immutable piece of code written in Rust and deployed on-chain to process instructions and modify account data.

Can I redeploy a Solana program?

Yes, but only if you deploy it to the same Program ID. By default, each deployment generates a new address. To upgrade, save the keypair used during initial deployment and reuse it with --program-id.

Why do I need BPF compilation?

Solana uses BPF (Berkeley Packet Filter) as its execution runtime for efficiency and security. All programs must be compiled into BPF bytecode before deployment.

How do I debug a failed transaction?

Use solana logs <PROGRAM_ID> to view detailed execution traces. Combine with error codes from TransactionError in responses for precise diagnosis.

Is it safe to use solana-test-validator for production testing?

The test validator is ideal for local development but does not fully replicate network conditions like congestion or consensus behavior. Always test on Devnet before mainnet deployment.

How are Solana programs upgraded?

Programs can be marked as upgradeable during deployment. This requires storing the program data in a separate account and managing upgrades via a designated authority.

👉 Explore secure deployment practices and learn how top developers audit their Solana programs.


Core Keywords: Solana smart contract, Solana CLI, Rust blockchain development, Solana program deployment, BPF compilation, local test validator, Devnet deployment, Solana logs