Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 41 ยท Smart Contracts

Building a Toy Smart Contract Engine

Build a tiny smart contract engine in Python: contract classes, metered storage, calls as transactions, gas counting, events and automatic reverts.

In the previous lesson you saw that a contract is code plus state, that every node runs each call, and that gas stops runaway programs. Now you will build the machinery yourself. Our engine is about sixty lines of Python, runs entirely in your browser, and has the same moving parts as a real virtual machine: a place to deploy code, calls that carry a sender and a gas limit, storage that costs gas, events, and a revert that undoes failed calls.

A real chain such as Ethereum runs compiled bytecode inside the EVM, but the ideas are the same; Python classes simply stand in for the bytecode so that you can concentrate on what the engine guarantees. If any of the vocabulary feels new, review What Are Smart Contracts? first.

The design

The engine has four pieces:

Piece Job
Storage A dictionary wrapper that charges gas for every read and write
Context What a contract may see in one call: the sender, its storage, the gas meter, an event list
Chain Holds deployed contracts and their state, executes calls, undoes failed ones, keeps a log
Contract classes Static methods that receive a ctx and do the real work
flowchart TD
    T["call(sender, contract, method, args, gas_limit)"] --> SN["Take a snapshot<br/>of the contract state"]
    SN --> RUN["Run the method with a<br/>fresh Context and gas meter"]
    RUN -->|"finishes"| OK["Keep the changes<br/>status: ok"]
    RUN -->|"Revert or OutOfGas"| UNDO["Restore the snapshot<br/>drop events"]
    OK --> LOG["Append to the call log"]
    UNDO --> LOG

Every call either fully succeeds or leaves the state exactly as it was.

Gas, storage and context

Contract methods are static: they own no data. All persistent data lives in ctx.storage, which the chain controls. That design has two benefits. First, a snapshot of the dictionary is a snapshot of the contract, so reverting is easy. Second, the engine sees every read and write and can charge for it.

The price list is a plain dictionary:

Python
GAS = {"read": 2, "write": 10, "event": 5, "step": 1}

Writes cost five times as much as reads, echoing real chains, where persistent storage is the most expensive resource because every node has to keep it. Missing keys read as 0, just like uninitialized variables in Solidity.

Context.charge() adds to gas_used and raises OutOfGas when the limit is exceeded. It also sets gas_used to the limit at that moment, because a call that runs dry pays for everything it was allowed to use. Context.require() is the check that turns a failed rule into a Revert.

The chain: deploy, call, revert

Chain.call() is the heart. It deep-copies the contract's storage, runs the method, and on any Revert (including OutOfGas, which is a subclass) puts the copy back and discards the events. Whatever happens, it appends one line to the log: the sender, the call, the status and the gas used.

Here is the whole engine with a tiny Counter contract. Run it and read the log:

Python The engine and a counter contract

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.

Four calls, four log lines:

  • Bob's first call costs 17 gas: one read (2), one write (10) and one event (5). The count becomes 5.
  • Bob's second call fails the require before touching storage, so it costs 0 gas and changes nothing.
  • Carol's first call has a limit of only 15. Her read and write cost 12, and the event pushes the total to 17, so the engine stops and reverts. The partially done write to count disappears, which is the reason for the snapshot. She pays all 15 gas.
  • Carol's retry with the default limit succeeds, and the final state is {'count': 7}.

Notice that a failed call is recorded in the log: failure is part of history, just as on a real chain.

A token on top of the engine

A counter is too simple to show why atomic reverts matter. Money moves in two steps: subtract from one balance, add to another. If the second step fails after the first succeeded, coins vanish. With snapshots, the pair always happens together or not at all.

The Token below uses the same engine, so the code from the previous example is repeated. The new part is the class at the end and the calls under it.

Python A token contract with failures

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.

Read the log carefully:

  • Alice's mint succeeds and costs 29 gas: two reads, two writes, one event.
  • Bob's attempt to mint a million coins is rejected by the minter check with no gas used, and nothing changes.
  • Bob's transfer of 30 to Carol succeeds (29 gas again). The balances become 70 and 30.
  • Bob's transfer of 500 fails the balance check after one read, so it costs 2 gas and is reverted.
  • Bob's last transfer has only 20 gas. The engine runs dry at the final write, after Bob's balance has already been debited in the working data. The snapshot restores it.

The state printed under the log proves that: bal:bob is 70, bal:carol is 30, supply is 100, and there is no entry for dave, so the half-finished transfer left no trace. The sum of balances (70 + 30) equals the supply of 100, the invariant every token must keep.

Exercises and ideas

  • Add a burn(amount) method that reduces both the sender's balance and the supply. Which gas cost does it have compared with transfer?
  • Add a rule that a transfer to the address "0x0" reverts.
  • Make Chain.call return the emitted events when the call succeeds, and print them.
  • Charge GAS["step"] inside a loop of your own and watch a long loop run out of gas.

What the toy leaves out

Real engines add many things: signed transactions with nonces, accounts that hold a balance of the native coin, calls from one contract to another (which makes reentrancy possible, a topic of Smart Contract Security Pitfalls), a bytecode interpreter with a stack, a Merkle trie of the state so its hash can be put in the block header, and refunds for freeing storage. But the three guarantees you built are the same ones: determinism, metering and atomic reverts.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does Chain.call take a snapshot of the contract's storage before running a method?

    The snapshot makes calls atomic. If anything fails part-way, the saved copy is put back and no partial change survives.
  2. 2. In the counter run, why does Carol's call with gas_limit=15 fail even though a single increment seems simple?

    The event is charged after the write, pushing the total above the limit, so the engine raises OutOfGas and restores the state.
  3. 3. Why is a token transfer a good example for atomicity?

    Debit and credit must happen together. A revert restores both, which keeps the sum of balances equal to the supply.
  4. 4. What does the engine do with events from a reverted call?

    Events are part of the effects of a call, so they are dropped together with the state changes when the call reverts.

Summary

  • A contract engine needs storage, a call context (sender, gas, events), a chain that keeps state, and a log.
  • Metered storage lets the engine charge more for writes than reads and stop calls that exceed their gas limit.
  • A snapshot taken before every call makes execution atomic: failures leave the state untouched.
  • Failed calls are still recorded and, as on real chains, still cost the gas they used.
  • Tokens show why atomic reverts matter: balances always add up to the supply.

Next: Reading Solidity: A First Contract, where you learn to read the language most real contracts are written in.