What Are Smart Contracts and How Do They Work?

Smart Contracts Definition
DEFINITION

A smart contract is a decentralized computer program running on a blockchain network that automatically and deterministically executes agreements based on predefined conditions.

Introduced in their current form by the Ethereum blockchain, smart contracts are a fundamental building block for the Web3 industry; the foundation for the DeFi, NFT, gaming, and other applications that have gained prominence in Web3. 

Whether to codify arbitrary agreement terms between mutually untrusting parties, create automated and decentralized exchanges, or create both fungible and non-fungible tokens, smart contracts are how developers build decentralized applications on blockchains. Read on for a simple introduction to smart contracts and what they mean for society.

What Is a Smart Contract?

Smart contracts are computer programs that are hosted and executed on a blockchain network. Each smart contract consists of code specifying predetermined conditions that, when met, trigger outcomes. By running on a decentralized blockchain instead of a centralized server, smart contracts allow multiple parties to come to a shared result in an accurate, timely, and tamper-proof manner.

Smart contracts are a powerful infrastructure for automation because they are not controlled by a central administrator and are not vulnerable to single points of attack by malicious entities. When applied to multi-party digital agreements, smart contract applications can reduce counterparty risk, increase efficiency, lower costs, and provide new levels of transparency into processes.

Blockchains and Smart Contracts

Smart contract-enabled blockchains unlock the ability for developers to write arbitrary application logic on top of the decentralized consensus that blockchains natively provide. That’s why blockchains, smart contracts, and applications can be thought of in terms of a hierarchical relationship: Applications (including tokens) are created by the code from a smart contract (or multiple connected smart contracts). The actions defined in a smart contract are, in turn, executed and stored by the underlying blockchain network.

How Smart Contracts Work

Smart contracts are tamper-proof programs on blockchains with the following logic: “if/when x event happens, then execute y action.” One smart contract can have multiple different conditions and one application can have multiple different smart contracts to support an interconnected set of processes. There are also multiple smart contract languages for programming, with Ethereum’s Solidity being the most popular.

Any developer can create a smart contract and deploy it on a public blockchain for their own purposes, e.g., a personal yield aggregator that automatically shifts their funds to the highest-earning application. However, many smart contracts involve multiple independent parties that may or may not know one another and don’t necessarily trust one another. The smart contract defines exactly how users can interact with it, involving who can interact with the smart contract, at what times, and what inputs result in what outputs.  The result is multi-party digital agreements that evolve from today’s probabilistic state, where they will probably execute as desired, to a new deterministic state where they are guaranteed to execute according to their code.

Do All Blockchains Have Smart Contracts?

Not all blockchains can run smart contracts. While blockchains and layer-2 networks including Arbitrum, Avalanche, Base, BNB Chain, and Ethereum are examples of smart-contract-compatible blockchains, blockchains like the base Bitcoin blockchain do not have native smart contract capability. The key difference between these blockchains is the ability of an underlying blockchain to execute and store arbitrary logic.

History of Smart Contracts

Smart contracts were first coined by American computer scientist Nick Szabo in 1994. In his seminal writing, he gave a broad smart contract definition as follows: “a computerized transaction protocol that executes the terms of a contract,” with general objectives to “satisfy common contractual conditions, minimize exceptions both malicious and accidental, and minimize the need for trusted intermediaries.

While a general notion of smart contracts could be seen in systems like vending machines (e.g., a specific code leads to an expected snack), blockchains formed the foundation of smart contracts that were digital, tamper-proof, and permissionless. The introduction of the Bitcoin blockchain in 2009 supported arguably the first protocol smart contract—establishing a set of conditions that had to be satisfied to transfer Bitcoins between users on the network. These conditions include the user signing the transaction with the correct private key that matches their public address (akin to a password linked to a specific account) and the user owning enough funds to cover the transaction.

