Loading...

Concept: Smart Contracts

Ozier Zarouq Khan
Ozier Zarouq Khan 29 September 2021

Smart contracts underlie many of the most productive new features of blockchains and blockchain-based platforms.

Decentralized finance, NFTs, decentralized applications, and even many tokens and altcoins, all rely on smart contracts.

Broadly speaking, a smart contract is computer code that automatically executes a function when pre-specified conditions have been met. That makes them both potentially very simple, and often very powerful. In this guide we’ll explore what they are, how they work, what they’re used for and even how to create one.

Let’s start at the beginning.

What is a smart contract?

A smart contract is a series of if-this-then-that gates that can’t be changed once they’re agreed to.

When two parties set up a conventional contract, they agree to each meet certain conditions in exchange for certain outcomes. If I buy a car from you, our agreement is that you give me the car and I give you the money.

Most formal contracts are more complex than this, with multiple conditions to be met in several stages. And at each stage, goods, services and finances change hands. In traditional contracts this process has to be managed manually, often with the assistance of trusted intermediaries, and there’s a certain degree of trust required between the parties too. You have to trust that I’ll ask my bank to transfer money to your bank. If I don’t, you have recourse but it’s unwieldy and expensive, and it can damage your business operations and reputation in the meantime.

Smart contracts eliminate the requirement for trust and for manual input. When conditions are met, actions are taken automatically, triggered by the contract. So if I buy something from you, I might put the funds in escrow controlled by the contract; they’re now out of my control. You might put the goods or services I’m buying under the contract’s control too. (This can be done with physical items via Internet of Things integrations which are discussed below.) Now, the contract delivers my car and your money automatically.

In fact, smart contracts are especially suited to particular types of agreements: those between anonymous, pseudo-anonymous, or mutually unknown parties; those that require multiple conditions to be fulfilled very quickly; and those involving chains of agreements between multiple parties. As connectivity improves, we can expect to see smart contracts used more in other roles, and it’s important to remember that they need not be contracts between parties in the conventional sense; they can be used in the same organization, or used as a substrate for other types of functionality.

A digital vending machine

One of the easiest ways to understand how a smart contract works is to consider it as a digital vending machine. When you put your money into a vending machine and select a product, you’re entering into a contract with the owner of that machine. But neither you nor the owner is required to trust, or even know about, the other. Your purchase is anonymous and under the control of the machine, not its owner. Put $1 in, choose a Snickers, and (barring technical malfunctions) that’s what you’ll get. The owner never has to think about you either; their revenues are just removed from the back end of the machine. Smart contracts work the same way.

How do smart contracts work?

Smart contracts work the same way as other computer programs, using inputs (data fed into the program), logic gates to process the inputs, and outputs. Smart contracts include logic to determine the validity of a transaction, including checking on available information like account balances and statuses. When smart contracts carry out transactions, they often result in altered states on their home blockchain and sometimes on other networks as well. Smart contracts usually include logic to determine the validity of transactions, meaning invalid transactions either get rejected by the network, or are included in a block but as failed transactions; either way they don’t result in a changed state.

Some smart contracts can publish events as a way to inform the outside world, notifying event listeners when the block containing the transaction is committed to the blockchain.

With smart contracts, the inputs can be instructions from other smart contracts; outputs can be instructions to other smart contracts. Smart contracts can be chained, and used to move value very rapidly — much more rapidly than a person could and orders of magnitude quicker than the traditional financial system. In fact, smart contracts can conditionally deploy other smart contracts!

Smart contracts fundamentally do three things:

1: Transfer value from the contract’s address

Smart contracts have an address and balance on the blockchain, just like any other participant. But their account has no private key. Instead, the code of the contract, viewable but not changeable, manages transfers.

2: Change states

Smart contracts can change the balances of accounts by paying to them, which changes the state of that account. But they can change other states too, on the same basis and using a set of rules known by everyone and built into the contract by its designers. Unlike altering balances these state changes are artefacts of the specific smart contract, rather than of the blockchain more generally.

