How to create Stellar Smart Contracts? (2024)

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 inOctober 2022that 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?
  • A brief about the Stellar blockchain
  • How does Stellar work?
  • Understanding Stellar smart contracts
  • What is Soroban?
  • How to create Stellar Smart Contracts using Soroban

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 withoutloss of time orthe 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 ismore 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 circ*mstance 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 operationsin 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” onsoroban.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 installrustup. Installrustupwith 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 usingcargo install.

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

Usage

Run thesorobancommand and you should see output like below.

soroban

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

Create New Project

Start by creating a new Rust library using thecargo newcommand.

cargo new --lib first-project

Open theCargo.toml, it should look something like this:

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

Addsoroban-sdkdependency

Add the following sections to theCargo.tomlthat will import thesoroban-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 = truedebug = 0strip = "symbols"debug-assertions = falsepanic = "abort"codegen-units = 1lto = 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

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

The config for thereleaseprofile configures the Rust toolchain to produce smaller contracts when built with the–releaseor–profile releaseoption.

The config for therelease-with-logsprofile enables contract logs when building with–profile release-with-logsoption. See thelogging examplefor more details.

Write the Code

Open thesrc/lib.rsfile, 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

Runcargo testand watch the contract run. You should see the following output:

cargo testrunning 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.wasmfile, use thecargo buildcommand.

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

A.wasmfile should be outputted in thetargetdirectory:

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

Deploy to Futurenet

If you have Docker installed, you can run a local node with theStellar QuickstartDocker image that joins theFuturenetnetwork, and then use that local node to deploy.

To run a local node for theFuturenetnetwork 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 theStellar Laboratory. Make note of both theG…andS…keys. TheG…key is the public key and will also be the account ID. TheS…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 inWrite a Contractand the resulting.wasmfile we built inBuildas our contract to deploy. Run the following commands to deploy the contract to the network. Use theS…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 toolhttps://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.

How to create Stellar Smart Contracts? (2024)
Top Articles
How to Admit You're Overwhelmed at Work
Settling an Estate: A Step-by-Step Guide - Trustworthy: The Family Operating System®
Riverrun Rv Park Middletown Photos
St Petersburg Craigslist Pets
The Pope's Exorcist Showtimes Near Cinemark Hollywood Movies 20
Trade Chart Dave Richard
Mustangps.instructure
Kent And Pelczar Obituaries
Chuckwagon racing 101: why it's OK to ask what a wheeler is | CBC News
Irving Hac
Tiger Island Hunting Club
Urban Dictionary Fov
The Rise of Breckie Hill: How She Became a Social Media Star | Entertainment
Craigslist Pets Southern Md
Winterset Rants And Raves
Superhot Unblocked Games
Samsung Galaxy S24 Ultra Negru dual-sim, 256 GB, 12 GB RAM - Telefon mobil la pret avantajos - Abonament - In rate | Digi Romania S.A.
Games Like Mythic Manor
Images of CGC-graded Comic Books Now Available Using the CGC Certification Verification Tool
Adam4Adam Discount Codes
Blue Rain Lubbock
Tips on How to Make Dutch Friends & Cultural Norms
Rogue Lineage Uber Titles
BJ 이름 찾는다 꼭 도와줘라 | 짤방 | 일베저장소
Abga Gestation Calculator
Uncovering the Enigmatic Trish Stratus: From Net Worth to Personal Life
Maths Open Ref
Vlocity Clm
O'reilly's Wrens Georgia
Fbsm Greenville Sc
Walter King Tut Johnson Sentenced
Shnvme Com
Craigslist Com Humboldt
Waffle House Gift Card Cvs
دانلود سریال خاندان اژدها دیجی موویز
Can You Buy Pedialyte On Food Stamps
Hindilinks4U Bollywood Action Movies
Merkantilismus – Staatslexikon
Trizzle Aarp
South Bend Tribune Online
Aita For Announcing My Pregnancy At My Sil Wedding
Kb Home The Overlook At Medio Creek
13 Fun & Best Things to Do in Hurricane, Utah
Leland Nc Craigslist
Does Target Have Slime Lickers
What is 'Breaking Bad' star Aaron Paul's Net Worth?
Willkommen an der Uni Würzburg | WueStart
Argus Leader Obits Today
Uncle Pete's Wheeling Wv Menu
What Responsibilities Are Listed In Duties 2 3 And 4
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 5993

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.