Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 41 ยท Smart Contracts

What Are Smart Contracts?

Understand smart contracts: programs stored on a blockchain, deterministic execution, contract state, gas as metering and the limits of on-chain code.

So far the ledger has held simple facts: Alice paid Bob. A smart contract goes further: it stores a small program on the chain, together with that program's data. Anyone can send it a transaction, every node runs the program in the same way, and the result becomes part of the shared record. The name is misleading; a smart contract is neither especially smart nor automatically a legal contract. It is best understood as a shared program whose rules nobody can quietly change, with state that everybody can inspect.

In this lesson you will see what a contract consists of, why execution must be deterministic, what gas does, and what contracts cannot do. You will run a miniature contract in Python, and in the next lesson you will grow it into a small engine.

Code plus state

A contract has two parts, both stored on the chain at an address:

  • Code, a set of functions, fixed at deployment (on most chains it cannot be edited afterwards).
  • State, the data those functions read and write, such as balances, an owner address or a counter.

Compare it with a vending machine: the rules (insert coins, press a button, receive a drink) are built in, and the inventory is the state. Nobody has to trust the shop owner to hand over the drink, because the machine enforces its own rules. A smart contract is a vending machine for agreements, such as "release these funds only when two of three signers approve".

flowchart LR
    U["User wallet"] -->|"signed transaction:<br/>call increment(5)"| N["Network of nodes"]
    N --> E["Each node runs the<br/>contract code"]
    E --> S["New state:<br/>count = 5"]
    S --> L["Recorded in a block"]

A call is a transaction: every node executes it and must reach the same new state.

Calls are transactions

You do not "run" a contract on your own computer. You sign and broadcast a transaction addressed to the contract, naming a function and its arguments. A block producer includes it in a block, and every node that validates the block re-executes the call. Two consequences follow:

  1. Order matters. The same two calls in a different order can give different results, so the order in the block is part of consensus.
  2. Failure is part of the record. If a call fails (for example, a rule check says "not enough balance"), the transaction is still recorded, but its changes to the state are reverted. The sender usually still pays a fee for the work the network did.

Reading the state without changing it needs no transaction; you simply ask a node, and it answers from its copy.

Determinism: every node gets the same answer

Thousands of independent computers execute the same call and must end up with byte-for-byte identical state. That is only possible if the program is deterministic: the same inputs and the same starting state must always produce the same outputs. This rules out many ordinary things:

  • Reading the clock of your computer, because nodes run at different moments (a contract can only use the block's timestamp, which everyone agrees on).
  • True randomness, because every node would draw a different number.
  • Calling the internet, because the website might answer differently, or fail, for different nodes.
  • Reading files or anything outside the chain.

Contracts therefore live in a sealed world: they see only their own state, the call arguments, who sent the call, and a few block facts. The next demo runs the same transaction list on two independent "nodes" and compares a fingerprint of the final state.

Python Two nodes, one result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both nodes reject Bob's attempt to reset, apply the others, and end with count = 7 and the same fingerprint. This is the same technique you used in Hash Pointers and Tamper Evidence: real chains store a hash of the entire state in each block header so that any disagreement is detected immediately. Try changing the order of two transactions and see how the result changes.

Gas: metering the work

If anyone can submit any program, someone will submit an endless loop. Because every node must run it, a loop would freeze the whole network. The solution is gas: every elementary step a contract takes (an addition, reading a value, writing a value, sending a message) has a fixed cost in gas units, and each transaction comes with a gas limit the sender is willing to pay for. When the meter runs out, execution stops and the call is reverted.

Gas solves three problems at once:

  • Halting. A program cannot run forever, since the budget is finite.
  • Fair pricing. Heavy computation and big storage cost more, because they burden every node.
  • Spam resistance. Flooding the chain costs real money.

Storage writes cost far more than arithmetic, because the data must be kept by every node essentially forever. Here is a meter at work:

Python Running out of gas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With n = 10 the call costs 50 gas of the 100 allowed. With n = 30 it would need 110, and with n = 1000 it stops after just over 100: the program never finishes the loop, yet the network was protected. Gas is why an unbounded loop over a growing list is dangerous in contract code: as the list grows, the function eventually becomes too expensive to call at all.

What smart contracts are good for

Contracts shine where several parties who do not trust each other need a neutral, transparent rule keeper:

  • Tokens: who owns how many units, and the rules for moving them (see Tokens, ERC-20 and NFTs).
  • Escrow: hold funds until a condition is met.
  • Voting and governance with auditable tallies.
  • Automated market makers and lending markets, which you will meet in DeFi, DAOs and Governance.
  • Registries and access control lists with a public history.

The limits of on-chain code

Knowing what contracts cannot do prevents the most common misunderstandings.

  • They cannot see the outside world. A contract cannot learn today's weather or a share price by itself. Special services called oracles bring data in, and they reintroduce trust (see dApps, Oracles and Wallet Integration).
  • They are expensive and small. Storage and computation cost real money, so heavy work and big files stay off-chain.
  • Bugs are permanent. Code is hard or impossible to change after deployment, and a flaw may let attackers drain funds. Smart Contract Security Pitfalls covers the classic mistakes.
  • Code is not law. A contract enforces what it says, not what the parties meant. A legal contract may reference one, but a court may disagree with the code.
  • Everything is public. State and calls are visible to everyone, so secrets must not be stored in plain form.

"Immutable" cuts both ways. A contract that cannot be changed cannot be fixed. Many projects use upgradeable patterns or an admin key, which brings back exactly the trust the contract was meant to remove. Always ask who can change the code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a smart contract consist of?

    A contract is a program (code) together with its persistent data (state), both recorded on the blockchain.
  2. 2. Why must contract execution be deterministic?

    Thousands of nodes re-execute each call. If they could get different results, they would disagree about the state of the chain.
  3. 3. What is the main job of gas?

    Each step costs gas against a limit the sender sets, which stops infinite loops, prices resources fairly and makes spam costly.
  4. 4. What happens to the state when a contract call fails a rule check?

    A failed call leaves the state as it was before; the failed attempt is still recorded and usually still costs a fee.

Summary

  • A smart contract is code plus state stored on a chain; users interact with it by sending transactions.
  • Every node executes each call, so execution must be deterministic and uses only on-chain information.
  • A failed call is reverted: its state changes vanish, but the transaction stays in the record.
  • Gas meters every operation against a limit, preventing infinite loops and pricing computation and storage.
  • Contracts cannot reach the outside world alone, are costly, public and hard to fix after deployment.

Next: Building a Toy Smart Contract Engine, where you build the machinery for calls, storage, gas and reverts yourself.