3: Inputs

Smart contracts have access to inputs including:

  • The current state of the contract
  • The current state of the blockchain, expressed by block number and timestamp
  • The sender of a transaction
  • The value sent with the transaction
  • Optional data fields for customized smart contract logic

Computationally feasible logic

In theory smart contracts are Turing complete: they could perform any computational task. However, because of the node-based nature of blockchains in which every node has to agree to every change, smart contracts are subject to sharp limitations on available computational resources. Smart contracts have to spend computational resources conservatively, so they often have relatively simple structures even where they deliver quite advanced functionality.

The halting problem

Smart contracts could, in theory, contain orders to endlessly replicate themselves or enter computational loops; in this way they could consume the entire resources of a computational network and prevent it from functioning. Given a sufficiently powerful coding language there is no way to know in advance whether this will happen, and the same coding capacity that would make it possible is required to make smart contracts maximally useful. So the preventative has to be at the blockchain level since it cannot be at the deployment or contract level. Bitcoin solves this problem by having a scripting language so restrictive that the issue does not arise. Ethereum solves it with gas fees, designed to make a smart contract-based DOS attack on the network prohibitively — indeed, impossibly — expensive.

Benefits of smart contracts

Smart contracts can’t be reneged upon, or otherwise altered after they have been set in motion. They’re controlled by their own code and it’s protected by the same blockchain-based encryption that protects digital assets like Bitcoin. This makes smart contracts attractive when disintermediation is desirable: instead of having to wait until your bank clears my funds before I get my money, a smart contract just releases it when the conditions are met. In some cases, the other party doesn’t even have to OK the funds’ release: the smart contract itself contains logic to do that. For contracts between businesses that is attractive (and when you cut out the middleman, you cut out the fees, which is also an attractive proposition).

However, the appeal of disintermediation goes a lot further than that. Smart contracts allow transactions to take place across national borders, something digital assets already excel at; but a smart contract-actuated transaction can take place when neither party is even awake. Timezone differences no longer delay even routine transactions. Neither do jurisdictional disputes.

A transaction between two businesses is often a vexing process as a bank or other trusted third party imposes delays for administration. International payments can be delayed for weeks on this basis. However, even the most rapid manual payment involves delay as clumsy human fingers, busy human minds, process the transaction. Unsurprisingly a few lines of code do the job faster. That may not matter at the checkout and scheduled payments can simply be backdated. But moving money in response to a quickly changing environment — for instance, investments in digital assets — sometimes can’t be done fast enough by manual means. Even more crucially, when several transactions, contingent upon each other and outside factors, are chained together, smart contracts offer an unbeatable combination of speed, security and precision. This is exactly the case with DeFi, of course, which often relies on several very rapid transactions to generate returns.

Smart contracts are not used only for transactions. They also underlie Dapps, Decentralized Applications. These are like the applications we’re used to using on computers, mobiles or the web, except that they run partially or wholly on a blockchain-based computing system like the EVM. Not every smart contract protocol, not every platform, is equally suitable for Dapp use but where they can be implemented, Dapps can offer the security inherent in blockchain technology and the distribution and ease of use of a web app.

Altcoins and tokens

The majority of what are called altcoins (originally meaning “alternative coin”, meaning alternative to Bitcoin) are tokens running on a smart contract on the Ethereum blockchain. These include stablecoins like USDC, which is a token backed 1:1 by full-reserve US dollars, as well as tokens like the Brave Browser’s Basic Attention Token. Underlying the ability to move these tokens around on the Ethereum blockchain, and the capacity to “wrap” tokens and coins from different chains, is a smart contract.

Agreements

Unsurprisingly smart contracts are used for interbusiness and occasionally even interpersonal agreements. Smart contracts are legally enforceable to the extent that they comply with contract law, and are sometimes used in lieu of other contract types.

NFTs

NFTs are Non-Fungible Tokens. Where most tokens are interchangeable, NFTs are unique. NFTs are sometimes game artefacts, or ownership indicators for nonfungible items like art pieces or historically notable digital items. They’re often based on the ERC-721 token protocol, though there are many which are not.

