Skip to main content

Write a Contract

Once you have a project setup, like how we setup a project in Create a Project, writing a contract involves writing Rust code in the projects lib.rs file.

#![no_std]

All contracts should begin with #![no_std] to ensure that the Rust standard library is not included in the build. The Rust standard library is large and not well suited to being deployed into small programs like those deployed to blockchains.

use soroban_sdk::{contractimpl, symbol, vec, Env, Symbol, Vec};

The contract will need to import the types and macros that it needs from the soroban-sdk crate. Take a look at Create a Project to see how to setup a project.

Many of the types available in typical Rust programs, such as std::vec::Vec, are not available, as there is no allocator and no heap memory in Soroban contracts. The soroban-sdk provides a variety of types like Vec, Map, BigInt, Bytes, BytesN, Symbol, that all utilize the Soroban environment's memory and native capabilities.

pub struct Contract;

#[contractimpl]
impl Contract {
pub fn hello(env: Env, to: Symbol) -> Vec<Symbol> {
todo!()
}
}

Contract functions live inside an impl for a struct. The impl block is annotated with #[contractimpl]. Functions that are intended to be called externally should be marked with pub visibility. The first argument can be an Env argument to get a copy of the Soroban environment, which is necessary for most things.

Putting those pieces together a simple contract will look like this.

src/lib.rs
#![no_std]
use soroban_sdk::{contractimpl, symbol, vec, Env, Symbol, Vec};

pub struct Contract;

#[contractimpl]
impl Contract {
pub fn hello(env: Env, to: Symbol) -> Vec<Symbol> {
vec![&env, symbol!("Hello"), to]
}
}