The Bitcoin blockchain then evolved to offer another major type of smart contract in 2012 called a multi-signature transaction. A multisig transaction requires a defined number of people (public keys) to sign a transaction with their private keys before it’s considered valid. This increases the security of user funds by mitigating single point of failures like a stolen or lost private key.

A simple framework for a multisig transaction on the Bitcoin blockchain that requires 2 out of 3 private keys to sign off on a transaction before it’s considered valid.

Blockchains began to experiment over the next few years by adding new programmatic conditions (called operation codes or opcodes). However, the next major leap in smart contracts came upon the publishing of the Ethereum whitepaper by Vitalik Buterin in 2013. In 2015, Ethereum launched as a new type of blockchain for programmable smart contracts. Instead of the blockchain acting effectively as a single smart contract application or offering a few limited opcodes, the Ethereum smart contract blockchain offered a “world computer” that could run many independent smart contracts at the same time.

Smart Contract Examples

One purpose of a smart contract is to automate a specific business process between a distinct group of entities. These entities collectively come to an agreement on all the smart contract’s terms like payouts, process flow, and dispute resolutions. A simple smart contract example for global trade may have terms like:

  • Term 1: If the goods arrive on time, then execute a payment from the retailer to the supplier in full amount.
  • Term 2: If the goods arrive one day late, then execute a payment from the retailer to the supplier for 98% of the full amount.

Other smart contracts support public decentralized applications (dApps) that anyone can interact with without needing any permissions. Public dApps are often open-source so anyone in the world can inspect exactly how they function before deciding whether or not to interact with them. One example of a public dApp is a decentralized lending/borrowing market, which may have the following terms:

  • Term 1: If the user deposits collateral into the specific smart contract, they can receive a loan that’s up to 50% of the value of their collateral (i.e., $100 deposit can borrow up to a $50 loan).
  • Term 2: If the user’s collateralization ratio (collateral/outstanding loan value) drops below 200%, then the user’s collateral is automatically liquidated and transferred to the lenders to ensure they don’t lose money.
  • Term 3: Lenders can deposit funds into a specific contract that other users can borrow from at predefined collateralization ratios, while the lender receives a claim to a portion of the interest rate payments.

Enforceability of Smart Contracts

Because they run on top of blockchains, smart contracts are automatically and deterministically executed exactly as programmed. In the context of enforcement, this hypothetically means that no party involved in a smart contract transaction can change its outcome or renege on terms outlined in a smart contract. 

Effectively, it’s possible for smart contracts—with the right design—to eliminate counterparty risk, often defined as the percentage risk that a counterparty will not fulfill its obligations. However, smart contracts introduce smart contract risk, or the risk that a smart contract’s code has an exploit or flaw that results in undesirable outcomes. Smart contracts always run as programmed, so if the program is faulty, then the smart contract will run the faulty code as expected. 

Another key consideration for smart contract enforceability is that some contracts are simply unenforceable through code. A key example is lending—DeFi protocols almost exclusively offer overcollateralized loans, where a borrower must put in >$100 to borrow $100, because there is no way to guarantee that a lender will pay back a loan unless the full amount is already in a smart contract. In these cases, the combination of smart contracts and offchain systems such as credit scores, proof of funds, and legal contracts can provide a defense-in-depth approach to mitigating counterparty risk.

Smart Contract Benefits and Limitations

Smart contracts undoubtedly offer the world a safer, more verifiable way of creating societal agreements that involve the transfer of value and data. However, the landscape of blockchains and smart contracts is still nascent, and developers must face a variety of limitations as they look to build out the vision of the verifiable web. 

Smart Contract Benefits

Most traditional digital agreements involve two parties that don’t know each other, introducing risk that either participant won’t uphold their commitments. To resolve counterparty risk, digital agreements are often hosted and executed by larger, centralized institutions like a bank that can enforce the contract’s terms. These digital contracts can be directly between a user and a large company or involve a large company acting as a trusted intermediary between two users. While this dynamic allows many contracts to exist that otherwise wouldn’t take on such risk, it also creates a situation where the larger, centralized institutions exert asymmetrical influence over the contracts.