DeFi

DeFi, Decentralized Finance, involves using a network of smart contracts, tokens and coins across multiple platforms to both replicate and expand the functionality offered to investors by the traditional financial system. Smart contracts are an irreplaceable component of the emerging DeFi ecosystem, and not just because they underpin the token economy and facilitate cross-chain exchanges; without smart contracts, the rapid, chained transactions needed for high-yield DeFi activities like yield farming would be impossible.

Dapps

Dapps are Decentralized Applications, and smart contracts allow them to access the blockchain. How much of a Dapp is reliant on blockchain functionality varies, with some all on-chain and others using blockchain access just for a few functions. Dapps can include smart contracts from third parties, since the code is open source. A Dapp can have any kind of front end, just like any other application, and it’s quite common for a Dapp to have a web app for a front end.

At a minimum, a Dapp must be:

  • Decentralized, meaning they can’t be controlled by a group or through a central point of control
  • Deterministic, performing the same function regardless of environment
  • Turing complete and able to perform any action given sufficient computational resources
  • Isolated and executed inside a system like the Ethereum Virtual Machine, meaning they can’t damage the rest of the network.

Common smart contract protocols: ERC-20 and ERC-721

Two of the most popular smart contract protocols are ERC-20 and ERC-721. Both are Ethereum-based, running on the Ethereum Virtual Machine. ERC stands for Ethereum Request for Comment, a standard form for Ethereum token protocols and descended from EIPs (Ethereum Improvement Proposals) with the same number.

ERC-20: the token protocol

Token Protocol

ERC-20 isn’t the only token protocol, but it’s by far the most commonly-used. ERC-20 tokens use a simple framework, and must include the following methods and events:

  • name: the name of the token, such as Tether
  • symbol: the token’s symbol, such as USDT, ₮
  • totalSupply: provides information about the total token supply
  • balanceOf: provides account balance of the owner’s account
  • allowance: returns a set number of tokens from a spender to the owner

Smart Contracts

  • Transfer: executes transfers of a specified number of tokens to a specified address
  • TransferFrom: executes transfers of a specified number of tokens from a specified address
  • Approve: allow a spender to withdraw a set number of tokens from a specified account

Smart Contracts 2

ERC-20 underlies popular tokens including:

  • Chainlink (LINK)
  • Tether (USDT)
  • Wrapped Bitcion (WBTC)
  • OmiseGO (OMG)
  • 0x (ZRX)
  • Populous (PPT)
  • Maker (MKR)
  • Augur (REP)
  • Golem (GNT)
  • IOStoken (IOST)
  • Status (SNT)
  • DigixDAO (DGD and DGX)
  • Loopring (LRC)
  • Basic Attention Token (BAT)

The full Ethereum guide to the ERC-20 token protocol is here. A step-by-step guide to creating an ERC-20 token is here.

ERC-721: The NFT token

Again, Non-Fungible Tokens run on many other tokens, including ERC-20 tokens, but ERC-721 is the industry standard at the time of writing. ERC-721 lets users create tokens that aren’t interchangeable with each other the way, say, dollar bills are; instead, each contains identifying data that makes it unique. This uniqueness is the basis of the emerging NFT economy.

Just like the ERC-20 protocol, ERC-721 prescribes a certain number of essential functions and events necessary to create and manage a non-fungible token. However, additional events can be added to ERC-721 implementations — for instance, CryptoKitties’ ERC-721 has custom Pregnant and Birth events. Standard events and functions include:

  • balanceOf: Account balance of the owner’s account
  • ownerOf: Identifies the owner
  • safeTransferFrom: Checks the recipient is a valid ERC-721 receiver contract, and lets the sender pass on some data to that contract

ERC721

  • ApprovalForAll: Emitted when an account grants or revokes permission to an operator to transfer their tokens.

Approval

A full guide to the terms in ERC-721 can be found here. The official ERC-721 website is here, and the Ethereum token standard is here.

