Начало работы
Основы контракта
Solidity — основной язык для смарт-контрактов Ethereum. pragma задаёт версию компилятора. Контракт похож на класс. Функции могут быть public, private, view (тол ько чтение) или payable.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 storedData;
function set(uint256 x) public {
storedData = x;
}
function get() public view returns (uint256) {
return storedData;
}
}Pragma и версия компилятора
pragma задаёт версию компилятора. ^0.8.0 допускает любой патч 0.8.x. Для продакшена фиксируйте версию точно (0.8.19), чтобы избежать сюрпризов. Всегда указывайте pragma в начале каждого .sol-файла.
// Lock to a single version
pragma solidity 0.8.19;
// Allow patches (^0.8.0 means >=0.8.0 <0.9.0)
pragma solidity ^0.8.0;
// Range of versions
pragma solidity >=0.8.0 <0.9.0;
// Experimental features (ABIEncoderV2 in older versions)
pragma experimental ABIEncoderV2;Комментарии и NatSpec
Комментарии NatSpec (/// или /** */) генерируют документацию. @notice — для пользователей, @dev — для разработчиков, @param описывает параметры, @return описывает возвращаемые значения. Их подхватывают инструменты вроде Etherscan и Remix.
// Single-line comment
/* Multi-line
comment */
/// @title A Simple Contract
/// @author Alice
/// @notice This is visible to end users
/// @dev This is for developers
contract Commented {
/// @notice Sets the value
/// @param _x The new value
/// @dev Internal details here
function set(uint256 _x) public {}
}Лицензия SPDX
Начиная с Solidity 0.6.8 идентификатор лицензии SPDX обязателен в начале файла. Он помогает инструментам и пользователям понять, как код можно переиспользовать. Используйте MIT для разрешительного open-source, GPL-3.0 для copyleft или UNLICENSED для приватного кода.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Common licenses:
// MIT - permissive
// GPL-3.0 - copyleft
// Apache-2.0 - permissive with patent grant
// UNLICENSED - private/no license
// BSD-2-Clause, BSD-3-Clause
contract Licensed {}Структура файла и импорты
Импорты подключают контракты, библиотеки или интерфейсы. Используйте {Name}, чтобы импортировать только определённые элементы. Относительные пути работают как ожидается. Ключевое слово 'is' задаёт наследование. Обычно в файле один основной контракт, но их может быть несколько.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./OtherContract.sol";
import {SpecificContract, Helper} from "./Library.sol";
import * as Lib from "./Library.sol"; // namespace
import "openzeppelin/contracts/token/ERC20.sol";
contract MyContract is OtherContract {
// ...
}Типы значений
Целые числа (uint / int)
uint = беззнаковый int (без отрицательных), int = знаковый. Размеры от 8 до 256 с шагом 8. uint по умолчанию uint256. С 0.8.0 арифметика автоматически проверяет переполнение и недополнение и откатывает транзакцию. Используйте type(T).max / type(T).min для границ.
uint256 public bigNumber = 1 ether; // 10^18
uint8 public small = 255; // max 255
int256 public signed = -100;
uint public defaultSize = 42; // uint256 by default
// Arithmetic
uint256 a = 10;
uint256 b = 3;
uint256 sum = a + b; // 13
uint256 diff = a - b; // 7 (0.8+ reverts on underflow)
uint256 product = a * b; // 30
uint256 quotient = a / b; // 3
uint256 remainder = a % b; // 1
uint256 power = a ** 2; // 100
// Type min/max (0.8+)
uint256 max = type(uint256).max;
int256 min = type(int256).min;Boolean
bool может быть только true или false. && и || вычисляются по короткой схеме: правая часть вычисляется только при необходимости. Значение по умолчанию — false. Булевы в некоторых контекстах стоят больше газа, чем uint256 (упаковка в storage).
bool public flag = true;
bool public negated = !flag; // false
bool public and = flag && false; // false
bool public or = flag || false; // true
// Short-circuit evaluation
bool result = (flag && expensiveCall()); // skips call if flag false
bool result2 = (!flag || expensiveCall());
// Equality
bool equal = (1 == 1); // true
bool notEq = (1 != 2); // true
// Boolean defaults to false
bool public defaultValue; // falseAddress
address хранит 20-байтовый адрес Ethereum. address payable может принимать Ether (имеет методы transfer/send). Для преобразования используйте payable(x). У адресов есть свойство .balance (в wei). Всегда проверяйте литералы адресов по контрольной сумме EIP-55, чтобы ловить опечатки.
address public owner = msg.sender;
address payable public treasury = payable(owner);
// Balance (read-only)
uint256 bal = owner.balance; // in wei
// Send Ether (payable address only)
treasury.transfer(1 ether);
bool sent = treasury.send(1 ether);
// Convert from address to payable
address addr = 0x123...;
address payable payableAddr = payable(addr);
// Address literals (checksummed)
address public constant BURN = 0x000000000000000000000000000000000000dEaD;
// Compare addresses
bool same = (addr1 == addr2);Bytes и массивы байтов
Фиксированные байты (bytes1..bytes32) дешевы и используются для хешей и селекторов. Динамический bytes — для сырых бинарных данных; string — для текста UTF-8. Используйте bytes32 для хешей (keccak256 возвращает bytes32). bytes.concat() (0.8.4+) дешевле abi.encodePacked для массивов байтов.
// Fixed-size byte arrays (bytes1 to bytes32)
bytes32 public hash = keccak256(abi.encodePacked("data"));
bytes1 public b1 = 0x41; // single byte
bytes4 public selector = bytes4(keccak256("transfer(address,uint256)"));
// Dynamic byte arrays
bytes public dynamic = "hello";
bytes public empty;
// String vs bytes
string public text = "Hello"; // UTF-8 string
bytes public raw = bytes(text);
// Operations on fixed bytes
bytes32 data = keccak256(abi.encode("x"));
bytes1 first = data[0]; // access by index
uint256 length = data.length; // 32
// Concatenation
bytes memory combined = bytes.concat(bytes("a"), bytes("b"));Enums
Enum задаёт конечный набор именованных значений. Хранится как uint8 (максимум 256 элементов). Значение по умолчанию — первый элемент (индекс 0). Преобразуйте между enum и uint приведениями типов. type(EnumName).max даёт последний элемент.
contract EnumExample {
enum Status { Pending, Active, Paused, Closed }
Status public status = Status.Pending;
function activate() public {
require(status == Status.Pending, "Not pending");
status = Status.Active;
}
function next() public {
// Cast to uint to do math
uint current = uint(status);
if (current < uint(type(Status).max)) {
status = Status(current + 1);
}
}
// Default value is the first member (Pending)
Status public defaultValue; // Pending
}Преобразование типов и приведение
Неявные преобразования возможны только без потери данных (uint8 -> uint256). Для сужающих преобразований (uint256 -> uint8) или знаковых и беззнаковых используйте явные приведения. Преобразование отрицательного int в uint даёт огромное число из-за дополнительного кода.
// Implicit conversion (safe, widening)
uint8 small = 10;
uint256 big = small; // OK: uint8 fits in uint256
// Explicit conversion (narrowing, may lose data)
uint256 large = 300;
uint8 narrow = uint8(large); // truncates to 44 (300 % 256)
// Address conversion
address addr = 0xAb8483F64d9C6d1Ec37F8D2C4fA6bA5d5C5e5C5e;
address payable payableAddr = payable(addr);
// Bytes conversion
bytes32 b32 = bytes32(uint256(42));
uint256 num = uint256(b32);
bytes4 selector = bytes4(keccak256("foo()"));
// String <-> bytes
string memory s = "hi";
bytes memory bs = bytes(s);
string memory s2 = string(bs);
// int <-> uint (explicit, watch for negatives)
int256 signed = -5;
uint256 unsigned = uint256(signed); // huge number!Ссылочные типы
String
Строки в Solidity — массивы байтов UTF-8: length() возвращает число байтов, а не символов (эмодзи и многобайтовые символы отличаются). Равенство нужно проверять через хеш keccak256. string.concat (0.8.12+) дешевле abi.encodePacked. Строки дороги по газу.
contract Strings {
string public greeting = "Hello, World!";
function concat(string memory a, string memory b)
public pure returns (string memory)
{
return string.concat(a, " ", b); // 0.8.12+
}
function length(string memory s) public pure returns (uint256) {
return bytes(s).length; // byte length, not char count
}
function equals(string memory a, string memory b)
public pure returns (bool)
{
return keccak256(bytes(a)) == keccak256(bytes(b));
}
// Storage string (state variable)
string public stored;
function set(string memory s) public { stored = s; }
}Массивы (фиксированные и динамические)
Фиксированные массивы [N] имеют размер, известный при компиляции; динамические [] растут через push/pop. Массивы в memory нужно создавать через 'new Type[](size)'. Чтение и запись массивов в storage стоят газа; для временных данных предпочитайте memory. push() с верс ии 0.6 возвращает ссылку.
contract Arrays {
// Fixed-size array
uint256[5] public fixedArr = [1, 2, 3, 4, 5];
// Dynamic array
uint256[] public dynamicArr;
function pushPop() public {
dynamicArr.push(10); // append: [10]
dynamicArr.push(20); // [10, 20]
dynamicArr.pop(); // remove last: [10]
}
function getLength() public view returns (uint256) {
return dynamicArr.length;
}
function iterate() public view returns (uint256 sum) {
for (uint256 i = 0; i < dynamicArr.length; i++) {
sum += dynamicArr[i];
}
}
// Array of arrays (2D)
uint256[][] public matrix;
// Memory array (must have fixed length when created)
function memArray() public pure returns (uint256[] memory) {
uint256[] memory arr = new uint256[](3);
arr[0] = 1; arr[1] = 2; arr[2] = 3;
return arr;
}
}Structs
Структуры группируют связанные поля. Их можно хранить в storage, memory или передавать аргументами функции. Определяйте их на уровне файла или контракта. Инициализация по именам полей {field: value} понятнее; позиционная короче. Значения mapping в старых версиях нельзя получить как структуру целиком.
contract Structs {
struct User {
address wallet;
uint256 balance;
bool active;
string name;
}
// Single struct (storage)
User public owner;
User[] public users; // array of structs
mapping(address => User) public userByAddr;
function createUser(string memory name) public {
User memory u = User({
wallet: msg.sender,
balance: 100,
active: true,
name: name
});
users.push(u);
}
// Shorter syntax
function createShort() public {
users.push(User(msg.sender, 50, true, "anon"));
}
// Update a field
function deactivate(uint256 index) public {
users[index].active = false; // direct storage write
}
}Mappings
Mappings — это хеш-таблицы: keccak256(key) => value. У них нет длины, и их нельзя перебрать. Ключи могут быть типами значений (uint, address, bytes, enum); значения — любыми. Вложенные mappings позволяют поиск по нескольким ключам. Для перебора ведите отдельный массив ключей. delete сбрасывает ключ в нулевое значение.
contract Mappings {
// keyType => valueType
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowance;
mapping(address => bool) public isRegistered;
function setBalance(uint256 amount) public {
balances[msg.sender] = amount;
}
function approve(address spender, uint256 amount) public {
allowance[msg.sender][spender] = amount;
}
function register() public {
isRegistered[msg.sender] = true;
}
// Iterable mapping pattern
address[] public userList;
mapping(address => bool) public exists;
function addUser(address u) public {
if (!exists[u]) {
userList.push(u);
exists[u] = true;
}
}
// CANNOT iterate or get length of a mapping directly
// CANNOT delete a mapping, only individual keys
function remove() public {
delete balances[msg.sender]; // sets to 0
}
}Области данных (storage / memory / calldata)
storage = постоянное состояние в сети (дорого). memory = временное, живёт во время вызова функции (дёшево). calldata = только чтение, только для аргументов external-функций (дешевле всего). Всегда используйте calldata для аргументов external-функций, которые только читаете. По умолчанию: переменные состояния — storage; локальные сложные типы — memory.
contract DataLocations {
string public stateVar; // storage (state)
function f(string calldata input) external {
// calldata: read-only, only for external function args
string memory local = input; // memory: temporary copy
stateVar = local; // writes to storage
// storage reference (only inside a function)
string storage ref = stateVar;
ref = "new value"; // modifies stateVar
}
// External params can be calldata (cheapest)
function g(string calldata s) external pure returns (bytes32) {
return keccak256(bytes(s));
}
// Public/internal params default to memory
function h(string memory s) public pure returns (uint256) {
return bytes(s).length;
}
// Assignment rules:
// storage -> storage: reference (both point to same slot)
// memory -> memory: reference (both point to same memory)
// storage <-> memory: copy
}Вложенные структуры
Структуры могут содержать массивы, mappings (только в storage) и другие структуры. Доступ к вложенным полям через ссылку storage экономит газ. Осторожно с глубокой вложенностью — она увеличивает число слотов storage и стоимость деплоя. Mapping из структур — самый частый паттерн базы данных в сети.
contract Nested {
struct Order {
uint256 id;
uint256 amount;
Item[] items;
}
struct Item {
string sku;
uint256 qty;
}
mapping(uint256 => Order) public orders;
Order[] public allOrders;
function addOrder(uint256 id, string memory sku, uint256 qty) public {
Order storage o = orders[id];
o.id = id;
o.amount += qty * 1 ether;
o.items.push(Item(sku, qty));
}
// Mapping of struct arrays
mapping(address => Item[]) public userItems;
// Struct in a struct
struct Profile {
User user;
uint256 score;
}
struct User {
address addr;
string name;
}
Profile public profile;
}Переменные состояния
Public и private переменные состояния
public переменные состояния автоматически создают getter-функцию. private ограничивает доступ внутри контракта; internal допускает и наследников. По умолчанию — internal. ВАЖНО: 'private' НЕ означает «секретно» — все данные блокчейна публично читаемы. Если нужна конфиденциальность, используйте шифрование или хеширование.
contract Visibility {
uint256 public publicVar = 1; // auto getter created
uint256 private privateVar = 2; // only this contract
uint256 internal internalVar = 3; // this + subclasses
// No 'external' for state variables
// internal is the default
uint256 defaultVar = 4; // internal
function readPrivate() public view returns (uint256) {
return privateVar; // readable from inside
}
// 'private' only means 'not via other contracts'.
// The data is still visible on-chain!
}
// public creates an automatic getter:
// function publicVar() external view returns (uint256) { return publicVar; }Константы
constant переменные вычисляются при компиляции и встраиваются в байткод — в рантайме они не стоят газа (нет SLOAD). Только типы значений (uint, address, bytes и т. д.) могут быть constant. Значение должно быть выражением времени компиляции. Используйте constant для фиксированных значений вроде MAX_SUPPLY, DECIMALS, адресов.
contract Constants {
// constant: evaluated at compile time, inlined into code
uint256 public constant MAX_SUPPLY = 1_000_000 * 10**18;
address public constant DEAD = 0x000000000000000000000000000000000000dEaD;
uint8 public constant DECIMALS = 18;
// Must be value types, assigned a literal/expression
// No assignment in constructor
// Numeric separators (1_000_000) work since 0.8.0
function compute() public pure returns (uint256) {
return MAX_SUPPLY / 2; // inlined, no SLOAD
}
}Immutable-переменные
immutable переменные задаются один раз в конструкторе и затем только читаются. Они хранятся в байткоде (не в storage), поэтому чтение дешевле обычных переменных состояния. В отличие от constant, immutable может использовать аргументы конструктора и значения времени выполнения. Используйте immutable для того, что задаётся при деплое: owner, имя токена, конфигурация сети.
contract Immutable {
// immutable: set once in constructor, then read-only
address public immutable owner;
uint256 public immutable creationBlock;
constructor(address _owner) {
owner = _owner;
creationBlock = block.number;
}
// Can be any value type
// Cheaper than regular state vars (no SLOAD slot, uses code)
// More flexible than constant (can use constructor args)
function check() public view returns (bool) {
return msg.sender == owner; // cheap read
}
}
// Use case: factory-deployed contracts with constructor args
contract Factory {
Child[] public children;
function create(address owner) public {
children.push(new Child(owner));
}
}
contract Child {
address public immutable owner;
constructor(address _owner) { owner = _owner; }
}Глобальные переменные (msg, tx, block)
msg даёт контекст вызова: msg.sender (непосредственный вызывающий), msg.value (отправленные wei), msg.data (сырые calldata), msg.sig (селектор функции). tx даёт информацию о транзакции: tx.origin (EOA, НЕ рекомендуется для авторизации). block даёт текущий блок: block.timestamp, block.number, block.chainid, block.coinbase. Никогда не используйте tx.origin для авторизации — используйте msg.sender.
contract Globals {
function msgVars() public view returns (
address sender,
bytes4 selector,
uint256 value,
bytes memory data
) {
sender = msg.sender; // caller address
selector = msg.sig; // function selector
value = msg.value; // wei sent with tx
data = msg.data; // full calldata
}
function txVars() public view returns (address origin, uint256 gasprice) {
origin = tx.origin; // EOA that started the tx
gasprice = tx.gasprice; // gas price in wei
}
function blockVars() public view returns (
uint256 number,
uint256 timestamp,
address miner,
uint256 chainId
) {
number = block.number; // current block height
timestamp = block.timestamp; // current block time (uint256 in 0.8+)
miner = block.coinbase; // block miner/validator
chainId = block.chainid; // chain ID
}
}Свойства block и tx
blockhash() возвращает хеши только для последних 256 блоков; для более старых — 0. block.timestamp задаётся майнером и может отклоняться примерно на 15 секунд — никогда не используйте его для точного времени или случайности. block.basefee — из EIP-1559. gasleft() заменяет устаревший msg.gas. chainid критичен для защиты от повторов.
contract BlockProps {
function getBlockInfo() public view returns (
uint256 number,
uint256 timestamp,
uint256 gasLimit,
uint256 gasPrice,
uint256 baseFee
) {
number = block.number;
timestamp = block.timestamp;
gasLimit = block.gaslimit;
gasPrice = tx.gasprice;
baseFee = block.basefee; // EIP-1559 (London)
}
function getChainId() public view returns (uint256) {
return block.chainid;
}
function getPrevHash(uint256 n) public view returns (bytes32) {
require(n < 256, "out of range");
return blockhash(block.number - n); // last 256 blocks
}
function gasLeft() public view returns (uint256) {
return gasleft(); // remaining gas
}
}Функции
Синтаксис функций
Синтаксис: function name(params) visibility mutability returns(...). Видимость (public/external/internal/private) обязательна. Мутабельность (pure/view/payable) необязательна, но рекомендуется. Поддерживается несколько возвращаемых значений. Именованные возвраты позволяют присваивать им напрямую и опускать return.
contract Func {
// function name(params) <visibility> <state-mutability> returns(...)
function add(uint256 a, uint256 b)
public
pure
returns (uint256)
{
return a + b;
}
// Multiple returns
function split(uint256 x)
public pure returns (uint256, uint256)
{
return (x / 2, x % 2);
}
// Named returns (no explicit return needed)
function named(uint256 x)
public pure returns (uint256 half, uint256 rest)
{
half = x / 2;
rest = x % 2;
// return statement optional
}
// Destructure returns
function caller() public pure returns (uint256) {
(uint256 h, uint256 r) = named(10);
return h + r;
}
}View-функции
view-функции могут читать состояние, но не изменять его. При внешнем вызове через eth_call они бесплатны (без комиссии). При внутреннем вызове из изменяющей функции они потребляют газ. Используйте view для любой функции, которая только читает состояние, — это отражает намерение и позволяет бесплатные чтения вне сети.
contract ViewFn {
uint256 public counter = 0;
// view: can READ state but not modify
function getCount() public view returns (uint256) {
return counter; // reading state
}
function doubleCount() public view returns (uint256) {
return counter * 2; // reading state
}
// Can call other view/pure functions
function combined() public view returns (uint256) {
return getCount() + 1;
}
// CANNOT:
// - write to state variables
// - emit events
// - call non-view functions
// - use selfdestruct
// - send Ether
// view functions can be called off-chain for free (eth_call)
}Pure-функции
pure-функции не могут читать или писать состояние — они вычисляют только по своим аргументам. Они самые ограниченные и дешёвые при вызове вне сети. Используйте pure для утилит (математика, хеширование входов). Если понадобились msg.sender или данные блока, используйте view. pure может вызывать только другие pure-функции.
contract PureFn {
// pure: cannot read OR write state
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
function square(uint256 x) public pure returns (uint256) {
return x * x;
}
// pure can only use:
// - function parameters
// - local memory variables
// - other pure functions
function combined(uint256 x) public pure returns (uint256) {
uint256 y = square(x); // calling another pure fn
return add(y, 1);
}
// CANNOT read: state variables, msg.sender, block.timestamp, etc.
// CANNOT call view functions
}Payable-функции
payable-функции могут принимать Ether через msg.value. Ether автоматически добавляется к балансу контракта. Принимать Ether могут только payable-функции и receive/fallback. Всегда проверяйте msg.value, если ожидаете конкретную сумму. Не-payable функции откатываются, если им отправить Ether.
contract Payable {
address payable public owner;
constructor() {
owner = payable(msg.sender);
}
// payable: function can receive Ether
function deposit() public payable {
// msg.value is the amount of wei sent
// Ether is automatically added to contract balance
}
function getBalance() public view returns (uint256) {
return address(this).balance;
}
// Withdraw to owner
function withdraw() public {
require(msg.sender == owner, "not owner");
owner.transfer(address(this).balance);
}
// payable address (the contract itself can be paid)
receive() external payable {
// called when calldata is empty + value sent
}
}Возвращаемые значения и именованные возвраты
Функции могут возвращать несколько значений через кортежи. Именованные возвраты улучшают читаемость и позволяют присваивать напрямую без return. Явный return переопределяет именованные возвраты. Используйте деструктуризацию (a, b) = f() для нескольких значений; (, b) или (a,) пропускает ненужные.
contract Returns {
// Single return
function one() public pure returns (uint256) {
return 42;
}
// Multiple returns
function two() public pure returns (uint256, bool) {
return (1, true);
}
// Named returns — assign directly
function named() public pure returns (uint256 a, uint256 b) {
a = 1;
b = 2;
// no return keyword needed
}
// Mixed: explicit return overrides
function mixed(bool x) public pure returns (uint256 a, uint256 b) {
a = 1;
if (x) return (10, 20); // explicit return
b = 2;
}
// Destructuring assignment
function caller() public pure returns (uint256) {
(uint256 x, uint256 y) = two();
return x + y;
}
// Skip values with commas
function skip() public pure returns (bool) {
(, bool y) = two();
return y;
}
}Перегрузка функций
Solidity поддерживает перегрузку: несколько функций с одним именем, но разными типами или количеством параметров. Компилятор выбирает нужную по типам аргументов. Только по типу возврата перегрузки различить нельзя. Перегрузки полезны, чтобы принимать и address, и address payable, или разные диапазоны чисел.
contract Overload {
// Same name, different parameter types/counts
function add(uint256 a, uint256 b) public pure returns (uint256) {
return a + b;
}
function add(uint256 a, uint256 b, uint256 c) public pure returns (uint256) {
return a + b + c;
}
function add(string memory a, string memory b)
public pure returns (string memory)
{
return string.concat(a, b);
}
// Caller selects which via argument types
function test() public pure returns (uint256, uint256, string memory) {
return (add(1, 2), add(1, 2, 3), add("a", "b"));
}
// NOTE: return type alone does NOT distinguish overloads
// function f() returns (uint256) and f() returns (bool) — INVALID
}Конструктор и специальные функции
Constructor
constructor выполняется один раз при деплое контракта и инициализирует состояние. Повторно вызвать его нельзя. Аргументы конструктора добавляются к байткоду деплоя или передаются через ABI в зависимости от фреймворка. При наследовании передавайте аргументы родителя в списке наследования (Owned(_owner)) или в стиле модификатора (A() B()).
contract Owned {
address public owner;
// constructor runs once at deployment
constructor(address _owner) {
owner = _owner;
}
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
}
// Inheritance: constructor args
contract Child is Owned {
constructor(address _owner) Owned(_owner) {}
}
// No constructor = default constructor (no args)
contract NoCtor {}
// Multiple inheritance: order matters
contract A { constructor() {} }
contract B { constructor() {} }
contract C is A, B {
constructor() A() B() {}
}Receive-функция
receive() вызывается, когда вызов без calldata отправляет Ether (например, send/transfer на контракт). Она должна быть 'external payable' без аргументов и возвратов. Разрешена только одна receive-функция. Если её нет и нет fallback, простые переводы Ether откатываются (кроме selfdestruct, который может принудительно отправить Ether).
contract Receiver {
event Received(address from, uint256 amount);
// receive: called on plain Ether transfers (no calldata)
// Must be 'external payable', no args, no returns
// Only ONE receive per contract
receive() external payable {
emit Received(msg.sender, msg.value);
}
// Triggered by: transfer(), send(), or empty calldata tx
// Use this to react to incoming Ether
function balance() public view returns (uint256) {
return address(this).balance;
}
}
// If no receive/fallback exists, the contract rejects plain Ether.
// Exception: contracts can be forced via selfdestruct (always).Fallback-функция
fallback() вызывается, когда ни одна функция не соответствует селектору, или когда receive отсутствует и пытаются отправить Ether напрямую. Она может быть payable. Держите логику fallback минимальной: при вызове через send()/transfer() у неё только 2300 газа (стипендия), чего не хватит на запись в storage или emit событий.
contract Fallback {
event Log(string message, address from, uint256 value, bytes data);
// fallback: called when no function matches the calldata
// OR when receive is absent and calldata is empty
fallback() external payable {
emit Log("fallback", msg.sender, msg.value, msg.data);
}
// With calldata (function not found)
// Without calldata + no receive => fallback runs
// Modern: separate receive and fallback
// receive() external payable { ... } // empty calldata + value
// fallback() external payable { ... } // unknown function
// Make fallback cheap — it can run out of gas on send()/transfer() (2300 stipend)
function safeFallback() external {
// logic here must be < 2300 gas if called via transfer/send
}
}Selfdestruct
selfdestruct отправляет весь оставшийся Ether на указанный адрес и (до Dencun) удаляет код контракта. После EIP-6780 (март 2024) он удаляет код, только если вызван в той же транзакции деплоя; иначе просто переводит Ether. Никогда не полагайтесь на selfdestruct для безопасности: принудительный Ether всё равно может прийти, а код может сохраниться.
contract SelfDestruct {
address payable public owner;
constructor() { owner = payable(msg.sender); }
function destroy() public {
require(msg.sender == owner, "not owner");
// Sends all Ether to recipient, then deletes the contract
selfdestruct(payable(msg.sender));
}
}
// IMPORTANT WARNINGS:
// - After EIP-6780 (Dencun), selfdestruct no longer deletes code
// unless called in the same transaction that deployed the contract
// - It still sends all Ether to the recipient
// - The recipient could be a contract with no receive/fallback and
// it still gets the Ether (forced transfer)
// - Do NOT rely on selfdestruct for security; prefer a 'paused' flagСелектор функции
У каждой функции есть 4-байтовый селектор = первые 4 байта keccak256(сигнатуры). Сигнатура — это имя функции и типы параметров без пробелов, например 'transfer(address,uint256)'. EVM использует селектор для маршрутизации вызовов. msg.sig даёт селектор текущей функции. abi.encodeWithSelector/Signature строят calldata для низкоуровневых вызовов.
contract Selector {
// First 4 bytes of keccak256 of the function signature
// signature = "functionName(paramType1,paramType2,...)"
bytes4 public constant SELECTOR =
bytes4(keccak256("transfer(address,uint256)"));
function getSelector() public pure returns (bytes4) {
return bytes4(keccak256("transfer(address,uint256)")));
// = 0xa9059cbb
}
function thisSelector() public pure returns (bytes4) {
return msg.sig; // selector of the currently running function
}
// Used for low-level calls
function callTransfer(address token, address to, uint256 amount)
public returns (bool, bytes memory)
{
(bool ok, bytes memory data) = token.call(
abi.encodeWithSelector(0xa9059cbb, to, amount)
);
return (ok, data);
}
// abi.encodeWithSignature uses the string form
function altCall(address token, address to, uint256 amount)
public returns (bool, bytes memory)
{
return token.call(
abi.encodeWithSignature("transfer(address,uint256)", to, amount)
);
}
}Модификаторы
Основы модификаторов
Модификаторы оборачивают функции многоразовыми условиями до и после. Плейсхолдер _; — место, где выполняется тело функции. Модификаторы хороши для контроля доступа (onlyOwner), валидации (validInput) и защиты от реентрантности. По умолчанию они применяются до тела функции — через _; управляйте, где выполняется тело.
contract ModBasics {
address public owner;
uint256 public count;
constructor() { owner = msg.sender; }
// Define a modifier
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_; // placeholder for the function body
}
// Apply it
function increment() public onlyOwner {
count += 1;
}
function reset() public onlyOwner {
count = 0;
}
// Anyone can read
function getCount() public view returns (uint256) {
return count;
}
}Модификатор с аргументами
Модификаторы могут принимать аргументы, что делает их гибкими. Аргументы вычисляются в точке вызова и связываются при выполнении модификатора. Частые паттерны: costs(price) для платы за вызов, onlyRole(role) для RBAC, rateLimit(window) для троттлин га. Логика до _; — предусловие, после _; — постусловие.
contract ModArgs {
modifier costs(uint256 price) {
require(msg.value >= price, "insufficient payment");
_;
// optional: refund excess after function runs
if (msg.value > price) {
payable(msg.sender).transfer(msg.value - price);
}
}
modifier onlyAddress(address allowed) {
require(msg.sender == allowed, "not allowed");
_;
}
function buyItem() public payable costs(1 ether) {
// msg.value must be >= 1 ether to enter
// excess refunded after body runs
}
function adminOnly() public onlyAddress(0xAbC...) {
// restricted to a hardcoded address
}
}Несколько модификаторов
У функции может быть несколько модификаторов. Они выполняются по порядку, оборачивая тело как стек: предусловие первого, затем второго, затем тело, затем они разворачиваются в обратном порядке. Порядок важен — ставьте самые дешёвые и вероятные к срабатыванию проверки первыми ради экономии газа.
contract MultiMod {
address public owner;
bool public paused;
uint256 public value;
constructor() { owner = msg.sender; }
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
modifier whenNotPaused() {
require(!paused, "paused");
_;
}
modifier validValue(uint256 v) {
require(v > 0, "invalid value");
_;
}
// Multiple modifiers — executed in order
// Stack-like: A B body B' A'
function setValue(uint256 v)
public
onlyOwner // 1. check owner
whenNotPaused // 2. check not paused
validValue(v) // 3. validate input
{
value = v;
}
}Порядок модификаторов и газ
Порядок модификаторов влияет на газ и читаемость. Ставьте дешёвые проверки первыми (булевы, сравнения адресов), дорогие — последними (запись в storage, внешние вызовы). Также ставьте первыми проверки, которые чаще всего падают, — это обрывает выполнение и возвращает неиспользованный газ. Документируйте порядок комментариями.
contract ModOrder {
// Order modifiers from cheapest to most expensive
// OR most likely to fail first (to short-circuit)
modifier onlyOwner() { require(msg.sender == owner, "1"); _; }
modifier nonZero(uint256 x) { require(x != 0, "2"); _; }
modifier withinRange(uint256 x) {
require(x >= 1 && x <= 100, "3");
_;
}
modifier notPaused() { require(!paused, "4"); _; }
// Good order: cheap + likely-to-fail first
function good(uint256 x)
public
notPaused // 1. cheap bool check
onlyOwner // 2. address compare
nonZero(x) // 3. cheap input check
withinRange(x) // 4. more complex range check
{}
address public owner;
bool public paused;
constructor() { owner = msg.sender; }
}Частые паттерны модификаторов
Частые паттерны: nonReentrant (ставит блокировку до тела и снимает после), whenNotPaused/whenPaused (аварийный выключатель), onlyRole (RBAC с ролями bytes32), rateLimit (ограничение на пользователя по времени). Защита от реентрантности важнее всего — применяйте её к любой функции, которая делает внешний вызов после изменения состояния.
contract Patterns {
// 1. Reentrancy guard
uint256 private _status = 1;
modifier nonReentrant() {
require(_status == 1, "reentrant");
_status = 2;
_;
_status = 1;
}
// 2. Pausable
bool public paused;
modifier whenNotPaused() {
require(!paused, "paused");
_;
}
modifier whenPaused() {
require(paused, "not paused");
_;
}
// 3. Role-based
mapping(bytes32 => bool) public hasRole;
modifier onlyRole(bytes32 role) {
require(hasRole[role], "missing role");
_;
}
// 4. Rate limit (basic)
mapping(address => uint256) public lastCall;
modifier rateLimit() {
require(block.timestamp >= lastCall[msg.sender] + 1 minutes, "rate");
lastCall[msg.sender] = block.timestamp;
_;
}
}События
Объявление и emit событий
События пишутся в блокчейн и читаются клиентами вне сети (через eth_getLogs). Другие контракты их НЕ читают. Используйте indexed максимум на 3 параметрах, чтобы их можно было фильтровать. События дешевле записи в storage. Всегда emit'ьте события при важных изменениях состояния, чтобы dApps и индексаторы могли реагировать.
contract Events {
// Declare event (outside functions, can be at file level)
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => uint256) public balances;
function transfer(address to, uint256 amount) public returns (bool) {
require(balances[msg.sender] >= amount, "insufficient");
balances[msg.sender] -= amount;
balances[to] += amount;
// Emit the event
emit Transfer(msg.sender, to, amount);
return true;
}
function approve(address spender, uint256 amount) public returns (bool) {
emit Approval(msg.sender, spender, amount);
return true;
}
}Indexed-параметры
indexed-параметры становятся топиками, по которым клиенты вне сети (dApps, The Graph, индексаторы) могут фильтровать. Максимум 3 indexed-параметра на событие (4-й топик зарезервирован под хеш сигнатуры события). Indexed типы значений (uint, address) хранятся напрямую; indexed ссылочные типы (string, bytes, массивы) хешируются keccak256 и невосстановимы.
contract Indexed {
// Up to 3 indexed params (in non-anonymous events)
// Indexed params become 'topics' that clients can filter on
event OrderPlaced(
address indexed buyer, // topic 1
address indexed token, // topic 2
uint256 indexed orderId, // topic 3
uint256 amount, // data (not filterable)
uint256 price // data
);
function placeOrder(address token, uint256 amount, uint256 price)
public returns (uint256 id)
{
id = uint256(keccak256(abi.encodePacked(msg.sender, block.number)));
emit OrderPlaced(msg.sender, token, id, amount, price);
}
// Clients can filter:
// eth_getLogs({topics: [sig, buyerAddr, tokenAddr, orderId]})
//
// Indexed arrays/strings/bytes are hashed (keccak256) —
// you can't recover the original value, only compare hashes.
}Анонимные события
Анонимные события пропускают хеш сигнатуры события в topic[0], освобождая слот — так получается 4 indexed-параметра вместо 3. Компромисс: клиенты не могут фильтровать по имени события (сигнатуре), поэтому различать несколько анонимных событий в контракте сложнее. Полезно редко; экономия газа крошечная.
contract Anonymous {
// anonymous: skips storing the event signature as topic[0]
// So you can have up to 4 indexed params instead of 3
event Log(
address indexed from,
address indexed to,
uint256 indexed amount,
uint256 indexed timestamp, // 4th indexed (only with anonymous)
bytes data
) anonymous;
function log() public {
emit Log(msg.sender, address(0), 100, block.timestamp, "");
}
// Trade-offs:
// + 1 more indexed param allowed
// - Clients cannot filter by event signature
// - Harder to distinguish multiple anonymous events
// - Slightly cheaper gas
// Rarely used; prefer named events for clarity.
}Лучшие практики событий
Практики: emit'ьте после изменений состояния (чтобы событие отражало итоговое состояние), включайте поля, помогающие индексаторам избежать лишних RPC-вызовов (вроде newBalance), не emit'ьте в плотных циклах (лучше батчами) и индексируйте поля, по которым чаще фильтруют (адреса, ID, коды статуса). События — основной канал связи контракта с внешним миром.
contract EventBest {
// 1. Name events with past tense or noun: Transfer, Deposit, OrderPlaced
event Transfer(address indexed from, address indexed to, uint256 value);
// 2. Emit AFTER state changes succeed
mapping(address => uint256) public balances;
function transfer(address to, uint256 amt) public {
balances[msg.sender] -= amt; // state first
balances[to] += amt;
emit Transfer(msg.sender, to, amt); // event after
}
// 3. Include enough data to reconstruct state
event Deposit(
address indexed account,
uint256 amount,
uint256 newBalance, // helps indexers avoid extra reads
uint256 timestamp
);
// 4. Don't emit in a loop — batch instead
event BatchTransfer(address[] to, uint256[] amounts);
function batch(address[] memory to, uint256[] memory amounts) public {
emit BatchTransfer(to, amounts); // one event, not N
}
// 5. Index the fields users filter on (addresses, IDs)
}События, логи и storage
Storage находится в дереве состояния — его читают другие контракты и view-функции, но он дорог (~20k газа за SSTORE). События и логи находятся в дереве квитанций — контракты их НЕ читают, но они дешёвы (~1–2k газа) и доступны вне сети через eth_getLogs. Storage — для решений в сети, события — для сообщения об изменениях dApps и индексаторам.
contract Compare {
// Storage: persistent, readable by contracts, expensive
uint256 public storedValue; // SSTORE costs ~20k gas
// Events (logs): persistent-ish, NOT readable by contracts, cheap
event ValueChanged(uint256 oldValue, uint256 newValue);
function set(uint256 newValue) public {
uint256 old = storedValue;
storedValue = newValue; // SSTORE (~20k gas)
emit ValueChanged(old, newValue); // LOG (~1-2k gas)
}
// Logs live in the block's receipt trie, NOT the state trie.
// They are NOT accessible from other contracts.
// function readLog() public view returns (...) {
// CANNOT access emitted events
// }
// Off-chain tools (dApps, The Graph) read logs via eth_getLogs.
// Use storage for on-chain logic; events for off-chain observers.
}Обработка ошибок
Require
require(cond, msg) откатывает транзакцию и возвращает неиспользованный газ, если cond ложно. Это самый частый примитив валидации — используйте для проверок входа, контроля доступа и предусловий. Строка сообщения стоит газа (хранится в байткоде). Для экономии газа используйте custom errors (revert ErrorName()) вместо строковых сообщений.
contract Require {
mapping(address => uint256) public balances;
function deposit() public payable {
require(msg.value > 0, "must send ether");
balances[msg.sender] += msg.value;
}
function withdraw(uint256 amount) public {
// require(condition, message)
// Reverts with the message if condition is false
// Refunds all unused gas to the caller (post-0.8.0 with custom errors, also refunds)
require(balances[msg.sender] >= amount, "insufficient balance");
balances[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
}
// Pre-0.8.0: require with no message was cheaper
// 0.8.4+: prefer custom errors (cheaper, see other item)
function cheap(uint256 x) public pure {
if (x == 0) revert ZeroValue(); // custom error
}
error ZeroValue();
}Revert
revert(msg) явно откатывает транзакцию с причиной. Используйте revert() в if-ветках, когда нужна ветвящаяся логика (require — просто синтаксический сахар). revert() без сообщения дешевле revert("msg"). Custom errors (revert ErrorName(args)) дешевле всего и информативнее — предпочитайте их в новом коде.
contract Revert {
function explicit(uint256 x) public pure {
if (x == 0) {
revert("zero not allowed"); // explicit revert with message
}
if (x > 100) {
revert("too big"); // can place anywhere
}
}
// revert() with no message (cheapest string revert)
function silent(uint256 x) public pure {
if (x == 0) revert(); // no reason
}
// Custom error (0.8.4+) — recommended
error TooBig(uint256 given, uint256 max);
function custom(uint256 x) public pure {
if (x > 100) revert TooBig(x, 100);
}
// Inside an internal function, revert propagates up
function caller(uint256 x) public pure {
inner(x); // reverts here if x is bad
}
function inner(uint256 x) internal pure {
if (x == 0) revert("zero");
}
}Assert
assert(cond) — для инвариантов, которые не должны быть ложными при корректном коде: сработавший assert указывает на баг. До 0.8.0 assert сжигал весь газ; с 0.8.0 он ведёт себя как revert. Используйте require для валидации входа и ожидаемых ошибок; assert — только для невозможных состояний, сигнализирующих о баге. Современные автопроверки переполнения используют revert, а не assert.
contract Assert {
function check(uint256 x) public pure returns (uint256) {
uint256 result = x + 1;
// assert: for invariants that should NEVER be false
// If it fails, something is critically broken.
assert(result > x); // overflow check (auto in 0.8+)
return result;
}
// Pre-0.8.0: assert was used for overflow checks (used all gas)
// Post-0.8.0: arithmetic auto-checks use revert, not assert
//
// Modern guidance:
// - Use require/revert for input validation & expected failures
// - Use assert ONLY for invariants that indicate a code bug
// (something that should be impossible if the code is correct)
//
// Example: a state machine that should never reach an invalid state
enum State { Created, Paid, Shipped }
State public state;
function ship() public {
require(state == State.Paid, "not paid");
state = State.Shipped;
assert(state == State.Shipped); // invariant
}
}Custom Errors
Custom errors (0.8.4+) — рекомендуемый способ отката. Они кодируются как 4-байтовый селектор плюс ABI-аргументы — намного дешевле строковых сообщений (которые хранятся как полный UTF-8 в байткоде). Клиенты декодируют селектор, чтобы понять, какая ошибка произошла, и прочитать структурированные аргументы. Определяйте ошибки на уровне файла или контракта, затем 'revert ErrorName(args);'.
contract CustomError {
// Define errors (outside functions, can be at file level)
error InsufficientBalance(uint256 available, uint256 required);
error Unauthorized(address caller);
error TransferFailed(address from, address to);
mapping(address => uint256) public balances;
function withdraw(uint256 amount) public {
if (balances[msg.sender] < amount) {
// Cheaper than require(..., "insufficient balance")
revert InsufficientBalance(balances[msg.sender], amount);
}
balances[msg.sender] -= amount;
(bool ok, ) = msg.sender.call{value: amount}("");
if (!ok) revert TransferFailed(address(this), msg.sender);
}
function adminOnly() public {
if (msg.sender != address(0x123)) {
revert Unauthorized(msg.sender);
}
}
// Why cheaper? The error selector (4 bytes) replaces a long string,
// saving bytecode size and gas per call.
// ABI decodes arguments so clients get structured data.
}Try / Catch
try/catch обрабатывает ошибки только внешних вызовов — он не перехватывает revert внутренних вызовов. Клауза 'returns' захватывает успешное значение. catch Error() ловит revert/require со строковыми сообщениями; catch Panic() ловит паники assert и переполнения; catch (bytes) — запасной вариант для custom errors и неизвестных revert'ов. Используйте для аккуратной обработки сбоев внешних контрактов.
contract TryCatch {
interface IToken {
function transfer(address to, uint256 amount) external returns (bool);
}
IToken public token;
constructor(address _token) { token = IToken(_token); }
function safeTransfer(address to, uint256 amount)
public returns (bool success, bool tokenOk)
{
try token.transfer(to, amount) returns (bool ok) {
// Called if no revert; 'ok' captures the return value
return (ok, true);
} catch Error(string memory reason) {
// revert("reason") or require(_, "reason")
// log reason
return (false, false);
} catch Panic(uint256 code) {
// assert failures (code 0x01) or overflow (0x11)
return (false, false);
} catch (bytes memory lowLevelData) {
// Any other revert (including custom errors)
return (false, false);
}
}
// try/catch ONLY works with EXTERNAL calls (or this.f()).
// It does NOT catch errors in internal calls.
// The called function MUST return something (not void).
}Сообщения об ошибках и паттерны
Современная обработка ошибок использует custom errors для структурированных и дешёвых откатов. Старые строковые сообщения всё ещё часты в коде до 0.8.4. Всегда добавляйте практичный контекст: какое значение было неверным, что ожидалось. Не вставляйте динамические адреса и числа в строки — они раздувают байткод и не парсятся. Если нужны строки, используйте префиксы ('INVALID:') для удобства индексации логов.
contract Errors {
// 1. Custom errors (best for new code)
error InvalidAmount(uint256 given);
error NotOwner(address caller, address owner);
// 2. String errors (older style)
function old(uint256 x) public pure {
require(x > 0, "INVALID: must be > 0"); // prefix helps indexing
require(x < 100, "INVALID: must be < 100");
}
// 3. Custom error with structured data
function newStyle(uint256 x) public pure {
if (x == 0) revert InvalidAmount(x);
}
// 4. Error with multiple fields
address public owner;
constructor() { owner = msg.sender; }
function guarded() public view {
if (msg.sender != owner) {
revert NotOwner(msg.sender, owner);
}
}
// 5. Don't put dynamic data in string errors (expensive & unparseable)
// BAD: require(msg.sender == owner, "not owner: caller 0x123...");
// GOOD: revert NotOwner(msg.sender, owner);
}Наследование
Наследование через 'is'
Наследование использует ключевое слово 'is'. Дочерний контракт наследует все переменные состояния, функции и модификаторы родителя. Аргументы конструктора родителя передаются в списке наследования (Animal("dog")) или в стиле модификатора конструктора. Ребёнок может переопределять функции, помеченные virtual у родителя. Solidity поддерживает множественное наследование (линеаризация C3).
contract Animal {
string public species;
constructor(string memory _species) {
species = _species;
}
function speak() public virtual returns (string memory) {
return "...";
}
}
contract Dog is Animal {
constructor() Animal("dog") {}
// Override parent function
function speak() public override returns (string memory) {
return "Woof";
}
}
// Multiple inheritance
contract Puppy is Dog {
function speak() public override returns (string memory) {
return "Yip";
}
}Virtual и override
virtual помечает функцию как переопределяемую; override помечает функцию как переопределяющую родительскую. По умолчанию функции не virtual (б езопаснее). При переопределении из нескольких родителей с общим предком перечислите их: override(A, B). Чтобы разрешить дальнейшие переопределения, используйте virtual override. Переменные состояния переопределять нельзя (только затенять в памяти).
contract Base {
function f() public pure virtual returns (string memory) {
return "base";
}
function g() public pure virtual returns (string memory) {
return "base-g";
}
}
contract Middle is Base {
// Override a single parent
function f() public pure override returns (string memory) {
return "middle";
}
}
contract Multi is Base {
// Override (also virtual so children can override again)
function g() public pure virtual override returns (string memory) {
return "multi";
}
}
contract Combined is Middle, Multi {
// Override multiple parents (explicit list)
function f() public pure override(Middle, Base) returns (string memory) {
return "combined";
}
function g() public pure override(Multi, Base) returns (string memory) {
return "combined-g";
}
}Ключевое слово super
super.method() вызывает родительскую версию метода, позволяя расширить поведение, а не заменить его. При одиночном наследовании это интуитивно. При множественном наследовании super следует линеаризации C3 — он может вызвать соседний контракт, а не лексического родителя. Всегда проверяйте порядок линеаризации (самый производный последний) при ромбовидном наследовании.
contract A {
function label() public pure virtual returns (string memory) {
return "A";
}
}
contract B is A {
function label() public pure virtual override returns (string memory) {
return string.concat("B>", super.label()); // calls A.label()
}
}
contract C is B {
function label() public pure override returns (string memory) {
return string.concat("C>", super.label()); // calls B.label()
}
}
// super refers to the NEXT contract in the linearization,
// not necessarily the lexical parent. With multiple inheritance,
// super.label() may call a sibling.
contract P1 { function f() public pure virtual returns (uint) { return 1; } }
contract P2 { function f() public pure virtual returns (uint) { return 2; } }
contract Child is P1, P2 {
function f() public pure override(P1, P2) returns (uint) {
return super.f(); // calls P2.f() (last in linearization)
}
}Множественное наследование
Solidity поддерживает множественное наследование через 'is'. Перечисляйте родителей от самого базового к самому производному: 'is Ownable, Pausable'. Алгоритм C3 даёт детерминированный порядок и решает проблему ромба. Используйте 'override(A, B)' при переопределении функции, унаследованной от нескольких родителей. Конструкторы выполняются в порядке линеаризации (родители первыми).