Writing and deploying smart contracts in Solidity
Practical, exam-focused notes on writing, testing and deploying Solidity smart contracts: definitions, key rules, important syntax, step-by-step examples and common mistakes.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Smart contracts are programs that run on blockchains like Ethereum. Engineers write them in Solidity to automate agreements, token logic, and decentralised applications; knowing how to code, test and deploy them safely is essential for building real systems and for answering practical exam questions.
Key ideas
Bytecode and ABI: when you compile Solidity, you get bytecode (binary instructions the EVM runs) and an ABI (Application Binary Interface — a JSON description of contract functions and types used to encode/decode calls).
Transaction vs Call: a transaction is a state-changing signed message that consumes gas and is included in a block; a call (or eth_call) is a read-only local execution that does not alter state and does not incur an on-chain gas fee. Note: eth_call still executes with a gas limit during simulation and can revert if the limit is too low, but the caller is not charged.
Address and Account: an address is a 20-byte identifier for an EVM account or contract. There are externally owned accounts (EOA) controlled by private keys, and contract accounts controlled by contract code.
Visibility and mutability: function visibility keywords are public, external, internal, private (define who can call the function). Function mutability keywords are view (reads state), pure (reads no state), and absence of them indicates the function can modify state. payable marks functions that can receive Ether. By default, functions are nonpayable and will revert if Ether is sent.
Storage vs Memory vs Stack: storage is persistent contract state (laid out in 32-byte slots with packing for small types; dynamic types like mappings/arrays use hashed locations); memory is temporary data for a single call; stack is the EVM's small LIFO area for intermediate 256-bit values (maximum depth 1024).
Storage layout rules commonly asked in exams (exact formulae below):
- State variables declared in order are assigned increasing storage slots (starting at 0), packed when types fit within 32 bytes.
- For a
mapping(K=>V) mat slot p, the storage slot for key k iskeccak256(encode(k) ++ encode(p))(see Formulas for exact padding/encoding rule).
Function selector / ABI encoding: the first 4 bytes of the calldata function selector are the first 4 bytes of
keccak256("functionSignature"). Example:transfer(address,uint256)->a9059cbb.Constructor, fallback and receive:
- constructor: function run once at deployment.
- receive() external payable: called when contract receives plain Ether with empty calldata. If both receive and fallback exist, receive is selected only when msg.data is empty; otherwise fallback runs. If neither is payable, Ether transfers revert.
- fallback() external: generic function when calldata doesn't match any function (can be payable or not).
Events and logs: events let contracts write indexed data to transaction logs; they are not accessible to contracts (only to off-chain listeners) and are cheaper than storage.
Modifiers: reusable function pre/post checks (e.g.,
onlyOwner) expressed withmodifier.Reentrancy and checks-effects-interactions: a critical safety pattern — first do checks, then update state, then interact with external addresses. If you call external code before updating state, that external can reenter your contract and cause inconsistencies.
Assumptions to state in answers: network is honest except where an attack is considered; gas refunds and exact gas usage vary by EVM implementation and version; Solidity language specifics depend on compiler version (specify pragma in real code).
Diagrams to draw in exams: draw a block labelled EVM with arrows: EOA -> Transaction -> Contract bytecode in contract account box -> storage (slots 0..n). For mapping storage, draw key k and slot p, arrow into keccak256 box -> resulting storage slot location.
Formulas
pragma solidity ^0.8.0; — compiler directive; use to enable 0.8.x features (overflow checks).
contract MyContract { ... } — basic contract declaration.
address public owner; — state variable declaration; address is 20-byte account.
constructor() { owner = msg.sender; } — constructor runs at deployment; msg.sender is the deployer (EOA or contract) that created the contract.
function f(uint256 x) external view returns (uint256) { ... } — function syntax; external visibility, view mutability, returns declares return types.
event Transfer(address indexed from, address indexed to, uint256 value); — event declaration.
mapping(address => uint256) balances; — mapping declaration.
require(condition, "error"); — runtime check that reverts on false.
modifier onlyOwner { require(msg.sender == owner); _; } — modifier structure; _ inserts function body.
abi.encodePacked(...) and abi.encode(...) — ABI encoding helpers.
keccak256(...) — cryptographic hash used throughout Solidity/EVM; function selectors are keccak256("functionSignature"), and storage location formulas use keccak256(abi.encode(...)) over 32-byte words.
Storage slot formula for mapping:
slot = keccak256(abi.encodePacked(padded_key, padded_slotIndex))
Where padded_key and padded_slotIndex are 32-byte (left or right padding as per ABI) representations. This yields the 32-byte storage slot containing the mapping value. For a dynamic array declared at slot p (e.g., uint[] a), the array length is stored at slot p, and element a[i] is stored at keccak256(abi.encode(uint256(p))) + i.
Function selector formula:
selector = first4bytes( keccak256( ascii_signature ) )
where ascii_signature is like "transfer(address,uint256)".
Gas conceptually: gas_cost = sum(each_op_gas) where each operation has a fixed gas cost per EVM gas table (variable by EVM version).
Worked examples
Example 1 — SimpleStorage trace (small-input execution)
Code sketch (explain in plain words):
- Contract has
uint256 public value;andfunction set(uint256 x) public { value = x; emit ValueSet(x); }andfunction get() public view returns (uint256) { return value; }.
Trace steps for one call sequence:
- Deployment: deployer D sends transaction with constructor, contract created at address C; storage slot 0 (
value) defaults to 0. - Call
set(42)by D (a state-changing transaction):- Check
msg.sender == D(not required here) — pass. - Execute assignment
value = 42: store 42 at storage slot 0. - Emit event
ValueSet(42)— log written. - Transaction mined; receipt contains
status=1, logs and gasUsed.
- Check
- Call
get()off-chain (eth_call): EVM executes read-only and returns 42 without gas or state change.
Answer to typical exam question: show initial storage 0, after set(42) slot0 = 42. Final answer: value returned by get() is 42.
Example 2 — ERC20-like transfer (mapping trace)
Minimal code sketch:
mapping(address => uint256) balances;andfunction transfer(address to, uint256 amount) public returns (bool) { require(balances[msg.sender] >= amount); balances[msg.sender] -= amount; balances[to] += amount; emit Transfer(msg.sender, to, amount); return true; }
Trace with sample data:
- Initial: Alice balance 1000 at slot mapping[Alice] (computed by keccak), Bob 200.
- Call: Alice calls transfer(Bob, 100):
- require: 1000 >= 100 true.
- balances[Alice] becomes 900 (1000 - 100).
- balances[Bob] becomes 300 (200 + 100).
- Emit
Transfer(Alice,Bob,100).
- Final answer: operation returns true, Alice: 900, Bob: 300.
In an exam, also state the mapping slot calculation for where the values are stored (use the storage slot formula above).
Common mistakes
- Forgetting
payableon functions meant to receive Ether. - Not handling overflow/underflow in older compiler versions (pre-0.8.0). From Solidity 0.8.0 upwards arithmetic overflow reverts by default — specify and verify compiler version in answers.
- Mixing up
viewandpureor failing to mark non-mutating functions asview(affects gas for internal calls and clarity). - Incorrect storage layout assumptions for mappings and dynamic arrays; forgetting the keccak256-based slot computation.
- Calling external untrusted contracts before updating state (reentrancy). Forgetting to use reentrancy guard or Checks-Effects-Interactions.
- Misunderstanding differences between
memoryandstoragefor struct/array variables (copy vs reference behaviour). - Miscomputing function selectors or calldata layout when building low-level calls.
- Not checking
requirerevert messages or not testing revert paths.
For your exam
Question types you will see:
- Definitions: explain terms (smart contract, EVM, gas, ABI) — give concise definitions and typical assumption.
- Short notes: explain storage layout, fallback vs receive, constructor behaviour — include examples and small diagrams.
- Derivations: compute mapping slot or function selector — show keccak256 steps and padding rules; explain storage packing.
- Programs / code writing: write a small Solidity contract (e.g., token or voting) — must include pragma, contract, state variables, constructor, major functions, events and visibility. Explain gas considerations and security notes.
- Traces: given code and calls, show storage changes and return values step-by-step.
- Diagrams: show EVM -> storage -> logs flow; mapping hashing diagram.
What full-marks answers include:
- Clear definitions with bold term first use and assumptions (compiler version / network behaviour).
- Correct Solidity syntax and required keywords (pragma, contract, constructor, visibility, payable where needed).
- Storage slot or calldata computation shown step-by-step (include keccak256 usage and padding note).
- Security considerations (reentrancy, overflow, access control) and short mitigation notes.
- For program questions: compile-ready code (not pseudo-code), and a short explanation of deployment steps (compile -> bytecode+ABI -> signed transaction -> contract address).
Quick check
- What is the first 4 bytes of the function selector for
transfer(address,uint256)? - What keyword must a function have to receive Ether directly?
- For a mapping
mapping(address=>uint) mdeclared at slot 5, what is the formula for the storage slot holdingm[key]?
Answers: a9059cbb; payable (or receive() payable for empty calldata); keccak256(abi.encodePacked(padded_key, padded_uint256(5))) (i.e., keccak256 of key padded to 32 bytes concatenated with 32-byte slot index).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?