The difference in how user funds are handled when making a payment through a blockchain vs. the banking system

Smart contracts improve upon digital agreements by offering several advantages.

  • Security – Running the contract on decentralized blockchain infrastructure ensures there is no central point of failure to attack, no centralized intermediary to bribe, and no mechanism for either party or a central admin to use to tamper with the outcome.
  • Reliability – Having the contract logic redundantly processed and verified by a decentralized network of nodes provides strong tamper-proof, uptime, and correctness guarantees that the contract will execute on time according to its terms.
  • Equitable – Using a decentralized network to host and enforce the terms of the agreement reduces the ability of a for-profit middleman to use their position of privilege to rent-seek and siphon off value.
  • Efficiency – Automating the backend processes of the agreement—escrow, maintenance, execution, and/or settlement—means neither party has to wait for manual data to be entered, the counterparty to fulfill their obligations, or a middleman to process the transaction.

Smart Contract Limitations

A hallmark limitation of smart contract development is their immutable nature: Once created, smart contract code cannot be changed. This can be viewed as both a powerful feature and a fundamental limitation: Immutable applications operate automatically for as long as the blockchain it runs on is live, but they cannot be upgraded for new features, functionality, bug fixes, or expansions. This highlights another limitation and risk for smart contracts—a smart contract that’s deployed with an undiscovered bug or exploit cannot be changed in a timely manner (or sometimes at all), making smart contract audits a core part of the smart contract development process.

One workaround that many developers use to combat this limitation is creating upgradable smart contracts, where a proxy contract is used to point to a new, updated smart contract. This does not break smart contract immutability, but rather unlocks the ability to direct users to a new, upgraded smart contract.

Smart Contract and Offchain Resources

Blockchains are isolated networks, meaning blockchains have no built-in connection to the outside world. Without external connectivity, smart contracts cannot communicate with external systems to confirm the occurrence of real-world events nor can they access cost-efficient computational resources. Similar to a computer without the Internet, smart contracts are extremely limited without real-world connectivity. For example, they can’t know the price of an asset before executing a trade, they can’t check the average monthly rainfall before paying out a crop insurance claim, and they cannot verify that goods have arrived before settling with a supplier.

Thus, the major evolution underway in the blockchain industry is programmable smart contracts that connect with real-world data and traditional systems outside a blockchain, expanding the inputs and outputs used within smart contract logic. These hybrid smart contracts use Chainlink to combine on-chain code with off-chain infrastructure—e.g., trigger a smart contract with external data or settle a contract off-chain on a traditional payment rail.

Oracles connect inputs and outputs to blockchains to create hybrid smart contracts

Similar to the Internet’s effect on computers, Chainlink’s decentralized computing platform is  the key to connecting emerging blockchain networks with today’s legacy systems to enable interconnected, performant, and privacy-preserving smart contracts that retain the security and reliability of the underlying blockchain network. By enabling externally connected smart contracts, Chainlink greatly expands and enhances the valuable properties of blockchains, leading to superior, verifiable digital agreements across more industries and use cases.

Smart Contract Use Cases

Rights Management (Tokens)

Token smart contracts are used to create, track, and assign ownership rights to specific digital tokens existing on blockchain networks. The token contract programs functionalities into the tokens it issues, providing holders features like utility/insurance in a dApp (utility token), voting weight in a protocol (governance token), equity in a company (security token), ownership claim to a unique real-world or digital asset (non-fungible token), and more. For example, the FIL token is used to pay for Filecoin’s decentralized storage services and the COMP token allows users to participate in the governance of Compound protocol.

Financial Products (DeFi)

