Smart Contracts: Agreements That Run Themselves
Disclaimer: This article is for informational and educational purposes only and simplifies underlying technical concepts for clarity. It is not financial, investment, legal, or security advice.
Smart contracts explained: imagine an agreement that carries itself out. No clerk approves the payment, no agent holds the money and no one has to remember to send the funds. The rules are written in code, and the code runs exactly as written.
That is the promise of a smart contract. It powers escrow arrangements, automatic payouts, crowdfunding, lending protocols, decentralized exchanges and tokenized securities.
But "runs exactly as written" cuts both ways. A smart contract will enforce a flawed rule just as faithfully as a correct one, and some of the most costly incidents in the history of blockchain came from exactly that.
Let us look at what a smart contract is, follow one from the moment a user clicks a button until the result appears on screen, and then explore where smart contracts help, where they fail and when they make business sense.
In This Article, You'll Learn
- ✓ What a smart contract is, and why it is neither "smart" nor necessarily a legal contract
- ✓ How a smart contract transaction moves from your wallet through the Ethereum network to execution and finality
- ✓ Real-world applications, from escrow and crowdfunding to lending and decentralized exchanges
- ✓ What smart contracts cannot do on their own, and what happens when they fail
- ✓ Lessons from The DAO, Parity and Euler Finance incidents, and how to reduce smart contract risk
- ✓ When a smart contract makes business sense
1. What Is a Smart Contract?
A smart contract is a program stored on a blockchain at its own address. It follows programmed rules whenever someone interacts with it. It can hold digital assets, maintain data and execute operations such as transferring tokens, recording ownership or checking whether specific conditions have been satisfied.
Despite the name, a smart contract is neither particularly intelligent nor necessarily a legal contract. It is better understood as a set of if-this-then-that rules enforced through code.
For example:
The contract does not decide whether the buyer's decision is fair. It follows its programmed instructions.
The Vending Machine Analogy
A vending machine is a useful way to understand a smart contract. When you insert the required amount of money and press a button, the machine checks the conditions and releases the selected product. You do not need a shopkeeper to approve the sale.
A smart contract works similarly:
- Rules are predefined: The code specifies what must happen.
- Conditions are checked: The contract determines whether the requirements have been satisfied.
- Actions are executed: If the rules permit it, the contract performs the programmed operation.
- Invalid requests are rejected: If a required condition is not met, execution can revert.
Computer scientist and lawyer Nick Szabo introduced the concept of smart contracts in the 1990s. Ethereum provided a shared blockchain environment in which contract code could be executed and its results agreed upon by a decentralized network, rather than relying on a single company's computer.
The analogy has limits, however. A vending machine handles a single, simple transaction. A smart contract can hold digital assets over time, manage complex financial relationships and interact with other contracts, but its code can also contain vulnerabilities that are difficult to fix once deployed.
2. How Does a Smart Contract Work?
A smart contract on Ethereum has the characteristics of a contract account:
- Address: A unique address through which users and other contracts can interact with it.
- Code: The instructions that define its behaviour, usually written in a programming language such as Solidity and compiled into bytecode that the blockchain can run.
- Storage: Data maintained by the contract, such as deposit balances or ownership records.
- Balance: It can hold ETH directly. Other tokens it owns are recorded in the relevant token contracts, which it can instruct to transfer them.
A smart contract operates within a blockchain's execution environment. On Ethereum, this environment is called the Ethereum Virtual Machine (EVM).
How a Smart Contract Executes on Ethereum
A smart contract does not run continuously in the background. It executes when a transaction or another contract interaction triggers it. The process involves the user interface, wallet, Ethereum network, validator, and Ethereum Virtual Machine (EVM). The journey can be grouped into four phases:
Let's break this down step by step.
Step 1: The User Initiates an Action
The user usually interacts with a decentralized application (dApp), such as clicking a button to transfer tokens, deposit funds, or purchase a tokenized asset. The user interface identifies the action the user wants to perform.
Step 2: The dApp Identifies the Required Smart Contract
Based on the action the user selected, the dApp determines which smart contract needs to be called, at which address, and which function should be executed with which inputs.
Step 3: The dApp Prepares the Transaction Request
The dApp encodes the function name and its inputs into a data field called calldata. It also prepares other transaction details, such as the network, the sender's address, the gas limit, and the transaction fee settings.
Step 4: The Wallet Receives the Request
The dApp sends the transaction request to the user's wallet. The wallet displays the relevant details so the user can review the action and approve or reject it.
The wallet may also estimate the gas required and check whether the user has sufficient ETH to cover the transaction fee.
Step 5: The User Authorizes the Transaction
If the user approves the request, the wallet uses the user's private key to create a digital signature. This signature proves that the transaction was authorized by the holder of the corresponding private key.
Step 6: The Wallet Submits the Signed Transaction
The wallet sends the signed transaction to an Ethereum node, usually through an RPC provider. The RPC provider acts as the communication interface between the wallet or dApp and an Ethereum node.
The node checks basic transaction validity, including the signature, account nonce, and transaction fee requirements. If the transaction passes these checks, the node can propagate it to other nodes.
Step 7: The Transaction Enters the Pending Transaction Pool
The transaction may enter the node's mempool, a pool of valid transactions that have not yet been included in a block. Other nodes can receive and propagate the transaction as well.
The transaction waits for inclusion in a block. Its waiting time depends on factors such as network demand, the offered priority fee, and block-building decisions. Submission does not guarantee immediate inclusion.
Step 8: A Block Builder Selects Transactions
A block builder assembles a candidate block by selecting and ordering transactions. The builder may consider transaction fees, execution constraints, and other factors when deciding which transactions to include and in what order.
The selected transactions are organized into a proposed block. On Ethereum today, most blocks are built by specialized block builders and offered to validators through relays (a system known as MEV-Boost), although a validator can also build its own block.
Step 9: A Validator Proposes the Block
An Ethereum proof-of-stake validator is selected in advance to propose a block for a particular slot (a 12-second interval). It typically chooses the most valuable block offered by builders, or builds one itself. The block may contain the user's transaction along with many other transactions.
The validator proposes the block to the network. Other validators subsequently participate in the consensus process to help establish which blocks belong to the canonical chain.
Step 10: The EVM Executes the Transaction
The block builder executes the transactions while assembling the block, and every Ethereum node re-executes them when it receives the block. When the user's transaction reaches the relevant position in the block, the EVM processes the call to the target smart contract.
Step 11: The Smart Contract Evaluates Its Rules
The smart contract executes its programmed logic using the transaction inputs and the blockchain state available at that point in execution. For example, it may check:
If the necessary conditions are met, execution proceeds. If a required condition fails or the execution encounters an error, the transaction may revert.
Step 12: Gas Is Consumed During Execution
As the EVM executes the instructions in Steps 10 and 11, gas is consumed step by step according to Ethereum's gas rules. The transaction must remain within its gas limit.
The final gas used depends on the operations performed. More computationally intensive operations and certain storage changes generally require more gas.
The transaction fee equals the gas used multiplied by the gas price, which is made up of the network's base fee (which is burned) and the priority fee (a tip paid to the validator). A transaction that reverts can still consume gas and incur a fee.
Step 13: The Transaction Produces a Result
If execution succeeds, the transaction's state changes are applied to Ethereum's evolving state as the block is processed. These changes may affect the smart contract's storage, token balances, account balances, or other contracts involved in execution.
The transaction may also emit events, which are recorded in the transaction receipt's logs. Applications use these logs to identify and display activity.
If execution reverts, the state changes made within that transaction are rolled back. However, the transaction can still be included in a block, and the gas consumed is still charged.
Step 14: Nodes Verify the Block's Execution
Other Ethereum nodes independently verify the proposed block by checking its transactions and executing them according to the protocol. They check that the resulting state transition is valid.
A block that violates Ethereum's execution rules is not accepted as a valid block. Consensus determines how valid blocks become part of the canonical chain.
Step 15: The Transaction Becomes Increasingly Confirmed
Once the transaction is included in a valid block, it has one confirmation. As additional blocks build on top of that block, confidence in the transaction's permanence increases.
Ethereum also has a formal finality mechanism. Once a block is finalized through consensus, reverting it would require at least one-third of all staked ETH to be destroyed through penalties (slashing), an extremely costly event. Finality is typically reached in about 13 minutes.
Step 16: The dApp Displays the Outcome
The wallet, dApp, or backend service retrieves the transaction receipt and relevant blockchain data, often through an RPC provider. It can check whether execution succeeded, inspect gas usage and emitted events, and read the updated contract state.
The user interface then displays the outcome, such as a successful transfer, an updated balance, or a failed transaction.
The Complete Flow
The key distinction is that:
3. Real-World Applications of Smart Contracts
Smart contracts are used across decentralized finance, tokenization and other applications where predefined rules can be executed automatically.
3.1 Escrow
The problem: A buyer in Abu Dhabi wants to purchase equipment from a seller abroad. The buyer does not want to pay before receiving the goods, while the seller does not want to ship without payment. Traditionally, an escrow agent or bank may hold the money until the agreed conditions are met.
The smart contract solution: The buyer deposits payment into a contract. When the buyer confirms delivery, the contract releases the payment to the seller. A more complete arrangement could include a deadline, a refund mechanism and a pre-agreed dispute-resolution process.
Business value: Reduces reliance on an intermediary to hold and release funds.
3.2 Automatic Payouts and Revenue Sharing
Suppose revenue from a song needs to be divided among its writers, producers and performers.
A smart contract can be programmed to distribute incoming funds according to agreed percentages. Similar mechanisms can distribute eligible payments to token holders or stream payments over time.
Business value: Automates payment calculations, reduces manual reconciliation and creates a transparent record of distributions.
3.3 Crowdfunding
On a traditional crowdfunding platform, participants trust the platform to hold funds and enforce the funding conditions.
A smart contract can implement an all-or-nothing funding model. For example:
- Backers contribute funds before a deadline.
- If the funding target is reached, the project owner can withdraw the funds.
- If the target is not reached, backers can claim refunds under the contract's rules.
Ethereum itself was funded through a crowdsale in 2014, an early example of blockchain-based fundraising.
Business value: Automates funding conditions and reduces dependence on a central platform to enforce them.
3.4 Flight-Delay Insurance
An insurance policy can specify that a passenger receives a payout if a flight is delayed beyond a particular threshold.
A smart contract can receive flight-status data from a trusted external data provider, known as an oracle. If the delay exceeds the policy's threshold, the contract can process the payout automatically.
AXA trialled an Ethereum-based flight-delay insurance product called fizzy in 2017. It was discontinued in 2019, partly because of low customer demand.
3.5 Lending and Borrowing
Protocols such as Aave and Compound use smart contracts to manage deposits, borrowing, interest calculations and collateral requirements.
For example, a user deposits USDC into a lending protocol. The contracts record the deposit, manage the available liquidity and apply the protocol's borrowing rules. If a borrower's collateral becomes insufficient, liquidation mechanisms may be triggered, usually by external participants (liquidators) who are rewarded for doing so.
Business value: Automates financial operations that would otherwise require significant manual processing.
3.6 Decentralized Exchanges
Decentralized exchanges (DEXs) such as Uniswap allow users to swap one token for another directly from their wallets, without a central exchange holding their funds.
Many DEXs use liquidity pools: smart contracts holding reserves of two or more tokens supplied by other users. When a user makes a swap, the contract calculates the price using a predefined formula based on the pool's reserves, transfers the tokens and charges a fee that is shared with the liquidity providers.
Business value: Enables continuous, automated trading and settlement without an exchange operator taking custody of users' assets.
However, users still face risks such as price slippage, front-running by other traders and vulnerabilities in the pool's code.
3.7 Tokenized Securities and Funds
A financial asset or fund interest can be represented by digital tokens. Smart contracts can maintain token balances, process permitted transfers and enforce certain restrictions, such as investor eligibility or lock-up periods.
Business value: Can support digital ownership records, programmable transfer rules and more efficient settlement processes.
3.8 Other Applications
| Application | What the smart contract does | Intermediary it may reduce |
|---|---|---|
| Tickets and memberships | Issues or verifies unique digital tokens | Ticketing platform |
| Supply chain records | Records handovers and timestamps | Paper records and reconciliation processes |
| Voting | Counts eligible token-holder votes and records outcomes | Certain administrative processes |
| Stablecoins | Manages the issuance, redemption and transfer of stablecoins | Some aspects of conventional payment infrastructure |
The actual benefits depend on the implementation. Recording a shipment on a blockchain, for example, does not prove that the shipment physically arrived unless reliable evidence is supplied.
4. Four Key Properties of Smart Contracts
Smart contracts have four important characteristics: transparency, automation, open access and resistance to changes after deployment. Each provides benefits, but each also creates risks.
| Property | Why it is useful | The downside |
|---|---|---|
| Transparent | Users can inspect verified code (source code published and matched to the deployed contract), balances and transactions | Activity may be publicly visible, and attackers can study vulnerabilities |
| Automatic | Executes rules consistently without requiring manual approval for every action | It follows incorrect rules just as consistently as correct ones |
| Open to anyone | Can provide global access without requiring a conventional account or permission | Bad actors can use it too, and access is not proof of identity |
| Hard to change | Rules cannot ordinarily be edited in place after deployment | Mistakes can be difficult or impossible to fix |
Transparency Does Not Mean Simplicity
Smart contract code and blockchain transactions are generally public on Ethereum, but that does not mean most users can understand the code. Users often rely on audits, reputation and tools that explain contract behaviour.
Automation Does Not Mean Judgment
A human escrow agent might notice suspicious circumstances and pause a payment. A smart contract executes its programmed rules and cannot independently decide that an outcome is unfair.
Immutability Has Trade-offs
Many deployed contracts cannot simply have their code edited. Some, however, use upgradeable designs or emergency pause mechanisms.
These features make it possible to respond to bugs, but they introduce additional trust assumptions. Someone may have the authority to change the implementation or suspend operations.
5. What Smart Contracts Cannot Do on Their Own
Smart contracts are powerful within a blockchain, but they have important limitations.
They Cannot Independently Observe the Outside World
A contract cannot directly check whether a flight is delayed, a shipment has arrived or the price of gold has changed. It needs an oracle or another trusted mechanism to supply that information.
The contract is only as reliable as the data and verification mechanisms on which it depends.
They Cannot Initiate Their Own Transactions
A smart contract executes when triggered by a transaction or another contract. It cannot independently wake up on the first day of the month and pay rent without an external mechanism initiating the operation, such as a user, a bot or an automation service like Chainlink Automation or Gelato.
They Cannot Control Physical Objects
A contract can record that ownership of a car has changed, but it cannot hand over the keys. Physical assets still require real-world enforcement, such as registries, legal agreements and courts.
They Are Not Automatically Legal Contracts
Whether a smart contract creates or fulfils a legally binding agreement depends on the jurisdiction and circumstances. Businesses often combine blockchain logic with traditional written agreements.
They Cannot Keep On-Chain Information Secret
Information stored on a public blockchain may be visible to other participants. Personal information, confidential pricing and other sensitive data should not be placed directly on-chain without careful consideration. Even variables marked as “private” in a contract's code can be read by anyone who inspects the blockchain's data.
They Cost Money to Operate
On-chain operations consume gas. Complex logic and large amounts of data can make transactions expensive, although Layer 2 networks may make some applications more economical.
6. What Happens When a Smart Contract Fails?
A failed transaction does not necessarily mean that the contract itself is defective. Sometimes the contract is working correctly by rejecting an invalid request.
6.1 A Condition Is Not Satisfied
Suppose you try to deposit 100 USDC into a lending protocol, but you have approved the contract to spend only 50 USDC. The contract attempts the transfer, but the token contract rejects it because the allowance is insufficient. The transaction reverts.
Other examples include trying to withdraw more funds than you own, borrowing without sufficient collateral or calling a restricted function without the required permission.
6.2 The Transaction Runs Out of Gas
If execution consumes all the gas supplied in the transaction before the operation finishes, it fails and its state changes are reverted. Because all the supplied gas has been used, the user pays for the full gas limit.
6.3 An External Dependency Fails
A contract may depend on another contract or a price oracle. If the required information is unavailable or fails validation, execution may revert.
6.4 The Code Contains a Vulnerability
A developer may implement an incorrect calculation, omit a safety check or fail to account for how functions interact.
The result may be an ordinary transaction failure, but it can also be much more serious: a vulnerable contract might successfully execute an operation that transfers funds improperly.
What Happens to the Money?
When an Ethereum transaction reverts, state changes made by that transaction are rolled back, but the gas fee for an included failed transaction is still paid.
For example, if a token swap reverts, the swap does not take place and no tokens change hands. However, the user pays the gas consumed. A separate approval transaction made earlier remains valid unless it is separately revoked or otherwise changed.
7. Real-World Smart Contract Failures
Smart contract incidents demonstrate that a blockchain can execute code correctly according to its rules while the code itself contains serious defects.
7.1 The DAO Hack (2016)
The DAO was an early decentralized investment organization built on Ethereum. Investors deposited ETH, received tokens and voted on which projects the organization should fund. The project raised approximately 12 million ETH, valued at around $150 million at the time.
What went wrong? The DAO's withdrawal logic contained a vulnerability known as a reentrancy bug.
The contract sent ETH to a user before updating the user's recorded balance. An attacker exploited this sequence with a malicious contract that called back into The DAO's withdrawal function each time it received ETH, repeatedly withdrawing funds before the balance was updated.
On 17 June 2016, the attacker began draining funds. Approximately 3.6 million ETH, roughly one-third of The DAO's funds, was moved into a separate contract.
What happened next? A built-in waiting period prevented the attacker from immediately spending the funds. The Ethereum community debated whether to leave the transaction history untouched or intervene to return the funds.
In July 2016, most of the community and major stakeholders supported a coordinated protocol change known as a hard fork, which allowed the original investors to reclaim the affected funds.
A minority opposed changing the blockchain's history and continued the original chain, which became Ethereum Classic (ETC). The Ethereum network most users know today followed the chain that implemented the recovery.
What did the industry learn? The DAO incident showed that a small coding mistake can have catastrophic consequences when contracts handle substantial financial assets.
It also exposed a difficult question: if code executes exactly as written but produces an unjust outcome, should the community intervene?
The response helped accelerate the development of professional smart contract audits, safer programming patterns and bug bounty programs.
7.2 Parity Multisignature Wallet Incidents (2017)
Parity provided smart-contract-based wallets that allowed multiple authorized parties to control access to funds. Two separate incidents occurred in 2017.
- July 2017: A vulnerability allowed an attacker to take control of affected wallets and steal approximately 150,000 ETH.
- November 2017: A user accidentally triggered the destruction of a shared smart contract library on which other wallets depended. Approximately 513,774 ETH became inaccessible.
The November incident did not involve the same kind of theft. Rather, the affected wallets could no longer execute the operations required to access their funds.
7.3 Euler Finance Exploit (2023)
Euler Finance was a decentralized lending protocol on Ethereum.
In March 2023, an attacker exploited a vulnerability involving the protocol's donation and liquidation logic. The flaw allowed the attacker to manipulate lending positions and collateral calculations using a combination of protocol operations and flash loans.
Approximately $197 million in assets was initially taken. The attacker later returned the funds following negotiations, and Euler reported recovery of the stolen assets.
| Incident | Year | What failed | Impact |
|---|---|---|---|
| The DAO | 2016 | Reentrancy bug in withdrawal logic | ~3.6 million ETH drained; led to the Ethereum / Ethereum Classic split |
| Parity (July) | 2017 | Wallet access-control vulnerability | ~150,000 ETH stolen |
| Parity (November) | 2017 | Shared library destroyed | ~513,774 ETH made inaccessible |
| Euler Finance | 2023 | Donation and liquidation logic | ~$197 million taken, later returned |
8. How Can Smart Contract Risks Be Reduced?
The incidents above demonstrate why serious projects need a deliberate security strategy.
- Use proven code. Build on established, well-tested libraries and patterns rather than writing everything from scratch.
- Obtain independent audits. Specialist auditors review the code for vulnerabilities before launch. Audits reduce risk but do not eliminate it.
- Offer bug bounties. Reward responsible disclosure of vulnerabilities before they are exploited.
- Start with limited exposure. Introduce limits on how much value a new contract can hold or process, then increase them as confidence grows.
- Plan for emergencies. Decide whether the contract can be paused or upgraded, who holds those permissions and how users will be informed.
- Pair code with legal agreements. Establish what happens if the code behaves unexpectedly and clarify the rights and responsibilities of the parties.
An immutable contract without recovery mechanisms may be impossible to repair directly. An upgradeable contract, on the other hand, can be corrected but introduces additional trust in whoever controls the upgrade process.
9. When Does a Smart Contract Make Business Sense?
Smart contracts are not the right solution for every process. Their value depends on the problem being solved.
Signs of a Good Fit
- Several parties need to transact but do not fully trust one another.
- Money or assets move according to clear, objective conditions.
- Existing intermediaries create significant fees, paperwork or delays.
- Participants need a shared record that is difficult to alter unilaterally.
- Users need global access without relying on one organization's operating hours.
Signs of a Poor Fit
- One trusted organization already performs the task cheaply and efficiently.
- Decisions depend heavily on negotiation, human judgment or confidential information.
- The process relies on physical events for which no reliable data source exists.
- Transaction volumes are high but the value of each transaction is tiny, making on-chain fees uneconomical without a suitable scaling solution.
10. Conclusion
Smart contracts allow predefined rules to be executed on a blockchain, supporting applications such as escrow, automatic payouts, crowdfunding, insurance, lending, decentralized exchanges and tokenized securities.
Their main strengths are transparency, automation, broad accessibility and resistance to unilateral changes. However, these characteristics come with trade-offs. Contracts can expose public activity, execute flawed logic, depend on unreliable external data and become difficult to repair after deployment.
The DAO, Parity and Euler Finance incidents show why smart contract security is essential. A blockchain can validate and execute a transaction without guaranteeing that the underlying program is safe.
The most effective approach is to use smart contracts where clear rules and shared execution provide a genuine advantage, while combining them with careful security reviews, appropriate governance and legal arrangements.
Key Takeaways
- A smart contract is a program stored on a blockchain that enforces if-this-then-that rules; it is neither intelligent nor automatically a legal contract.
- A smart contract runs only when triggered: the wallet authorizes the transaction, the EVM executes the contract, and the network validates and agrees on the result.
- Every operation consumes gas, and a reverted transaction still pays for the gas it used.
- Smart contracts cannot observe the outside world, act on their own, control physical objects or keep on-chain data secret without additional mechanisms such as oracles.
- The DAO, Parity and Euler Finance incidents show that a blockchain can execute flawed code perfectly; security depends on audits, testing, governance and recovery planning.
- Smart contracts make the most sense where parties lack mutual trust and value moves according to clear, objective rules.





