Select Page

How to create Stellar Smart Contracts?

Smart Contract on Stellar

Smart contracts allow for the transparent and conflict-free exchange of money, shares, and property without using an intermediary. A smart contract can be viewed as the digital version of traditional vending machines. People often think of smart contracts when they think about Ethereum because it was designed to support smart contracts. However, a lot of other blockchains later adopted this feature and made more options available for users to choose from. Talking about Stellar, it does not include a smart contract language or a built-in virtual machine to execute codes. Instead, it is optimized for sending, storing and trading value.

However, the Stellar Development Foundation (SDF) announced in October 2022 that the Stellar network’s native smart contracts platform, Soroban, was live on Futurenet. So, anyone interested in building smart contracts on Stellar must know about Soroban. Soroban is a platform for smart contracts that has been purposefully designed and built to be compatible with Stellar.

This article will explain how to create smart contracts on the Stellar blockchain using Soroban. But before we discuss how to create Stellar smart contracts, let us discuss about the Stellar platform and smart contracts in general.

What is a smart contract?

Smart contracts are programs that are stored on a blockchain and run when certain conditions are met. Smart contracts are typically used to automate an agreement’s execution so all parties can know the outcome immediately without loss of time or the need for any intermediary to intervene. They can automate a workflow and trigger action if conditions are met.

Smart contracts are based on simple “if/when…then” statements, which are then translated into codes on a blockchain. When predetermined conditions are met and verified, a network of computers executes the actions. These actions include anything like sending notifications or issuing tickets, releasing funds to the right parties, registering a vehicle, etc. When a transaction is complete, the blockchain is updated. This means that the transaction can’t be modified, and only those who have been granted permission to see the results are able to view them.

A smart contract can have as many conditions as necessary to ensure that all participants are satisfied with the outcome. Participants must agree on how transactions and data will be represented on the blockchain. They also need to determine the “if/when…then” rules that regulate those transactions.

A developer can then program the smart contract. However, templates, web interfaces and other online tools are now readily available, making it easier to build and execute smart contracts.

There are many benefits of smart contracts. Some of them are as follows:

  • Speed and accuracy – Since smart contracts are digital and automated, there is no manual intervention. Thus, they are error-free and instantaneous.
  • Transparency – As no third party is involved in the transaction and encrypted records are used, there is no chance of information tampering.
  • Security – Smart contract transactions are blockchain-based, so they are immutable.
  • Savings – Since there is no intermediary, it removes transaction time delays and fees.

A brief about the Stellar blockchain

Stellar is an open-source network that allows for asset issuance and payments. Stellar allows you to create, send and trade digital representations in any form of value, including U.S. dollars or Argentine pesos. You can also trade Bitcoins and real estate using Stellar. It was designed to allow all global financial systems to interact freely with one another on a single network. Stellar is a public network and has no owners. It is owned entirely by the public. Stellar runs on a decentralized open network that handles millions of transactions per day. Like Ethereum and Bitcoin, Stellar relies on blockchain to keep its network in sync. However, the end-user experience with Stellar is more like cash. Stellar is faster, cheaper and more efficient than other blockchain-based systems.

Stellar has been cryptocurrency-adjacent from the beginning, but it has always been intended to enhance rather than supplant the existing financial system. Unlike the Bitcoin network, Stellar was not designed to trade bitcoins only and is a decentralized system that can be used to trade any kind of value efficiently and transparently.

Stellar has a native digital currency called the lumen. This currency is used in small amounts to initiate accounts and make transactions. Stellar does not privilege any currency beyond these requirements. It was specifically created to make traditional forms of value more usable and easily accessible in the digital world.

How does Stellar work?

Stellar, at its most basic level, is a system to track ownership. It uses an immutable ledger, just like accountants do every day. However, Stellar’s innovation is that there is no accountant. There is, instead, a network of computers that independently check and recheck one another’s work. Stellar is an autonomous system that doesn’t have a central authority. This means that no one can block the network or alter the numbers to their liking. Stellar’s ledger can be verified and updated every five seconds without a central authority. The unique algorithm known as the Stellar Consensus Protocol (SCP) is able to achieve this. It keeps everything in sync using Proof-of-Agreement. There are many methods to reach an agreement or attain consensus in a decentralized system. SCP and PoA strive to be more perfect by being flexible, efficient, and fast.

In Stellar, all balances and operations are broadcast to the entire network every five seconds. To accomplish this, computers called nodes run Stellar core software. They publish and verify the ledger. The nodes verify that the right balances have been debited and credited when you send someone a token through a Stellar-built application. Each node then verifies that all other nodes are approving the transaction. Once consensus is reached, the transaction details are published to the ledger.

