freecoding.school100% FREE · NO SIGNUP
The EVM CoreISSUE #47 of 48

state machines on-chain

SoliaVSThe Reentrancy Reaper
Solia saysAn on-chain state machine encodes lifecycle as an enum with explicit allowed transitions — making invalid moves revert instead of corrupting state silently.

Many protocols have lifecycle stages: an escrow goes Created → Funded → Active → Completed; an auction goes Open → Bidding → Settling → Closed. Encoding the stage as an explicit state machine on-chain — an enum plus a transition table — turns "did I forget to check?" bugs into hard reverts. Every state-mutating function checks the current state and the requested transition.

The pattern is verbose but auditable: anyone reading the contract sees exactly which transitions are legal. The demo walks Created → Funded → Active → Completed and tries an illegal transition.

Power-ups you unlock

The Reentrancy Reaper attacks — common mistakes

Boss battleWalk an escrow through Created → Funded → Active → Completed and reject an illegal Completed → Funded move.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>
const transitions = {
  Created:   { fund: 'Funded' },
  Funded:    { activate: 'Active' },
  Active:    { complete: 'Completed' },
  Completed: {}
};
function transition(state, action){
  const next = transitions[state] && transitions[state][action];
  if(!next) throw new Error('illegal transition: ' + state + ' --' + action + '-->');
  return next;
}
let s = 'Created';
const log = ['start: ' + s];
s = transition(s, 'fund');     log.push('  fund     → ' + s);
s = transition(s, 'activate'); log.push('  activate → ' + s);
s = transition(s, 'complete'); log.push('  complete → ' + s);
let err = null;
try { transition('Completed', 'fund'); } catch(e){ err = e.message; }
log.push('');
log.push('illegal move "fund" from Completed: ' + (err || 'allowed (BAD)'));
document.getElementById('o').textContent = log.join('\n');
</script></body></html>
▶ Open the interactive comic issue
‹ Factory & Registry PatternsRate Limiting · Timelocks · Guardians ›