Get the App

Chapter 5 of 9

Smart Contracts and Programmable Money

Explain how smart contracts enable programmable logic on blockchains and form the basis of DeFi.

15 min readen

1. From Static Ledger to Programmable Money

In earlier modules, you saw how blockchains:

  • Maintain a shared ledger of who owns what
  • Use consensus mechanisms (like Proof of Work / Proof of Stake) so nodes agree on that ledger
  • Track tokens, cryptocurrencies, and stablecoins as digital assets

This step introduces the next layer: smart contracts.

You can think of a blockchain like a global spreadsheet that everyone agrees on. Smart contracts turn that spreadsheet into a global computer that everyone can run and verify.

Key idea: Instead of just storing balances, blockchains like Ethereum, Solana, and others can also store and run code. That code can:

  • Hold and move cryptoassets automatically
  • Enforce rules (e.g., loans, swaps, auctions)
  • Run without a central administrator

This is what makes programmable money possible and is the foundation of Decentralized Finance (DeFi).

In this module you will learn:

  • What smart contracts are and how they execute on-chain
  • Why determinism matters
  • How oracles connect blockchains to real-world data
  • The main risks: bugs, exploits, and oracle failures

2. What Is a Smart Contract?

A smart contract is:

> A piece of code deployed on a blockchain that automatically executes rules when predefined conditions are met.

Despite the name, smart contracts are usually not legal contracts by themselves. They are more like:

  • Vending machines: insert coins (inputs), press a button (function call), get a product (output) if conditions are satisfied.
  • If–then programs: `if condition is true, then do X`.

On smart-contract platforms (e.g., Ethereum, BNB Chain, Polygon, Solana, Avalanche, Arbitrum, Optimism):

  • Developers write contracts in languages like Solidity (Ethereum-compatible) or Rust (Solana, others).
  • The compiled code is deployed to the blockchain at a contract address.
  • Anyone can call the contract by sending a transaction to that address.

Common smart contract use cases in DeFi as of early 2026:

  • Decentralized exchanges (DEXs) – e.g., Uniswap, Curve
  • Lending/borrowing protocols – e.g., Aave, Compound
  • Stablecoin systems – e.g., MakerDAO’s DAI
  • Automated asset management – yield aggregators, vaults

The crucial property: once deployed, the contract’s logic is transparent and (usually) hard or impossible to change. That creates trust in code, but also makes bugs very costly.

3. A Minimal Smart Contract Example

Let’s look at a simplified Solidity contract on an Ethereum-like chain.

```solidity

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

// A simple piggy bank contract

contract PiggyBank {

address public owner; // who can withdraw

constructor() {

owner = msg.sender; // deployer becomes owner

}

// Function to receive ETH deposits

receive() external payable {}

// Anyone can check the balance

function getBalance() public view returns (uint256) {

return address(this).balance;

}

// Only owner can withdraw all funds

function withdraw() public {

require(msg.sender == owner, "Not owner");

payable(owner).transfer(address(this).balance);

}

}

```

What’s happening conceptually:

  • The contract is deployed at a fixed address on the blockchain.
  • It can hold ETH (or the chain’s native coin) like a mini bank account.
  • Rules are encoded in the code:
  • Anyone can deposit.
  • Only `owner` can withdraw.
  • Every node in the network runs this code when a relevant transaction is processed.

This is a tiny example of programmable money: the money (ETH) can only move according to the program’s rules.

4. Deterministic, On-Chain Execution

For a blockchain to reach consensus, every honest node must reach the same result when executing contract code.

This requires deterministic execution:

  • The same inputs → always the same outputs
  • No dependence on local time, random OS behavior, or hidden external data

On-chain execution typically has these properties:

  1. Every node re-runs the transaction
  • When you call `withdraw()` on the PiggyBank, all validating nodes re-execute that function.
  • If any node got a different result, consensus would break.
  1. Gas / resource limits
  • Platforms like Ethereum use gas to meter computation.
  • Complex or infinite loops are effectively prevented because they would run out of gas.
  1. State transitions
  • A smart contract stores state (e.g., `owner`, balances, configuration).
  • A transaction triggers code that updates this state.
  • Consensus is about agreeing on the sequence of state transitions for all contracts.

Because of determinism, smart contracts cannot directly call arbitrary web APIs or rely on non-deterministic system calls. This is why we need oracles to bring in external data.

