How to create Stellar Smart Contracts?

stellar smart contracts

A smart contract is a computer protocol proposed to verify, facilitate or enforce the performance or negotiation. Smart Contracts enable the execution of transactions without the involvement of third parties.

Smart Contracts help in exchanging money, shares, property or anything of value in a conflict-free and transparent way without any middleman. We will describe smart contracts by comparing it to a vending machine. Generally, you go to a notary or a lawyer, pay them and wait till you get the document. However, with smart contracts, you only need to drop a crypto token, for example, bitcoin, into a vending machine and your escrow, social identity or whatever falls into the account.

Moreover, smart contracts define penalties and rules in the same way a traditional contract does but enforces obligations automatically. This article will explain how to create smart contracts on Stellar Blockchain that is one of the best blockchain platforms to execute financial functions in a decentralized way.

  1. What are Stellar Smart Contracts?
  2. Here are the steps to create Stellar Smart Contracts:
  3. Example of Stellar Smart Contracts

Before we discuss how to create Stellar Smart Contracts, let us explain a bit about the Stellar Platform and how it is used to create smart contracts.

What are Stellar Smart Contracts?

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

  • Multisignature: What all operations must take place together or fail? What must happen to force this to fail or pass?

    Batching is the concept of involving multiple operations in one transaction. Atomicity ensures that a given series of operations, upon submission to the network, all operations in the transaction fail if one operation fails.

  • Atomicity/Batching: What keys are required to authorize a specific operation? What are the necessary parties to agree on a circumstance in order to perform steps?

    Multisignature is the concept that requires signatures of various parties to sign transactions originating from an account.

  • 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 period over which a transaction is valid. Time bounds enable time periods to be represented in an SSC.

    Now that we have explained what are stellar smart contracts, we will now discuss the steps to create SSCs.

Here are the steps to create Stellar Smart Contracts:

