Using Rust for Smart Contracts
Setting up
Let’s first install the Solana CLI:
sh -c "$(curl -sSfL <https://release.solana.com/stable/install>)"
Now, we can create a new directory, and a solana wallet keypair:
mkdir ~/my-solana-wallet
solana-keygen new --outfile ~/my-solana-wallet/keypair.json
Now that we have a wallet, we can create a cluster on devnet, and add some test SOL to our wallet:
solana config set --url <https://api.devnet.solana.com>
solana airdrop
Writing the Code
Let’s first create a new project using Cargo in our local directory. This will come with all of the files we need to start building a smart contract
cargo init hello_world --lib
cd hello_world
Open up your Cargo.toml file and add the following code snippets at the bottom:
[lib]
name = "hello_world"
crate-type = ["cdylib", "lib"]
Now, navigate to “src/lib.rs” and open up the file. This is where we will create our Solana smart contract.
Step 1 is to import solana_program and create an entrypoint for our code.
use solana_program::{
account_info::AccountInfo,
entrypoint,
entrypoint::ProgramResult,
pubkey::Pubkey,
msg,
};
entrypoint!(process_instruction)
Here, we import a few key aspects of solana_program and call the method entrypoint
. This defines the first function to be called when our contract is run, which in our case is process_instruction
.
Let’s now create the process_instruction
function.
pub fn process_instruction(
program_id; &Pubkey,
accounts: &[AccountInfo],
instruction_data: &[u8]
) -> ProgramResult {
msg!("Hello World!");
Ok(());
}
We define process_instruction
as a public function using pub fn
, which takes in 3 parameters and returns a ProgramResult
. This will call the method msg!
, which prints “Hello World!” to the console. We then call the Ok(())
method to validate that our code ran successfully.
Deploying our Code
We can build our code using cargo, and deploy it with the solana cli:
cargo build-bpf
solana program deploy ./target/deploy/hello_world.so
Once you run this command, a programID will be returned (hence the ProgramResult
in the process_instruction
function.
Last updated