Introduction
Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.
I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.
I also build and publish a variety of tools, libraries, and open-source projects.
This article walks through Hello Solana, one of the Solana Playground tutorials, explaining each part along the way.
The explanation also draws on the official documentation.
As the first article in the series, this walkthrough goes into considerable detail. Feel free to focus on the sections relevant to you.
solana_program

use solana_program::{
account_info::AccountInfo,
entrypoint,
entrypoint::ProgramResult,
msg,
pubkey::Pubkey,
};solana_program is the foundational library used by contracts written in Rust that run on the Solana blockchain.
It acts as a standard library for Solana programs, providing functions and definitions needed during execution.
Provided functionality
It provides functionality such as the following.
Program entrypoint declaration macro
A macro declares the starting point (entrypoint) of a Solana program. This allows the Solana runtime to begin executing the program correctly.
What is a macro?
In programming languages, macros are a mechanism for automatically generating or reusing portions of code. Macros allow developers to automate more work with less code and implement recurring or common patterns easily. They expand at compile time into code incorporated into the program.
Rust macros are powerful and can significantly improve coding efficiency. For example, Rust's println! and vec! are macros.
They expand into particular code at compile time, which determines the program's runtime behavior.
Macros are particularly useful in the following situations.
- Avoiding repetitive code
- If a code pattern is needed in several places, define it once as a macro and reuse it wherever necessary.
- Improving abstraction and reusability
- Defining common functionality as a macro makes it easy to reuse in different contexts.
- Conditional compilation
- Macros can provide compile-time branching when code must be included or excluded under particular conditions.
Rust macros are powerful, but it is important to use them appropriately. Overusing macros can reduce code readability, so use them only when needed.
Core data types
The library defines fundamental data types required for Solana program development.
Logging macros
Macros for emitting logs during program execution help with debugging and monitoring.
Serialization methods
Methods convert data into formats that can be transmitted and received on the Solana blockchain.
Cross-program instruction execution
The library provides methods for constructing and executing instructions that invoke other programs.
Program IDs and instruction constructors for the system program and other native programs
IDs and functions are provided for using Solana's core functionality.
Sysvar accessors
Functions are provided for accessing Solana's system variables.
Programs executed on the Solana blockchain are built on the solana-program crate.
The Rust standard library is also adapted for Solana's runtime environment.
What is a crate?
A crate is a package of code or a library. Rust projects consist of one or more crates, which compile into executable files or libraries. Crates sit at the top level of Rust's module system and are the fundamental units for building, distributing, and managing dependencies.
There are two main types of crates.
- Binary crate
- A crate that produces an executable file.
- It contains a program entrypoint (the main function) and is intended to be executed on its own.
- A project typically has one binary crate.
- Library crate
- A crate that provides reusable code intended for use by other programs or libraries.
- It provides functions, types, and traits that other crates can use, improving code reusability.
Crate types
Crate types can be specified in Cargo.toml as follows.
- cdylib
- Produces a dynamic-link library (such as
.so,.dll, or.dylib). - This can be used to call Rust code from executables or applications written in other languages.
- Produces a dynamic-link library (such as
- rlib
- The standard format for compiling a Rust library crate.
- Used when linking with other Rust crates.
Dependency management
Cargo, Rust's package manager and build system, manages crates. It resolves dependencies, builds, tests, and generates documentation based on information in Cargo.toml.
Cargo automatically downloads and compiles project dependencies, substantially reducing the effort of dependency management.
Crates play a central role in the Rust ecosystem by promoting modularity, reusability, and code sharing.
Many crates are published to Rust's official package registry, crates.io, where developers can use them freely.
Reference
Off-chain programs (programs running outside the blockchain) that interact with Solana rarely use solana-program directly and generally use the solana-sdk crate instead.
solana-sdk re-exports all modules from solana-program.
Examples of using solana-program are available in the Solana Program Library (SPL).
SPL is a collection of commonly used programs on the Solana platform and is useful for learning practical applications of solana-program.
Defining a Solana program
Compared with ordinary Rust programs, Solana programs have several distinctive characteristics.
Distinctive characteristics of Solana programs
Key points
- Compiled for both on-chain and off-chain environments
- Solana programs are compiled for both environments because, in addition to running on-chain, their data types may need to be accessible to off-chain clients.
- No main function
- Unlike ordinary Rust programs with a
mainfunction, Solana programs define their entrypoint using theentrypoint!macro.
- Unlike ordinary Rust programs with a
- Compiled as the
cdylibcrate type- Solana programs compile as
cdylibcrates so the Solana runtime can load them dynamically.
- Solana programs compile as
- Executed in a restricted VM
- Solana programs run in a restricted virtual machine. They have access to the Rust standard library, but many OS-related functions fail, do nothing, or are undefined at runtime.
What is cdylib?
cdylib is a Rust compilation crate type that produces a binary usable as a C-compatible dynamic-link library (DLL).
It is often used to call Rust libraries from C or other languages.
Characteristics and uses of cdylib
- Compatibility
- The generated dynamic-link library conforms to the C ABI (Application Binary Interface), making it usable from many programming languages, including C.
- Cross-platform distribution
- Libraries can be provided in formats supported by different platforms, including
.so(Linux),.dll(Windows), and.dylib(macOS).
- Libraries can be provided in formats supported by different platforms, including
- Application integration
- Useful for integrating Rust components or libraries into existing applications written in C or other languages.
cdylib use cases
- Plugins for external applications
- Develop safe, efficient plugins or extensions in Rust and load them dynamically into existing applications.
- Integration with existing systems
- Leverage Rust's strong type system and performance to implement specific operations and integrate them into existing systems written in languages such as C.
- Bridging languages
- Develop high-performance libraries in Rust and call them from languages such as Python or Ruby to improve overall application performance.
To use the cdylib crate type, specify it in Cargo.toml as follows.
[lib]
crate-type = ["cdylib"]This configuration makes Cargo generate a C-compatible dynamic-link library when compiling the crate. It makes libraries written in Rust easier to use from other languages.
Solana program skeleton
The basic structure of a Solana program consists of a module defining the entrypoint and a function containing the program logic. The following code snippet illustrates the structure.
#[cfg(not(feature = "no-entrypoint"))]
pub mod entrypoint {
use solana_program::{
account_info::AccountInfo,
entrypoint,
entrypoint::ProgramResult,
pubkey::Pubkey,
};
entrypoint!(process_instruction);
pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
instruction_data: &[u8],
) -> ProgramResult {
todo!()
}
}This code defines the Solana program entrypoint and a process_instruction function that receives a program ID, account information, and instruction data.
The actual program logic is implemented in process_instruction.
Code explanation
This code shows the basic skeleton of a smart contract, or program, written in Rust for the Solana blockchain. Specifically, it demonstrates how to define the program entrypoint, the first function executed when the blockchain invokes the program.
Defining the entrypoint
#[cfg(not(feature = "no-entrypoint"))]- This attribute uses Cargo feature flags to control whether the module is compiled under particular conditions.
- Here, the
entrypointmodule below is compiled only if theno-entrypointfeature is not enabled. - This excludes entrypoint code when it is unnecessary, such as in tests or other contexts.
pub mod entrypoint { ... }- Defines a public module named
entrypoint. - This module defines the functions and logic that serve as the program's entrypoint.
- Defines a public module named
Using the Solana program library
use solana_program::{...};- Imports types and functions needed for Solana program development from the
solana_programcrate. - The imports are
AccountInfo, theentrypointmacro,ProgramResult, andPubkey.
- Imports types and functions needed for Solana program development from the
Setting up the entrypoint function
entrypoint!(process_instruction);- Uses the
entrypoint!macro to registerprocess_instructionas the program's entrypoint. - The Solana runtime executes this function whenever the program is invoked.
- Uses the
Entrypoint function
pub fn process_instruction(...)- The entrypoint function containing the actual program logic.
- It receives the program ID, a list of account information, and instruction data as arguments.
program_id: &Pubkey- The public key (ID) of this program.
accounts: &[AccountInfo]- A list containing information about the accounts involved in the transaction.
instruction_data: &[u8]- Encoded data representing the instruction or command for this transaction.
-> ProgramResult- The function returns
ProgramResult. ProgramResultis an alias forResult<(), ProgramError>, indicating whether program execution succeeded or an error occurred.
- The function returns
Logic to implement
todo!()- Write the code that actually processes the transaction here.
- The
todo!()macro is currently present, indicating that this portion is not yet implemented.
This snippet demonstrates the basic structure of a Solana program. Developers build on this skeleton to implement specific business and transaction-processing logic.
Cargo.toml configuration
A Solana program needs the following configuration in Cargo.toml.
[lib]
crate-type = ["cdylib", "rlib"]
[features]
no-entrypoint = []This ensures that the program is compiled as a cdylib, allowing the Solana runtime to load it dynamically.
Specifying the rlib crate type also makes it possible to link against other Rust crates.
What is Cargo.toml?
Cargo.toml is a Rust project configuration file used by Cargo, the project's build system and package manager.
It contains project metadata (name, version, authors, and so on), dependencies, build configuration, and other project information.
Cargo.toml is written in TOML (Tom's Obvious, Minimal Language), a format designed to be easy to read and edit.
Main sections
[package]- Contains project metadata, including its name, version, authors, and license information.
- These details are important when publishing the project to package registries such as
crates.io.
[dependencies]- Specifies external crates (libraries or frameworks) on which the project depends.
- Each dependency is specified by its crate name and version. Cargo uses this information to download dependencies and link them when building the project.
[dev-dependencies]- Specifies dependencies needed only during development, such as tests and examples.
- These dependencies are not included in production builds.
[build-dependencies]- Specifies dependencies needed to execute build scripts.
- Build scripts run before project compilation and are typically used to configure the build environment.
[lib]- Configures the library crate.
- For example,
crate-typecontrols how the crate is built as a library, such ascdyliborrlib.
[features]- Cargo features can define optional functionality and configurations.
- They allow specific functionality to be enabled and parts of the code to be treated as optional at compile time.
Example
[package]
name = "my_crate"
version = "0.1.0"
authors = ["Author Name <author@example.com>"]
edition = "2018"
[dependencies]
serde = "1.0"
[dev-dependencies]
tokio = "0.2"
[build-dependencies]
cc = "1.0"
[lib]
crate-type = ["cdylib", "rlib"]
[features]
default = []This example defines basic project metadata, several dependencies, the library crate types, and an empty set of default features.
Cargo.toml is a fundamental part of a project,
playing a central role in its build and management.
What are features?
Cargo's features mechanism manages conditional compilation and optional functionality in Rust projects.
It lets developers enable or disable specific parts of a project and compile code with different configurations or sets of features.
Basic concepts
- Feature definitions
- Define project features in the
[features]section ofCargo.toml. - Each feature has a name and a list of dependencies or other features included when it is enabled.
- Define project features in the
- Default features
- The special feature name
defaultspecifies features enabled by default when a project is used as a dependency. - Developers can include features in
defaultthat should always be enabled unless users specify otherwise.
- The special feature name
- Optional dependencies
- Dependencies can be associated with specific features and included in compilation only when the corresponding feature is enabled.
Example
The following example defines features in Cargo.toml.
[features]
# Define the optional "gui" feature
gui = ["serde/json", "tokio"]
# List of features enabled by default
default = ["cli"]This example defines two features, gui and cli.
The gui feature enables the json feature of serde and the tokio crate.
The default feature includes cli, although the definition of cli is not shown here.
In practice, conditional compilation such as #[cfg(feature = "cli")] lets you specify code that is compiled only when the cli feature is enabled.
Selecting features at compile time
The Cargo command-line tools let you enable or disable particular features.
For example, running cargo build --features "gui" builds the project with the gui feature enabled.
The features mechanism lets you manage the codebase flexibly for different users and use cases.
It is useful when offering experimental features or features tailored to particular environments.
Understanding and making appropriate use of these characteristics and structures is important when developing Solana programs.
On-chain and off-chain compilation targets
Programs for the Solana platform are designed to work both on-chain (on the blockchain) and off-chain (outside the blockchain). Solana programs execute on the rbpf VM, a virtual machine implementing a variant of the eBPF instruction set. Because on-chain and off-chain execution environments differ substantially, conditional compilation is used extensively to provide implementations appropriate to each environment.
What is the rbpf VM?
The rbpf VM (Rust-based Berkeley Packet Filter Virtual Machine) is a virtual machine implemented in Rust and based on the eBPF (extended Berkeley Packet Filter) instruction set. eBPF was originally used in the Linux kernel for tasks such as packet filtering. It is used for advanced packet processing, system call filtering, and performance monitoring. Its flexibility and performance have led to the adoption of eBPF in a wide variety of applications.
The rbpf VM builds on eBPF and is specialized for use on the Solana blockchain platform. On Solana, smart contracts and programs execute on the rbpf VM, allowing efficient on-chain transaction processing and account management.
Main characteristics of the rbpf VM
- High performance
- The rbpf VM executes instructions quickly, making it suitable for blockchain platforms such as Solana that require high transaction throughput.
- Safety
- eBPF is designed with security in mind, with mechanisms to minimize risks such as invalid memory access and infinite loops.
- The rbpf VM inherits these safety characteristics.
- Flexibility
- The eBPF instruction set supports advanced programming, including complex business logic and data processing.
- This allows programs running on Solana to provide a wide variety of features and services.
- Program isolation
- Programs executing on the rbpf VM operate in isolation from other programs and system resources.
- This prevents interference between programs and provides a stable execution environment.
By executing smart contracts and other programs efficiently and safely through the rbpf VM, Solana supports fast transaction processing and flexible blockchain application development. As a result, Solana plays an important role in the development of decentralized applications (dApps), financial services, and other blockchain-based solutions.
Differences between on-chain and off-chain execution
On-chain and off-chain execution
- On-chain execution
- The program executes directly on the Solana blockchain.
- This is used when taking advantage of the immutable and decentralized nature of the blockchain, such as for smart contracts and transaction processing.
- Off-chain execution
- The program executes in an environment outside the blockchain.
- Examples include client applications providing an interface to the blockchain network and server-side applications performing data preprocessing or analysis.
Example of conditional compilation
Solana programs use Rust's cfg attribute for conditional compilation to distinguish between on-chain and off-chain execution.
The sol_log function is one example.
When executed on-chain, the function outputs a log message through a system call; when executed off-chain, it uses a library call.
pub fn sol_log(message: &str) {
#[cfg(target_os = "solana")]
unsafe {
sol_log_(message.as_ptr(), message.len() as u64);
}
#[cfg(not(target_os = "solana"))]
program_stubs::sol_log(message);
}This cfg pattern also applies to user code that needs to run both on-chain and off-chain.
Solana Program and Solana SDK
solana-program and solana-sdk once existed as a single crate but were split to support different execution environments.
The solana-program crate includes functionality unavailable to on-chain programs at compile time and on-chain functionality that fails at runtime in off-chain scenarios.
Solana's eBPF implementation and its limitations
On-chain program development lifecycle
The lifecycle for developing on-chain programs on Solana consists of the following steps. This process outlines the steps required to develop and deploy smart contracts and applications on the Solana platform.
Steps
- Set up the development environment
- Install the Solana CLI tools
- A reliable way to begin Solana development is to install Solana's command-line interface (CLI) tools on your local computer.
- This gives you a powerful development environment.
- Use Solana Playground
- Developers can also use Solana Playground, a browser-based IDE.
- It lets you write, build, and deploy programs entirely in the browser without installing anything.
- Install the Solana CLI tools
- Write the program
- Rust is the primary language for writing Solana programs.
- These programs are written much like conventional Rust libraries.
- C/C++ is also supported, as are languages such as Python through frameworks.
- Compile the program
- Once written, the program must be compiled into Berkeley Packet Filter (BPF) bytecode.
- This bytecode is then deployed to the blockchain.
- Generate a public address for the program
- Using the Solana CLI, developers generate a unique keypair (a public and private key pair) for the new program.
- The public key (Pubkey) of this keypair is used on-chain as the program's public address (or programId).
- Deploy the program
- Using the CLI again, you can deploy the compiled program to the selected blockchain cluster.
- This is done by creating multiple transactions containing the program bytecode.
- Because transactions have size limits, each transaction sends a small chunk of the program to the blockchain.
- Once the entire program has been sent, a final transaction writes the complete buffered bytecode to the program's data account.
- The new program is then marked executable, or the upgrade of an existing program is completed.
Limitations
There are several constraints when developing programs on the Solana blockchain. These constraints ensure platform safety and efficiency and are important for developers to understand.
Limitations
- Rust library restrictions
- Solana on-chain programs must behave deterministically and execute in a resource-constrained, single-threaded environment, so the Rust libraries they can use are restricted.
- Not all libraries are suitable for such a specialized execution environment.
- Compute budget
- Each transaction is assigned a compute budget to prevent abuse of blockchain computational resources.
- The transaction fails if it exceeds this budget.
- Call stack depth
- Solana programs must execute quickly, so the program call stack is limited to a depth of 64 frames.
- Exceeding the permitted call stack depth produces a
CallDepthExceedederror.
- CPI call depth
- Cross-program invocation (CPI) allows a program to call other programs directly. At the time of writing, the depth is limited to four.
- Exceeding the permitted CPI call depth produces a
CallDeptherror.
- Floating-point support
- Programs support only a limited subset of Rust floating-point operations.
- Attempting to use an unsupported floating-point operation causes the runtime to report an unresolved symbol error.
- Floating-point operations are performed through software libraries and consume more compute units than integer operations.
- Fixed-point arithmetic is generally recommended where possible.
- Static writable data
- Program shared objects do not support writable shared data.
- The same read-only code and data are shared across multiple parallel program executions.
- Developers should therefore avoid including static writable variables or global variables in their programs.
- Signed division
- The SBF instruction set does not support signed division.
- Adding a signed division instruction is under consideration.
These constraints are important for understanding the characteristics and objectives of Solana and should be considered when designing efficient and safe programs.
Core data types
This section describes the main data types used on the Solana blockchain. These data types play a central role in developing Solana smart contracts (programs).
Pubkey
The address of a Solana account. It is typically represented by an ed25519 public key.
What is an ed25519 public key?
ed25519 is a public-key cryptographic algorithm used for digital signatures. It is characterized by fast signature generation and verification, high security, and collision resistance. ed25519 is a specific implementation of the Edwards-curve Digital Signature Algorithm (EdDSA), an elliptic-curve signature scheme. The algorithm operates on an elliptic curve related to Curve25519, enabling fast operations and resistance to various security threats.
Main characteristics
- Security
- ed25519 provides a security level of approximately 128 bits.
- At this level, breaking a key within a practical timeframe is considered infeasible using modern conventional computing technology.
- Fast signing and verification
- ed25519 provides very fast signature generation and verification.
- This makes it efficient in resource-constrained environments or when processing a large number of signatures.
- Collision resistance
- ed25519 offers strong collision resistance, making the risk of generating the same signature for different messages with the same key very low.
- Short keys and signatures
- ed25519 public keys are 256 bits (32 bytes), and signatures are 512 bits (64 bytes).
- This helps minimize communication overhead.
Applications
ed25519 is used in a wide range of security-sensitive fields, including SSH authentication, TLS, and cryptocurrencies such as Solana. In blockchain technology, it is often used for transaction signing and wallet address generation.
Solana and ed25519
The Solana blockchain uses ed25519 public keys to identify accounts and verify transaction signatures. This allows fast processing while maintaining transaction security. For keypair-based Solana accounts, the account address is the ed25519 public key, and the corresponding private key controls signing. This lets users securely control their assets and data.
Addresses are used to uniquely identify accounts. Some account addresses have corresponding private keys. Others, such as Program Derived Addresses, have no corresponding private key, or the private key is irrelevant to program operations.
See the following article for more information about Program Derived Addresses (PDAs).

Hash
A cryptographic hash used to identify data uniquely.
It is used to uniquely identify blocks and for general-purpose hashing.
AccountInfo
A description of a single Solana account. Accounts contain SOL (Solana's native token), data, ownership information, and other fields.
When a program is invoked, all accounts it operates on are provided to the program's entrypoint as AccountInfo values.
Instruction
A directive instructing the runtime to execute a program. It includes a set of accounts and program-specific data.
It is used to execute a specific program as part of a transaction.
ProgramError and ProgramResult
An error type that a Solana program can return.
ProgramResult is an alias for Result<(), ProgramError> and represents the result of executing a program.
It reports to the runtime whether the program completed successfully or encountered an error.
Sol
A type representing Solana's native token. It can be converted to and from lamports (the smallest unit of SOL).
SOL is used to pay transaction fees, for staking, and for other financial activities.
These data types are fundamental to program development and execution on Solana. Programs use them to manage accounts, process transactions, and handle errors.
Serialization
At least three different serialization formats are used within Solana's runtime, programs, and network.
The solana-program crate provides access to the serialization formats that programs require.
Serialization converts data into a defined sequence of bytes so that it can be transmitted or stored.
Serialization formats in use
Serialization formats
- Borsh
- A compact, well-defined serialization format developed by the NEAR project.
- Suitable for protocol definitions and archival storage.
- Rust and JavaScript implementations are available, and it is recommended for general use.
- The
solana-programcrate does not re-export Borsh, so users must import the Borsh crate themselves. - The
Instruction::new_with_borshfunction serializes a value with Borsh and creates anInstruction.
- Bincode
- A compact serialization format implementing the Serde Rust API.
- It lacks a specification and a JavaScript implementation and consumes more CPU than Borsh, so it is not recommended for new code.
- Instructions for system and native programs are serialized with Bincode, which is also used for other purposes in the runtime.
- The
Instruction::new_with_bincodefunction serializes a value with Bincode and creates anInstruction.
- Pack
- A Solana-specific serialization API used by many older Solana Program Library programs to define their account formats.
- It is difficult to implement and does not define a language-independent serialization format, so it is generally not recommended for new code.
new_with_borsh
pub fn new_with_borsh<T: BorshSerialize>(
program_id: Pubkey,
data: &T,
accounts: Vec<AccountMeta>
) -> SelfThis code demonstrates how to encode data in the Borsh serialization format and create a new instruction (Instruction) when developing Solana programs.
Borsh is an efficient serialization format for data structures. It has implementations in both Rust and JavaScript and is suitable for protocol definitions and archival storage.
Borsh serialization
Borsh is a compact serialization format with a stable specification, recommended for use on blockchain platforms such as Solana. It is preferred for new code because it uses less CPU than Bincode and has a stable specification and a JavaScript implementation.
The new_with_borsh function
The new_with_borsh function encodes a value of any type T implementing the BorshSerialize trait in Borsh format and creates a new Instruction containing it as data.
The function takes three parameters.
Key points
program_id- The address of the program to execute.
data- The data to serialize with Borsh.
accounts- Descriptions of all accounts that the program may access.
Example
#[derive(BorshSerialize, BorshDeserialize)]
pub struct MyInstruction {
pub lamports: u64,
}
pub fn create_instruction(
program_id: &Pubkey,
from: &Pubkey,
to: &Pubkey,
lamports: u64,
) -> Instruction {
let instr = MyInstruction { lamports };
Instruction::new_with_borsh(
*program_id,
&instr,
vec![
AccountMeta::new(*from, true),
AccountMeta::new(*to, false),
],
)
}A struct named MyInstruction is defined.
This struct derives the BorshSerialize and BorshDeserialize traits and contains a lamports field of type u64.
The create_instruction function receives program_id (the program address), from (the sender's address), to (the recipient's address), and lamports (the amount to transfer). It serializes an instance of MyInstruction with Borsh and creates an Instruction object.
This Instruction also includes the account metadata needed to perform the operation.
This mechanism allows Solana programs to work efficiently on-chain with data structures tailored to their logic. Borsh serialization provides a powerful way to exchange and store data between programs while maintaining consistency.
CPU cost of serialization
Developers should carefully weigh the CPU cost of serialization against the need for correctness and ease of use. Standard serialization formats are more expensive than hand-written, application-specific formats, but the latter make it difficult to ensure correctness and provide implementations in multiple languages. It is not uncommon for programs to pack and unpack data using hand-written code.
Effective serialization in Solana programs is fundamental to data management and communication between programs. Choosing the appropriate serialization format significantly affects program performance and interoperability.
Cross-program instruction execution
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint,
entrypoint::ProgramResult,
program::invoke,
pubkey::Pubkey,
system_instruction,
system_program,
};
entrypoint!(process_instruction);
fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
instruction_data: &[u8],
) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
let payer = next_account_info(account_info_iter)?;
let recipient = next_account_info(account_info_iter)?;
assert!(payer.is_writable);
assert!(payer.is_signer);
assert!(recipient.is_writable);
let lamports = 1000000;
invoke(
&system_instruction::transfer(payer.key, recipient.key, lamports),
&[payer.clone(), recipient.clone()],
)
}This example demonstrates how a Solana program calls another program through a cross-program invocation (CPI). The example implements a transfer of lamports (Solana's base currency unit) from one account to another. CPI allows Solana programs to use the functionality of other programs, enabling interaction between them.
CPI fundamentals
Use the invoke and invoke_signed functions to call other programs.
invoke forwards existing signer privileges, while invoke_signed additionally allows the calling program to authorize the invocation using its PDAs.
Constructing the transaction
Key points
- Retrieve account information
- Obtain the
AccountInfovalues needed for the transaction (the paying account and the recipient account). - Use
next_account_infoto retrieve each account in sequence and assign it to a variable.
- Obtain the
- Check assertions
- Verify that the paying account is writable and is a signer, and that the recipient account is writable.
- Create the transfer instruction
- Use
system_instruction::transferto create an instruction specifying the amount of lamports to transfer from the paying account to the recipient. - In this example, the transfer amount is one million lamports.
- Use
Executing the CPI
Pass the transfer instruction and the associated account information (the paying account and the recipient) to invoke to execute the instruction.
This function enables the transfer of lamports through the System Program.
Code explanation
The preceding code demonstrates a cross-program invocation (CPI) from a Solana smart contract (program) to another program, in this case the System Program. Specifically, it transfers lamports (Solana's base currency unit) from one account to another.
Code walkthrough
Key points
- Imports
- Import the necessary modules and functions from the
solana_programcrate. - These include modules for handling account information, defining the program entrypoint, and the
invokefunction for calling another program.
- Import the necessary modules and functions from the
- Entrypoint
entrypoint!(process_instruction);defines the entrypoint of this program.- It tells the Solana runtime which function to call to begin executing the program.
- The
process_instructionfunction- The Solana runtime calls this function when the program executes. Its arguments include the program ID, the list of accounts the program needs to access, and instruction data.
- Retrieve account information
- Use
next_account_infoto retrieve the paying account (payer) and the recipient account (recipient) from the account list passed as an argument.
- Use
- Assertions
- Verify that
payeris writable and is a signer, and thatrecipientis writable. These are prerequisites for the transfer.
- Verify that
- Transfer lamports
- Use
invoketo execute a system instruction transferring1,000,000lamports frompayertorecipient. invoketakes the instruction to execute and the associated accounts (in this case,payerandrecipient).
- Use
Why CPI matters
In this example, the Solana program not only executes its own logic but also uses the functionality of another program (the System Program) to perform a more complex operation (transferring funds). CPI plays an important role in building decentralized applications on Solana by enabling interaction and cooperation between programs.
Creating an account at a PDA
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint,
entrypoint::ProgramResult,
program::invoke_signed,
pubkey::Pubkey,
system_instruction,
system_program,
};
entrypoint!(process_instruction);
fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
instruction_data: &[u8],
) -> ProgramResult {
let account_info_iter = &mut accounts.iter();
let payer = next_account_info(account_info_iter)?;
let vault_pda = next_account_info(account_info_iter)?;
let system_program = next_account_info(account_info_iter)?;
assert!(payer.is_writable);
assert!(payer.is_signer);
assert!(vault_pda.is_writable);
assert_eq!(vault_pda.owner, &system_program::ID);
assert!(system_program::check_id(system_program.key));
let vault_bump_seed = instruction_data[0];
let vault_seeds = &[b"vault", payer.key.as_ref(), &[vault_bump_seed]];
let expected_vault_pda = Pubkey::create_program_address(vault_seeds, program_id)?;
assert_eq!(vault_pda.key, &expected_vault_pda);
let lamports = 10000000;
let vault_size = 16;
invoke_signed(
&system_instruction::create_account(
&payer.key,
&vault_pda.key,
lamports,
vault_size,
&program_id,
),
&[
payer.clone(),
vault_pda.clone(),
],
&[
&[
b"vault",
payer.key.as_ref(),
&[vault_bump_seed],
],
]
)?;
Ok(())
}The process_instruction function is defined within a Solana smart contract (program) and processes a particular instruction, in this case creating a new account.
It demonstrates how a program creates a new account using a Program Derived Address (PDA) when invoking another program (the System Program) through CPI.
Execution flow
Key points
- Retrieve account information
- Use
next_account_infoto retrieve accounts in sequence from the supplied array of accounts. - These include the paying account (
payer), the account to be created (vault_pda), and the System Program account (system_program).
- Use
- Validate conditions
- Verify that the paying account is writable and is a signer, and that the account to be created is writable and owned by the System Program.
- Verify that the System Program ID is correct.
- Validate the PDA
- Obtain the bump seed from the first byte of
instruction_dataand usePubkey::create_program_addressto derive the expected PDA. - Verify that this PDA matches the key of
vault_pdapassed to the function.
- Obtain the bump seed from the first byte of
- Create a new account
- Use
invoke_signedto call thecreate_accountsystem instruction and create a new account. - The instruction includes the paying account's key, the key of the account to create (the PDA), the amount of lamports to transfer, the account size, and the program ID.
invoke_signedalso receives the seeds needed to authorize the PDA as a signer ("vault", the paying account's key, and the bump seed).
- Use
Cross-program invocation (CPI)
When invoking another program using invoke_signed, the calling program can act as though it has signed for its PDA.
Because a PDA has no corresponding private key, this mechanism uses specific seeds to let the deriving program act as the signer for that address.
This function is useful when a Solana program dynamically creates accounts and manages them according to its own logic. Applications and protocols can thereby manage user assets securely or move them automatically when particular conditions are satisfied.
Cross-program invocation
This section describes cross-program invocation (CPI), the mechanism for interaction between programs on the Solana blockchain. CPI allows one program to execute another program's instructions. Multiple programs can therefore cooperate to perform more complex operations.
Basic CPI flow
- Prepare the instruction
- One program prepares an instruction to be executed by another program, such as a token payment or transfer.
- Use the
invokefunction
- The calling program invokes the prepared instruction using
invokeorinvoke_signed. These functions interact with the Solana runtime, which routes the instruction to the specified program ID.
- Validate accounts
- When the calling program executes the instruction, the Solana runtime checks that all accounts needed by the instruction are supplied correctly.
- The caller must provide the relevant accounts for the instruction, apart from the executable program account as described in this example.
Ensuring security and consistency
- The Solana runtime compares account states before and after instruction execution to ensure that a program has not improperly modified accounts owned by other programs.
- This enables programs to exchange data and assets safely.
CPI example
- Combining payment with an action
- Suppose a client creates a transaction combining two fictional game actions, a token payment from Alice and a missile launch directed at Bob. The
acmeprogram can call thepay()instruction of thetokenprogram on behalf of the client. - This allows multiple programs to cooperate in performing a sequence of operations.
- Suppose a client creates a transaction combining two fictional game actions, a token payment from Alice and a missile launch directed at Bob. The
CPI is an important mechanism that substantially extends the flexibility and functionality of programs on Solana. It allows developers to combine functionality from different programs to build more complex applications and services.
let message = Message::new(vec![
token_instruction::pay(&alice_pubkey),
acme_instruction::launch_missiles(&bob_pubkey),
]);
client.send_and_confirm_message(&[&alice_keypair, &bob_keypair], &message);This code demonstrates how a client creates a transaction and sends it to the Solana blockchain network.
The transaction consists of a message (Message) containing particular instructions (instructions), which define the actions executed on-chain.
This example specifically includes instructions for two different programs.
token_instruction::pay(&alice_pubkey)
- This instruction uses the token program (
token_instruction) to make a payment involving Alice's public key (alice_pubkey). - The exact operation, such as the amount of tokens transferred, depends on the implementation of
pay. Generally, this refers to an operation sending tokens to Alice.
acme_instruction::launch_missiles(&bob_pubkey)
- This instruction uses the
acme_instructionprogram to perform an action associated with Bob's public key (bob_pubkey), represented symbolically in this example aslaunch_missiles. - Its exact behavior also depends on the implementation of
launch_missiles.
These instructions are combined into a message object using Message::new and then submitted to the Solana network using client.send_and_confirm_message.
This function submits the transaction to the network and waits for confirmation of its execution.
Signing a transaction requires the private keys of the relevant signers. In this example, Alice's and Bob's keypairs (alice_keypair and bob_keypair) are used.
This code shows how to execute operations involving multiple programs in a single Solana transaction, illustrating the ability to execute complex sequences of actions efficiently on-chain.
let message = Message::new(vec![
acme_instruction::pay_and_launch_missiles(&alice_pubkey, &bob_pubkey),
]);
client.send_and_confirm_message(&[&alice_keypair, &bob_keypair], &message);This code shows a client-side instruction for executing a composite operation provided by a particular program on Solana, in this case the fictional acme_instruction program.
Specifically, it calls pay_and_launch_missiles defined in acme_instruction, combining a payment involving Alice and Bob with a fictional launch_missiles action in a single transaction.
Code details
- Create a message
- Use
Message::newto create a new message object containing the instruction to execute. - Here,
acme_instruction::pay_and_launch_missilesis called with Alice's and Bob's public keys (alice_pubkeyandbob_pubkey) as arguments. - This instruction is intended to combine a payment involving Alice and Bob with another action.
- Use
- Submit and confirm the transaction
client.send_and_confirm_messagesubmits the constructed message (transaction) to the Solana network and waits for processing to complete.- The transaction requires signatures. In this example, Alice's and Bob's keypairs (
alice_keypairandbob_keypair) are used as signers.
Significance of this code
The code shows how Solana's cross-program invocation (CPI) can coordinate multiple different operations within a single transaction.
Defining a composite function such as pay_and_launch_missiles within a program makes it possible to implement business logic involving multiple steps efficiently.
Applications can thereby offer more advanced functionality in a transparent, straightforward way for users.
This approach is particularly useful for decentralized finance (DeFi) applications and scenarios where specific actions need to be triggered automatically under different conditions. Combined with Solana's fast transaction processing, it allows complex operations to be executed quickly.
mod acme {
use token_instruction;
fn launch_missiles(accounts: &[AccountInfo]) -> Result<()> {
...
}
fn pay_and_launch_missiles(accounts: &[AccountInfo]) -> Result<()> {
let alice_pubkey = accounts[1].key;
let instruction = token_instruction::pay(&alice_pubkey);
invoke(&instruction, accounts)?;
launch_missiles(accounts)?;
}The preceding code illustrates modules and functions used in Solana program development.
It defines two functions within a module named acme, using token_instruction to make a token payment and then perform a particular action.
Code overview
- Module definition
mod acmedefines a module namedacme.- The module defines functions for performing particular operations.
- Use an external module
use token_instruction;brings thetoken_instructionmodule (or crate) into the current scope.- This makes it possible to call functions such as
token_instruction::paydirectly.
Function explanations
- The
launch_missilesfunction- A function symbolically representing a particular action.
- Its concrete implementation would be included in the omitted portion (
...). - The function receives an array of account information and returns a
Result<()>.
- The
pay_and_launch_missilesfunction- This function executes a token payment followed by the action represented by
launch_missiles. - Specifically, it includes the following steps.
- Retrieve Alice's public key from the account information array.
- Use
token_instruction::payto create a payment instruction, paying tokens to Alice. - Call
invoketo execute the payment instruction. If it succeeds, proceed to the next step. - Call
launch_missilesto perform the symbolic action represented by that function.
- This function executes a token payment followed by the action represented by
Using CPI (cross-program invocation)
This code example illustrates the concept of cross-program invocation (CPI) on Solana.
invoke is used to execute an instruction of another program (in this example, the program defined by token_instruction) from the current program.
CPI allows a program to combine the functionality of other programs to perform complex operations.
Instructions requiring privileges
This section explains how the Solana runtime handles particular privileges during cross-program invocations (CPIs).
Here, privileges refer specifically to signer accounts (signers) and writable accounts (writable).
Propagating privileges
On Solana, when one program (the caller) invokes another program (the callee), the runtime determines which privileges can be passed to the callee based on the privileges granted to the caller. For example, if the instruction being processed by the caller includes signer or writable accounts, the caller can issue an instruction to the callee that includes those signers or accounts.
This propagation of privileges relies on the fact that programs are immutable. Except in the special case of program upgrades, program code does not change.
Example: the acme program
In the acme program example, the runtime can safely propagate the transaction's signer privileges to the token instruction.
When the runtime sees a token instruction referencing Alice's public key (alice_pubkey), it verifies whether that key corresponds to an account marked as a signer in the acme instruction.
If the corresponding account is a signer, the runtime permits the signer privilege to be passed to the token program, subject to the other account access and ownership checks.
This process enables secure interaction between Solana programs, allowing one program to safely delegate privileges to another. It makes various operations, such as complex application logic and asset transfers, efficient and secure.
Program-signed accounts
This section explains how Solana programs use Program Derived Addresses (PDAs) to issue instructions involving accounts that did not sign the original transaction. Using PDAs, a program can act as a signer to authorize operations involving particular accounts.
Program Derived Addresses (PDAs)
- PDAs are special addresses associated with a particular program but without corresponding private keys.
- They are derived deterministically from the program ID and other parameters, such as strings used as seeds.
- Using PDAs, a program can authorize particular operations without directly signing the transaction.
The invoke_signed function
invoke_signedcalls an instruction of another program and allows the calling program to sign for accounts included in that instruction.- This allows a PDA to act as a signer.
- The function takes the instruction to execute, the associated accounts, and lists of seeds used to derive the PDAs.
Example
- The preceding code example issues an instruction using
invoke_signed.- Because PDAs act as signers in this instruction, operations involving the accounts can be authorized.
- The seed lists (
&["First addresses seed"]and&["Second addresses first seed", "Second addresses second seed"]) provide information about the seeds used to derive the PDAs.- This allows the runtime to verify that the supplied accounts are properly authorized as signers using the PDAs.
Using PDAs and invoke_signed, Solana programs can securely invoke instructions of other programs and authorize operations involving particular accounts.
This gives programs the ability to authorize accounts as signers during a transaction without any PDA private key being required.
Call depth
Cross-program invocations (CPIs) allow Solana programs to call other programs directly. This lets programs share functionality and execute composite operations. However, at the time of writing, Solana limits the depth of such calls to a maximum of four levels of CPI.
What is call depth?
Call depth refers to the number of nested levels in a chain where one program calls another program, which then calls another program. For example, if program A calls program B and program B calls program C, the CPI depth is two.
Purpose of the restriction
The limit on call depth in Solana (four levels at the time of writing) is intended to ensure system stability and security. Unlimited program calls could lead to infinite loops or unexpected complex interactions, harming system performance or introducing security vulnerabilities. Such restrictions are also necessary for managing the consumption of computational resources.
Practical implications
This constraint is important to consider when designing Solana programs. When a program calls another program, its design must account for the maximum depth. If a complex operation requires cooperation between many programs, the design or the structure of the calls must accommodate this restriction.
Reentrancy
Reentrancy occurs when a program is called again while it is still executing. On Solana, reentrancy is limited to direct self-recursion, and its depth is subject to a fixed upper bound. This restriction prevents a program from calling another program while in an intermediate state and then being unexpectedly called again by that program.
Purpose of restricting reentrancy
- Clear state management
- Direct self-recursion allows the program to manage the state at the point where it calls itself. This helps prevent unexpected state changes and supports more stable execution.
- Improved security and stability
- Restricting recursive calls from intermediate states minimizes unexpected behavior and security risks, such as infinite recursion. This improves overall program stability and reliability.
Practical implications
This restriction is an important consideration in program design and development. In particular, if a program requires recursive behavior as part of its processing, developers must remember that only direct self-recursion is permitted and its depth is limited. Developers need to plan their use of recursion carefully to design programs that operate efficiently and safely under these constraints.
This design in Solana aims to make program behavior more predictable and reduce the risks of complex interactions. It helps developers manage the program's execution flow more reliably.
Native programs
Native programs execute native machine code distributed with the runtime and have specific program IDs. They provide basic Solana functionality and security. Some can be invoked by other programs, while others execute only as top-level instructions in a transaction.
Roles of native programs
Key points
System Programsolana_program::system_program- Creates new accounts, allocates account data, specifies the program that owns an account, transfers lamports from accounts owned by the System Program, and supports transaction fee payments.
- It can be invoked by other programs.
Compute Budget Programsolana_sdk::compute_budget- Requests additional CPU or memory resources for a transaction.
- It has no effect when invoked by other programs.
ed25519 Programsolana_program::ed25519_program- Verifies ed25519 signatures.
secp256k1 Programsolana_program::secp256k1_program- Verifies secp256k1 public key recovery operations.
BPF Loadersolana_program::bpf_loader- Deploys and executes immutable programs on the blockchain.
Upgradable BPF Loadersolana_program::bpf_loader_upgradeable- Deploys, upgrades, and executes upgradeable programs.
Deprecated BPF Loadersolana_program::bpf_loader_deprecated- Deploys and executes immutable programs on the blockchain.
Usage considerations
Native programs have different implications for Solana developers depending on their functionality and whether they can be invoked by other programs. For example, the System Program and BPF loaders can accept instructions from other programs and are widely used in Solana program development and account management. Conversely, the Compute Budget Program and signature verification programs (ed25519 and secp256k1) cannot be invoked directly by other programs, but their functionality may be needed within a particular transaction.
Program IDs and instructions
These programs are uniquely identified by program IDs, which Solana developers use to access particular native program functionality.
Many native programs also define an enum representing the instructions they handle and constructors for building instructions.
This facilitates interactions between programs.
The process_instruction function

pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
instruction_data: &[u8],
) -> ProgramResult {
msg!("Hello, World!");
Ok(())
}A function named process_instruction is defined.
It receives the following three arguments.
Arguments
program_id- The public key of the program.
accounts- The accounts involved in the instruction executed within the function.
instruction_data- Instruction data.
It prints Hello World! and then finishes execution.
Entrypoint

entrypoint!(process_instruction);To interact with an on-chain program, its entrypoint must be defined.
if __name__ == "__main__"On Solana, entrypoint! specifies where program execution begins.
Conclusion

We have walked through Hello Solana, one of the Solana Playground tutorials, explaining each part in turn.
Since this is the first article in the series, the explanations are fairly extensive.
I hope this has helped you understand the fundamentals.
If you have any questions, feel free to contact me through Twitter DMs.
I mainly share information about Python and blockchain development.
I also post illustrated explanations on Twitter, so feel free to follow me there.
References

https://solana.com/docs/programs