5. Oracles: Connecting Blockchains to Real-World Data

Smart contracts by design cannot see the outside world (prices, weather, sports results, bank balances). Yet DeFi heavily depends on real-world data, especially prices.

An oracle is:

> A mechanism (usually a set of off-chain services plus on-chain contracts) that supplies verified external data to a blockchain.

Common oracle uses in DeFi as of early 2026:

  • Price feeds: ETH/USD, BTC/USD, stablecoin pegs, long-tail asset prices
  • Interest rate benchmarks: on-chain or off-chain reference rates
  • Event triggers: liquidation thresholds, options expiries

Typical architecture (e.g., Chainlink, Pyth, Chronicle):

  1. Off-chain data providers fetch data from multiple sources (exchanges, APIs).
  2. They aggregate and sign the data.
  3. The data is periodically pushed on-chain (or made available for on-chain verification).
  4. DeFi protocols read from these oracle contracts to make decisions:
  • Is the collateral still sufficient?
  • What’s the exchange rate for a swap?

Key trade-off:

  • Oracles reintroduce some level of trust and centralization (in data sources, operators, or governance).
  • But without them, smart contracts would be limited to purely on-chain logic.

6. Thought Exercise: Designing a Simple DeFi Loan

Imagine you are designing a simple overcollateralized loan smart contract.

Goal: Users can deposit ETH as collateral and borrow a USD-pegged stablecoin.

Think through these questions step by step (write down your answers):

  1. State variables
  • What information does the contract need to store per user?
  • Examples: deposited collateral amount, borrowed amount, liquidation threshold.
  1. Key functions
  • `depositCollateral()` – What checks should it perform?
  • `borrow()` – How will it ensure the user is sufficiently collateralized?
  • `repay()` – How does it update the user’s debt and collateral status?
  • `liquidate()` – Under what conditions can others liquidate an unsafe position?
  1. Where do prices come from?
  • How does the contract know the ETH/USD price?
  • Which oracle does it read from?
  • How often should the oracle update prices?
  1. Failure scenarios
  • What happens if the oracle stops updating?
  • What if the oracle reports a wildly incorrect price for a few blocks?

Reflect: Which parts are purely on-chain logic and which parts depend on external data and trust?

7. Common Smart Contract Risks in DeFi

Smart contracts are powerful but not automatically safe. Real DeFi protocols have lost billions of dollars to exploits since 2020.

Key risk categories (still very relevant through early 2026):

  1. Coding bugs and logic errors
  • Example: forgetting to check permissions, or using an outdated math library.
  • Famous historical case: The 2016 DAO hack on Ethereum exploited a re-entrancy bug.
  1. Re-entrancy attacks
  • A contract calls an external contract before updating its own state.
  • The external contract calls back into the original function again, exploiting the outdated state.
  1. Integer overflows/underflows (less common in newer Solidity)
  • Earlier Solidity versions (before 0.8.x) did not check arithmetic overflow by default.
  • Modern code often uses Solidity ≥0.8 (with built-in checks) or safe math libraries.
  1. Access control & upgrade risks
  • Admin keys can pause, upgrade, or drain contracts.
  • Proxy patterns allow upgrades but introduce complexity and new vulnerabilities.
  1. Oracle manipulation and failure
  • If a protocol relies on a single DEX price, an attacker can move that price temporarily (e.g., via a large trade or flash loan) and trigger bad liquidations.
  • If an oracle stops updating, protocols may freeze or behave incorrectly.
  1. Economic / game-theoretic attacks
  • Flash loan attacks: borrowing huge amounts in one transaction to manipulate markets or governance.
  • Sandwich attacks: MEV (Maximal Extractable Value) where a trader’s transaction is front-run and back-run.

Understanding these risks is essential to evaluating DeFi protocols and using them safely.

8. Quiz: Deterministic Execution

Check your understanding of deterministic, on-chain execution.

Why can’t a smart contract on Ethereum simply call a web API (e.g., https://api.exchange.com/price) during execution?

  1. Because external web calls are non-deterministic and not visible to all nodes, which would break consensus
  2. Because Solidity does not support HTTP as a programming language feature
  3. Because gas fees would become too high if web APIs were called
Show Answer

Answer: A) Because external web calls are non-deterministic and not visible to all nodes, which would break consensus

