Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 47 ยท Practice and Review

Solidity Cheat Sheet

A one-page Solidity cheat sheet: types, data locations, visibility, globals, panic codes, patterns, token standards and a security checklist, with live helpers.

This page is a compact reference for Solidity 0.8.x: the facts you look up again and again, in tables. It is not a tutorial, and each section links to the lesson that explains the topic. Code and tables are read-only, because the site cannot run an EVM. Three small JavaScript helpers (type ranges, storage packing and ether units) are runnable stand-ins you can edit.

Keep it open while you work. When you want practice, try the exercises, and for interview preparation, see the interview questions. Numbers about gas are approximate and change with network upgrades, so confirm them before relying on them.

What this sheet covers

Language Types, locations, visibility.
Globals msg, block, tx and friends.
Patterns Guards, pull payments, proxies.
Security A checklist for every contract.
1 / 2

File skeleton

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract Example is Ownable {
    uint256 public constant MAX = 100;     // compile-time value
    address public immutable deployer;     // set once, in the constructor
    mapping(address => uint256) public balances;

    event Deposited(address indexed who, uint256 amount);
    error TooMuch(uint256 requested, uint256 max);

    constructor() Ownable(msg.sender) { deployer = msg.sender; }

    receive() external payable { emit Deposited(msg.sender, msg.value); }

    function deposit() external payable {
        if (msg.value > MAX) revert TooMuch(msg.value, MAX);
        balances[msg.sender] += msg.value;
    }
}

See Your First Contract.

Types

See Value Types and Strings, Bytes, Arrays and Structs.

Type Notes Default
bool true, false false
uint8 to uint256 steps of 8 bits; uint is uint256 0
int8 to int256 two's complement, signed 0
address 20 bytes; cannot receive ether directly zero address
address payable adds transfer, send and call{value: ...} use zero address
bytes1 to bytes32 fixed-size byte arrays, cheap all zero
bytes, string dynamic; string has no length or indexing empty
enum named values stored as small integers; conversion out of range panics first member
struct a group of named fields each field's default
T[], T[n] dynamic and fixed arrays; push and pop for storage arrays empty or zeros
mapping(K => V) no keys list, no length; storage only V default for every key
type X is uint256 user-defined value type 0

Literals: 1 ether = 1e18 wei, 1 gwei = 1e9 wei, 1 days = 86400 (seconds), 0xff is hex, 1_000_000 uses separators.

JS Type range helper

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

No output.

Data locations

See Storage, Memory and Calldata.

Location Lifetime Mutable Typical use
storage permanent, part of contract state yes state variables; storage pointers are references
memory one external call yes temporary arrays, structs, strings; assignment from storage copies
calldata one external call no read-only arguments of external functions; cheapest
stack while a function runs yes value-type locals; limited depth (1024 slots, 16 reachable)
transient storage one transaction yes EIP-1153 scratch state such as reentrancy locks; cleared at the end of the transaction

Slot rules: state variables take slots in declaration order starting at 0, small variables that fit share a slot, structs and arrays start a new slot, and a mapping value for key k lives at keccak256(k . slot).

JS Slot packing calculator

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

No output.

Functions and visibility

See Functions and Visibility.

Keyword Meaning
public callable inside and outside; state variables get a getter
external callable from outside (and as this.f()); can use calldata arguments
internal this contract and derived contracts (default for state variables)
private this contract only, but never secret
view reads state, never writes it
pure neither reads nor writes state
payable accepts ether with the call
virtual / override allows or marks an overridden function (Inheritance)

Function forms: receive() external payable (plain ether), fallback() external [payable] (no matching function), constructor(...) (runs once at deployment), modifier m() { ...; _; }.

Global variables and functions

See msg.sender, msg.value and Global Variables.

Name Meaning
msg.sender the direct caller (account or contract)
msg.value wei sent with the call
msg.data, msg.sig the call data and its first four bytes
tx.origin the account that started the transaction; avoid for authorization
tx.gasprice gas price of the transaction
block.timestamp block time in seconds (producers can nudge it slightly)
block.number, block.chainid block height, chain identifier
block.basefee, block.coinbase, block.gaslimit fee, producer address, gas limit
block.prevrandao beacon-chain randomness value: not safe as a lottery source
blockhash(n) hash of a recent block (last 256 only)
gasleft() remaining gas
address(this), address(this).balance the contract's address and ether balance
keccak256(b), sha256(b), ecrecover(...) hashing and signature recovery
addmod, mulmod modular math without intermediate overflow
type(uint256).max, type(I).interfaceId type information

Encoding helpers: abi.encode, abi.encodePacked (ambiguous with dynamic types), abi.encodeWithSelector, abi.encodeWithSignature, abi.encodeCall, abi.decode. See ABI Encoding and Low-Level Calls.

Errors and panic codes

See Control Flow, require, revert and Custom Errors.

Tool Use
require(cond, "msg") validate input and state; reverts with Error(string)
revert CustomError(args) cheaper, structured failure data
assert(cond) an invariant that must always hold; failure is a Panic
try ext.f() returns (...) { } catch { } handle a failing external call
Panic code Cause
0x01 failed assert
0x11 arithmetic overflow or underflow
0x12 division or modulo by zero
0x21 invalid enum conversion
0x22 incorrectly encoded storage byte array
0x31 pop on an empty array
0x32 array index out of bounds
0x41 too much memory requested
0x51 call to an uninitialized internal function value

