Solidity Documentation
Write smart contracts for Ethereum and EVM blockchains — with security in mind.
Solidity is the main language for writing smart contracts — programs that run on Ethereum and other EVM blockchains (Polygon, BNB Chain, Arbitrum, Base). A deployed contract's code can't be changed, holds its own balance and executes exactly as written, so security is as important as features. Its syntax looks like JavaScript/C++, with static types.
1. Introduction & Setup
- Fastest start: Remix IDE in the browser — write, compile, deploy and test with no installation.
- Local development: Hardhat or Foundry, plus MetaMask and a test network (Sepolia) with free test ETH from a faucet.
mkdir my-dapp && cd my-dapp
npm init -y
npm install --save-dev hardhat
npx hardhat init # choose a JavaScript or TypeScript project
npx hardhat compile
npx hardhat test
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Hello {
string public greeting = "Hello, Codify!";
}
Output (calling the auto-generated getter greeting() in Remix):
0: string: Hello, Codify!
Every file starts with a licence identifier and a pragma that fixes the compiler version.
⚠️ Common error:
ParserError: Source file requires different compiler version— select a compiler matching thepragma(e.g. 0.8.24+) in Remix orhardhat.config.js.
2. Basic Syntax & Contract Structure
A contract is like a class: state variables (stored on the blockchain), functions, events, modifiers and a constructor that runs once at deployment.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Counter {
uint256 public count; // state variable (stored permanently)
address public owner;
event Incremented(address indexed by, uint256 newCount);
constructor(uint256 start) {
count = start;
owner = msg.sender; // the deployer's address
}
function increment() external {
count += 1;
emit Incremented(msg.sender, count);
}
function current() external view returns (uint256) {
return count;
}
}
Output (deploy with start = 5, call increment() twice, then current()):
0: uint256: 7
⚠️ Common error: forgetting
viewon a function that only reads state gives a compiler warning — and calling non-view functions costs gas because they create a transaction.
3. Variables & Data Types
| Type | Example / notes |
|---|---|
bool |
true / false |
uint256 / int256 |
unsigned / signed integers (also uint8 … uint256); no decimals |
address |
20-byte account address; address payable can receive ETH |
bytes32, bytes |
fixed / dynamic byte arrays |
string |
UTF-8 text (expensive to store and compare) |
enum |
named constants |
arrays, mapping, struct |
collections and custom types |
Data locations: storage (permanent, on-chain), memory (temporary during a call), calldata (read-only function arguments — cheapest).
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Types {
bool public active = true;
uint256 public total = 1_000;
int256 public delta = -5;
address public admin = 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4;
bytes32 public id = keccak256("codify");
uint256 public constant FEE_PERCENT = 2; // fixed at compile time
uint256 public immutable createdAt; // set once in the constructor
constructor() {
createdAt = block.timestamp;
}
function priceInWei() external pure returns (uint256) {
return 0.5 ether; // 500000000000000000 wei
}
}
priceInWei() → 0: uint256: 500000000000000000
total() → 0: uint256: 1000
Units: 1 ether = 10^18 wei, 1 gwei = 10^9 wei. Time units: 1 minutes, 1 hours, 1 days.
⚠️ Common error: using floating point — Solidity has none. Work in the smallest unit (wei, or "cents") and multiply before dividing:
amount * 3 / 100.
4. Operators
Arithmetic + - * / % **, comparison == != < > <= >=, logical && || !, bitwise & | ^ ~ << >>, and the ternary ?:. Since 0.8.0, overflow and underflow revert automatically.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Maths {
function divide(uint256 a, uint256 b) external pure returns (uint256 q, uint256 r) {
return (a / b, a % b); // integer division
}
function percent(uint256 amount, uint256 bps) external pure returns (uint256) {
return amount * bps / 10_000; // multiply first (basis points)
}
function underflow() external pure returns (uint256) {
uint256 x = 0;
return x - 1; // reverts: arithmetic underflow
}
function wrap() external pure returns (uint8) {
uint8 x = 255;
unchecked { x += 1; } // opt out of checks → wraps to 0
return x;
}
}
divide(17, 5) → 0: uint256: q 3 1: uint256: r 2
percent(2000, 250) → 0: uint256: 50
underflow() → reverted: panic code 0x11 (Arithmetic operation overflowed or underflowed)
wrap() → 0: uint8: 0
5. Conditionals & Error Handling
Use if/else for logic and require, revert (with custom errors) or assert to stop execution — reverting undoes all state changes of the transaction.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Voting {
error AlreadyVoted(address voter);
error InvalidChoice(uint256 choice);
mapping(address => bool) public hasVoted;
uint256[3] public votes;
function vote(uint256 choice) external {
if (hasVoted[msg.sender]) revert AlreadyVoted(msg.sender); // custom error (cheap)
if (choice >= votes.length) revert InvalidChoice(choice);
hasVoted[msg.sender] = true;
votes[choice] += 1;
}
function leader() external view returns (uint256 best) {
for (uint256 i = 1; i < votes.length; i++) {
if (votes[i] > votes[best]) best = i;
}
}
function label(uint256 count) external pure returns (string memory) {
return count == 0 ? "no votes" : count < 10 ? "few votes" : "popular";
}
}
vote(1) from account A → success
vote(2) from account A → reverted with custom error AlreadyVoted(0x5B38...ddC4)
vote(7) from account B → reverted with custom error InvalidChoice(7)
leader() → 0: uint256: best 1
require(cond, "message") is the older style, still common; assert is for internal invariants that should never fail.
6. Loops
for, while and do/while work like in C/JavaScript — but every iteration costs gas, and a transaction has a gas limit.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Loops {
function sumTo(uint256 n) external pure returns (uint256 total) {
for (uint256 i = 1; i <= n; i++) {
total += i;
}
}
function firstPowerOfTwoAbove(uint256 n) external pure returns (uint256 p) {
p = 1;
while (p <= n) p *= 2;
}
}
sumTo(10) → 0: uint256: total 55
firstPowerOfTwoAbove(100) → 0: uint256: p 128
⚠️ Common error: looping over an array that users can grow without limit. Once it's large enough the function always runs out of gas and becomes unusable (a denial-of-service bug). Use mappings, pagination or "pull" patterns instead.
7. Functions, Visibility & Modifiers
| Visibility | Callable from |
|---|---|
public |
anywhere (also creates a getter for variables) |
external |
only from outside (other contracts / transactions) |
internal |
this contract and contracts that inherit it |
private |
only this contract |
State mutability: view (reads state), pure (no state at all), payable (can receive ETH).
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Shop {
address public owner;
mapping(address => uint256) public paid;
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_; // the function body runs here
}
constructor() {
owner = msg.sender;
}
function buy() external payable { // receives ETH
require(msg.value >= 0.01 ether, "Minimum 0.01 ETH");
paid[msg.sender] += msg.value;
}
function balance() external view returns (uint256) {
return address(this).balance;
}
function withdraw() external onlyOwner {
(bool ok, ) = payable(owner).call{value: address(this).balance}("");
require(ok, "Transfer failed");
}
function _fee(uint256 amount) internal pure returns (uint256) {
return amount / 50; // 2%
}
}
buy() with value 0.05 ether → success
balance() → 0: uint256: 50000000000000000
withdraw() from non-owner → reverted: Not owner
8. Arrays, Mappings & Structs
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Library {
struct Book {
string title;
address borrower;
bool available;
}
Book[] public books; // dynamic array of structs
mapping(address => uint256[]) private borrowedBy; // address → book ids
function addBook(string calldata title) external {
books.push(Book({title: title, borrower: address(0), available: true}));
}
function borrow(uint256 id) external {
Book storage b = books[id]; // storage reference: edits persist
require(b.available, "Already borrowed");
b.available = false;
b.borrower = msg.sender;
borrowedBy[msg.sender].push(id);
}
function myBooks() external view returns (uint256[] memory) {
return borrowedBy[msg.sender];
}
function count() external view returns (uint256) {
return books.length;
}
}
addBook("Clean Code"), addBook("Atomic Habits"), borrow(1)
count() → 0: uint256: 2
books(1) → title: Atomic Habits, borrower: 0x5B38...ddC4, available: false
myBooks() → 0: uint256[]: 1
Mappings are hash tables with every key existing (default value 0/false/empty) — you can't loop over them or get their length; keep a separate array if you need that.
⚠️ Common error:
Book memory b = books[id]; b.available = false;changes only a copy. Usestorageto modify the stored struct.
9. Object-Oriented Features: Inheritance & Interfaces
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface IGreeter {
function greet() external view returns (string memory);
}
abstract contract Ownable {
address public owner;
constructor() { owner = msg.sender; }
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
function transferOwnership(address next) external onlyOwner {
require(next != address(0), "Zero address");
owner = next;
}
}
contract Greeter is Ownable, IGreeter {
string private message = "Hello";
function greet() external view virtual override returns (string memory) {
return message;
}
function setMessage(string calldata m) external onlyOwner {
message = m;
}
}
contract LoudGreeter is Greeter {
function greet() external pure override returns (string memory) {
return "HELLO!";
}
}
Greeter.greet() → 0: string: Hello
LoudGreeter.greet() → 0: string: HELLO!
In real projects, inherit audited building blocks from OpenZeppelin (Ownable, ERC20, ERC721, ReentrancyGuard, AccessControl) instead of writing them yourself.
10. Advanced Concepts: Tokens, Security & Gas
An ERC-20 token with OpenZeppelin (npm install @openzeppelin/contracts):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract CodifyCoin is ERC20, Ownable {
constructor() ERC20("Codify Coin", "CDF") Ownable(msg.sender) {
_mint(msg.sender, 1_000_000 * 10 ** decimals());
}
function mint(address to, uint256 amount) external onlyOwner {
_mint(to, amount);
}
}
Security checklist
- Reentrancy: update state before sending ETH (Checks-Effects-Interactions) and/or use
ReentrancyGuard. - Access control: protect admin functions (
onlyOwner, roles). - Don't use
tx.originfor authorisation; usemsg.sender. - Don't rely on
block.timestampor blockhash for randomness — use Chainlink VRF. - Validate inputs, beware of unbounded loops, front-running and oracle manipulation.
- Test thoroughly, run static analysers (Slither) and get audits before handling real money.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract SafeVault {
mapping(address => uint256) public balances;
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw() external {
uint256 amount = balances[msg.sender];
require(amount > 0, "Nothing to withdraw");
balances[msg.sender] = 0; // 1. effects first
(bool ok, ) = msg.sender.call{value: amount}(""); // 2. then the interaction
require(ok, "Transfer failed");
}
}
Gas tips: use calldata for external array/string params, constant/immutable for fixed values, custom errors instead of revert strings, pack small variables together, avoid storage writes in loops, and emit events instead of storing data you only need off-chain.
Testing with Hardhat (JavaScript):
const { expect } = require("chai");
describe("Counter", () => {
it("increments", async () => {
const counter = await ethers.deployContract("Counter", [5]);
await counter.increment();
expect(await counter.current()).to.equal(6n);
});
});
Front-ends talk to contracts with ethers.js or viem through the user's wallet (MetaMask).
11. Examples with Output
Example 1 — Simple savings goal
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract PiggyBank {
address public immutable owner = msg.sender;
uint256 public immutable goal;
constructor(uint256 goalWei) {
goal = goalWei;
}
receive() external payable {} // accept plain ETH transfers
function progress() external view returns (uint256 percent) {
return address(this).balance * 100 / goal;
}
function breakOpen() external {
require(msg.sender == owner, "Not owner");
require(address(this).balance >= goal, "Goal not reached");
payable(owner).transfer(address(this).balance);
}
}
deploy with goalWei = 1 ether, send 0.25 ether
progress() → 0: uint256: percent 25
breakOpen() → reverted: Goal not reached
Example 2 — Event log for a to-do list
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract Todos {
struct Todo { string text; bool done; }
Todo[] public todos;
event Added(uint256 indexed id, string text);
function add(string calldata text) external {
todos.push(Todo(text, false));
emit Added(todos.length - 1, text);
}
function toggle(uint256 id) external {
todos[id].done = !todos[id].done;
}
}
add("Learn Solidity") → logs: Added(id: 0, text: "Learn Solidity")
toggle(0); todos(0) → text: Learn Solidity, done: true
12. Practice Problems
- Write a
Counterwithincrement,decrement(must not go below 0) andreset(owner only). - Build a
Votingcontract with a fixed list of candidates and one vote per address. - Create a crowdfunding contract: contribute until a deadline, refund if the goal isn't reached.
- Deploy an ERC-20 token with OpenZeppelin and transfer it between two accounts in Remix.
- Write an ERC-721 NFT contract with a limited supply and a mint price.
- Write Hardhat tests for every function, including the failure cases (
revertedWith). - Find and fix the reentrancy bug in a vault that sends ETH before updating balances.
- Build a small front-end with ethers.js that connects MetaMask and calls your contract.
13. Interview Questions
1. What is a smart contract? A program deployed on a blockchain that holds state and runs deterministically when called by transactions; its code is immutable once deployed.
2. storage vs memory vs calldata?
storage is persistent contract state; memory is temporary data during a call; calldata is read-only input data of external calls (cheapest).
3. view vs pure?
view functions read but don't modify state; pure functions neither read nor modify it. Both are free when called off-chain.
4. What is gas?
The unit measuring computation and storage cost of transactions; users pay gas used × gas price to prevent spam and reward validators.
5. What is a reentrancy attack and how do you prevent it?
A malicious contract calls back into your function before it finished updating state (e.g. withdrawing repeatedly). Prevent with Checks-Effects-Interactions and ReentrancyGuard.
6. require vs revert vs assert?
require validates inputs/conditions; revert aborts (with custom errors); assert checks invariants that should never be false. All undo state changes.
7. msg.sender vs tx.origin?
msg.sender is the immediate caller; tx.origin is the original externally owned account. Use msg.sender for authorisation.
8. What are events used for? Cheap logs that front-ends and indexers listen to; they can't be read by contracts.
9. How are contracts upgraded if code is immutable? Via proxy patterns (transparent/UUPS proxies) that delegate calls to a replaceable implementation contract.
10. What are ERC-20 and ERC-721? Token standards: ERC-20 for fungible tokens (balances), ERC-721 for non-fungible tokens (unique ids, NFTs).
14. Cheat Sheet & References
Contract skeleton
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract C { uint256 public x; constructor(uint256 _x) { x = _x; } }
Types and variables
bool b; uint256 n; int256 i; address a; address payable p; bytes32 h; string s;
uint256 constant MAX = 100; uint256 immutable start;
mapping(address => uint256) balances; uint256[] list; struct S { uint256 id; string name; }
enum Status { Open, Closed }
Functions
function f(uint256 x) external pure returns (uint256) { return x * 2; }
function g() public view returns (uint256) { return n; }
function pay() external payable { require(msg.value > 0, "No ETH"); }
modifier onlyOwner() { require(msg.sender == owner, "Not owner"); _; }
receive() external payable {} fallback() external payable {}
Globals and errors
msg.sender; msg.value; block.timestamp; block.number; address(this).balance;
error NotAllowed(address who); if (!ok) revert NotAllowed(msg.sender);
require(cond, "message"); assert(invariant);
event Paid(address indexed from, uint256 amount); emit Paid(msg.sender, msg.value);
(bool ok, ) = payable(to).call{value: amount}("");
keccak256(abi.encodePacked(a, b));
Hardhat
# compile, test, deploy
npx hardhat compile
npx hardhat test
npx hardhat node
npx hardhat run scripts/deploy.js --network sepolia
Official documentation