Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 47 ยท Practice and Review

Practice Exercises With Solutions

Fifteen graded Solidity exercises on types, mappings, errors, tokens and security, each with a runnable JavaScript stand-in solution you can edit.

Reading about Solidity is not the same as writing it. These fifteen exercises go from warm-ups to small security puzzles, and they cover the main ideas of the track: value types, mappings, errors, events, storage layout, tokens and common bugs. Each exercise asks you to write a piece of contract logic. Try it on paper, in Remix or in your head first, then open the solution.

The site cannot run Solidity, so every solution is a JavaScript stand-in: it models what the contract does, with a thrown error playing the part of a revert, and BigInt playing the part of 256-bit integers. The idea carries over directly, but gas, signatures and real storage are not part of the stand-in. Edit the code, break it on purpose, and run it again.

Three levels, five each

Warm-up Types, defaults, mappings, structs.
Builder Errors, events, modifiers, storage slots.
Defender Tokens, reentrancy, math and commit-reveal.

Do them in order. Each level uses ideas from the one before.

1 / 2

Level 1: warm-ups

Exercise 1: the range of a type

Write a function that returns the smallest and largest value of uintN and intN for any N that is a multiple of 8. Remember that signed integers use two's complement. See Value Types.

JS Exercise 1 solution

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

No output.

Exercise 2: checked addition

Solidity 0.8 reverts when an addition overflows. Write addChecked(a, b, bits) that does the same, and a second function that wraps around the way an unchecked block does. See Integers, Overflow and Checked Math.

JS Exercise 2 solution

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

No output.

Exercise 3: balances with defaults

A mapping returns zero for keys that were never written. Model mapping(address => uint256) balances with a Map, so reading an unknown address gives 0n, delete resets an entry, and nothing can be listed from the mapping itself. See Mappings.

JS Exercise 3 solution

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

No output.

Exercise 4: tracking holders

Because a mapping cannot be iterated, contracts keep a parallel array of keys. Write add and remove for a holder list, where remove uses swap and pop so it does not shift every element.

JS Exercise 4 solution

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

No output.

Exercise 5: copy or reference

A struct read into memory is a copy, while a storage pointer is a reference. Model a Player struct and show that changing the memory copy leaves storage untouched, while the storage pointer changes it. See Strings, Bytes, Arrays and Structs.

JS Exercise 5 solution

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

No output.

Level 2: builders

Exercise 6: custom errors and rollback

Write a withdraw that reverts with InsufficientBalance(available, requested) and leaves every balance as it was. A real revert undoes writes automatically, so the stand-in checks first and writes last. See Control Flow, require, revert and Custom Errors.

JS Exercise 6 solution

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

No output.

Exercise 7: filtering events

A log has a name, indexed topics and non-indexed data. Write getLogs({ name, topic1 }) that finds Transfer events sent by a given address without scanning the data. See Events and Logs.

JS Exercise 7 solution

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

No output.

Exercise 8: stacking modifiers

Combine an onlyOwner guard with a nonReentrant lock on one function, and show that a second call made while the first is still running reverts. See Modifiers and Access Control.

JS Exercise 8 solution

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

No output.

Exercise 9: slot packing

The EVM stores 32-byte slots. Variables packed in declaration order share a slot if they fit. Write a function that takes a list of [name, bytes] and returns the slot and offset of each. Treat anything of 32 bytes or more as using whole slots. See Storage, Memory and Calldata.

JS Exercise 9 solution

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

No output.

Exercise 10: a selector table

Contracts dispatch calls by the first four bytes of a hash of the function signature. Write a tiny dispatcher that maps a signature string to a four-byte tag and calls the matching function. The real hash is keccak-256, which is not built into plain JavaScript, so use a simple 32-bit FNV-1a hash as a stand-in. See ABI Encoding and Low-Level Calls.

JS Exercise 10 solution

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

No output.

The last call fails because uint and uint256 are different spellings: the signature must use the canonical type name, or the tag will not match.

Level 3: defenders

Exercise 11: an allowance transfer

Write transferFrom(spender, from, to, amount) for an ERC-20 stand-in. It must check the allowance, spend it, move the balance, and treat the maximum value as an allowance that is never reduced. See Building an ERC-20 Token.

JS Exercise 11 solution

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

No output.

Exercise 12: fix the reentrancy

The vault below sends ether before it zeroes the balance, so a malicious receiver can call withdraw again from inside the payment. Fix it with checks-effects-interactions and compare. See Reentrancy Step by Step.

JS Exercise 12 solution

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

No output.

Exercise 13: a voting deadline

Write vote(sender, choice, now) that allows one vote per address, rejects votes after a deadline, and rejects unknown choices. Time should be passed in, as the stand-in for block.timestamp, so your tests are deterministic.

JS Exercise 13 solution

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

No output.

Exercise 14: fixed-point math

Solidity has no decimals, so prices use "wad" math: values scaled by 10^18. Write wmul and wdiv, each rounding down, and a version that rounds up. Show why rounding direction matters when the contract must never pay out more than it holds. See Integers, Overflow and Checked Math.

JS Exercise 14 solution

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

No output.

Exercise 15: commit and reveal

A guessing game must not let a player see an earlier guess and copy it. Write a commit-reveal flow: players commit a hash of guess + salt, then reveal. The reveal must match the commitment, be on time, and happen only once. The hash is a 32-bit FNV-1a stand-in for keccak-256. See Oracles, Randomness and Off-Chain Data.

JS Exercise 15 solution

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

No output.

How to use these exercises

Do each one three times. First, solve it without help. Second, compare with the stand-in and note what you missed, such as an unchecked case or the order of effects and interactions. Third, rewrite it as real Solidity in Remix and write a test with one passing case and at least two failing ones. The failure cases are where contract bugs live.

If an exercise felt easy, change the rules to make it hard: add a new owner role, make the vault pay in tokens instead of ether, or let two actions happen in the same block. Every added feature is a new way to be wrong, which is why Common Vulnerabilities and the audit checklist exist.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In exercise 4, why is swap and pop used to remove a holder?

    Moving the last element into the gap and popping the end costs the same however long the array is, while shifting would write every following element.
  2. 2. Why does exercise 14 round down when issuing shares?

    Rounding in the contract's favour on issuance and payouts means tiny rounding errors can never be exploited to drain the pool.
  3. 3. In exercise 12, what makes the fixed vault safe?

    When the balance is already zero, a re-entering call finds nothing to withdraw. That is checks-effects-interactions.
  4. 4. What does the commit-reveal scheme in exercise 15 protect against?

    Only a hash is public during the commit phase, so a guess stays secret until its owner reveals it, and a reveal that does not match the hash is rejected.
  5. 5. Why do the stand-ins pass the current time in as an argument?

    A function that reads the real clock gives different results on each run. Passing the time in lets you test the exact moments around a deadline.

Summary

  • The fifteen exercises cover value types, checked math, mappings, structs, errors, events, modifiers, storage layout, selectors, tokens, reentrancy, voting, fixed-point math and commit-reveal.
  • Each solution is a JavaScript stand-in: it models the logic, but has no real gas, signatures or storage.
  • Check conditions first, change state next, interact with other contracts last.
  • Round in the contract's favour, and test the failing paths as carefully as the passing ones.
  • Rebuild your favourites in real Solidity and write tests for them.

Next: Solidity Interview Questions.