Decentralized finance (DeFi) consists of applications that use smart contracts to recreate traditional financial products and services such as money markets, options, stablecoins, exchanges, and asset management, as well as combine multiple services to create new financial primitives via permissionless composability. The smart contract can hold user’s funds in escrow and distribute them between users based on predefined conditions. For example, BarnBridge uses smart contracts to automate trades for users wanting fixed asset exposure to a price pair (e.g., 45% token A, 55% token B), and Aave uses smart contracts to facilitate lending and borrowing in a permissionless and decentralized manner.

Aave supports decentralized lending markets by using asset prices to determine a user’s borrowing borrower and to see if loans are undercollateralized and subject to liquidation

Gaming and NFTs

Blockchain-based games use smart contracts for tamper-proof execution of in-game actions. One example is PoolTogether, a no-loss savings game where users stake their funds in a shared pool that is then routed into a money market where it earns interest. After a predefined time period, the game ends and a winner is randomly awarded all the accrued interest while everyone else can withdraw their original deposit. Similarly, limited-edition NFTs can have fair distribution models and RPGs can support unpredictable loot drops using randomness, helping to ensure all users have a fair shot at getting rare digital assets. Many projects access randomness using Chainlink Verifiable Random Function (VRF)—a random number generator (RNG) that uses cryptography to prove it's tamper-proof, meaning the RNG process is publicly auditable.

MLB baseball player Trey Mancini did an NFT drop to raise money for cancer patient support, where Chainlink VRF was used to randomly assign additional utility to some NFTs

Insurance

Parametric insurance is a type of insurance where a payout is tied directly to a specific predefined event. Smart contracts provide tamper-proof infrastructure for creating parametric insurance contracts that trigger based on data inputs. For example, crop insurance can be created using smart contracts, where a user purchases a policy based on specific weather information like seasonal rainfall in a geographic location. At the end of the policy, the smart contract will automatically issue a payout if the amount of rainfall in the specific location exceeds the original stated amount. Not only do end-users receive timely payouts with less overhead, but the supply side of insurance can become open to the public via smart contracts. The smart contract allows users to deposit funds into a pool and then distributes collected premiums to pool participants based on the percentage of their contribution to the pool.

Arbol uses Ethereum smart contracts and Chainlink oracles to enable parametric insurance based on weather data in a particular geographic region

{{cta-block}}

Frequently Asked Questions (FAQ) on Smart Contracts

How Do I Create a Smart Contract?

Creating a smart contract requires preliminary knowledge of smart contract development. This blog provides an example of a bare-bones, “Hello World” smart contract written in Solidity. 

How Do I Deploy a Smart Contract?

Much of smart contract development happens on test networks (testnets), where developers test their code before deploying on mainnet. Read this blog for a guide to deploying your first smart contract. 

How Are Smart Contracts Executed?

Smart contracts require an external party to trigger functions based on preset triggers, which requires a dedicated automation service. To learn how to automatically execute smart contract functions, read this blog.

How Do I Audit a Smart Contract?

Smart contract security isn’t just a nice-to-have, it’s a necessity. Learn the basics of auditing smart contracts by reading this blog

How Do I Start Learning Smart Contract Development?

One of the best resources for getting up to date on smart contract development this Chainlink smart contract bootcamp, which provides step-by-step guidance on the basics of smart contract coding. 

What Is a Smart Contract ABI?

ABIs are application binary interfaces. They define the methods and variables that are available in a smart contract and which we can use to interact with that smart contract. For a deeper dive on Solidity, the Ethereum Virtual Machine (EVM), bytecode, and ABIs, read this blog

What Is a Smart Contract Oracle?

Smart contract oracles provide smart contracts with a connection to offchain data, compute, and systems, which is necessary for developers to build real-world use cases. 

What Is the Best Smart Contract Programming Language?  

There are a variety of popular smart contract programming languages, including Solidity, Vyper, Rust, and more. This blog walks through the most popular programming languages.

Learn more about blockchain technology

Get the latest Chainlink content straight to your inbox.