Hundreds of nodes around the world are verifying the Stellar protocol. This public information includes the names and addresses of nodes. Anyone can download Stellar core, an SCP implementation, to join the consensus process. This differs from accounting at a central institution, where one authority decides what happens. Horizon is a powerful API located above the core layer. This allows you to use Stellar without having to learn all about SCP. You can move digital assets with familiar models using simple, well-documented functions. It is very simple to transfer between accounts, make market transactions, and issue assets.

Understanding Stellar smart contracts

Stellar does not offer an in-built smart contract language or virtual machine like Ethereum to write smart contract code or optimize the contract’s logic to support features. However, a smart contract on Stellar combines transactions and various constraints to furnish the intended result.

A Stellar Smart Contract (SSC) is expressed as the composition of executed and connected transactions via different constraints. Following are some examples of constraints that can be implemented when creating SSCs:

  • Multisignature: What keys are required to authorize a specific operation? What are the necessary parties to agree on a circumstance to perform steps? Multisignature is the concept that requires the signatures of various parties to sign transactions originating from an account.
  • Atomicity/Batching: What operations must take place together or fail? What must happen to cause this to fail or pass? Batching is the concept of involving multiple operations in one transaction. Atomicity ensures that an entire given series of operations in a transaction, upon submission to the network, fails if one operation fails.
  • Sequence: In what order should a transaction series be processed? What are the dependencies and limitations? The concept of the sequence is shown on the Stellar Network via sequence number. Leveraging sequence numbers in transaction manipulation can ensure that particular transactions do not execute if an alternative transaction is submitted.
  • Time bounds: When can a transaction be executed? Time bounds are restrictions on the time over which a transaction is valid. Time bounds enable periods to be represented in an SSC.

Now that we have explained stellar smart contracts, we will discuss the steps to create SSCs using Soroban.

What is Soroban?

Launched by Futurenet, Soroban is a platform for smart contracts that has been purposefully designed and built to perform. With the support of a $100 million fund, the native smart contract platform Soroban was launched on the Stellar network in October 2022. Soroban is now live on Futurenet and has issued a call to developers to help it with its smart contract service. The Rust-based code is available for download. The platform will undergo several tests before it launches in early 2023. It is worth noting that the platform has been designed with simplicity and ease of use in mind.

Soroban introduces turing complete smart contracts to the Stellar network, built in WASM with Rust. As mentioned above, Soroban is designed to be highly performant. This, in combination with the Stellar network’s power, will lead to use cases that will expand financial services access. As Soroban is now live on Futurenet, developers can start writing and deploying smart contracts in a testing environment called Soroban Fiddle and be rewarded.

Soroban will operate independently of Stellar but will be paired with this network to provide developers and users with access and “equitable access” to decentralized finance (DeFi).

The Soroban Adoption Fund has allocated $100M to developers who create products and tools that support the Soroban ecosystem. “Sorobanathon: First Light” will offer an incentive program to encourage developers to test Soroban, share their feedback, and create Soroban content. This includes tutorials and code examples. You can find more details on “Sorobanathon: First Light” on soroban.stellar.org.

How to create Stellar Smart Contracts using Soroban

Here are the steps to create a smart contract on Stellar using Soroban:

Install Rust

If you use macOS, Linux, or another Unix-like OS, the simplest method to install a Rust toolchain is to install rustup. Install rustup with the following command.

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

And install the wasm32-unknown-unknown target.

rustup target add wasm32-unknown-unknown

If you use Windows, or need an alternative method of installing Rust, check out:
https://www.rust-lang.org/tools/install

Install the Soroban CLI

The Soroban CLI can execute Soroban contracts in the same environment the contract will execute on network, however in a local sandbox.

Install the Soroban CLI using cargo install.

cargo install --locked --version 0.2.1 soroban-cli
## if the above command doesn't work, run 
cargo install soroban-cli

Usage

Run the soroban command and you should see output like below.

soroban

Once you’ve Setup your development environment, you’re ready to create your first Soroban contract.

Create New Project

Start by creating a new Rust library using the cargo new command.

cargo new --lib first-project

Open the Cargo.toml, it should look something like this:

Cargo.toml

[package]
name = "first-project"
version = "0.2.1"
edition = "2021"

Add soroban-sdk dependency

Add the following sections to the Cargo.toml that will import the soroban-sdk.

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

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

[dependencies]
soroban-sdk = "0.2.1"

[dev_dependencies]
soroban-sdk = { version = "0.2.1", 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

The features list includes a testutils feature, which will cause additional test utilities to be generated for calling the contract in tests.

INFO

The testutils test utilities are automatically enabled inside Rust unit tests inside the same crate as your contract. If you write Rust integration tests, or write tests from another crate, you’ll need to add #[cfg(feature = “testutils”)] to those tests and enable the testutils feature when running your tests with cargo test –features testutils to be able to use those test utilities.

The config for the release profile configures the Rust toolchain to produce smaller contracts when built with the –release or –profile release option.

The config for the release-with-logs profile enables contract logs when building with –profile release-with-logs option. See the logging example for more details.

Write the Code

Open the src/lib.rs file, and copy-paste the following code.

#![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 {
        vec![&env, symbol!("Hello"), to]
    }
}

