Solidity Cheatsheet
A comprehensive Solidity cheatsheet from beginner to advanced — types, storage layout, functions, modifiers, events, inheritance, interfaces, libraries, payable patterns, gas optimization, security, assembly, upgradeable contracts, and modern 0.8.x features.
Solidity is a statically typed, contract-oriented language for writing smart contracts on Ethereum and EVM-compatible chains. This cheatsheet targets Solidity 0.8.x (pin a recent audited version such as 0.8.28–0.8.38 for production).
// SPDX-License-Identifier: MITpragma solidity ^0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";import "./libraries/Math.sol";
// Free functions (file-level) are allowedfunction helper(uint x) pure returns (uint) { return x * 2;}
contract MyContract { // 1. Type declarations (enums, structs) // 2. State variables // 3. Events // 4. Errors // 5. Modifiers // 6. Constructor // 7. Receive / Fallback // 8. External functions // 9. Public functions // 10. Internal functions // 11. Private functions}Recommendation: Pin an exact version for production (pragma solidity 0.8.28;) and verify it against the official bug list before mainnet deployment.
bool flag = true;
uint8 u8 = 255; // 0 … 255uint16 u16;uint256 u = 42; // most common (alias: uint)int256 i = -10; // alias: int
address addr; // 20 bytesaddress payable wallet; // can receive ETH
bytes1 b1; // fixed 1–32 bytesbytes32 hash;bytes dynamicBytes; // dynamicstring name = "Solidity"; // dynamic UTF-8
enum Status { None, Pending, Active, Closed }Status status = Status.Pending;// Fixed & dynamic arraysuint[5] fixedArr;uint[] dynamicArr;uint[][] nested;
// Structsstruct Position { address trader; uint256 size; int256 entryPrice; bool isLong;}
// Mappings (only in storage)mapping(address => uint256) balances;mapping(address => mapping(address => uint256)) allowances;mapping(bytes32 => Position) positions;type(uint256).mintype(uint256).maxtype(MyContract).nametype(MyContract).creationCodetype(MyContract).runtimeCode| Keyword | Where it lives | Mutable | Gas cost | Typical use |
|---|---|---|---|---|
storage |
Blockchain state | Yes | High | State variables |
memory |
Temporary RAM | Yes | Medium | Local variables, return values |
calldata |
Transaction input | No | Lowest | External/public function arguments |
// Good: cheap read-only inputfunction process(uint[] calldata ids) external { // ...}
// Copying from storage → memory is expensivefunction expensive() external view returns (uint[] memory) { return dynamicArr; // copies entire array}Rules of thumb
- External function arguments → prefer
calldata - Local complex types →
memory - State →
storage(implicit for state variables) - Never return large storage arrays to untrusted callers without need
function name(<params>) {public|external|internal|private} {pure|view|payable} {virtual|override} returns (<types>){ // body}| Specifier | This contract | Derived | External callers |
|---|---|---|---|
public |
✓ | ✓ | ✓ |
external |
via this |
✗ | ✓ |
internal |
✓ | ✓ | ✗ |
private |
✓ | ✗ | ✗ |
pure— no state read or writeview— may read state, cannot writepayable— can receive ETH- (no keyword) — can read and write state
function stats() public view returns (uint total, uint count) { total = 100; count = 5; // automatic return of named variables}
(uint t, uint c) = stats();function process(uint x) public { ... }function process(uint x, uint y) public { ... }address public owner;bool private locked;
modifier onlyOwner() { require(msg.sender == owner, "Not owner"); _;}
modifier nonReentrant() { require(!locked, "Reentrant"); locked = true; _; locked = false;}
modifier moreThan(uint amount) { require(msg.value > amount, "Too small"); _;}
function sensitive() external onlyOwner nonReentrant { // ...}
function donate() external payable moreThan(0.01 ether) { // ...}Modifiers can take arguments and can be chained. Keep them simple; complex logic often belongs in internal functions.
event Transfer(address indexed from, address indexed to, uint256 amount);event Approval(address indexed owner, address indexed spender, uint256 amount);event Log(string message); // non-indexed
emit Transfer(msg.sender, to, amount);- Up to 3
indexedparameters become topics (searchable). - Non-indexed data goes into the log data section.
- Events are the cheapest way to store historical information for off-chain consumers.
error Unauthorized(address caller);error InsufficientBalance(uint256 available, uint256 required);error ZeroAddress();
function withdraw(uint amount) external { uint bal = balances[msg.sender]; if (bal < amount) revert InsufficientBalance(bal, amount); // ...}Custom errors cost far less gas than require(..., "string").
receive() external payable { // plain ETH transfers (empty calldata)}
fallback() external payable { // unknown function selector or ETH + data}
function deposit() external payable { balances[msg.sender] += msg.value;}// Recommended pattern(bool success, bytes memory data) = recipient.call{value: amount, gas: 50000}("");require(success, "Transfer failed");
// Low-level alternativespayable(recipient).transfer(amount); // 2300 gas, reverts on failurebool ok = payable(recipient).send(amount); // 2300 gas, returns falseModern best practice: Prefer call + check success + reentrancy guard. transfer/send are limited to 2300 gas and can break with gas cost changes.
msg.sendermsg.valuemsg.datatx.origin // avoid for authorizationblock.timestampblock.numberblock.prevrandao // post-Merge randomness sourceblock.chainidgasleft()this // current contractcontract Ownable { address public owner; constructor() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "Not owner"); _; } function transferOwnership(address newOwner) public virtual onlyOwner { owner = newOwner; }}
contract Pausable is Ownable { bool public paused; modifier whenNotPaused() { require(!paused, "Paused"); _; } function pause() external onlyOwner { paused = true; }}
contract Token is Pausable { function transfer(address to, uint amount) external whenNotPaused { // ... }}abstract contract Base { function foo() public virtual returns (uint); function bar() public virtual returns (uint) { return 1; }}
contract Derived is Base { function foo() public pure override returns (uint) { return 42; } function bar() public pure override returns (uint) { return 2; }}interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address from, address to, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value);}Interfaces cannot have state variables or constructors. They are the standard way to interact with external contracts.
library SafeMath { function add(uint a, uint b) internal pure returns (uint) { unchecked { uint c = a + b; require(c >= a, "overflow"); return c; } }}
library Address { function isContract(address account) internal view returns (bool) { return account.code.length > 0; }}
contract Example { using SafeMath for uint; using Address for address;
function test(uint x, uint y) public pure returns (uint) { return x.add(y); }}Libraries are embedded (internal functions) or deployed once and linked (public/external functions). Prefer internal libraries for gas efficiency.
if (cond) {} else if (other) {} else {}
for (uint i = 0; i < n; ) { // ... unchecked { ++i; } // gas saving when overflow is impossible}
while (cond) {}do {} while (cond);
break;continue;
// Ternaryuint x = cond ? 1 : 0;
// Scoping{ uint local = 1;}// local no longer visiblerequire(condition, "reason"); // input validationassert(condition); // internal invariantrevert();revert CustomError(arg);
try token.transfer(to, amount) returns (bool ok) { require(ok, "transfer returned false");} catch Error(string memory reason) { // high-level revert with string} catch Panic(uint errorCode) { // panic codes (overflow, division by zero, etc.)} catch (bytes memory lowLevelData) { // any other failure}In 0.8+ arithmetic overflows panic (assert-style) unless inside unchecked.
State variables are packed into 32-byte slots when possible:
contract Packing { uint128 a; // slot 0 uint128 b; // slot 0 (packed) uint256 c; // slot 1 address d; // slot 2 bool e; // slot 2 (packed with address)}Tips
- Order smaller types together to share slots.
- Mappings and dynamic arrays occupy a slot for the length/base and store data at
keccak256(slot). - Changing the order of state variables in an upgradeable contract breaks storage — use storage gaps or a structured storage pattern.
address public owner;event OwnershipTransferred(address indexed previous, address indexed next);
modifier onlyOwner() { require(msg.sender == owner, "Not owner"); _;}
function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0), "Zero address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner;}uint private constant NOT_ENTERED = 1;uint private constant ENTERED = 2;uint private status = NOT_ENTERED;
modifier nonReentrant() { require(status != ENTERED, "Reentrant call"); status = ENTERED; _; status = NOT_ENTERED;}function withdraw(uint amount) external nonReentrant { // Checks require(amount > 0, "Zero"); uint bal = balances[msg.sender]; require(bal >= amount, "Insufficient");
// Effects balances[msg.sender] = bal - amount;
// Interactions (bool ok, ) = msg.sender.call{value: amount}(""); require(ok, "Transfer failed");}Instead of pushing ETH/tokens to many users in a loop, record credits and let users withdraw.
contract Child { address public immutable parent; constructor() { parent = msg.sender; }}
contract Factory { event Created(address child); function create() external returns (address) { Child c = new Child(); emit Created(address(c)); return address(c); }}- Use
calldatainstead ofmemoryfor external args. - Prefer custom errors over string requires.
- Cache storage variables in memory when read multiple times.
- Pack storage variables tightly.
- Use
uncheckedfor safe increments/decrements in loops. - Short-circuit boolean expressions.
- Avoid public variables if you don’t need the auto-generated getter.
- Use events for data that only needs to be consumed off-chain.
- Prefer
bytes32overstringwhen possible. - Minimize external calls and storage writes.
// Beforefor (uint i = 0; i < arr.length; i++) { ... }
// Afteruint len = arr.length;for (uint i = 0; i < len; ) { // ... unchecked { ++i; }}| Risk | Mitigation |
|---|---|
| Reentrancy | Checks-Effects-Interactions + nonReentrant modifier |
| Access control | onlyOwner / role-based access (AccessControl) |
| Integer issues | Solidity 0.8+ checked arithmetic; careful casting |
| Front-running | Commit-reveal, private mempools, careful ordering |
| Denial of service | Pull payments, avoid unbounded loops |
| tx.origin auth | Never use for authorization |
| Unchecked external call | Always check return value of call |
| Delegatecall to untrusted | Only to trusted, audited targets with matching layout |
| Timestamp dependence | Prefer block numbers or oracles when precision matters |
| Uninitialized storage | Explicitly initialize; be careful with structs/arrays |
High-value contracts should be audited and tested with Foundry (fuzz + invariant tests).
function addAssembly(uint a, uint b) pure returns (uint result) { assembly { result := add(a, b) }}
function getCodeSize(address account) view returns (uint size) { assembly { size := extcodesize(account) }}Use assembly sparingly, document it well, and understand memory safety. Prefer high-level Solidity when the compiler can optimize equally well.
Common pattern: Proxy + Implementation
- Users interact with a Proxy.
- Proxy uses
delegatecallto an Implementation contract. - Storage lives in the Proxy; logic lives in the Implementation.
- Upgrades change the implementation address.
Popular standards:
- Transparent Proxy
- UUPS (Universal Upgradeable Proxy Standard)
- Beacon Proxy
Critical rules
- Never change the order or type of existing state variables.
- Use storage gaps (
uint256[50] private __gap;) in base contracts. - Initialize via an
initializerinstead of a constructor. - Protect the upgrade function with access control.
OpenZeppelin’s upgradeable contracts are the standard reference implementation.
# Foundry (recommended)forge initforge testforge test --gas-reportforge coverageforge fmt
# Hardhatnpx hardhat testUseful Foundry features:
- Fuzz testing
- Invariant testing
- Fork testing against mainnet state
- Gas snapshots
1 wei1 gwei = 1e9 wei1 ether = 1e18 wei
uint256 constant MAX_SUPPLY = 1_000_000e18;address constant DEAD = 0x000000000000000000000000000000000000dEaD;immutable variables are set once at construction and stored in code (cheaper than storage):
address public immutable factory;uint public immutable deploymentTime;
constructor(address f) { factory = f; deploymentTime = block.timestamp;}// Typesuint256, int256, address, bool, bytes32, string, mapping, struct, array, enum
// Functionfunction f(uint x) external view returns (uint) { return x; }
// Modifiermodifier onlyOwner() { require(msg.sender == owner); _; }
// Event / Errorevent Transfer(address indexed from, address indexed to, uint amount);error Unauthorized(address caller);
// Ethermsg.value;(bool ok,) = recipient.call{value: amount}("");
// Controlrequire / revert / assert / try-catch / unchecked
// Inheritancecontract Child is Parent { function f() public override { ... } }
// Data locationfunction g(uint[] calldata xs) external returns (uint[] memory)- Official documentation: https://docs.soliditylang.org
- Solidity by Example: https://solidity-by-example.org
- OpenZeppelin Contracts: https://docs.openzeppelin.com/contracts
- Foundry Book: https://book.getfoundry.sh
- Ethernaut (security wargame): https://ethernaut.openzeppelin.com
- Damn Vulnerable DeFi: https://www.damnvulnerabledefi.xyz
- Solidity GitHub (bugs & changelog): https://github.com/ethereum/solidity
Pin your compiler version, run a thorough test suite (including fuzz and invariant tests), and obtain a professional audit before deploying contracts that hold significant value.
Frequently asked questions
What is the difference between storage, memory, and calldata?
storage is persistent on-chain state. memory is temporary and mutable during execution. calldata is read-only, non-modifiable input data for external calls and is the cheapest location for function arguments.
Why prefer custom errors over require strings?
Custom errors are significantly cheaper in gas because they do not store a string in the bytecode. They also provide better typed error handling for callers and off-chain tooling.
What is the Checks-Effects-Interactions pattern?
Perform all checks first, then update state (effects), and only afterwards make external calls (interactions). This ordering prevents many reentrancy attacks.
How does Solidity 0.8 protect against overflow?
Starting with 0.8.0, arithmetic operations automatically revert on overflow and underflow. You can use unchecked blocks when you deliberately want wrapping behavior for gas savings.
When should I use delegatecall?
delegatecall runs another contract's code in the context of the calling contract's storage. It is the foundation of proxy patterns but is dangerous if the target is untrusted or storage layouts diverge.