Cover photo

Soroban: Guessing num game

📎 “Soroban: Guessing num game” smart contract code repo is here.


Stellar has previously not supported open smart contracts, unlike most other notable L1s. That is about to change with Soroban, Stellar’s Smart Contract Platform. The platform is expected to co-exist with the current Stellar network, taking advantage of all Assets already issued on the network (yes including USDC).

In this tutorial we will go over how to create and test a smart contract for Soroban in rust. The example contract we will create is a simple guessing number game.

So, buckle up and get ready to read that.

Best of luck in your new role, you're going to do great things!
Best of luck in your new role, you're going to do great things!

Environment Setup

For this tutorial you’ll need to:

  1. install Rust

  2. have a code-editor (vscode highly recommended)

  3. install the Soroban CLI (for testing)

Assuming you’ve configured those things we start our project by creating a new crate with cargo where we will write out our contract:

cargo new --lib guess-num
cd guess-num

Open the generated cargo.toml file. It should look something like this:

[package]
name = "guess-num"
version = "0.1.0"
edition = "2021"

See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

Change its content to look like this:

[package]
name = "guess-num"
version = "0.1.0"
edition = "2021"

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

[features]
testutils = ["soroban-sdk/testutils"]

[dependencies]
soroban-sdk = "0.1.0"

[dev_dependencies]
soroban-sdk = { version = "0.1.0", features = ["testutils"] }

[profile.release]
opt-level = "z"
overflow-checks = true
debug = 0
strip = "symbols"
debug-assertions = false
panic = "abort"
codegen-units = 1
lto = true

[profile.release-with-logs]
inherits = "release"
debug-assertions = true

Strictly speaking because we will not be releasing this contract to Soroban the .release keys are not necessary. But we’ll still leave them in just to be thorough.

Open src/lib.rs and remove all the code from that file. Start with a clean slate. In this file is where we will implement our contract.

Implementing Guess Num

Every lib.rs file that contains a smart contract for Soroban will start with the following line:

#![no_std]

This ensures 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. - SorobanDocs

Because we don’t have the std library to lean on for types like strings and vectors we turn to the help of the Soroban Rust SDK and import the types we want to use in our contract by adding the following line to our lib.rs

#![no_std]

use soroban_sdk::{ contracterror, contractimpl, contracttype, panic_error, symbol, vec, Address, Env, Symbol, Vec,
};