Smart contracts must execute deterministically on every node. A direct web API call would depend on off-chain infrastructure and might return different results for different nodes or be invisible to them, breaking consensus. This is why oracles are used instead.

9. Quiz: Oracles in DeFi

Test your understanding of oracle roles and risks.

A lending protocol uses a single on-chain DEX price as its only oracle for ETH/USD. What is the main risk?

  1. Users will be unable to deposit collateral
  2. An attacker can manipulate that DEX price briefly and trigger incorrect liquidations or under-collateralized loans
  3. The protocol will stop producing new blocks
Show Answer

Answer: B) An attacker can manipulate that DEX price briefly and trigger incorrect liquidations or under-collateralized loans

Relying on a single, easily-moved price source allows attackers to manipulate the price (often via flash loans) long enough to cause bad liquidations or borrow more than they should. Robust oracles aggregate multiple sources and often use time-weighted prices.

10. Flashcards: Key Terms Review

Flip these cards (mentally or with a partner) to review the core concepts from this module.

Smart contract
Code deployed on a blockchain that automatically executes predefined rules when triggered by transactions, often managing assets without a central administrator.
Programmable money
Digital assets whose movement and behavior are governed by code (smart contracts), enabling automatic enforcement of financial logic such as swaps, loans, and interest.
Deterministic execution
Property where the same inputs always produce the same outputs, essential so all blockchain nodes can agree on contract state after executing transactions.
On-chain state
All data stored directly on the blockchain, including account balances and smart contract variables, which is updated by transactions.
Oracle
A system that supplies external (off-chain) data, such as asset prices, to a blockchain in a way that smart contracts can reliably use.
Re-entrancy attack
An exploit where a contract is called back into before it has finished updating its state, allowing repeated withdrawals or other unintended behavior.
Flash loan attack
An attack that uses a large, uncollateralized on-chain loan within a single transaction to manipulate prices, governance, or protocol logic, then repays the loan before the transaction ends.
Access control
Mechanisms in a smart contract that restrict who can perform sensitive actions (e.g., admin-only functions), a common source of security issues if misconfigured.

11. Apply It: Evaluating a DeFi Protocol

Choose any well-known DeFi protocol (e.g., Uniswap, Aave, MakerDAO) and answer these questions using its documentation or a block explorer:

  1. What contracts does it use?
  • Identify at least one core smart contract address.
  • What is its main purpose (e.g., pool, lending market, governance)?
  1. Where do its prices come from?
  • Does it have its own oracle design (like Maker’s oracles)?
  • Does it rely on external oracle providers (e.g., Chainlink, Pyth)?
  1. What are the key risks?
  • Contract bugs: Is there an audit report? Multiple audits?
  • Oracle risk: How are price feeds secured or aggregated?
  • Governance/admin risk: Who can upgrade or pause the protocol?

Write a short paragraph (4–6 sentences) summarizing:

  • How the protocol uses smart contracts to implement programmable money
  • Which oracle design it uses
  • Which risk you consider most significant and why

This exercise connects the abstract concepts in this module to real protocols active in early 2026.

Key Terms

Oracle
A mechanism that provides external, off-chain data (e.g., market prices, events) to a blockchain in a way that smart contracts can consume.
Flash loan
A loan that must be borrowed and repaid within a single blockchain transaction, often used in arbitrage or, maliciously, in complex DeFi exploits.
Price feed
An oracle-delivered data stream providing current asset prices to smart contracts, commonly used for lending, derivatives, and liquidations.
Re-entrancy
A pattern where a contract calls into another contract (or itself) and that contract calls back before the first call finishes updating state; if not handled carefully, it can be exploited.
Access control
Rules and mechanisms in smart contracts that determine which addresses can call which functions, especially sensitive admin or upgrade functions.
On-chain state
All data stored directly on the blockchain, including account balances, contract storage, and configuration variables.
Smart contract
Code deployed and executed on a blockchain that automatically enforces predefined rules, often managing digital assets without a central intermediary.
Programmable money
Money or tokens whose behavior is controlled by software logic (smart contracts), enabling automated financial operations like swaps, loans, and interest payments.
Deterministic execution
Execution model in which the same inputs always yield the same outputs, allowing all blockchain nodes to independently verify and agree on smart contract results.
DeFi (Decentralized Finance)
A set of financial applications built on blockchains that use smart contracts instead of traditional intermediaries like banks or brokers.