This episode features smart contracts. After reading through the article, you will have a basic understanding of smart contract functionality, use cases, composition, and history. I want to provide you with an edge in knowledge that will set you apart from the standard smart contract crowd; this part also describes Live contracts.
In most cases, Smart Contracts are similar to paper contracts of the analogue world but instead of ink on paper, they are written as digital text in computer-readable code. The same way a local computer program can be run by selecting it in the operating system, a smart contract can be triggered by calling a method on the contract using a blockchain transaction (TX). The 'program' that the contract executes is stored on a node, which is part of a peer-to-peer (P2P) network of servers. The smart contract is distributed with hundreds of copies over hundreds of nodes that, with other parts, create a blockchain network. When executed, both the programs in your PC and blockchain smart contracts (which are also programs) do what they have been designed to do, assuming there are no software bugs.
“In the end, a smart contract is nothing more than the exact same piece of code that's executed on many (hundreds) of computers that all calculate the exact same result.” - Arnold Daniels
Storage, written in Solidity
pragma solidity ^0.4.0;
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
The Smart kid wants to invite his friends from kindergarten to his birthday party, but only the smart ones, who know how to count. To resolve this conundrum, he decides to ask the kids “does one plus one equal two?” If they're correct, they’ll get invited. His dad, however, has a different method in mind...
Father: Let’s do things a little bit differently. Instead of asking if they agree with our result one by one, we will do it as a smart contract does.
Son: Like a smart-what?
Father: Instead of saying “1 + 1 = 2” and asking others if they agree, you will distribute a few paper letters to your friends with the "1 + 1 = ?" message and let others calculate the result for themselves. When they solve it, they will tell us their result. We will be observing their participation and counting right and wrong answers.
Son: That way we find out who is able to count like me and could be a good friend for my birthday party on Friday?
Father: Exactly! Now, here are some pencils and papers, let's create a paper for each of your potential friends, tell them to solve it after they count to 10 then get back to me.
Son: Heyyyy my potenti... friends! Let's play a counting game!
A few moments later...
Father: We know the result is 2, let's see how your friends handle this...
Scotti calculates 2.
Unikum also calculates 2.
Gimp has also calculated 2, even though it took him a long time.
Then, out of the blue, JohnDoe finishes his calculation and shouts, "1 + 1 is 3!".
Father: See? Go and play with other cool kids from the block and leave JohnDoe to eat rocks.
DeFi is a cryptocurrency use case that has recently been attracting significant attention. DeFi refers to financial services that use smart contracts, which for example:
Smart contracts are automated consensus-relaying agreements that do not need intermediaries, such as banks or lawyers, and use online blockchain timestamping and identities as proof of authority instead. The beauty of a smart contract is that it can hold value (for instance by holding SOV tokens on the RSK blockchain) and is enforced automatically by the blockchain full nodes and miners when the pre-set contract conditions are met.
Let's assume a simple example with a crowdfunding platform. There are investors (also known as "backers") who want to support a project that requires money to be realized. If the project gets funded and is successful, the investors are likely to gain a hefty return on their investment. Using the decentralized trust mechanism of smart contracts, the crowdfunding platform provides backer insurance of sorts, where a significant chunk of the funds are locked and released in tranches only when the team reaches a promised milestone. If the funding goal is not met or the project’s team does not deliver the promised results, the invested money is returned to the backers. Oracles provided information that the team has already run out of the time they claimed to use for fulfilling targets from their roadmap. In addition, smart contracts ensure that the money from backers goes from the crowdfunding platform directly to the project team and nowhere else.
On top of all this, smart contracts can also be used to define possibilities. In the chess game example featured in Episode 1, smart contracts could fuel an application that reads the game record and designs a playable possibility for each move played, while at the same time monitoring the current state or position of the piece on the playing field. As a result, the observer could, for instance, see highlighted fields around the figures of his choice that would indicate his possibilities on where and how to move his pieces in accordance with the game rules. In a case where both players bet on themselves (staked something in the contract) before the game started, this smart contract would award a prize to the winner after the checkmate.
Other real-world adaptations:
Main benefits of smart contracts:
The states of these contracts and these state transitions have value only as long as all participants in the blockchain believe they have. An example could be, again, the miners of the Ethereum network. They decided by a large portion of the votes that the state of the blockchain on Ethereum Classic was not valuable to them and decided to abandon it.
An example of a token-swap on uniswap.
Examples:
A successful swap between two tokens that happened with market volatility lower than your maximal slippage rate. The user pays for the associated transaction fee.
Tokens were returned to a staker after the end of the staking period with additional tokens from the reward pool for keeping the tokens staked for its complete staking period.
ICO investors obtained tokens from the crowdfunded project. These new tokens are obtained in exchange for a pre-agreed amount of RBTC users sent on the crowdfunded project address (fees are paid by the crowdfunded project).
If somebody interfered with the contract and the contract thus didn't fulfill its original purpose due to non-compliance, or additional global conditions were not met -> the ”smart-contract-B-plan” is executed for the interferer in its original design and:****
For the interferer:
NOTE: Any penalties, slashings, losses can only occur if the contract is executed. such penalties, like the slashing in case of early unstaking, are rules set on the smart contract level. hence, it's to be considered a successful execution according to the contract rules.
For a user who did not interfere with the contract but the global (or smart contract) conditions were not met (thus, not always the user's fault)):
Examples:
In the scenario where two parties in agreement fulfilled their obligation to the smart contract, thus the predetermined conditions have been met, the contract will be executed as originally designed. When a party decides not to meet the predetermined conditions and wants to break the contract, the part of the contract code of our aforementioned staking example will be executed in a way that benefits the party that was in the right and penalizes the party who walked away from the contract. That's the typical description of the legal-ish type of smart contract, where both (or several) parties are required to stake a value that will be transferred to a counterparty if one of the parties doesn't stand for what was agreed upon. This particular smart contract setup is not universal and can be written in a way to fit any use case or possible scenario.
In the blockchain world of late 2018, ICO smart contracts (where a user got a direct amount of tokens for the ETH amount they sent into the ICO contract) were trendy. Then, consider the Uniswap decentralized exchange. Each of their swaps between two crypto assets triggers a smart contract that delivers the new asset to the buyer's wallet and removes the asset they paid with.
Since smart contracts are completely digital, rule-based, and configured as machine-readable algorithms, they automate much of the data mechanics on the blockchain and remove the need for the middle-man third party. Smart contracts never execute themselves; they always need to be triggered from the outside by a blockchain transaction. Often, if a function is supposed to be executed under certain conditions, these functions are executable by anybody. Take the liquidation of margin trade positions as an example. The contract cannot liquidate the position without being triggered. But because anyone can initiate a liquidation, anyone can make sure that the system behaves as expected. It does not depend on a single party doing the liquidations. For such crucial functions, there's often an economic incentive for the executor. Liquidations, for example, offer the liquidator the option to purchase the position's collateral for a discounted price.
Smart contracts gained even more attention during the movement to free financial assets from the yoke of intermediaries - a movement also known as decentralized finance, or DeFi. And that's the space where smart contracts, because of their ability to make crypto-asset lending possible, found their greatest demand in 2021.
Even though smart contracts may appear to be a fundamental aspect of every blockchain, some of them, such as Bitcoin, do not support them in the way the Ethereum blockchain does. Still, it is possible to add this functionality through a sidechain, the use case of which can be imagined as a software "extension" or a "plug-in" for a particular chain. This “plug-in” enhances the use of the native chain while keeping the original setup untouched. In the case of Bitcoin, the RSK sidechain "plug-in", even though it is difficult to find a proper metaphor here, is bound to their Bitcoin blockchain and provides 100% on-chain settlement.
The RSK side-chain is Ethereum virtual machine (EVM) compatible, which allows for the execution of smart contracts code. Simply said: All the things that can not be handled on Bitcoin directly can be adapted and brought to the Bitcoin ecosystem through Bitcoin sidechains.
RSK sidechain:
Difference between a sidechain and Layer-2 solution:
Layer 2 generally relies on the security of the main chain while a sidechain has its own security properties.
More about sidechains in chapter 10 of this series. Now, let's get back to smart contracts.
These contracts were first introduced as “Ricardian Contracts'' in 1994 by Nick Szabo, a computer scientist, legal scholar, and cryptographer. The term “smart contract” was first introduced long before the invention of Bitcoin, but it underwent a long gestation period of inactivity and disinterest since there was no platform that could enforce a smart contract, until the advent of Bitcoin blockchain technology in 2009. Nick Szabo’s intention was to use a distributed ledger to store contracts.
The smart contract concept is rooted in basic contract law. Usually, the judicial system adjudicates contractual disputes and enforces terms, but it is also common to have a different arbitration method, especially for international transactions. With smart contracts, a program enforces the contract built into the code. Smart contracts have been gaining popularity over recent years. Most notably, Ethereum (one of many ICOs on Bitcoin - the first was Mastercoin) has made it a basic tenet of their blockchain’s power to program smart contracts using a special language called Solidity. This exponential growth of smart contract usage was a major contributor to the DeFi boom that started in the summer of 2020.
Smart contracts have to be deterministic because each node of the network has to be able to find the same result when given the same input for a contract method. Otherwise, each node that executes the contract method to validate the transaction would end with different results, and no consensus would be possible. For this reason, some smart contract programming languages do not allow the use of functions that round numbers or generate randomness. Even though this is not a rule of the thumb, the most famous language for writing smart contracts, Solidity, doesn’t allow the use of these functions that would lead to a non-deterministic result.
However, it is possible to round numbers in Solidy, but it is not possible to create true randomness. No computer can. It's always pseudo-random, because it's an algorithm creating it and an algorithm is just following rules. A random number generator always needs to be fed with a seed. That's where the problem for smart contracts lies. You can't use data on the contract as input, because it's publicly available information (also if the variable is private -> because it needed to be set at some point), you can't use user input, because the user would then be able to compute the result in advance and manipulate the outcome, you can't use the timestamp as input if considerable funds are at stake, because the timestamp can be influenced by miners.
Example:
Using the fixed set of rules, the `Math.round` function rounds 0.499999... down to 0 and 0.5 up to 1.
It is possible to write functions for doing the same with solidity since the Numbers are always rounded the same way.
Let's take a token like SOV as an example now:
SOV has 18 decimals, but SOV is represented as an integer on the contract. The contract knows that the last 18 digits are supposed to be the decimals, so, if you would like to round, let's say to 2 decimal, you will look at the 3rd decimal and establish the result from there:
An example of such code:
function roundTo2Decimals(uint number){
number = number / 10^15; //assuming 18 decimals
if ((number + 5) / 10 > number / 10) number = number + 5;
return number / 10 * 10^16;
}
Smart contracts ensure that the result is always deterministic. So, there is no random number generator inbuilt because it would generate a different number each time the code is executed. This means that no one would be able to verify if a miner was computing the correct result or not.
Functions that can produce randomness, and as such, are forbidden in Solidity by design:
An example of a project that used a non-deterministic programming language for writing smart contracts is Lisk. They used JavaScript, which is a popular, powerful, and easy-to-use language, but allows for the potential for human error in the matter of writing smart contracts. If the above-mentioned functions are not handled with utter vigilance, they can completely wreck your contracts and their purpose, which is to deliver a deterministic output.
- For the record, team Lisk warned developers properly using their documentation.
The power of Solidity and other deterministic languages is that developers don't even have to care about being correct about final determinism in their contracts in the first place. It's simply because there are no non-deterministic functions they could use in the language by default.
Oracles are an interesting concept, directly related to smart contracts. In the blockchain world, oracles are something like data workers, which put the off-chain data (data stored out of a blockchain) on a blockchain (on-chain). Because the smart contracts can't use off-chain data directly, they need the help of oracles, which stores this data on-chain first.
Oracles deliver a real-world representation of information, such as:
and they can also have an agent-like property that directs the smart contract to behave in a certain way.
Example of cooperation between smart contracts and oraclesPermission to join DeFi crypto lending based on the US residence or notThis will be decided by a smart contract which will obtain information about user-sensitive information always stored off-chain using a centralized oracle.The decentralized oracle will publish a list of addresses of identities allowed to participate in the DeFi crypto lending contract.An oracle concerned with a user's ability to participate in crypto lending will check: an off-chain identity using the information provided during KYC (verifying passport or driver’s license)an on-chain identity utilizing the user's blockchain address through a cryptographic challenge by requesting a public key pair signature (each address has its private/public key pair)The smart contract as the authority can then determine if this user, based on checking up their identity, is allowed to participate in crypto lending or not.
Oracles can be arranged into various classes based on their intended purpose. There are centralized and decentralized oracles. Then there are oracles that put information into smart contracts and oracles that take the info out of them. We can distinguish them even further based on the input they are using. The next category of oracles is if their information intake is based on software or hardware solutions. The two current inputs for blockchain oracles are obtained from devices for data digitization, such as scanners or various types of sensors, or directly from the internet. We need to mention that this classification is not finite. Combining different applications and technologies makes it possible to obtain variations, such as software centralized inbound oracles.
The following classification summarizes the commonly used types of blockchain oracles:
Classification of oracles:
Types of oracles
Contract-specific oracles are oracles bound to a specific smart contract.
Much like smart contracts got into the general consciousness because Ethereum was designed to operate with them, Live contracts are getting public attention via utilization on the LTO Network blockchain. While a smart contract has been designed as a program operating on the blockchain and readable by computers, a Live contract is described as deterministic graphs produced by finite-state machine algorithms, readable by both humans and computers. It is a way for two parties to communicate with each other, and also an encapsulation of rules and conditions that are essential to do business on a blockchain, into a single unit. Since the Live contract is in the secure environment provided by a blockchain, they can act as the guides and validators.
To make Live contracts easily understandable for both computers and humans, they are split into several units. The parts that are considered simple and safe can be executed by computers in the same way smart contracts are. Other parts can, and should, be left to human interpretation.
A Live contract provides a dynamic method for defining logic on the blockchain similar to a smart contract. However, the purpose of a Live contract is not just to determine the state of a process, but to actively instruct humans and computers about the steps it contains. In other words, a Live contract is a workflow - that is, a sequence of related steps or processes that are necessary to complete a particular task. Think of it this way: a workflow has rules, where a specific action triggers another action, and so on. A workflow is essentially the general template of a business process.
Example:
Consider a workflow of a simple lease agreement approval, in which a document gets:
The process we need now to define is a specific instance of a workflow, so, for example, the lease agreement between parties A and B, which was drafted by an employee of B company, approved by the B company CEO, and then signed by both parties. A workflow always contains and follows certain logic that acts as the rules and pointers for a particular workflow.
Workflow logic example:
To summarize this:
Smart contract or Live contract diagram - LTO Network, 2019 (click for larger image).
Imagine that we encoded the rules of chess into smart contracts. Smart contracts validate if the moves you are about to take on the chessboard are valid or not. The problem with smart contracts is that they were designed to be easily readable by computers, not humans. In a situation when you would want to play blockchain chess with somebody who is not able to read smart contracts, nor is familiar with the exact rules of Chess, you would have to provide an application to your opponent that would read those smart contracts for them and display playable possibilities from the current position. The player would then see highlighted fields that would determine his options for a valid move. The problem that occurs is that we cannot be sure that the paper rules, which we used to code the Chess game using smart contracts, are in sync with those put into a blockchain. Also, we can’t say for certain that we read and understood the paper rules correctly before we used this knowledge for writing the chess-move smart contracts. What if we use an old or unsupported edition of the Chess rules for programming Chess? Smart contracts, as they are designed, would then allow a forbidden move as valid or would call an invalid move as correct.
This is where finite state machines, which create a backbone of Live contracts (sometimes combined with smart contracts combined and oracles) come into play. Using this language, you can create graphs that are understandable by both humans and computers.
As a result:
These graphs can display the player's current state and show you the allowed steps from their positions. Oracles would validate that the chess game uses the most updated official rules. Now, instead of the possibility where you have a combination of a blockchain, paper rules, and smart contracts, you can encode and encapsulate all of this into a single Live contract.
But yet one critical element would have to be implemented, the last piece, which would seal the whole play of the deterministic game of chess using the blockchain. This aspect is called a multi-signature. If two players play a friendly chess game while sharing a table in the same room, there is no big problem. If this was a tournament where human factors can influence the game, a record of each move must be validated and signed by both parties. By doing so, a player would create a record of their move and a record of the move their opponent has made. This procedure would be followed by adding a player signature to the record, which would act as a timestamp. The opponent would do the same. If both records were identical, they would fit into each other and create a block of data called blockchain chess-round-one. As the game would continue, the recordings of gaming events are linearly stored in a sequential order that establishes a blockchain. Now imagine a situation where one of these players needs to leave the room for a moment, and the opponent uses this opportunity to tamper with the state of the current game in their favor by modifying a move they made four moves back. Thanks to the blockchain architecture and the way blockchain handles attempts to manipulate the history of the chain, the next move of the cheating player would automatically disqualify them, since their next move would not be in harmony with the history of the moves they already did and recorded. That's an important fact: every action on the blockchain carries the history of previous efforts. This information is then handed over to the upcoming block, keeping the game record accurate, ordered, and protected.
Use this analogy for certification sharing or real estate contracts, and you have a model where a blockchain can make the world a more trustworthy place to live.
Congratulations. You made the eighth step in becoming a blockchain expert.
This series is mirrored on the Sovryn Wiki here. It is also published on Hackernoon.
See you later in episode 9, where we will investigate Blockchain's impact on the world!
Until then, stay Sovryn!