Low-level calls

Call Context Notes
target.call{value: v}(data) target's storage returns (bool ok, bytes memory ret); check ok
target.staticcall(data) target's storage, read-only state changes revert
target.delegatecall(data) caller's storage and msg.sender the basis of proxies; dangerous with untrusted targets
payable(t).transfer(v), send(v) forwards only 2300 gas not recommended for new code

A selector is the first four bytes of keccak256("name(type1,type2)") with canonical type names, for example transfer(address,uint256) gives 0xa9059cbb.

Ether units and a helper

JS Units converter

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

No output.

Real: the type ranges, the slot-packing rules for simple variables, and the unit sizes. Stand-in: the helpers use BigInt and simple loops, and the packing calculator ignores structs, arrays and inheritance order, which also affect real layouts.

Patterns

Pattern Idea Lesson
Checks-effects-interactions validate, update state, then call out Reentrancy
Pull payments record what is owed; users withdraw Sending and Receiving Ether
Access control modifiers, roles, two-step ownership Modifiers
Circuit breaker a pause switch for risky functions Modifiers
Factory a contract that deploys others Interfaces and Libraries
Proxy storage in one contract, logic in another Proxies
Commit-reveal publish a hash first, reveal later Oracles
State machine an enum for phases and checked transitions Crowdfunding

Token and interface standards

See Building an ERC-20 Token, ERC-721 NFTs and ERC-1155, ERC-4626 and Friends.

Standard What it defines Key identifiers
ERC-20 fungible tokens: balanceOf, transfer, approve, transferFrom, allowance transfer is 0xa9059cbb, approve is 0x095ea7b3, transferFrom is 0x23b872dd
ERC-721 unique tokens, ownerOf, safe transfers, approvals interface id 0x80ac58cd
ERC-1155 many token types in one contract, batch transfers interface id 0xd9b67a26
ERC-165 asking a contract whether it supports an interface supportsInterface, id 0x01ffc9a7
ERC-4626 tokenized vaults and shares built on ERC-20
ERC-2612 gasless approvals with a signature (permit) uses ERC-712 typed data
ERC-712 typed structured data signing domain separator with chain id and contract
ERC-1967 standard storage slots for proxy data implementation and admin slots

Security checklist

See Common Vulnerabilities and Audits, Tools and Best Practices.

  • Every state-changing function has the access check it needs (including initialize).
  • State is updated before external calls; critical functions use a reentrancy guard.
  • Return values of low-level calls are checked; token calls use safe wrappers for non-standard tokens.
  • tx.origin is not used for authorization.
  • No unbounded loops over user-controlled data; money goes out by pull payments.
  • Math uses checked arithmetic; every unchecked block has a written proof of safety.
  • Rounding favours the contract; division happens last.
  • Randomness is not derived from block values; prices do not come from a single manipulable pool.
  • Signed messages include a nonce, the chain id and the contract address.
  • delegatecall targets are trusted and storage layouts match; upgrades go through a multisig or timelock.
  • Tests cover failure paths, fuzzing and invariants (Testing Contracts); static analysis has been run.
  • Source is verified on the block explorer; keys are in a hardware wallet or multisig, never in the repository.

Approximate gas costs

Operation Rough cost
Base cost of any transaction 21,000 gas
Writing a new non-zero value to a storage slot about 20,000 gas (plus 2,100 if the slot is cold)
Reading a storage slot about 2,100 when cold, 100 when warm
Transient storage read or write about 100 gas
Calldata 16 gas per non-zero byte, 4 per zero byte

These figures follow recent network rules and can change. For a real contract, measure with your test framework's gas report (Gas Costs and Optimization).

Limits worth remembering

Limit Value
Deployed contract code size 24,576 bytes (EIP-170)
Init code size 49,152 bytes (EIP-3860)
Stack slots 1,024, with only the top 16 reachable by most instructions
Event indexed parameters at most 3 (4 topics including the signature)
blockhash window last 256 blocks

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which panic code means an arithmetic overflow or underflow?

    0x11 is the arithmetic panic. 0x01 is a failed assert, 0x12 is division by zero and 0x32 is an out-of-bounds index.
  2. 2. Which data location is read-only and used for the arguments of external functions?

    calldata holds the raw input of an external call. It cannot be modified, and reading it avoids a copy.
  3. 3. In which situation should you use delegatecall?

    delegatecall runs the target's code on the caller's storage. That is exactly what proxies need, and exactly why untrusted targets are dangerous.
  4. 4. How many bytes does address occupy?

    An address is 20 bytes, so it can share a 32-byte storage slot with a small variable.

Summary

  • Types, locations and visibility are the three things to state precisely in every declaration.
  • msg.sender, msg.value and block.timestamp are the globals you will use most; tx.origin and block values are risky.
  • Prefer custom errors, check low-level call results and know the panic codes.
  • Patterns such as checks-effects-interactions, pull payments, roles and pausing prevent most common bugs.
  • Standards have fixed function names and interface ids: reuse audited implementations.
  • Run through the checklist before every deployment, and measure gas instead of guessing.

This is the end of the Solidity track. To keep practicing, revisit the projects or the exercises.