lesson
30 min

Code That Keeps a Promise

A smart contract is an if-then rule that runs on a blockchain. Trace one yourself in JavaScript.

What you will be able to do

By the end of this lesson, you can explain a smart contract as an if-then rule and trace how a simple one works.

The vending machine idea

Computer scientist Nick Szabo described smart contracts in the 1990s using a vending machine. You put in the right money, you press a button, and the machine gives you a snack. No clerk needs to check. The rules are built into the machine.

A smart contract is a small program stored on a blockchain that runs automatically when its conditions are met. If this happens, then do that.

  • It is not "smart" the way a person is. It does exactly what the code says.
  • It is not always a legal contract. It is code. Whether a court treats it as a contract depends on the situation and the law.

Why people use them

Smart contracts help when several parties do not fully trust each other and do not want a middleman holding the money.

ProblemSmart contract idea
A freelancer worries the client will not payMoney is locked first, then released when work is approved
Many people pool money for a shared goalFunds release only if the goal is reached, otherwise everyone is refunded
Royalties are slow and unclearEach sale automatically splits payment to the creators

Most smart contracts run on the Ethereum blockchain or similar networks. They are written in languages like Solidity. You do not need to learn those here. The logic is what matters.

Trace an escrow contract

Escrow means a neutral party holds money until both sides keep their promise. Below, the "neutral party" is code. This is a JavaScript simulation, not a real blockchain, so nothing real is at stake.

Read the code, then press run and watch the console. Keyboard users: press Esc, then Tab, to leave the editor.

Escrow in plain code

Run it. Then change approved to false on the last line and run again. What happens to the money? Then try depositing less than the price.

Loading the code editor...

Press Esc, then Tab, to move focus out of the editor.

Notice three things:

  1. The rules are fixed in advance. Both sides can read them before they agree.
  2. No one can bend them. Not a manager, not a bank, and not the person who wrote them, unless the code allows it.
  3. The code only knows what it is told. Who decides that the work was "approved"? That question is the weak spot you will study next.

Reflection

Private. Saved only in this browser. No one else can see it.

Go deeper: Smart Contracts, Simple: How Trustworthy Code Automates Deals and Opens New Business Models

Ask. Answer. Build together.