An Introduction to IOTA Smart Contracts
The full article was originally published by Evaldas Drąsutis on Medium. Read the full article here.
I want to thank my colleagues in the IOTA Foundation who provided input and feedback for this article. In particular, Eric Hop, who headed the Qubic project and now joins IOTA Smart Contracts, and Jake Cahill, who is responsible for most of the wording.
IOTA Smart Contracts is an ongoing effort by the IOTA Foundation. The goal of this article is to inform the community about what we are doing and where we are heading with IOTA Smart Contracts. It also presents an opportunity for the community to begin contributing to the project with questions and feedback.
Recently, Eric Hop presented the Qubic project in his article The State of Qubic, and explained our decision to focus exclusively on smart contracts for the time being. Naturally, these developments raised many questions from the community about how IOTA Smart Contracts relate to Qubic’s vision.
This article will answer those questions, providing some context and a technical introduction to IOTA Smart Contracts. Although many aspects of IOTA Smart Contracts were derived from the Qubic project, in many ways it is a standalone project in its own right. We believe the direction we are taking has lots of potential and we are now taking the steps necessary to prove this potential in practice.
What is a Contract?
Before we define a smart contract, it is important to first understand what a legal contract is.
Legal contracts are non-deterministic agreements that are subject to complex legal systems. The laws surrounding contracts vary depending on a number of factors, such as the country in which all parties entered into the contract. The most important word here is “non-deterministic”. This means that contracts are often ambiguous, and their subjective interpretation can lead to disputes.
What is a Smart Contract?
In contrast, a smart contract is a programmed agreement that is completely deterministic and automatically enforced. This makes it impossible to dispute.
The concept of a smart contract was invented by Nick Szabo in the 90s in his paper titled Forming and Securing Relationships on Public Networks. In this paper, he envisioned contract rules encoded as computer code.
For example, a smart contract could be programmed for the following agreement:
If flight F is delayed for more than 3 hours, then pay insurance amount A to Alice’s account.
‘The flight is delayed’ is a condition of the agreement and ‘pay insurance amount A to Alice’ is a consequence of that condition.
The consequences of executing a smart contract depend on a set of conditions, which we call its state.
A smart contract’s state may include, for example:
Flight F: On-time
Alice’s account: 0
Smart contract account: 1000
Cover amount: 100
Paid out: False
A smart contract’s state is published to a distributed ledger. When an update occurs and the network reaches a consensus on the change, a new transaction is appended to the ledger to update the contract’s state:
Flight F: Delayed (a reference to another transaction with evidence of the delay)
Alice’s account: 100
Smart contract account: 900
Cover amount: 100
Paid out: True
Smart contracts leave an immutable audit trail on the distributed ledger and their automation saves time and money for the parties involved. The concept is simple and can be applied in just about every industry in a variety of interesting use cases, from tracking goods throughout the supply chain to exchanging ownership of stocks and bonds. However, smart contracts are an emerging technology. It remains an open question of how they will fit into existing legal frameworks and there is work to be done before they reach their full potential.
Types of Smart Contracts
Layer 1 (“On-chain”)
“On-chain” smart contracts, such as those on Ethereum, are part of the core protocol. This means that they are executed and validated by all nodes in the network.
- The security of smart contracts is proportional to the size of the network
- Smart contracts can transfer tokens from their account without providing a signature
- Smart contracts scale poorly because their programs must be executed by all nodes
- Smart contracts are subject to network transaction fees, which are as volatile as the underlying token price
- The average cost of a smart contract transaction is roughly proportional to the underlying token price
Layer 2 (“Off-chain”)
“Off-chain” smart contracts are executed outside of the core protocol. Only a subset of nodes, called a committee, need to execute them and a consensus can be reached outside of the core protocol.
- Smart contracts do not put a burden on the rest of the network
- The average cost of a smart contract transaction is low and predictable
- The necessary level of decentralization (and therefore security) of a smart contract can be adjusted to each use case.
- To transfer tokens, smart contract programs must sign transactions to prove they have access to the account address
- The decentralization (and therefore the security) of smart contracts depends on the size of the committee, the members of the committee, and the entity that sets up the committee
Why does IOTA need smart contracts?
Smart contracts are essential across many of IOTA’s verticals including Supply Chain, Smart Cities, Industrial IoT and others. IOTA Smart Contracts can automate contractual obligations within those industries.
How do smart contracts work in IOTA?
IOTA Smart Contracts are defined as immutable state machines:
- State machine: Each smart contract has a state, which is attached to the Tangle. The state contains data such as account balances, input conditions and consequences over time. Each state update represents a state transition on the Tangle.
- Immutable: The state and the smart contract program code are both immutable because they are stored on the Tangle. The state can be incrementally updated by attaching new transactions to the Tangle.
The Tangle provides a verifiable audit trail of the state transitions. It allows us to trust that the state transitions are valid and they cannot be corrupted by malicious or erroneous nodes.
The Case for Layer 2 Smart Contracts
To facilitate IOTA’s use cases, including the Internet of Things, we are building IOTA smart contracts on layer 2, ”off-Tangle”.
Although Ethereum’s “on-chain” smart contracts are popular due to their properties, they have some significant drawbacks. The most salient one is that for every smart contract in existence every node needs to keep a copy of the contract’s program code and state. Every node in the network has to execute the exact same code when the smart contract is triggered.
There is no limit to the number of nodes that have to run this identical code just to generate a single result. And as the network grows, the amount of processing needed to produce that same result increases. This is a huge barrier to scalability.
In addition to the transaction fees you need to pay to be considered for inclusion in the ledger, you also need to pay gas fees to keep the program running long enough for it to complete. This means the cost to run these smart contracts becomes prohibitively high for anything but certain classes of use cases where the cost overhead is relatively insignificant.
This is why IOTA Smart Contracts are not implemented as part of the core protocol but as a layer 2 protocol.
As a result, IOTA smart contracts provide a more natural way of running distributed computations. Each smart contract can be executed in a localized context without forcing the whole network to execute them. This also means that IOTA Smart Contracts will not become a barrier towards scaling the IOTA network with sharding solutions in the future.
The Owner of a Smart Contract
Each smart contract has an owner, who is responsible for:
- Creating the smart contract program and submitting it to the network.
- Deciding how big the committee will be (the number N) and selecting network nodes to be part of it.
- Deciding how many committee nodes must reach a consensus on smart contract state updates. This number is called a quorum.
- Defining other general configuration parameters of the smart contract.
An owner can be a single entity, such as an organization or a person, or it can be a decentralized collection of peers, such as a consortium of organizations. In each case, the owner manages only the setup and configuration of the smart contract and does not participate in running it.
Owners can choose how to set up smart contracts, depending on their context and purpose. For example, a smart contract that handles high-value transactions may require a large committee of nodes. While a smart contract that handles microtransactions may need only 20–30 nodes in the committee.
Motivations: Rewards and Reputation
There are many possible reasons for wanting to create or run a smart contract. One reason is the rewards.
Although IOTA transactions are feeless, IOTA smart contracts present an opportunity for businesses to charge a fee in IOTA tokens such as for covering operational costs. We call this fee a reward.
Both owners and committee nodes can receive smart contract rewards. It is up to the owner to negotiate with committee node operators to decide the minimum acceptable reward.
- Committee nodes can earn rewards by processing a particular smart contract that offers a reward.
- Owners also have an option to create smart contracts that send the owner a percentage of the reward.
Another potential motivation for being part of a committee is to build a good reputation. Smart contract owners may choose to form committees only of nodes with a good reputation.
This kind of reputation system could create an open market for committee nodes that encourages good behavior on the network.
The Smart Contract Program
A smart contract program is an algorithm that contains instructions for a Virtual Machine (VM). We will use WebAssembly (WASM) as the main VM for IOTA Smart Contracts. But in general, the VM can be in any language or even hard-coded in the node’s software.
The program takes two transactions as input: the request transaction and the current state transaction. The next state transaction always references the request transaction and the previous state transaction. This way, the smart contract program has a deterministic way of building a chain of state updates triggered by incoming requests.
The hash of the program is stored in the Tangle and is therefore immutable.
An Example of a Smart Contract Program
What follows is a short description of the FairRoulette smart contract: our internal PoC we use for testing.
Consider a smart contract that takes bets on a roulette wheel. The smart contract would contain staked IOTA tokens in its account as well as data about each placed bet (sum, color, player). The latter is needed for payouts to the roulette game-winners.
To place a bet, you send a request transaction to the smart contract. The transaction would contain:
- A fee payment of IOTA tokens for processing costs
- A deposit of IOTA tokens that you want to bet
- The color you are betting on
Then, when the committee nodes see this transaction, they will execute the smart contract’s program to update the state with your bet.
Payout to winners will be executed automatically according to the smart contract’s program after the game is over.
The Committee and the Quorum
The smart contract’s account address is owned by the committee. This address contains the deposited IOTA tokens. Only a quorum of committee nodes is able to transfer tokens away from the address. In other words, a quorum of committee nodes must cooperate to move IOTA tokens from the account.
We use BLS multi-signature addresses to give nodes in the committee equal ownership over the address. These addresses enable threshold signatures, which means that a certain quantity of nodes in the committee, the quorum, must sign the same transaction with their secret key to produce a valid signature, and therefore update the smart contract’s state and move funds controlled by the smart contract.
How Smart Contracts are Created
The owner of a smart contract creates the program and its binary code is stored in committee nodes. The hash of the program is always accessible through the state transaction, so the smart contract is immutable.
The owner sets up a committee of nodes who are responsible for executing the program, listening to the Tangle for request transactions, and collectively updating the smart contract’s state.
During the committee set up, the owner decides the size of the committee and the quorum and initializes a Distributed Key Generation (DKG) process among the committee nodes. This process generates:
- An account address controlled by the smart contract.
- A private key for each committee node (not known by the owner or other committee nodes).
This process can either be centralized or decentralized. In the centralized version, the owner is able to use a master key to override committee decisions when needed. In the decentralized version, the owner cannot override decisions.
How a Smart Contract’s State is Updated
Committee nodes are always listening to the Tangle for request transactions to be sent to the smart contract.
When a committee node detects a transaction, it calculates the next state by executing the smart contract program. This way, honest and synchronized nodes will always produce exactly the same state update transaction. Committee nodes never exchange real results, only hashes. So, there is no risk of nodes copying each others’ results to try and game the reward.
If the nodes don’t agree on the updated state, they will each sign a different transaction, resulting in an invalid signature. Nodes must, therefore, reach a majority consensus on the updated state.
In the asynchronous setting of the Tangle, each committee node may see a different state, depending on its local clock or neighbors. Committee nodes must, therefore, run a distributed consensus algorithm to reach a consensus on the result. The result of the consensus is a hash of the result essence, collection of partial BLS signatures and a timestamp. All smart contract transactions are time-stamped and the timestamp is consistent with the majority of nodes’ local clocks.
When all nodes have reached a consensus, one member of the committee, called the leader, aggregates all the nodes’ partial BLS signatures before submitting the final transaction to the Tangle. This transaction must reference the previous state to produce a chain of state updates, which acts as an audit trail. When the transaction is confirmed, it becomes the new state of the smart contract.
IOTA Smart Contracts are extremely flexible but that flexibility also comes with challenges, some of which we have already developed solutions for.
A state fork is a conflicting copy of the smart contract’s state. This can happen when two or more transactions are attached to the Tangle, which both update the state in different ways. Although we expect state forks to be rare, they could theoretically happen in an asynchronous environment. For example, immediately before posting the final transaction, the leading node loses connection with the Tangle and after a timeout, another node takes over leadership. In this case, two leading nodes could post-state updates to the Tangle.
In order to prevent state forks — upon setup of the smart contract a unique colored token called a smart contract token (with a total supply of 1) is created and transferred to the smart contract address. Each state update sends the only smart contract token to the same address, which moves corresponding unspent output to the new transaction. This way, the transactions form a non-forkable chain, because it is impossible to split and spend the output of the smart contract token twice.
A snapshot is a way for a node to save disk space. Transactions before a certain date might be ‘snapshotted’ away. In doing so, older smart contract state transactions and updates may be lost.
To mitigate this problem, smart contracts can perform their own snapshots by collecting all state information and adding it to a single transaction. This transaction becomes the start of the new chain.
Large sums of tokens
Locking a large sum of money in a contract for a long period is much safer when you can rely on the entire network being there to process it, like with Ethereum level 1 smart contracts. However, a limited-size committee is not guaranteed to exist after a long period of time. For these use cases, a smart contract owner might enact other contingency plans on a case by case basis.
Nodes need to manage a key for each committee that they are a part of. Therefore, when a node is part of many committees, storing and managing these keys is an essential task. Nodes will need a solution for secure and scalable key management.
IOTA Smart Contracts are smart contract programs that are executed by a permissioned committee on layer 2 (off-Tangle). The committee of nodes collectively updates the ledger by submitting signed transactions (using threshold signatures) to the Tangle.
IOTA Smart Contracts are very flexible and require much fewer resources than the blockchain alternatives. They allow for use cases that could not have been possible with fees as the only incentive. This is particularly true in the IoT realm, where micro-contracts and micro-transactions are expected to be the norm. We plan to use WebAssembly in the first version, but we are not limited to a single virtual machine (VM) with the possibility to use other programming languages and VMs in the future.
We invite the community to share their thoughts, ideas and feedback in the #smartcontracts channel on the official IOTA Discord.