We shall use the Stellar Javascript SDK, Node JS and the Stellar testnet for creating Stellar Smart Contracts.

  • Create pairs of seed/public keys

    The Stellar SDK provides a random key generated method:


    2 pairs are created and saved locally in a file to run the scripts one after the other.

  • Add funds to the account

    A stellar account needs to have a minimum amount of Lumens (XLM) validated by the platform. The testnet has a friendbot that gives you 10000 Lumens for free.

    Therefore, it is essential to ask the friendbot to fund accounts with XLMs (Lumens) using an HTTP request. In a real use case, you would have to go through an anchor to an exchange platform to add XLMs to an account and exchange fiats.

    Once the script is executed, you need to verify that accounts are funded with 10,000 Lumens.

  • Create, sign and submit the transaction

    const Stellar = require(‘stellar-sdk’)
    const { TimeoutInfinite } = require(‘stellar-base’);
    const [ pairA, pairB ] = require(‘../pairs.json’)
    const server = new Stellar.Server(‘https://horizon-testnet.stellar.
    const transaction = async () => {
    const paymentToB = {
    destination: pairB.publicKey,
    asset: Stellar.Asset.native(),
    amount: ‘20.0000000’, // Notice the use of the type string

    const txOptions = {
    fees: await server.fetchBaseFee(),
    networkPassphrase: Stellar.Networks.TESTNET
    const accountA = await server.loadAccount(pairA.publicKey)
    const transaction = new Stellar.TransactionBuilder(accountA,
    .addMemo(Stellar.Memo.text(‘Test Transaction’))
    const StellarPairA = Stellar.Keypair.fromSecret(pairA.
    await server.submitTransaction(transaction)
    .then(() => console.log(‘ok’))
    .catch((e) => { console.error(e); throw e}

    In line 13 of the code, the amount of Lumens is defined as a string because of the Stellar platform’s underlying data type. In line 23, the transaction is created to send 20 Lumens from account A to account B. You only need account A and B’s public keys required to set up.

    In Line 31 of the code, Account A signs the transaction where you require the private key of Account A. In line 33, the transaction is submitted to the network.

Example of Stellar Smart Contracts

2-Party MultiSignature Escrow Account with Time & Recovery

John sells 50 CODE tokens to Ben, under the condition that Ben won’t resell these tokens before one year passes. Since John does not trust Ben completely, he wants to hold Ben’s tokens for one year.

However, Ben protests for how he will know that John will have all those tokens after a year. How can Ben trust John to hold his tokens and deliver them eventually?

Moreover, Ben is sometimes forgetful. There’s a chance that he won’t remember to claim tokens at the end of the year. Therefore, John would like to develop a recovery mechanism so that they can be recovered if Ben forgets to claim tokens. Using this method, tokens cannot be lost forever.

Here is a way to implement this approach:

An escrow agreement is created between two entities: the target (entity receiving funds at the end of the contract) and the origin (entity funding the agreement).

You need three accounts, i.e., source account, destination account and escrow account, to execute a time-locked escrow contract between two parties. The source account is the origin account that is funding and initializing the escrow agreement. The destination account is the target account that will get control over the escrowed funds. The origin creates the escrow account and holds the escrowed funds during the lock-up period.

Five transactions are required to create an escrow account. They are mentioned below in the order of creation.

  • N, M – The sequence number of an escrow account and source account, respectively; N+1
    means the next sequence number.
  • D – The date on which the lock-up period starts.
  • R – Recovery Period
  • T – Lock-up Period

Transaction 1: Create the Escrow Account

Account: Source Account

Sequence Number: M


Create an account: Create an escrow account in the system with starting balance= transaction fee+minimum balance.

Signers: Source Account

The origin submits transaction 1 to the network via the source account. It creates the escrow account, funds it with the current minimum reserve, and provides the origin access to the escrow account’s private and public key. It is offered additional money to manage the transfer fee of moving assets at the end of the escrow agreement. It is suggested to fund the account with a larger balance than the calculated starting balance when creating new accounts.

Transaction 2: Enable multi-sig

Account: Escrow Account

Sequence Number: N


Set Option – Signer: Add destination account as a signer for the escrow account and set the weight on transactions to 1.

Set Option – Thresholds & Weights: Set the weight of master key and thresholds weight to require all signatures.

Master Weight: 0

Low, Medium and High Threshold: 1

Time Bounds:

Minimum time: Unlock date

Maximum time: 0

Eventual Signer: Destination Account
Immediate Signer: Escrow Account

Transaction 3: Recovery

Account: Escrow Account

Sequence Number: N+1


Set Option – Signer: Eliminate the destination account as a signer and assign Weight: 0.

Set Option – Thresholds & Weights: Assign a weight of master key and change
thresholds weights to require only 1 signature.
Low, medium and high threshold: 1

Time Bounds:

Minimum time: Recovery Date

Maximum time: 0

Immediate Signer: Escrow Account

Eventual Signer: Destination Account

The escrow account creates and signs Transaction 3 and 4 by the origin. The origin then provides transactions 3 and 4 in XDR format to the target to sign it using the destination account. Then, the target publishes them for the origin to review and store in a safe location. Once both parties sign the transaction, they cannot be modified. Both the target and origin must have a copy of the transactions in XDR format and transactions can be saved in a publicly accessible location without worrying about tampering.

Transaction 3 and 4 are created and signed before funding the escrow account and have the same transaction number. It is done to ensure that two parties are in agreement. If circumstances had to be changed before submitting any of these two transactions, both the target and origin have to authorize transactions utilizing the escrow account.

Transaction 3 eliminates the escrow account as a signer for transactions generated from itself. It transfers complete control of the escrow to the target. After the lock-up time period ends, the destination account is the only account required to sign for transactions from the escrow account. The unlock date (D+T) is the first date when the unlock transaction is submitted. If transaction 3 is submitted before the unlock date, the transaction will not be considered valid. The max time is set to 0 which implies that the transaction does not have an expiration date.

Transaction 4 is for account recovery if the target does not submit the unlock transaction. It eliminates the destination account as a signer and resets weights for signing transactions to need its signature. It returns the full control of the escrow account to the origin. Transaction 4 can only be submitted after the recovery date (D+T+R) and does not have the expiration date.

Transaction 3 can be submitted any time during the recovery period R. If the target does not submit transaction 3 to provide access to funds in the escrow account, the origin submits transaction 4 after the recovery date. The origin can reclaim the locked-up assets if required to sign transactions for escrow. Both transactions 3 and 4 are considered valid after the recovery date and can be submitted to the network. However, only one transaction will be accepted by the network.

Therefore, it can be concluded that if the target does not submit transaction 3, then the origin submits transaction 4 after the recovery period.

Transaction 5: Funding

Account: Source Account

Sequence Number: M +1


Payment: Pay the appropriate asset amount to the escrow account

Signers: Source Account

Transaction 5 deposits the appropriate amount of assets into the escrow account from the source account. It should be submitted once the destination account signs transaction 3 and 4 and publish them back to the source account.



When designing and writing Stellar Smart Contracts, all the involved parties must come together and outline the contract’s purpose clearly. Ensure to analyze and agree upon the conditions and outcomes when designing smart contracts. Also, the written smart contracts are required to 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.

If you don’t have the technical expertise and are looking to design and create Stellar Smart Contracts, get in touch with our Stellar Blockchain Developers Team and get started.

Author’s Bio

Akash Takyar
Akash Takyar
CEO LeewayHertz
Akash Takyar is the founder and CEO at LeewayHertz. With the experience of building over 100+ platforms for startups and enterprise 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.

 Send me the signed Non-Disclosure Agreement (NDA)


DeFi Development

DeFi Development We provide decentralized finance development services to help clients bring transparency, trust and security into their finance operations by developing decentralized finance applications. Our DeFi Development ServicesAs a DeFi Development Company, we...

read more

How to build a Fintech App?

A fintech app should be easy-to-use and highly secure. Hiring an experienced development team can help you ensure robust fintech app development.

read more