Solidity Basics
Solidity is the primary programming language for writing smart contracts on Ethereum and EVM-compatible blockchains. It is a statically-typed, contract-oriented language inspired by JavaScript, C++, and Python.
Contract Structure
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract MyContract {
// State variables
uint256 public count;
address public owner;
// Constructor (runs once on deploy)
constructor() {
owner = msg.sender;
count = 0;
}
// Function
function increment() public {
count += 1;
}
// Function with return value
function getCount() public view returns (uint256) {
return count;
}
}
Data Types
Value Types:
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ bool โ true or false โ
โ uint256 โ Unsigned integer (256 bits) โ
โ int256 โ Signed integer (256 bits) โ
โ address โ 20-byte Ethereum address โ
โ bytes32 โ Fixed-size byte array โ
โโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Reference Types:
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ string โ Dynamic UTF-8 string โ
โ bytes โ Dynamic byte array โ
โ uint[] โ Dynamic array โ
โ mapping โ Key-value storage โ
โโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Functions and Modifiers
// Function visibility
function publicFn() public { } // Anyone can call
function internalFn() internal { } // This contract + children
function privateFn() private { } // Only this contract
// View functions (read-only, no gas)
function getName() public view returns (string memory) {
return name;
}
// Pure functions (no state access)
function add(uint a, uint b) public pure returns (uint) {
return a + b;
}
// Modifier
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
function adminAction() public onlyOwner {
// Only owner can execute
}
Events
Events let contracts emit logs that off-chain applications can listen to. They are much cheaper than storing data in contract state.
event Transfer(address indexed from, address indexed to, uint amount);
function send(address to) public payable {
balances[msg.sender] -= msg.value;
balances[to] += msg.value;
emit Transfer(msg.sender, to, msg.value);
}