#[cfg(test)]
mod test {
    use super::{Contract, ContractClient};
    use soroban_sdk::{symbol, vec, Env};

    #[test]
    fn test() {
        let env = Env::default();
        let contract_id = env.register_contract(None, Contract);
        let client = ContractClient::new(&env, &contract_id);

        let words = client.hello(&symbol!("Dev"));
        assert_eq!(
            words,
            vec![&env, symbol!("Hello"), symbol!("Dev"),]
        );
    }
}

Run the Tests

Run cargo test and watch the contract run. You should see the following output:

cargo test
running 1 testtest test::test ... ok

Try changing the values in the test to see how it works.

Build the Contract

To build the contract into a .wasm file, use the cargo build command.

cargo build --target wasm32-unknown-unknown --release

.wasm file should be outputted in the target directory:

target/wasm32-unknown-unknown/release/first_project.wasm

Deploy to Futurenet

If you have Docker installed, you can run a local node with the Stellar Quickstart Docker image that joins the Futurenet network, and then use that local node to deploy.

To run a local node for the Futurenet network with the Stellar Quickstart Docker image, run the following command.

docker run --rm -it \
  --platform linux/amd64 \
  -p 8000:8000 \
  --name stellar \
  stellar/quickstart:soroban-dev@sha256:0993d3350148af6ffeab5dc8f0b835236b28dade6dcae77ff8a09317162f768d \
  --futurenet \
  --enable-soroban-rpc

Once the image is started you can check its status by querying the Horizon API:

curl http://localhost:8000

Generate a key by going to the Stellar Laboratory. Make note of both the G… and S… keys. The G… key is the public key and will also be the account ID. The S… key is the secret key and is that you use to control the account.

Once you have an account on the network, we’ll use the code we wrote in Write a Contract and the resulting .wasm file we built in Build as our contract to deploy. Run the following commands to deploy the contract to the network. Use the S… key as the secret key.

soroban deploy \
    --wasm target/wasm32-unknown-unknown/release/first_project.wasm \
    --secret-key S... \
    --rpc-url http://localhost:8000/soroban/rpc \
    --network-passphrase 'Test SDF Future Network ; October 2022'

A contract ID will be outputted.

cd4dae2c409c433b1e1d83994a20214d3e5f60bdd3a817978d8aa7c797864313

Using the contract ID that was outputted, use the soroban-cli to invoke the hello function with a single argument friend.

soroban invoke \
    --id cd4dae2c409c433b1e1d83994a20214d3e5f60bdd3a817978d8aa7c797864313 \
    --secret-key S... \
    --rpc-url http://localhost:8000/soroban/rpc \
    --network-passphrase 'Test SDF Future Network ; October 2022' \
    --fn hello \
    --arg friend

The following output should appear.

["Hello","friend"]

Note: It seems that we can’t yet query the current state of the contract with the horizon, but we can fetch the deployment transaction and inspect the result meta xdr to see things like the contract id, WASM code, and invocations. But you use this experimental tool https://leighmcculloch.github.io/soroban-fiddle/

Conclusion

When designing and writing Stellar smart contracts, all parties involved must come together and clearly outline the contract’s purpose. Ensure to analyze and agree upon the conditions and outcomes when building smart contracts. Also, the written smart contracts must be translated into a series of operations and transactions using the code. Code with bugs may not perform as desired. Therefore, it is essential to design and build smart contracts carefully.

Stellar (XLM) users have been eagerly awaiting Soroban’s announcement. This platform could offer new uses for the network and encourage adoption. It might also allow it to compete with other major blockchains, such as Ethereum. Stellar’s smart contract vision is to provide users with an easy-to-use, user-friendly and scalable platform. According to the team behind the project, Soroban could become the standard smart contract platform in the crypto industry.

If you are looking to design and create Stellar Smart Contracts, get in touch with our Stellar blockchain developers‘ team, who have hands-on knowledge of creating smart contracts using Soroban. 

Author’s Bio

 

Akash Takyar

Akash Takyar LinkedIn
CEO LeewayHertz
Akash Takyar is the founder and CEO at LeewayHertz. The experience of building over 100+ platforms for startups and enterprises allows Akash to rapidly architect and design solutions that are scalable and beautiful.
Akash's ability to build enterprise-grade technology solutions has attracted over 30 Fortune 500 companies, including Siemens, 3M, P&G and Hershey’s.
Akash is an early adopter of new technology, a passionate technology enthusiast, and an investor in AI and IoT startups.

Start a conversation by filling the form

Once you let us know your requirement, our technical expert will schedule a call and discuss your idea in detail post sign of an NDA.
All information will be kept confidential.

Insights

Follow Us