How smart contracts are deployed

Once a smart contract has been created, it needs to be deployed to the network before it can be used. On the Ethereum network, this is done by sending an Ethereum transaction containing the code of the smart contract, but without specifying a recipient. Sending this transaction will incur gas fees like any Ethereum transaction, but gas fees are higher for contract deployment than for a simple ETH transaction.

To deploy an Ethereum-based smart contract, you need the contract’s bytecode, which is generated through compilation. Compiling a smart contract turns the contract’s Solidity code into bytecode, which is computer object code that is processed by a program. It might help to think of it as machine code, but for the Ethereum Virtual Machine. When it’s coded, the contract might look like this:

EVM

When it’s compiled, it looks more like this:

PUSH1 0x80 PUSH1 0x40 MSTORE PUSH1 0x4 CALLDATASIZE LT PUSH2 0x41 JUMPI PUSH1 0x0 CALLDATALOAD PUSH29 0x100000000000000000000000000000000000000000000000000000000 SWAP1 DIV PUSH4 0xFFFFFFFF AND DUP1 PUSH4 0xCFAE3217 EQ PUSH2 0x46 JUMPI JUMPDEST PUSH1 0x0 DUP1 REVERT JUMPDEST CALLVALUE DUP1 ISZERO PUSH2 0x52 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH2 0x5B PUSH2 0xD6 JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 DUP1 PUSH1 0x20 ADD DUP3 DUP2 SUB DUP3 MSTORE DUP4 DUP2 DUP2 MLOAD DUP2 MSTORE PUSH1 0x20 ADD SWAP2 POP DUP1 MLOAD SWAP1 PUSH1 0x20 ADD SWAP1 DUP1 DUP4 DUP4 PUSH1 0x0 JUMPDEST DUP4 DUP2 LT ISZERO PUSH2 0x9B JUMPI DUP1 DUP3 ADD MLOAD DUP2 DUP5 ADD MSTORE PUSH1 0x20 DUP2 ADD SWAP1 POP PUSH2 0x80 JUMP JUMPDEST POP POP POP POP SWAP1 POP SWAP1 DUP2 ADD SWAP1 PUSH1 0x1F AND DUP1 ISZERO PUSH2 0xC8 JUMPI DUP1 DUP3 SUB DUP1 MLOAD PUSH1 0x1 DUP4 PUSH1 0x20 SUB PUSH2 0x100 EXP SUB NOT AND DUP2 MSTORE PUSH1 0x20 ADD SWAP2 POP JUMPDEST POP SWAP3 POP POP POP PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 RETURN JUMPDEST PUSH1 0x60 PUSH1 0x40 DUP1 MLOAD SWAP1 DUP2 ADD PUSH1 0x40 MSTORE DUP1 PUSH1 0x5 DUP2 MSTORE PUSH1 0x20 ADD PUSH32 0x48656C6C6F000000000000000000000000000000000000000000000000000000 DUP2 MSTORE POP SWAP1 POP SWAP1 JUMP STOP LOG1 PUSH6 0x627A7A723058 KECCAK256 SLT 0xec 0xe 0xf5 0xf8 SLT 0xc7 0x2d STATICCALL ADDRESS SHR 0xdb COINBASE 0xb1 BALANCE 0xe8 0xf8 DUP14 0xda 0xad DUP13 LOG1 0x4c 0xb4 0x26 0xc2 DELEGATECALL PUSH7 0x8994D3E002900

The contract’s code is turned into Application Binary Interface code which allows web applications to access and display it, usually in the form of a JSON file. These are the top 15 lines of the ABI file for the ERC-20 token:

ABI

You’ll also need a deployment script or plugin such as the one provided by Remix, though some projects choose to do this entirely in JS. Finally, you must have access to an Ethereum node, either belonging to you or via a public node or an API key-powered service like Infura or Alchemy. Once a smart contract is deployed, it is a “first class citizen” on the Ethereum mainnet with the same rights and privileges as any other account.

Smart contracts outside Ethereum

So far in this post, we’ve talked as if Ethereum is the only network capable of running smart contracts. But other networks offer smart contracts too. Ethereum has the first-mover advantage and is regarded as the tried-and-tested solution, but there are other options, including:

Smart contracts on XRP

XRP Ledger, the blockchain of the Ripple coin, has announced plans to enable smart contracts as part of its plans for Federated Sidechains. Developers can test-deploy XRPL smart contracts on fully-functional sidechains, where they may be sharing space with Central Bank Digital Currencies (CBDCs).

Smart contracts on Cardano

Cardano announced the completion of its Alonzo hard fork on September 13 2021, which among other changes introduces smart contract functionality to the Cardano blockchain. In a blog post published the same day, Cardano’s marketing and communications director Tim Harrison noted that now is “when the mission truly begins”.

Cardano will treat smart contracts slightly differently depending on their purpose. Some smart contracts are designed simply to transfer value, which requires relatively simple code and ideally a domain-specific language focused on value exchange. For this purpose, Cardano has Marlowe, a domain-specific language that covers the world of financial contracts. Other smart contracts have a wider scope and underlie decentralized applications; they require more flexibility and need a full-featured language. For this, Cardano offers Plutus, a platform to write full applications that interact with the Cardano blockchain.

Cardano’s smart contract capabilities were not live at the time of writing, but developers and projects wishing to test the network can use the Marlowe Playground, a browser-based editor for potential Marlowe smart contracts.

Smart contracts on Solana

Solana refers to smart contracts as Programs and natively supports them in C, C++ and its own Rust language. It’s oriented more toward Dapps than tokens, and can be written entirely on-chain or use an API.

Smart Contracts on Solana

Where Polkadot has pallets, Solana has ready-made Programs including an ERC-20 analogue called the Token Program. Developers who wish to begin creating Dapps on Solana can start with the Solana Labs Dapp Scaffold.

Because Solana offers native support for smart contracts and a powerful and versatile platform to run them on, it’s attracted a lot of attention, especially from DeFi traders struggling with the congestion and high gas fees of the Ethereum network. From August 2020 to August 2021, Solana’s native coin rose over 3,200%, tripling during the month of August 2021 alone to peak at over $100.

Smart contracts on PolkaDot

Polkadot has an overarching relay chain, and parachains: chains that function as independent blockchains with their own rules, but that connect to the overarching relay chain. The Polkadot relay chain will not natively support cmart contracts, but several parachains on Polkadot will support them.

Polkadot offers its users “pallets”, boxes of readymade code that can easily be bolted together for specific functions, written in the network’s own Substrate code. There’s a smart contract pallet, indicating the network’s expectations that smart contracts will form a major part of its activity. That’s particularly important because Polkadot intends to be the place where the nascent DeFi industry grows, and also because of its EVM pallet which allows parachains to implement the EVM natively and support direct ports of Ethereum contracts. This is already being used by some projects, including Edgeware, Moonbeam and Frontier.

Polkadot smart contract creation resources include: + Edgeware Contracts: Edgeware’s documentation on Smart Contracts + Ink!: Parity’s code for writing smart contracts. + Substrate Contracts Workshop: a walkthrough of the basics of writing and deploying an ERC20 token using ink!

Conclusion

Smart contracts are here to stay. As blockchains get better at offering and apportioning computational resources, we can expect to see development of smart contracts get easier; it’s already possible to create one without even knowing how to code. As that happens, more and more applications will become Dapps, with one foot in the blockchain and one in web 2.0 or even desktop applications. The current crop of DeFi and other applications can also be expected to grow in scale and complexity, both requiring more developed smart contracts and being driven by their increasingly easy availability on platforms like Solana and Polkadot.

Disclaimer:

Disclaimer: This publication is general in nature and is not intended to constitute any professional advice or an offer or solicitation to buy or sell any financial or investment products. You should seek separate professional advice before taking any action in relation to the matters dealt with in this publication. Please note our full disclaimer here.