Primeros pasos
Conceptos básicos de contratos
Solidity es el lenguaje principal para los smart contracts de Ethereum. pragma fija la versión del compilador. Un contrato es como una clase. Las funciones pueden ser public, private, view (solo lectura) o 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 y versión del compilador
pragma especifica la versión del compilador. ^0.8.0 permite cualquier parche 0.8.x. Para producción, fija la versión exacta (0.8.19) para evitar sorpresas. Incluye siempre el pragma al inicio de cada archivo .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;Comentarios y NatSpec
Los comentarios NatSpec (/// o /** */) generan documentación. @notice va dirigido a los usuarios finales, @dev a los desarrolladores, @param describe los parámetros y @return los valores de retorno. Herramientas como Etherscan y Remix los recogen.
// 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 {}
}Licencia SPDX
Desde Solidity 0.6.8, el identificador de licencia SPDX es obligatorio al inicio del archivo. Ayuda a las herramientas y a los usuarios a entender cómo puede reutilizarse el código. Usa MIT para open source permisivo, GPL-3.0 para copyleft, o UNLICENSED para código privado.
// 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 {}Estructura del archivo e imports
Los imports traen contratos, librerías o interfaces. Usa {Name} para importar solo elementos concretos. Las rutas relativas funcionan como es de esperar. La palabra clave 'is' establece la herencia. Los archivos suelen tener un contrato principal, pero pueden contener varios.
// 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 {
// ...
}Tipos de valor
Enteros (uint / int)
uint = entero sin signo (sin negativos), int = con signo. Los tamaños van de 8 a 256 en pasos de 8. uint por defecto es uint256. Desde 0.8.0, la aritmética comprueba automáticamente overflow/underflow y revierte. Usa type(T).max / type(T).min para obtener los límites.
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;Booleano
bool solo puede ser true o false. && y || hacen cortocircuito, es decir, el lado derecho solo se evalúa si hace falta. El valor por defecto es false. Los booleanos cuestan más gas que uint256 en algunos contextos (empaquetado de 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 guarda una dirección Ethereum de 20 bytes. address payable puede recibir Ether (tiene las funciones transfer/send). Usa payable(x) para convertir. Las direcciones tienen la propiedad .balance (en wei). Verifica siempre los literales de dirección contra el checksum EIP-55 para detectar erratas.
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 y arrays de bytes
Los bytes fijos (bytes1..bytes32) son baratos y se usan para hashes/selectores. bytes dinámico es para datos binarios crudos; string es para texto UTF-8. Usa bytes32 para hashes (keccak256 devuelve bytes32). bytes.concat() (0.8.4+) es más barato que abi.encodePacked para arrays de bytes.
// 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
Los enums definen un conjunto finito de valores con nombre. Se almacenan como uint8 (máximo 256 miembros). El valor por defecto es el primer miembro (índice 0). Convierte entre enum y uint mediante casts. type(EnumName).max da el miembro más alto.
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
}Conversión y casting de tipos
Las conversiones implícitas solo ocurren cuando no hay posible pérdida de datos (uint8 -> uint256). Para conversiones que reducen (uint256 -> uint8) o entre signado/sin signo, usa casts explícitos. Convertir un int negativo a uint produce un número enorme debido al complemento a dos.
// 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!Tipos de referencia
String
Los strings en Solidity son arrays de bytes UTF-8 — length() devuelve el número de bytes, no de caracteres (los emoji/caracteres multibyte difieren). La igualdad debe comprobarse mediante el hash keccak256. string.concat (0.8.12+) es más barato que abi.encodePacked. Los strings son caros en gas.
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; }
}Arrays (fijos y dinámicos)
Los arrays fijos [N] tienen tamaño de compilación; los dinámicos [] crecen con push/pop. Los arrays en memoria deben crearse con 'new Type[](size)'. Leer/escribir arrays de storage cuesta gas; prefiere memory para datos temporales. push() devuelve una referencia desde 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
Los structs agrupan campos relacionados. Pueden guardarse en storage o memory, o pasarse como argumentos de funciones. Defínelos a nivel de archivo o de contrato. Inicializarlos con campos con nombre {field: value} es más claro; la forma posicional es más corta. Los valores de mapping no pueden accederse como struct completo en versiones antiguas.
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
Los mappings son tablas hash: keccak256(key) => value. No tienen longitud y no se pueden iterar. Las claves pueden ser tipos de valor (uint, address, bytes, enum); los valores pueden ser cualquier cosa. Los mappings anidados permiten búsquedas de varias claves. Para iterar, mantén un array aparte de claves. delete restablece una clave a su valor cero.
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
}
}Ubicaciones de datos (storage / memory / calldata)
storage = estado persistente en cadena (caro). memory = temporal, vive durante la llamada a la función (barato). calldata = solo lectura, únicamente para entradas de funciones external (lo más barato). Usa siempre calldata para los argumentos external que solo lees. Ubicación por defecto: las variables de estado son storage; los tipos complejos locales de una función son memory por defecto.
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
}Estructuras anidadas
Los structs pueden contener arrays, mappings (solo en storage) y otros structs. Acceder a campos de structs anidados vía una referencia de storage es eficiente en gas. Cuidado con el anidamiento profundo — aumenta el uso de slots de storage y el coste de despliegue. El mapping-de-struct es el patrón de base de datos en cadena más común.
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;
}Variables de estado
Variables de estado públicas y privadas
Las variables de estado public generan automáticamente una función getter. private restringe el acceso al contrato; internal también lo permite a las subclases. Por defecto es internal. CRÍTICO: 'private' NO significa secreto — la totalidad de los datos de la blockchain son legibles públicamente. Usa cifrado/hashing si necesitas confidencialidad.
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; }Variables constant
Las variables constant se evalúan en tiempo de compilación y se incrustan en el bytecode — no cuestan gas en tiempo de ejecución (sin SLOAD). Solo los tipos de valor (uint, address, bytes, etc.) pueden ser constant. El valor debe ser una expresión de compilación. Usa constant para valores fijos como MAX_SUPPLY, DECIMALS, direcciones.
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
}
}Variables immutable
Las variables immutable se asignan una vez en el constructor y luego son de solo lectura. Se guardan en el bytecode (no en storage), así que leerlas cuesta menos que las variables de estado normales. A diferencia de constant, immutable puede usar argumentos del constructor y valores en tiempo de ejecución. Usa immutable para cosas fijadas al desplegar, como owner, nombre del token o configuración específica de la cadena.
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; }
}Variables globales (msg, tx, block)
msg aporta el contexto de la llamada: msg.sender (llamador inmediato), msg.value (wei enviados), msg.data (calldata crudo), msg.sig (selector de función). tx da información de la transacción: tx.origin (la EOA, NO recomendado para autenticación). block da el bloque actual: block.timestamp, block.number, block.chainid, block.coinbase. Nunca uses tx.origin para autorización — usa 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
}
}Propiedades de bloque y transacción
blockhash() solo devuelve hashes de los últimos 256 bloques; los más antiguos devuelven 0. block.timestamp lo fija el minero y puede desviarse ~15 segundos — nunca lo uses para tiempos precisos ni aleatoriedad. block.basefee viene de EIP-1559. gasleft() sustituye al obsoleto msg.gas. chainid es clave para la protección contra replay.
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
}
}Funciones
Sintaxis de funciones
Sintaxis de función: function name(params) visibility mutability returns(...). La visibilidad (public/external/internal/private) es obligatoria. La mutabilidad (pure/view/payable) es opcional pero recomendada. Se soportan múltiples valores de retorno. Los retornos con nombre permiten asignarles directamente y omitir la palabra clave 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;
}
}Funciones view
Las funciones view pueden leer estado pero no modificarlo. Llamadas externamente vía eth_call son gratuitas (sin comisión de gas). Llamadas internamente desde una función que modifica, consumen gas. Usa view para cualquier función que solo lea estado — señala la intención y permite lecturas gratuitas fuera de la cadena.
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)
}Funciones pure
Las funciones pure no pueden leer ni escribir estado — solo computan sobre sus entradas. Son las más restringidas y las más baratas de llamar fuera de la cadena. Usa pure para funciones utilitarias (matemáticas, hashing de entradas). Si necesitas msg.sender o datos del bloque, usa view. pure solo puede llamar a otras funciones 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
}Funciones payable
Las funciones payable pueden recibir Ether vía msg.value. El Ether se añade automáticamente al balance del contrato. Solo las funciones payable y receive/fallback pueden aceptar Ether. Valida siempre msg.value si esperas un importe concreto. Las funciones no payable revierten si se les envía 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
}
}Valores de retorno y retornos con nombre
Las funciones pueden devolver varios valores mediante tuplas. Los retornos con nombre mejoran la legibilidad y permiten asignar directamente sin sentencia return. Las sentencias return explícitas anulan los retornos con nombre. Usa desestructuración (a, b) = f() para capturar múltiples retornos; usa (, b) o (a,) para saltar valores que no necesites.
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;
}
}Sobrecarga de funciones
Solidity soporta sobrecarga de funciones: varias funciones con el mismo nombre pero distintos tipos o cantidad de parámetros. El compilador resuelve cuál llamar según los tipos de los argumentos. El tipo de retorno solo no puede distinguir sobrecargas. Las sobrecargas son útiles para aceptar tanto address como address payable, o distintos rangos numéricos.
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 y funciones especiales
Constructor
El constructor se ejecuta una vez al desplegar el contrato, para inicializar el estado. No puede volver a llamarse. Los argumentos del constructor se añaden al bytecode de despliegue o se pasan vía ABI según el framework. Con herencia, pasa los argumentos del constructor padre en la lista de herencia (Owned(_owner)) o al estilo modificador (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() {}
}Función receive
receive() se invoca cuando una llamada sin calldata envía Ether (p. ej., send/transfer al contrato). Debe ser 'external payable' sin argumentos ni retornos. Solo se permite una función receive. Si no existe y tampoco hay fallback, las transferencias simples de Ether revierten (excepto vía selfdestruct, que puede forzar 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).Función fallback
fallback() se llama cuando ninguna función coincide con el selector, o cuando receive no existe y se intenta una transferencia simple de Ether. Puede ser payable. Mantén la lógica del fallback mínima — cuando se invoca vía send()/transfer() solo tiene 2300 de gas (el stipend), que no cubre escrituras de storage ni emit de eventos.
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 envía la totalidad del Ether restante a una dirección especificada y (antes de Dencun) elimina el código del contrato. Tras EIP-6780 (marzo de 2024), solo elimina el código si se llama dentro de la misma transacción de despliegue — si no, solo transfiere el Ether. Nunca dependas de selfdestruct para la seguridad: el Ether forzado puede seguir llegando, y el código puede persistir.
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' flagSelector de función
Cada función tiene un selector de 4 bytes = los primeros 4 bytes de keccak256(firma). La firma es el nombre de la función y los tipos de parámetros sin espacios, p. ej., 'transfer(address,uint256)'. El EVM usa el selector para enrutar las llamadas. msg.sig da el selector de la función actual. abi.encodeWithSelector/Signature construyen calldata para llamadas de bajo nivel.
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)
);
}
}Modificadores
Conceptos básicos de modificadores
Los modificadores envuelven funciones con condiciones previas/posteriores reutilizables. El marcador _; es donde se ejecuta el cuerpo de la función. Los modificadores son geniales para control de acceso (onlyOwner), validación (validInput) y guards de reentrancy. Se aplican antes del cuerpo por defecto — usa _; para controlar dónde corre el cuerpo.
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;
}
}Modificadores con argumentos
Los modificadores pueden recibir argumentos, lo que los hace flexibles. Los argumentos se evalúan en el punto de llamada y se vinculan cuando corre el modificador. Patrones comunes: costs(price) para pago por llamada, onlyRole(role) para RBAC, rateLimit(window) para limitar frecuencia. La lógica antes de _; es precondición, después de _; es postcondición.
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
}
}Múltiples modificadores
Una función puede tener varios modificadores. Se ejecutan en orden, envolviendo el cuerpo como una pila: la precondición del primer modificador corre primero, luego la del segundo, ..., luego el cuerpo, y después se desenvuelven en orden inverso. El orden importa — pon primero las comprobaciones más baratas o más propensas a fallar para ahorrar gas.
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;
}
}Orden de modificadores y gas
El orden de los modificadores afecta al gas y a la claridad. Pon las comprobaciones baratas primero (booleanos, comparaciones de direcciones) y las caras al final (escrituras de storage, llamadas externas). Pon también primero las comprobaciones con más probabilidad de fallar — esto corta en cortocircuito y reembolsa el gas no usado. Documenta el orden previsto con comentarios.
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; }
}Patrones de modificadores comunes
Patrones de modificadores habituales: nonReentrant (fija un lock antes del cuerpo, lo retira después), whenNotPaused/whenPaused (interruptor de emergencia), onlyRole (RBAC con roles bytes32), rateLimit (limitación por usuario usando timestamps). El reentrancy guard es el más importante — aplícalo a cualquier función que haga una llamada externa tras un cambio de estado.
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;
_;
}
}Eventos
Declaración y emit de eventos
Los eventos se registran en la blockchain y son legibles por clientes fuera de la cadena (vía eth_getLogs). NO son legibles por otros contratos. Usa indexed en hasta 3 parámetros para hacerlos filtrables. Los eventos cuestan menos gas que las escrituras de storage. Emite siempre eventos para los cambios de estado importantes, así los dApps y los indexadores pueden reaccionar.
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;
}
}Parámetros indexed
Los parámetros indexed se convierten en topics que los clientes fuera de la cadena (dApps, The Graph, indexadores) pueden filtrar. Máximo 3 parámetros indexed por evento (el cuarto topic se reserva para el hash de la firma del evento). Los tipos de valor indexed (uint, address) se guardan directamente; los tipos de referencia indexed (string, bytes, arrays) se hashean con keccak256 y son irrecuperables.
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.
}Eventos anónimos
Los eventos anonymous omiten el hash de la firma del evento en topic[0], liberando un slot — así obtienes 4 parámetros indexed en vez de 3. El compromiso: los clientes no pueden filtrar por nombre de evento (firma), así que es más difícil distinguir varios eventos anónimos en un contrato. Poco útiles; el ahorro de gas es mínimo.
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.
}Buenas prácticas con eventos
Buenas prácticas: emite tras los cambios de estado (así el evento refleja el estado final), incluye campos que eviten llamadas RPC extra a los indexadores (como newBalance), evita emitir en bucles estrechos (haz lotes en su lugar) e indexa los campos más filtrados (direcciones, IDs, códigos de estado). Los eventos son el canal principal de comunicación del contrato hacia fuera de la cadena.
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)
}Eventos vs logs vs storage
El storage está en el state trie — legible por otros contratos y funciones view, pero caro (~20k de gas por SSTORE). Los eventos/logs están en el receipt trie — NO legibles por contratos, pero baratos (~1-2k de gas) y accesibles fuera de la cadena vía eth_getLogs. Usa storage para decisiones en cadena y eventos para comunicar cambios de estado a dApps e indexadores.
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.
}Manejo de errores
Require
require(cond, msg) revierte la transacción y reembolsa el gas no usado si cond es falsa. Es la primitiva de validación más común — úsalo para comprobaciones de entrada, control de acceso y precondiciones. El string del mensaje cuesta gas (se guarda en el bytecode desplegado). Para ahorrar gas, usa custom errors (revert ErrorName()) en lugar de mensajes de texto.
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) revierte explícitamente la transacción con un string de motivo. Usa revert() dentro de if cuando necesites lógica con ramas (require es solo azúcar sintáctico). revert() sin mensaje es más barato que revert("msg"). Los custom errors (revert ErrorName(args)) son lo más barato y descriptivo — prefierelos en código nuevo.
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) es para invariantes que nunca deberían ser falsas si el código es correcto — un assert que falla indica un bug. Antes de 0.8.0, assert consumía la totalidad del gas; desde 0.8.0 se comporta como revert. Usa require para validación de entradas y condiciones de error esperadas; usa assert solo para estados imposibles que señalan un bug. Las comprobaciones automáticas de overflow modernas usan revert, no 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
Los custom errors (0.8.4+) son la forma recomendada de revertir. Se codifican como un selector de 4 bytes más argumentos codificados con ABI — mucho más barato que los mensajes de texto (que se guardan como UTF-8 completo en el bytecode). Los clientes decodifican el selector para saber qué error ocurrió y leen los argumentos estructurados. Define los errors a nivel de archivo o de contrato y luego '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 maneja errores solo de llamadas externas — no puede capturar reverts de llamadas a funciones internas. La cláusula 'returns' captura el valor de éxito. catch Error() captura revert/require con mensajes de texto; catch Panic() captura los panics de assert/overflow; catch (bytes) es el fallback para custom errors y reverts desconocidos. Úsalo para manejar con elegancia fallos de contratos externos.
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).
}Mensajes y patrones de error
El manejo de errores moderno usa custom errors para reverts estructurados y baratos. Los mensajes de texto antiguos siguen siendo comunes en código previo a 0.8.4. Incluye siempre contexto accionable: qué valor estaba mal y qué se esperaba. Evita meter direcciones/números dinámicos en mensajes de texto — hinchan el bytecode y no son parseables. Usa mensajes con prefijo ('INVALID:') si tienes que usar strings, para facilitar el indexado de logs.
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);
}Herencia
Herencia con 'is'
La herencia usa la palabra clave 'is'. Un contrato hijo hereda todas las variables de estado, funciones y modificadores de su padre. Los argumentos del constructor padre se pasan en la lista de herencia (Animal("dog")) o con el estilo modificador del constructor. Un hijo puede sobrescribir las funciones marcadas virtual en el padre. Solidity soporta herencia múltiple (linealización vía 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 y Override
virtual marca una función como sobrescribible; override marca una función como sobrescribiendo a su padre. Las funciones no son virtual por defecto (más seguro). Al sobrescribir desde varios padres que comparten una base, lístalos: override(A, B). Para permitir más sobrescrituras, usa virtual override. Las variables de estado no pueden sobrescribirse (solo sombreadas en memoria).
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";
}
}Palabra clave super
super.method() llama a la versión del padre de esa función, permitiendo extender el comportamiento en lugar de reemplazarlo. Con herencia simple es intuitivo. Con herencia múltiple, super sigue la linealización C3 — puede llamar a un contrato hermano, no al padre léxico. Comprueba siempre el orden de linealización (el más derivado al final) al usar super en herencia en rombo.
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)
}
}Herencia múltiple
Solidity soporta herencia múltiple mediante la palabra clave 'is'. Lista los padres de la base más antigua a la más derivada: 'is Ownable, Pausable'. El algoritmo de linealización C3 produce un orden determinista que resuelve el problema del rombo. Usa 'override(A, B)' al sobrescribir una función heredada de varios padres. Los constructores corren en orden de linealización (padres primero).
contract Ownable {
address public owner;
constructor() { owner = msg.sender; }
modifier onlyOwner() { require(msg.sender == owner); _; }
}
contract Pausable {
bool public paused;
modifier whenNotPaused() { require(!paused); _; }
}
// Multiple inheritance: list parents from most base to most derived
contract Token is Ownable, Pausable {
mapping(address => uint256) public balances;
function mint(address to, uint256 amount)
public
onlyOwner // from Ownable
whenNotPaused // from Pausable
{
balances[to] += amount;
}
}
// C3 Linearization order (for 'Token'):
// Token -> Pausable -> Ownable -> (object)
// Determined by the order in 'is' list (left to right, base first)
//
// Diamond problem is resolved by C3 — there is a single
// deterministic order, no ambiguity. But you must understand it
// when using super.Herencia de constructores
Los argumentos del constructor padre pueden pasarse en la lista de herencia (A(42)) para valores fijos, o en el constructor del hijo vía sintaxis de modificador (A(_a)) para valores en tiempo de ejecución. Con varios padres, pásalos en orden de linealización (la base más antigua primero). Si un padre tiene un constructor sin argumentos, puedes omitirlo. Los constructores corren una vez al desplegar, en orden de linealización.
contract A {
uint256 public a;
constructor(uint256 _a) { a = _a; }
}
// Style 1: pass args in inheritance list
contract B1 is A(42) {
// 'a' is set to 42 at deployment
}
// Style 2: pass via modifier-style in child constructor
contract B2 is A {
constructor(uint256 _b) A(_b * 2) {
// 'a' is set to _b * 2
}
}
// Style 3: child has its own constructor + parent args
contract B3 is A {
uint256 public b;
constructor(uint256 _a, uint256 _b) A(_a) {
b = _b;
}
}
// With multiple parents, order = linearization order
contract C1 { constructor(uint) {} }
contract C2 { constructor(uint) {} }
contract C3 is C1, C2 {
constructor(uint x) C1(x) C2(x+1) {}
}Contratos abstractos e interfaces
Contratos abstractos
Un contrato abstract tiene al menos una función sin cuerpo (declarada con virtual, sin implementación). No puede desplegarse directamente — un hijo debe implementar todas las funciones abstractas. Usa contratos abstractos cuando quieras estado compartido + modificadores + implementación parcial. La palabra clave 'abstract' es obligatoria antes de 0.6.0 si alguna función carece de cuerpo.
abstract contract Ownable {
address public owner;
constructor() { owner = msg.sender; }
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
// abstract function — no body, must be implemented by children
function sensitiveAction() public virtual;
// Can have implemented functions too
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
}
contract Vault is Ownable {
function sensitiveAction() public override onlyOwner {
// implementation here
}
}Interfaces
Las interfaces son como contratos abstractos puros: sin estado, sin constructores, sin funciones implementadas, todas las funciones external. Definen el ABI de un contrato para interactuar con implementaciones desconocidas. Usa interfaces para llamar a otros contratos sin heredar su lógica. Nómbralas con prefijo 'I' (IERC20, IUniswapV2Pair). Las funciones de una interfaz no pueden tener modificadores distintos de external view/payable.
interface IERC20 {
// Functions only — no implementation, no state, no constructor
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender)
external view returns (uint256);
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);
}
contract MyToken is IERC20 {
// Must implement ALL functions declared in the interface
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
// ... implement the rest
}Virtual vs Abstract
abstract = al menos una función sin cuerpo; el contrato no puede desplegarse. virtual = una función con cuerpo que los hijos PUEDEN sobrescribir. Una función puede ser ambas cosas (virtual + sin cuerpo). Las interfaces son implícitamente totalmente abstractas — cada función es virtual, no tiene cuerpo y es external. Usa abstract para lógica compartida, interfaces para definiciones puras de ABI.
// ABSTRACT contract: has at least one unimplemented function
// Must declare 'abstract'; cannot be deployed directly
abstract contract Counter {
uint256 public count;
function increment() public virtual; // no body -> abstract
function reset() public {
count = 0;
}
}
// VIRTUAL: function HAS a body, but CAN be overridden
contract Base {
function f() public pure virtual returns (uint) {
return 1;
}
}
contract Child is Base {
function f() public pure override returns (uint) {
return 2;
}
}
// A function can be both virtual and abstract (no body)
abstract contract A {
function f() public pure virtual; // virtual + no body
}
// Interfaces are implicitly abstract — all functions virtual+abstract
interface I {
function f() external; // implicit virtual, no body
}Buenas prácticas con interfaces
Buenas prácticas con interfaces: prefijo 'I', mantenlas mínimas (solo lo que los llamadores necesitan), todas las funciones external, sin estado/constructores/implementación, eventos permitidos. Usa interfaces para: (1) llamar a contratos cuyo código fuente no tienes, (2) definir estándares (IERC20, IERC721), (3) reducir bytecode al no heredar implementación. Implementar una interfaz obliga a tu contrato a cumplir el estándar.
// 1. Name with 'I' prefix
interface IERC721 {
function ownerOf(uint256 tokenId) external view returns (address);
function transferFrom(address from, address to, uint256 tokenId) external;
}
// 2. Keep minimal — only what callers need
interface IPriceFeed {
function latestAnswer() external view returns (int256);
function decimals() external view returns (uint8);
}
// 3. All functions external (required)
// 4. No state variables, no constructors, no implemented functions
// 5. Events ARE allowed in interfaces
interface IEvents {
event SomethingHappened(uint256 indexed id);
}
// 6. Use to call contracts you don't have source for
contract Consumer {
IPriceFeed public feed;
constructor(address _feed) { feed = IPriceFeed(_feed); }
function price() public view returns (int256) {
return feed.latestAnswer();
}
}
// 7. Implement to satisfy a standard (ERC20, ERC721)
contract MyToken is IERC20 { /* ... */ }Ejemplo IERC20 (interfaz)
IERC20 define el estándar de tokens fungibles ERC-20. La interfaz declara las 6 funciones obligatorias (totalSupply, balanceOf, transfer, approve, allowance, transferFrom) más los metadatos opcionales (name, symbol, decimals) y 2 eventos. Cualquier contrato que implemente esta interfaz puede tratarse como un token ERC-20. Usa la interfaz para interactuar con cualquier ERC-20 sin conocer su implementación interna.
// Canonical ERC-20 interface
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
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);
}
// Minimal interaction using the interface
contract Wallet {
IERC20 public token;
constructor(address _token) { token = IERC20(_token); }
function balance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function send(address to, uint256 amount) public returns (bool) {
return token.transfer(to, amount);
}
}Librerías
Conceptos básicos de librerías
Las librerías son como contratos, pero no pueden tener estado, heredar ni ser heredadas. Se despliegan una vez y se reutilizan vía DELEGATECALL (external) o incrustándose (internal). Las funciones internal de una librería se incrustan en el contrato llamador — sin despliegue separado. Usa librerías para agrupar funciones reutilizables (matemáticas, validación, formateo). La directiva 'using SafeMath for uint256' permite llamar a las funciones como a.b().
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "underflow");
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "overflow");
return c;
}
// Libraries CANNOT have state variables
// Libraries CANNOT inherit or be inherited
// All functions must be internal or external
// No constructor, no fallback, no receive
}
contract UsingSafeMath {
using SafeMath for uint256;
function calc(uint256 a, uint256 b) public pure returns (uint256) {
return a.add(b).mul(2); // a.add(b) calls SafeMath.add(a, b)
}
}Using For
'using Library for Type' adjunta las funciones de la librería a ese tipo, así puedes llamar a value.method() en lugar de Library.method(value). El primer parámetro de la función de la librería debe coincidir con el tipo. También puedes usar la directiva a nivel de archivo (0.8.13+) con 'using {fn1, fn2} for Type;'. Es puro azúcar sintáctico — el compilador lo reescribe como llamadas directas.
library Strings {
function toString(uint256 value) internal pure returns (string memory) {
// convert uint to decimal string
if (value == 0) return "0";
uint256 temp = value;
uint256 digits;
while (temp != 0) { digits++; temp /= 10; }
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + value % 10));
value /= 10;
}
return string(buffer);
}
}
contract UsingExample {
// Attach library functions to a type
using Strings for uint256;
function describe(uint256 x) public pure returns (string memory) {
// x.toString() calls Strings.toString(x)
return string.concat("Value: ", x.toString());
}
// Attach to a specific type globally (Solidity 0.8.13+)
// using {toString} for uint256; // file-level
// using SafeMath for uint256;
// using SafeMath for *; // not allowed
}Librerías internas
Las funciones internal de una librería se incrustan en el bytecode del contrato llamador en tiempo de compilación — no hay DELEGATECALL en tiempo de ejecución, ni despliegue de librería, ni sobrecarga de llamada. Esto las hace prácticamente gratuitas de llamar (solo el gas de las operaciones en sí). Usa librerías internas para helpers pure/view (matemáticas, conversión de strings). El tamaño del bytecode del llamador crece, pero el gas de llamada es menor que con librerías externas.
library Math {
// internal functions are INLINED into the caller's bytecode
// No separate deployment needed — saves gas on each call
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b)
internal pure returns (uint256)
{
// (a + b) / 2 can overflow; this avoids it
return (a & b) + ((a ^ b) / 2);
}
}
contract Calc {
using Math for uint256;
function doMath(uint256 x, uint256 y)
public pure returns (uint256, uint256, uint256)
{
return (x.max(y), x.min(y), x.average(y));
}
}
// Internal libraries are like helper functions that don't add
// runtime call overhead. Good for: math, validation, conversions.Librerías externas (desplegadas)
Las funciones external de una librería se despliegan como un contrato separado y se llaman vía DELEGATECALL — corren en el contexto del llamador (storage, msg.sender). Útil para código utilitario compartido por muchos contratos (ahorra gas de despliegue total). Compromisos: sobrecarga de DELEGATECALL por llamada (~1400 de gas) y la librería debe desplegarse y enlazarse su dirección en tiempo de compilación. La mayoría de librerías usan funciones internal; external es raro.
library BigMath {
// external functions => library is DEPLOYED as a separate contract
// Calls use DELEGATECALL — runs in caller's context (storage/msg)
function complexOperation(uint256[] storage arr)
external view returns (uint256 sum)
{
for (uint256 i = 0; i < arr.length; i++) {
sum += arr[i];
}
}
}
contract UsesExternal {
uint256[] public data;
using BigMath for uint256[];
function total() public view returns (uint256) {
return data.complexOperation(); // DELEGATECALL to BigMath
}
}
// External library trade-offs:
// + Shared bytecode: many contracts use one deployed library (saves deployment gas)
// + Caller bytecode stays small
// - DELEGATECALL overhead per call (~1400 gas)
// - Library must be deployed first and its address linked at compile time
//
// Most libraries are internal; external is rare (e.g., Create2BeaconProxy).Ejemplo SafeMath (pre-0.8.0)
SafeMath era la librería canónica de comprobación de overflow antes de 0.8.0. Desde 0.8.0, la aritmética revierte automáticamente en overflow, haciendo innecesario SafeMath para matemáticas básicas. Sigue siendo útil para: (1) leer código heredado, (2) envolver explícitamente operaciones unchecked, (3) el patrón de 'postcondición con require' como ejemplo didáctico. La versión de OpenZeppelin sigue siendo muy referenciada.
// Before 0.8.0, arithmetic did NOT auto-check overflow.
// SafeMath was essential. Now it's mostly historical,
// but the pattern is instructive and still useful for
// explicit intent.
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage)
internal pure returns (uint256)
{
require(b <= a, errorMessage);
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage)
internal pure returns (uint256)
{
require(b > 0, errorMessage);
return a / b;
}
}Transferencias de Ether
Payable y msg.value
Las funciones payable aceptan Ether vía msg.value (en wei). El Ether se añade automáticamente al balance del contrato — no necesitas llevar la cuenta manualmente salvo que quieras contabilidad por usuario. Valida msg.value para pagos exactos o mínimos. Reembolsa siempre el Ether sobrante para evitar bloquearlo en el contrato. 1 ether = 10^18 wei.
contract PayableContract {
address payable public owner;
constructor() {
owner = payable(msg.sender);
}
// payable = function accepts Ether
function deposit() public payable {
// msg.value = wei sent with this call
// Ether auto-added to address(this).balance
// No need to update a balance variable here
}
function getBalance() public view returns (uint256) {
return address(this).balance;
}
// Specify required payment
function buyItem() public payable {
require(msg.value == 1 ether, "must pay 1 ether");
// process purchase
}
// Send excess back
function refundExcess(uint256 price) public payable {
uint256 excess = msg.value - price;
if (excess > 0) {
(bool ok, ) = msg.sender.call{value: excess}("");
require(ok, "refund failed");
}
}
}Transfer
address.transfer(amount) envía Ether y revierte ante fallo. Reenvía un stipend fijo de 2300 de gas, que históricamente prevenía la reentrancy pero hoy se considera frágil (los costes de gas cambiaron en Istanbul 2019). Guía moderna: usa transfer solo al enviar a una dirección confiable (como el owner). Para destinatarios arbitrarios, usa .call{value:} con guards de reentrancy explícitos, ya que el stipend de 2300 puede ser insuficiente para lógica receive/fallback legítima.
contract TransferExample {
address payable public recipient = payable(0xAbC...);
function sendViaTransfer() public payable {
// transfer: throws on failure, forwards 2300 gas stipend
// Simple and safe against reentrancy (limited gas)
recipient.transfer(1 ether);
}
function sendFromContract() public {
// address(this).balance = current contract balance
recipient.transfer(address(this).balance);
}
// Characteristics:
// - Reverts if recipient's receive/fallback uses > 2300 gas
// - 2300 gas stipend: enough for an event log, not a storage write
// - Safer than send (which returns false on failure)
// - But BEWARE: post-Istanbul (2019), some operations cost more,
// breaking contracts that relied on 2300 gas. Prefer .call{}.
}
// transfer is DEPRECATED for pushing to arbitrary addresses.
// Use .call{value:} and handle the return value.Send
address.send(amount) devuelve un booleano (true si tuvo éxito, false si falló) — NO revierte automáticamente. DEBES comprobar el valor de retorno y revertir ante fallo. Como transfer, solo reenvía 2300 de gas. send es propenso a errores (los desarrolladores olvidan comprobar el retorno) y rara vez se usa en código moderno. Prefiere .call{value:} en contratos nuevos.
contract SendExample {
address payable public recipient = payable(0xAbC...);
function sendViaSend() public payable returns (bool) {
// send: returns false on failure (does NOT revert)
// Also forwards 2300 gas stipend like transfer
bool success = recipient.send(1 ether);
require(success, "send failed"); // you MUST check the return value
return success;
}
// Common bug: forgetting to check the return value
function buggy() public payable {
recipient.send(1 ether); // BUG: silently fails
// state already updated => funds lost
}
// Correct: check + revert
function correct() public payable {
bool ok = recipient.send(1 ether);
require(ok, "send failed");
}
}
// send is rarely used in modern code.
// Prefer .call{value:} which gives more control + return data.Call (recomendado)
.call{value: x}(...) es la forma recomendada de enviar Ether desde 0.8.0. Reenvía la totalidad del gas disponible (sujeto a la regla 63/64), así que los destinatarios pueden ejecutar lógica compleja. Devuelve (bool, bytes) — DEBES comprobar el booleano y revertir ante fallo. Como reenvía la totalidad del gas, es vulnerable a reentrancy — combínalo siempre con un modificador nonReentrant o sigue checks-effects-interactions. Usa call para destinatarios arbitrarios; transfer solo para direcciones confiables.
contract CallExample {
address payable public recipient = payable(0xAbC...);
function sendViaCall() public payable returns (bool) {
// .call returns (bool success, bytes memory data)
// Forwards ALL gas (63/64 rule), so recipient can do more
(bool success, ) = recipient.call{value: 1 ether}("");
require(success, "call failed");
return success;
}
// With calldata (call a function while sending Ether)
function callWithFunction(address token, address to, uint256 amount)
public returns (bool, bytes memory)
{
(bool ok, bytes memory data) = token.call{value: 0}(
abi.encodeWithSignature("transfer(address,uint256)", to, amount)
);
return (ok, data);
}
// Forward gas explicitly
function withGas() public returns (bool) {
(bool ok, ) = recipient.call{gas: 100000, value: 0}("");
return ok;
}
// IMPORTANT: call forwards all gas, so a malicious recipient
// can re-enter your contract. Always use a reentrancy guard.
}Comprobación de balances
address.balance devuelve el balance en wei de cualquier dirección (incluida address(this) para el propio contrato). Es una vista, gratuita de llamar fuera de la cadena. AVISO: el balance puede inflarse por cualquiera vía selfdestruct (Ether forzado), así que nunca dependas de igualdades exactas de balance para la lógica — usa >= o mantén tus propias variables de contabilidad. Comprueba siempre que la suma de depósitos coincide con el balance del contrato como invariante.
contract BalanceCheck {
mapping(address => uint256) public deposits;
function deposit() public payable {
deposits[msg.sender] += msg.value;
}
function contractBalance() public view returns (uint256) {
// Balance of THIS contract
return address(this).balance;
}
function userBalance(address user) public view returns (uint256) {
// Balance of any address (in wei)
return user.balance;
}
function myBalance() public view returns (uint256) {
return msg.sender.balance;
}
// Verify accounting invariant
function verify() public view returns (bool) {
// Sum of deposits should equal contract balance
// (in a real contract, this would be expensive to compute)
return address(this).balance >= deposits[msg.sender];
}
// CAUTION: address.balance can be manipulated by an attacker
// who forces Ether via selfdestruct. Never use balance == X
// as a strict equality check for logic — use >= or tracking vars.
function dangerous() public view returns (bool) {
// BAD: an attacker can selfdestruct-ETH into the contract
// and break this exact check
return address(this).balance == 1 ether;
}
}Optimización de gas
Storage vs Memory
Las lecturas de storage (SLOAD) cuestan ~2100 de gas en frío / 100 en caliente por acceso. Las lecturas de memoria (MLOAD) cuestan solo 3 de gas. Cuando una función lee una variable de estado varias veces (especialmente en un bucle), guárdala primero en una variable de memoria. El primer SLOAD es caro; las siguientes lecturas de memoria son casi gratis. Esta es una de las optimizaciones más fáciles y de mayor impacto.
contract StorageVsMemory {
uint256 public stateVar; // storage slot 0
function expensive(uint256 x) public view returns (uint256) {
// Each access to stateVar = SLOAD (~2100 gas cold, 100 warm)
uint256 sum = 0;
for (uint256 i = 0; i < x; i++) {
sum += stateVar; // SLOAD every iteration
}
return sum;
}
function cheap(uint256 x) public view returns (uint256) {
// Cache to memory once: MLOAD costs 3 gas
uint256 cached = stateVar; // 1 SLOAD
uint256 sum = 0;
for (uint256 i = 0; i < x; i++) {
sum += cached; // MLOAD (cheap)
}
return sum;
}
// Rules of thumb:
// - storage: persistent, ~2100 gas per cold SLOAD, ~5000-20000 per SSTORE
// - memory: temporary, ~3 gas per access, free to create
// - calldata: read-only, free (passed in)
// Always cache state variables used multiple times in a function.
}Empaquetado de variables
Solidity empaqueta variables de estado consecutivas en slots de storage de 32 bytes. Para ahorrar gas, agrupa tipos pequeños (uint8, uint64, address) juntos para que compartan un slot. Reordena los campos del struct para que los pequeños se empaqueten apretados. Cada slot ahorrado = ~20k de gas en el primer acceso. Ojo: las entradas de mapping y de array dinámico siempre empiezan un slot nuevo y no se pueden empaquetar.
contract Packing {
// BAD: each takes a full 32-byte slot
// 3 slots = 60k gas for cold SLOADs
struct Bad {
uint64 time;
address from; // 20 bytes
uint64 amount;
}
// GOOD: pack small types together into 32 bytes
// 1 slot = 20k gas (one SLOAD)
struct Good {
uint64 time;
uint64 amount;
address from; // 20 bytes => total 8+8+20 = 36... still 2 slots
}
// Pack carefully: declare small types together
struct Packed {
uint32 a; // 4
uint32 b; // 4
uint32 c; // 4
uint32 d; // 4 => 16 bytes => can fit address (20)? No, 16+20=36 > 32
address e; // => 2 slots
}
struct Tight {
uint128 a; // 16
uint128 b; // 16 => 1 slot (32 bytes)
}
// Order matters: variables are packed in declaration order.
// A variable that doesn't fit starts a new slot.
// Mapping/dynamic-array always start a new slot.Bloques unchecked
unchecked { ... } desactiva las comprobaciones de overflow/underflow dentro del bloque, ahorrando gas (~50-80 por operación). Es seguro cuando ya validaste los límites (p. ej., tras require(a >= b), a - b no puede hacer underflow). El caso de uso seguro clásico son los contadores de bucle (i++ en un for nunca desbordará 2^256). No uses unchecked a ciegas — un overflow silencioso es un riesgo de seguridad.
contract UncheckedBlock {
function loopWith(uint256 n) public pure returns (uint256 sum) {
// 0.8+ checks overflow on every operation (extra gas)
for (uint256 i = 0; i < n; i++) {
sum += i;
}
}
function loopUnchecked(uint256 n) public pure returns (uint256 sum) {
unchecked {
for (uint256 i = 0; i < n; i++) {
sum += i; // skips overflow check (cheaper)
}
}
}
// Safe to use when overflow is impossible:
// - Loop counters that won't reach 2^256
// - Differences of values you've already bounds-checked
function safeSub(uint256 a, uint256 b) public pure returns (uint256) {
require(a >= b, "underflow"); // checked here
unchecked { return a - b; } // safe: can't underflow now
}
// NEVER use unchecked when overflow/underflow is possible
// unless you intentionally want wraparound (rare).
}Custom errors vs require
Los custom errors (0.8.4+) son más baratos que require(_, "msg") porque el string del mensaje se guarda en el bytecode (costando gas por byte) y se re-codifica en cada revert. Un custom error es solo un selector de 4 bytes más argumentos con ABI. Para mensajes de error no triviales, los custom errors ahorran miles de gas por llamada Y reducen el tamaño del bytecode de despliegue. Prefiere siempre custom errors en código nuevo.
contract Errors {
// BAD: string messages bloat bytecode + cost gas per call
function oldStyle(uint256 x) public pure {
require(x > 0, "value must be greater than zero");
require(x < 100, "value must be less than one hundred");
}
// GOOD: custom errors are cheap and structured
error InvalidValue(uint256 given, uint256 min, uint256 max);
function newStyle(uint256 x) public pure {
if (x == 0 || x >= 100) {
revert InvalidValue(x, 1, 99);
}
}
// Gas comparison (approximate):
// require(_, "msg") ~ 400 + 50 per byte of message
// revert CustomError() ~ 400 + small selector cost
//
// For long messages, custom errors save thousands of gas
// and reduce deployed bytecode size.
// Define errors at file level to reuse across contracts
error Unauthorized(address caller);
function guarded() public {
if (msg.sender != address(0)) revert Unauthorized(msg.sender);
}
}Cachear variables de estado en bucles
Cachea la longitud del array en una variable local antes del bucle (ahorra un SLOAD por iteración). Si el array es pequeño, cópialo a memoria una vez (un SLOAD por elemento, luego MLOADs baratos en el bucle). Los acumuladores deben ser siempre variables locales (memoria). Para campos de structs de storage, cachea el struct entero en memoria si se usa varias veces.
contract Cache {
uint256[] public data;
mapping(address => uint256) public balances;
address[] public users;
// BAD: reads mapping in every iteration (SLOAD each time)
function sumBad() public view returns (uint256) {
uint256 total = 0;
for (uint256 i = 0; i < users.length; i++) {
total += balances[users[i]]; // SLOAD each iteration
}
return total;
}
// GOOD: cache length, use local var for accumulator
function sumBetter() public view returns (uint256) {
uint256 total = 0;
uint256 len = users.length; // cache length
for (uint256 i = 0; i < len; i++) {
address u = users[i]; // SLOAD once
total += balances[u]; // still SLOAD, but unavoidable
}
return total;
}
// BEST: cache array to memory (if small enough)
function sumMemory() public view returns (uint256) {
address[] memory memUsers = users; // copy to memory once
uint256 total = 0;
uint256 len = memUsers.length;
for (uint256 i = 0; i < len; i++) {
total += balances[memUsers[i]]; // MLOAD each iteration
}
return total;
}
}Cortocircuito y optimización de bucles
Evaluación de cortocircuito: pon las comprobaciones baratas primero en && y ||. Usa ++i (prefijo) en vez de i++ (algo más barato — sin temporal). Envuelve los contadores de bucle en unchecked (i no puede desbordar 2^256 de forma realista). Sal del bucle antes cuando encuentres lo que buscas. Evita operaciones caras (llamadas externas, escrituras de storage) dentro de bucles — hazlas por lotes fuera.
contract ShortCircuit {
// && and || short-circuit: right side only evaluated if needed
function cheap(address a, address b) public view returns (bool) {
// Put the cheap check first
return (a == b || expensiveCheck(a));
}
function expensiveCheck(address) internal view returns (bool) {
// imagine a heavy computation
return true;
}
// Loop optimization: prefer prefix increment
function good() public pure returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 10; ++i) { // ++i slightly cheaper than i++
sum += i;
}
return sum;
}
// Use unchecked for loop counters (always safe)
function best() public pure returns (uint256) {
uint256 sum = 0;
uint256 i = 0;
unchecked {
while (i < 10) {
sum += i;
++i;
}
}
return sum;
}
// Avoid unnecessary work: precompute, batch, early-exit
function find(uint256[] memory arr, uint256 target)
public pure returns (int256)
{
for (uint256 i = 0; i < arr.length; ++i) {
if (arr[i] == target) return int256(i); // early exit
}
return -1;
}
}Unidades de tiempo y propiedades de bloque
block.timestamp
block.timestamp (alias 'now' antes de 0.7.0) es el timestamp Unix en segundos del bloque actual. Lo fija el minero/validador y puede manipularse ~15 segundos — NUNCA lo uses para aleatoriedad ni tiempos precisos. Va bien para duraciones gruesas (>=1 minuto) y para ordenar. Usos habituales: time-locks, calendarios de vesting, plazos límite. Usa block.number para garantías más estrictas.
contract Time {
uint256 public startTime;
uint256 public constant DURATION = 1 days;
constructor() {
startTime = block.timestamp; // uint256 in 0.8+
}
function isExpired() public view returns (bool) {
return block.timestamp >= startTime + DURATION;
}
function elapsed() public view returns (uint256) {
return block.timestamp - startTime;
}
// WARNING: block.timestamp is set by the miner/validator.
// They can manipulate it by ~15 seconds. NEVER use it for:
// - Randomness (keccak256(block.timestamp) is exploitable)
// - Precise timing (use block.number as a fallback)
// It's fine for:
// - Coarse durations (>= 1 minute)
// - Deadlines that tolerate 15s drift
// - Order of events (timestamp comparison)
// Time locks: require(block.timestamp > unlockTime)
function lock() public payable returns (uint256) {
return block.timestamp + 1 weeks;
}
}block.number y blockhash
block.number es la altura del bloque actual. blockhash(n) devuelve el hash del bloque n, pero SOLO de los últimos 256 bloques (los más antiguos devuelven 0) y no del bloque actual (devuelve 0). Tanto block.number como blockhash pueden ser influidos por mineros, así que no los uses para aleatoriedad de alto riesgo. Para aleatoriedad real, usa Chainlink VRF o un esquema commit-reveal con entropía aportada por el usuario.
contract BlockInfo {
function currentBlock() public view returns (uint256) {
return block.number;
}
function prevHash(uint256 n) public view returns (bytes32) {
// Only the last 256 blocks' hashes are available
require(n > 0 && n <= 256, "out of range");
return blockhash(block.number - n);
}
// blockhash returns 0 for current block, future blocks, or >256 old
function currentHash() public view returns (bytes32) {
return blockhash(block.number); // returns 0!
}
// Use case: weak randomness (still exploitable by miners)
function pseudoRandom() public view returns (uint256) {
// A miner CAN see this and choose to withhold blocks
// to manipulate the result. Don't use for high value.
return uint256(keccak256(abi.encodePacked(
blockhash(block.number - 1),
block.timestamp,
msg.sender
)));
}
// For real randomness, use Chainlink VRF or a commit-reveal scheme.
}Unidades de tiempo (seconds/minutes/hours/days/weeks)
Los sufijos de unidad de tiempo (seconds, minutes, hours, days, weeks) se convierten a segundos como uint256. 'years' se eliminó en 0.5.0 por la ambigüedad de los años bisiestos. Las unidades de Ether (wei, gwei, ether) son aparte: 1 ether = 10^18 wei, 1 gwei = 10^9 wei. Guarda siempre los importes en wei y usa los sufijos para legibilidad en los cálculos.
contract TimeUnits {
// Suffixes convert to seconds (uint256):
uint256 public oneSecond = 1 seconds; // 1
uint256 public oneMinute = 1 minutes; // 60
uint256 public oneHour = 1 hours; // 3600
uint256 public oneDay = 1 days; // 86400
uint256 public oneWeek = 1 weeks; // 604800
// 'years' was removed in 0.5.0 (leap years made it ambiguous)
function deadline() public view returns (uint256) {
return block.timestamp + 7 days;
}
function hourly() public pure returns (uint256) {
return 24 hours; // 86400
}
// Ether units (different from time units!):
uint256 public oneWei = 1 wei; // 1
uint256 public oneGwei = 1 gwei; // 10^9
uint256 public oneEther = 1 ether; // 10^18
function fromEther(uint256 e) public pure returns (uint256) {
return e * 1 ether; // convert to wei
}
function toEther(uint256 weiAmount) public pure returns (uint256) {
return weiAmount / 1 ether;
}
}Gas y gasleft()
gasleft() devuelve el gas restante en el punto de la llamada (sustituye al obsoleto msg.gas). Es útil para medir cuánto gas consume un fragmento de código. La regla de 63/64: las llamadas externas reenvían 63/64 del gas restante, reservando 1/64 para que el llamador pueda gestionar el retorno. No dependas de valores de gas exactos entre hard forks — los costes de los opcodes cambian.
contract GasTrack {
function checkGas() public returns (uint256, uint256) {
uint256 start = gasleft(); // gas remaining at this point
// ...do some work...
uint256 sum = 0;
for (uint256 i = 0; i < 100; i++) {
sum += i;
}
uint256 end = gasleft();
return (start, start - end); // (initial, used)
}
// 63/64th rule: when an external call is made, only 63/64 of
// remaining gas is forwarded; 1/64 is reserved so the caller
// can finish processing (e.g., revert handling).
function forwardGas(address target) public returns (bool, uint256) {
uint256 before = gasleft();
(bool ok, ) = target.call{gas: 100000}("");
uint256 after = gasleft();
return (ok, before - after);
}
// gasleft() replaces the deprecated msg.gas.
// It's a view, so it can be used in modifiers to enforce budgets.
modifier usesLessThan(uint256 maxGas) {
uint256 start = gasleft();
_;
require(start - gasleft() <= maxGas, "too much gas");
}
}Chain ID y detección de red
block.chainid devuelve el ID de la cadena actual. Es esencial para la protección contra replay (EIP-155) y para las firmas de datos tipados EIP-712 (el domain separator incluye chainId). Cachea chainId como immutable en el constructor por eficiencia de gas, pero con EIP-712 puede que necesites recalcularlo si el contrato se bifurca a una cadena nueva. Incluye siempre chainId en cualquier hash que firme autorizaciones.
contract Chain {
function getChainId() public view returns (uint256) {
return block.chainid; // current chain ID
}
// Common chain IDs:
// 1 = Ethereum mainnet
// 5 = Goerli testnet (deprecated)
// 11155111 = Sepolia testnet
// 137 = Polygon
// 42161 = Arbitrum One
// 10 = Optimism
// 56 = BNB Smart Chain
modifier onlyMainnet() {
require(block.chainid == 1, "only mainnet");
_;
}
// Prevent cross-chain replay attacks by including chainId in hashes
function domainSeparator() public view returns (bytes32) {
return keccak256(abi.encode(
keccak256("EIP712Domain(...)"),
block.chainid,
address(this)
));
}
// For multi-chain deployments, store chainId at construction
uint256 public immutable chainId;
constructor() {
chainId = block.chainid;
}
// NOTE: chainId can change during a fork (rare). For EIP-712
// signatures, cache it but allow re-initialization on mismatch.
}Modificadores de visibilidad
Public
Las funciones public pueden llamarse desde cualquier lugar: externamente (por usuarios u otros contratos), internamente (desde el propio contrato) y desde contratos derivados. Las variables de estado public obtienen automáticamente una función getter. Public es lo más permisivo, pero añade bytecode (la función debe soportar convenciones de llamada internas y externas). Cuando una función public se llama internamente vía 'this.f()', se convierte en una llamada externa cara.
contract Public {
uint256 public counter; // public state var => auto getter
// public function: callable from anywhere
// - externally (via transaction or call)
// - internally (from this contract)
// - from derived contracts
function increment() public {
counter += 1;
}
function caller() public {
increment(); // internal call (cheap)
this.increment(); // external call (expensive, creates a msg)
}
// Public is the most permissive. Auto-getters for state vars
// are 'external' view functions generated by the compiler.
//
// Cost: public functions are part of the ABI and add bytecode.
// Internal calls to public functions skip the external wrapper.
}External
Las funciones external SOLO pueden llamarse desde fuera del contrato — no internamente. Son ligeramente más baratas que public porque leen directamente de calldata (sin copia a memoria). Usa external para funciones que deben ser solo puntos de entrada. Si necesitas llamar a una función tanto interna como externamente, hazla public O divídela en un envoltorio external + implementación internal.
contract External {
// external: ONLY callable from outside the contract
// CANNOT be called internally (this.f() works but is expensive)
function doWork(uint256 x) external pure returns (uint256) {
return x * 2;
}
function caller() public pure returns (uint256) {
// doWork(5); // COMPILER ERROR: external not callable internally
return this.doWork(5); // works but creates an external call (expensive)
}
// external with calldata params is cheapest for inputs
function process(string calldata input)
external
pure
returns (bytes32)
{
return keccak256(bytes(input));
}
// Use external when:
// - The function is only meant to be called by users/other contracts
// - You want to read calldata directly (cheaper than memory)
//
// State variables CANNOT be external.
}Internal
Las funciones internal pueden llamarse desde el contrato y desde cualquier contrato derivado (subclases). Es el valor por defecto de las variables de estado. internal es más barato que public porque no necesita el envoltorio de llamada externa. Usa internal para funciones auxiliares y lógica central que las subclases deban poder llamar o sobrescribir. La convención es prefijar las funciones internal con guion bajo (_helper).
contract Internal {
uint256 internal secret; // internal state var (default)
// internal: callable from this contract AND derived contracts
function _helper(uint256 x) internal pure returns (uint256) {
return x + 1;
}
function caller() public pure returns (uint256) {
return _helper(5); // internal call works
}
// Cannot be called externally:
// contract Other { function f() public { Internal._helper(5); } } // ERROR
}
contract Child is Internal {
function useParent() public pure returns (uint256) {
return _helper(10); // OK: child can call internal
}
function readSecret() public view returns (uint256) {
return secret; // OK: child can read internal
}
}
// internal is the DEFAULT for state variables.
// Use internal when:
// - You want subclasses to use/override it
// - You don't need external access
// It's cheaper than public (no external wrapper).Private
Las funciones y variables de estado private solo son accesibles dentro del contrato que las define — ni siquiera por subclases. Es la visibilidad más restrictiva. CRÍTICO: 'private' NO significa secreto — la totalidad de los datos de la blockchain son legibles públicamente vía eth_getStorageAt y análisis de bytecode. Usa private solo para evitar que otros contratos llamen/hereden; usa cifrado/hashing para confidencialidad real.
contract Private {
uint256 private counter; // private state var
// private: ONLY callable from THIS contract (not even subclasses)
function _secret(uint256 x) private pure returns (uint256) {
return x * 42;
}
function caller() public pure returns (uint256) {
return _secret(5); // OK: same contract
}
}
contract Sub is Private {
// function useIt() public pure returns (uint256) {
// return _secret(5); // COMPILER ERROR: not accessible
// }
// function readCounter() public view returns (uint256) {
// return counter; // COMPILER ERROR: not accessible
// }
}
// IMPORTANT: 'private' does NOT mean hidden on-chain.
// All storage and bytecode are publicly readable via RPC.
// 'private' only means 'not part of the contract's ABI'
// and 'not callable/inheritable by other contracts'.
// For real confidentiality, use encryption or zero-knowledge proofs.Buenas prácticas de visibilidad
Buenas prácticas: usa la visibilidad más restrictiva que funcione (private > internal > external > public). Evita variables de estado public salvo que quieras el auto-getter — los getters explícitos te permiten añadir validación después. Usa external+calldata para los puntos de entrada. Prefija los helpers internal/private con guion bajo. Cada función public/external añade bytecode; minimizar el ABI reduce el gas de despliegue y de llamada.
contract Best {
// 1. Default to the MOST restrictive visibility that works.
// Order: private < internal < external < public
// 2. State variables: NEVER public unless you want a free getter.
// Prefer private/internal + explicit getter functions,
// so you can add validation/logic later.
uint256 private _balance;
function balance() public view returns (uint256) {
return _balance;
}
// 3. External functions: use 'external' + 'calldata' for entry points
function buy(uint256[] calldata ids) external payable {
for (uint256 i = 0; i < ids.length; i++) {
_buyOne(ids[i]);
}
}
// 4. Internal helper: prefix with underscore convention
function _buyOne(uint256 id) internal {
// ...
}
// 5. Private for truly internal-only logic
function _computeFee(uint256 amount) private pure returns (uint256) {
return amount / 100;
}
// 6. Avoid public functions that are never called externally
// (wastes bytecode). Make them internal.
}
// Summary: visibility is part of the contract's API design.
// Smaller ABI = less bytecode = lower deployment + call gas.Interacción entre contratos
Llamar a otros contratos
Para llamar a otro contrato, convierte su dirección a un tipo de interfaz: IToken(addr).method(). Las llamadas view son gratis fuera de la cadena pero cuestan gas desde una transacción. Comprueba siempre los valores de retorno de las llamadas que cambian estado (token.transfer devuelve bool). Convertir una dirección a una interfaz NO verifica que el contrato la implemente de verdad — si la función no existe, la llamada revierte.
interface IToken {
function balanceOf(address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
}
contract Caller {
IToken public token;
address public owner;
constructor(address _token) {
token = IToken(_token);
owner = msg.sender;
}
// Call a view function on another contract
function getBalance(address who) public view returns (uint256) {
return token.balanceOf(who); // external call
}
// Call a state-changing function
function sendTokens(address to, uint256 amount)
public returns (bool)
{
require(msg.sender == owner, "not owner");
bool ok = token.transfer(to, amount);
require(ok, "transfer failed");
return true;
}
// Cast any address to an interface (no validation!)
function checkAny(address maybeToken)
public view returns (uint256)
{
return IToken(maybeToken).balanceOf(address(this));
}
}Llamadas basadas en interfaces
Usa interfaces para interactuar con cualquier contrato cuyo ABI conozcas, sin necesitar su código fuente. Esto desacopla a los llamadores de las implementaciones y funciona con cualquier token/protocolo que siga un estándar (ERC20, ERC721, feeds de Chainlink). Las interfaces mantienen tu bytecode pequeño (sin lógica heredada) y te permiten escribir código genérico (un wallet que funciona con cualquier ERC20). Prefiere siempre interfaces sobre contratos concretos para llamadas externas.
interface IERC20 {
function name() external view returns (string memory);
function balanceOf(address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
}
contract Wallet {
IERC20 public immutable token;
address public owner;
constructor(address _token) {
token = IERC20(_token);
owner = msg.sender;
}
function tokenBalance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function withdraw(uint256 amount) public {
require(msg.sender == owner, "not owner");
token.transfer(owner, amount);
}
function tokenName() public view returns (string memory) {
return token.name();
}
}
// Why use interfaces?
// - Decouple: Wallet doesn't need to know token implementation
// - Reusability: works with ANY ERC20 (USDC, DAI, WETH, ...)
// - Smaller bytecode: don't inherit the token's code
// - Standardization: IERC20 is a documented ABILlamada de bajo nivel (call)
address.call(payload) es la llamada de nivel más bajo, devuelve (bool, bytes). Úsala cuando no tienes una interfaz, quieres reenviar calldata arbitrario o necesitas control fino (gas, value). Construye el calldata con abi.encodeWithSignature/Selector/Call. CRÍTICO: 'ok' es false solo ante fallos del EVM (revert, out-of-gas), no ante fallos lógicos — decodifica 'data' para inspeccionar los motivos del revert o los custom errors.
contract LowLevel {
// call: lowest-level call, returns (bool, bytes)
function callFn(address target, bytes memory payload)
public returns (bool, bytes memory)
{
(bool ok, bytes memory data) = target.call(payload);
require(ok, "call failed");
return (ok, data);
}
// With Ether
function callWithEth(address target, bytes memory payload)
public payable returns (bool, bytes memory)
{
(bool ok, bytes memory data) = target.call{value: msg.value}(payload);
return (ok, data);
}
// With gas limit
function callWithGas(address target, bytes memory payload, uint256 gas)
public returns (bool, bytes memory)
{
return target.call{gas: gas}(payload);
}
// Helpers to build calldata:
// abi.encodeWithSignature("transfer(address,uint256)", to, amount)
// abi.encodeWithSelector(bytes4(selector), to, amount)
// abi.encodeWithCall(IERC20.transfer.selector, to, amount)
// WARNING: low-level call returns true even if the called function
// reverts internally — you only get false on EVM-level failure.
// Decode 'data' to inspect custom errors or return values.
function safeCall(address target) public returns (uint256) {
(bool ok, bytes memory data) = target.call(
abi.encodeWithSignature("getValue()")
);
require(ok, "call reverted");
return abi.decode(data, (uint256));
}
}Delegatecall
delegatecall ejecuta el código del destino en el contexto de storage del LLAMADOR — así que los cambios de estado afectan al llamador, no al destino. msg.sender y msg.value se conservan. Es la base de los proxies actualizables (EIP-1967, UUPS) y del patrón Diamond (EIP-2535). CRÍTICO: el layout de storage debe coincidir entre llamador y destino, o el estado se corrompe. Usa siempre un layout de storage compartido o el patrón AppStorage.
contract Delegate {
// delegatecall: executes target's code in CALLER's context
// - msg.sender is the ORIGINAL caller (preserved)
// - msg.value is preserved
// - Storage reads/writes affect the CALLER, not the target
// - address(this) is the CALLER
uint256 public num;
address public sender;
function delegateSet(address target, uint256 value) public {
// target's setNum() runs in THIS contract's storage
(bool ok, ) = target.delegatecall(
abi.encodeWithSignature("setNum(uint256)", value)
);
require(ok, "delegatecall failed");
}
}
contract Target {
// MUST have the same storage layout as Delegate for sane behavior!
uint256 public num;
address public sender;
function setNum(uint256 value) public {
num = value;
sender = msg.sender; // this is the ORIGINAL caller, not Delegate
}
}
// Use cases:
// - Proxy patterns (EIP-1967, UUPS, Transparent): upgradeable logic
// - Diamond pattern (EIP-2535): modular facets
//
// DANGER: storage layout mismatch => corrupted state.
// Both contracts MUST declare variables in the same order/types.
// Use a shared storage contract or app storage pattern.Staticcall
staticcall ejecuta el código del destino pero revierte si ocurre cualquier modificación de estado — es la forma segura de leer de contratos no confiables. El compilador usa staticcall automáticamente cuando llamas a una función view/pure vía una interfaz. Usa staticcall directamente cuando quieras garantizar una llamada de solo lectura a un contrato que podría mentir sobre ser view. Devuelve (bool, bytes) como call.
contract Static {
// staticcall: like call, but REVERTS if the target modifies state.
// Used to safely READ from untrusted contracts.
function safeRead(address target, bytes memory payload)
public view returns (bytes memory)
{
(bool ok, bytes memory data) = target.staticcall(payload);
require(ok, "staticcall reverted");
return data;
}
function getBalance(address token, address who)
public view returns (uint256)
{
(bool ok, bytes memory data) = token.staticcall(
abi.encodeWithSignature("balanceOf(address)", who)
);
require(ok, "balanceOf failed");
return abi.decode(data, (uint256));
}
// Use cases:
// - Read from untrusted contracts without risk of state changes
// - Verify a contract behaves as a view function
// - Compose view-only queries across multiple contracts
// Distinguish from call():
// - call: allows state changes (target can write)
// - staticcall: forbids state changes (reverts if target writes)
// view/pure functions are called via staticcall automatically
// by the compiler when you call them normally.
function normalCall(IToken t, address who) public view returns (uint256) {
return t.balanceOf(who); // compiler emits staticcall
}
}
interface IToken { function balanceOf(address) external view returns (uint256); }Patrones de seguridad
Reentrancy guard
El reentrancy guard es un mutex que impide que una función se reentre mientras aún se ejecuta. Fija un flag antes del cuerpo y retíralo después. Previene el ataque clásico donde el receive/fallback de un contrato malicioso vuelve a llamar a withdraw() antes de que el balance se ponga a cero (el patrón del hack de The DAO). Aplica nonReentrant a cualquier función que haga una llamada externa tras un cambio de estado — incluso si también sigues checks-effects-interactions (defensa en profundidad).
contract ReentrancyGuard {
// Classic mutex pattern using a storage flag
uint256 private _status = 1; // 1 = NOT_ENTERED, 2 = ENTERED
modifier nonReentrant() {
require(_status == 1, "REENTRANT");
_status = 2;
_;
_status = 1;
}
mapping(address => uint256) public balances;
function withdraw() public nonReentrant {
uint256 amount = balances[msg.sender];
require(amount > 0, "no balance");
// CRITICAL: update state BEFORE the external call
balances[msg.sender] = 0;
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "send failed");
}
// Why needed: if we sent Ether FIRST, the attacker's receive()
// could call withdraw() again before balances was zeroed,
// draining the contract. This is the DAO hack pattern.
//
// Even with checks-effects-interactions, the guard is defense-in-depth.
// Apply nonReentrant to ANY function that:
// - Sends Ether to msg.sender
// - Calls an external contract
// - Then continues executing
}Checks-Effects-Interactions
Checks-Effects-Interactions (CEI) es el patrón de seguridad más importante: (1) ejecuta todas las comprobaciones require/validaciones, (2) actualiza todas las variables de estado, (3) ENTONCES haz las llamadas externas. Si una llamada externa reentra en tu contrato, el estado ya está actualizado, así que el atacante no puede gastar doble. CEI por sí solo previene la mayoría de bugs de reentrancy; combínalo con un modificador nonReentrant como defensa en profundidad en funciones críticas.
contract CEI {
mapping(address => uint256) public balances;
// BAD: interaction BEFORE effect => reentrancy vulnerability
function vulnerable() public {
uint256 amount = balances[msg.sender];
(bool ok, ) = msg.sender.call{value: amount}(""); // INTERACTION
require(ok);
balances[msg.sender] = 0; // EFFECT (too late!)
// Attacker's receive() re-called this; balances still has funds.
}
// GOOD: checks, then effects, then interactions
function safe() public {
// 1. CHECKS: validate conditions
uint256 amount = balances[msg.sender];
require(amount > 0, "no balance");
// 2. EFFECTS: update state BEFORE external calls
balances[msg.sender] = 0;
// 3. INTERACTIONS: external calls LAST
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "send failed");
// If attacker re-enters, balances[msg.sender] is already 0.
}
// Pattern: order your code as
// require() checks first,
// state updates second,
// external calls last.
// This single rule prevents most reentrancy bugs.
// Pair with nonReentrant for defense-in-depth.
}Pull sobre Push
Pull sobre Push: en lugar de empujar Ether a muchos destinatarios en una transacción (donde un destinatario malo bloquea al resto), abona el balance de cada usuario y deja que retire sus fondos vía withdraw(). Esto aísla los fallos (el receive/fallback defectuoso de un usuario no bloquea a los demás) y reduce el gas por transacción. Úsalo en airdrops, exchanges, pagos de subastas, reembolsos. Combínalo con nonReentrant en withdraw().
contract PullOverPush {
// BAD (push): send Ether to many recipients in one tx
// If any recipient reverts (or is a contract that blocks), the WHOLE tx fails.
mapping(address => uint256) public pendingWithdrawals;
function pushPay(address[] memory recipients) public payable {
uint256 share = msg.value / recipients.length;
for (uint256 i = 0; i < recipients.length; i++) {
// If recipients[i].call fails, the whole loop reverts.
(bool ok, ) = recipients[i].call{value: share}("");
require(ok, "push failed");
}
}
// GOOD (pull): credit each user, let them withdraw individually
function credit(address[] memory recipients) public payable {
uint256 share = msg.value / recipients.length;
for (uint256 i = 0; i < recipients.length; i++) {
pendingWithdrawals[recipients[i]] += share; // just update state
}
}
function withdraw() public {
uint256 amount = pendingWithdrawals[msg.sender];
require(amount > 0, "nothing to withdraw");
pendingWithdrawals[msg.sender] = 0; // effect
(bool ok, ) = msg.sender.call{value: amount}(""); // interaction
require(ok, "withdraw failed");
}
// Pull pattern isolates failures: one user's failed withdrawal
// doesn't block others. Common in: airdrops, exchanges, auctions.
}Patrón Pausable
El patrón Pausable añade una parada de emergencia: un booleano 'paused' que bloquea las funciones críticas vía el modificador whenNotPaused. El owner puede pausar/reanudar. Úsalo como interruptor de emergencia al detectar un bug o ataque — pausa para frenar el daño mientras preparas un arreglo. Suele combinarse con proxies actualizables (pausar y luego desplegar la lógica parcheada). OpenZeppelin ofrece un contrato Pausable probado en batalla que deberías usar en lugar de fabricar el tuyo.
contract Pausable {
bool public paused;
address public owner;
constructor() { owner = msg.sender; }
modifier whenNotPaused() {
require(!paused, "contract is paused");
_;
}
modifier whenPaused() {
require(paused, "contract is not paused");
_;
}
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
}
function unpause() public onlyOwner whenPaused {
paused = false;
}
// Critical functions check whenNotPaused
function deposit() public payable whenNotPaused {
// ...
}
function withdraw(uint256 amount) public whenNotPaused {
// ...
}
// Use case: emergency stop. If a bug is discovered, pause the
// contract to prevent further damage while a fix is prepared.
// Often combined with upgradeable proxies to deploy a patched version.
}
// OpenZeppelin provides Pausable as a reusable contract.Control de acceso
Patrones de control de acceso: (1) Ownable — un único owner con el modificador onlyOwner (simple, centralizado). (2) RBAC — basado en roles con roles bytes32 y el modificador onlyRole (flexible, multiadministrador). (3) Multi-sig o Timelock — para contratos de alto valor, delega en Gnosis Safe u OpenZeppelin Timelock. CRÍTICO: usa siempre msg.sender para autenticar, NUNCA tx.origin (que puede suplantarse mediante contratos intermedios maliciosos). OpenZeppelin ofrece Ownable y AccessControl.
contract AccessControl {
// 1. Simple owner (Ownable pattern)
address public owner;
constructor() { owner = msg.sender; }
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
function setOwner(address newOwner) public onlyOwner {
require(newOwner != address(0), "zero address");
owner = newOwner;
}
// 2. Role-based (RBAC)
mapping(bytes32 => mapping(address => bool)) public roles;
bytes32 public constant ADMIN = keccak256("ADMIN");
bytes32 public constant MINTER = keccak256("MINTER");
modifier onlyRole(bytes32 role) {
require(roles[role][msg.sender], "missing role");
_;
}
function grantRole(bytes32 role, address account)
public onlyRole(ADMIN)
{
roles[role][account] = true;
}
function revokeRole(bytes32 role, address account)
public onlyRole(ADMIN)
{
roles[role][account] = false;
}
function mint(address to, uint256 amount) public onlyRole(MINTER) {
// ...
}
// 3. Multi-sig / time-locked (defer to Gnosis Safe or OpenZeppelin Timelock)
// Always use msg.sender (NOT tx.origin) for authorization.
// tx.origin can be spoofed if a user interacts with a malicious
// intermediate contract.
}Estándar de tokens ERC20
Interfaz ERC20
ERC-20 es el estándar de los tokens fungibles (USDC, DAI, UNI). La interfaz define 6 funciones obligatorias (totalSupply, balanceOf, transfer, allowance, approve, transferFrom) y 2 eventos (Transfer, Approval). Los metadatos opcionales (name, symbol, decimals) se implementan universalmente. Usa siempre el contrato base ERC20 de OpenZeppelin para tokens nuevos — está auditado, maneja casos límite y es reconocido por wallets y DEXs.
interface IERC20 {
// Events
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// Metadata (optional but standard)
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Required functions
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);
}
// ERC-20 is THE standard for fungible tokens (USDC, DAI, UNI, ...).
// Implemented by thousands of tokens; supported by every wallet/Dex.
// Implementing the interface correctly ensures interoperability.
// Use OpenZeppelin's ERC20 base contract — battle-tested and audited.Función transfer
transfer(to, amount) mueve tokens del llamador a 'to'. Comprobaciones estándar: dirección destino distinta de cero, balance suficiente. Actualiza los balances ANTES de emitir el evento Transfer (patrón CEI). El minting se modela como Transfer desde address(0); el burning como Transfer hacia address(0). El campo decimals (normalmente 18) significa que los importes están en unidades atómicas (equivalente a wei); las UIs dividen por 10^decimals para mostrarlos.
contract SimpleToken is IERC20 {
string public name = "Simple Token";
string public symbol = "SIM";
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
constructor(uint256 _initialSupply) {
totalSupply = _initialSupply;
balanceOf[msg.sender] = _initialSupply;
emit Transfer(address(0), msg.sender, _initialSupply);
}
function transfer(address to, uint256 amount) external returns (bool) {
require(to != address(0), "zero address");
require(balanceOf[msg.sender] >= amount, "insufficient");
balanceOf[msg.sender] -= amount;
balanceOf[to] += amount;
emit Transfer(msg.sender, to, amount);
return true;
}
// Note: 0.8+ auto-checks underflow, so we can simplify:
// balanceOf[msg.sender] -= amount;
// If insufficient, it reverts automatically.
// But explicit require gives clearer error messages.
}Approve y allowance
approve(spender, amount) fija cuánto puede transferir 'spender' en tu nombre (vía transferFrom). Habitual en DEXs y staking. AVISO: la condición de carrera de approve — cambiar el allowance de A a B permite a un atacante gastar tanto A como B si hace front-running. Mitiga poniendo primero 0 y luego el valor nuevo, O usa increaseAllowance/decreaseAllowance (OpenZeppelin). El evento Approval debe emitirse en cada cambio.
contract ApprovalExample is IERC20 {
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
// approve: allow 'spender' to spend up to 'amount' on your behalf
function approve(address spender, uint256 amount) external returns (bool) {
require(spender != address(0), "zero address");
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// Common use cases:
// - DEX trading: approve the DEX router to spend your tokens
// - Staking: approve the staking contract
// - Subscriptions: approve a recurring spender
// WARNING: the approve race condition.
// If you change allowance from 100 to 50, an attacker who saw 100
// could spend 100 BEFORE your tx, then spend 50 AFTER = 150 total.
// Mitigation (EIP-20): set to 0 first, then to new value.
// approve(spender, 0); approve(spender, 50);
// Or use increaseAllowance / decreaseAllowance (OpenZeppelin).
function increaseAllowance(address spender, uint256 added)
public returns (bool)
{
uint256 newAllowance = allowance[msg.sender][spender] + added;
allowance[msg.sender][spender] = newAllowance;
emit Approval(msg.sender, spender, newAllowance);
return true;
}
}TransferFrom
transferFrom(from, to, amount) permite a un spender aprobado mover tokens de 'from' a 'to'. El allowance del spender debe ser >= amount; decrementa el allowance como parte del efecto (CEI). Lo usan los routers de DEXs, los contratos de staking y cualquier flujo basado en pull. Peculiaridades de tokens: USDT no decrementa el allowance; algunos tokens revierten en transferencias a dirección cero. Prueba siempre con el token concreto antes de integrarlo.
contract TransferFromExample is IERC20 {
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
// transferFrom: spender moves tokens from 'from' to 'to'
// Requires allowance[from][spender] >= amount
function transferFrom(address from, address to, uint256 amount)
external returns (bool)
{
require(to != address(0), "zero address");
require(balanceOf[from] >= amount, "insufficient balance");
require(allowance[from][msg.sender] >= amount, "insufficient allowance");
// Update allowance FIRST (CEI)
allowance[from][msg.sender] -= amount;
balanceOf[from] -= amount;
balanceOf[to] += amount;
emit Transfer(from, to, amount);
return true;
}
// Used by:
// - DEX routers (user approves router, router calls transferFrom)
// - Staking contracts
// - Any 'pull' workflow where a contract takes tokens from a user
// Note on infinite allowance:
// Some tokens (USDT) do NOT decrement allowance on transferFrom,
// and others set allowance to max uint256 by default. Read the
// specific token's docs before integrating.
}Eventos ERC20
ERC-20 define dos eventos: Transfer (emitido en cada movimiento de tokens, incluido el mint desde address(0) y el burn hacia address(0)) y Approval (emitido en cada cambio de allowance). Estos eventos son la forma en que los dApps e indexadores (The Graph, Dune, Etherscan) rastrean la actividad de los tokens sin consultar el estado directamente. Emítelos siempre — omitir eventos rompe la interoperabilidad con wallets y exchanges que dependen de los logs.
contract ERC20Events {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
uint256 public totalSupply;
function _mint(address to, uint256 amount) internal {
require(to != address(0), "zero address");
totalSupply += amount;
balanceOf[to] += amount;
// Minting = transfer from address(0)
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal {
require(balanceOf[from] >= amount, "insufficient");
balanceOf[from] -= amount;
totalSupply -= amount;
// Burning = transfer to address(0)
emit Transfer(from, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
emit Approval(owner, spender, amount);
}
// Events let dApps and indexers (The Graph, Dune) track:
// - Every transfer (incl. mint/burn)
// - Every approval change
// - Token holdings over time
// Without events, integrating with wallets/DEXs is much harder.
}Despliegue y pruebas
Remix IDE
Remix es la forma más fácil de empezar con Solidity — un IDE en el navegador sin instalación. Incluye compilador, JavaScript VM para pruebas locales, despliegue a testnets, un depurador de transacciones y análisis estático. Genial para aprender y crear prototipos. Para producción, pásate a Hardhat o Foundry para scripting, pruebas automatizadas e integración con CI/CD.
// Remix is a browser-based IDE for Solidity.
// URL: https://remix.ethereum.org
// Features:
// - File explorer, editor, compiler, deployer in one tab
// - Built-in Solidity compiler (no install needed)
// - Deploy to JavaScript VM, local node, or testnet
// - Interact with deployed contracts via GUI
// - Debug transactions step-by-step
// - Static analysis tools (Remix Analyzer)
// Workflow:
// 1. Create a .sol file in the File Explorer
// 2. Compile in the "Solidity Compiler" tab (pick version)
// 3. Deploy in the "Deploy & Run Transactions" tab
// 4. Interact via the deployed contract panel
// Good for: learning, prototyping, quick tests, debugging.
// Not ideal for: production workflows, automated testing, scripting.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Hello {
string public msg = "Hello from Remix";
}Configuración de Hardhat
Hardhat es un entorno de desarrollo basado en JavaScript/TypeScript. Instálalo vía npm y configura redes y compilador en hardhat.config.ts. Ofrece compilación, pruebas (Mocha/Chai), un nodo local (hardhat node), scripts de despliegue y consola. El paquete de plugins Hardhat Toolbox incluye ethers.js, chai, typechain y más. Usa .env para los secretos (claves privadas, URLs RPC).
// Hardhat: JavaScript/TypeScript development environment
// Install: npm install --save-dev hardhat
// Init: npx hardhat init
// hardhat.config.ts
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
const config: HardhatUserConfig = {
solidity: {
version: "0.8.19",
settings: { optimizer: { enabled: true, runs: 200 } },
},
networks: {
hardhat: {}, // built-in local network
sepolia: {
url: `${process.env.ALCHEMY_URL}`,
accounts: [process.env.PRIVATE_KEY ?? ""],
},
},
};
export default config;
// Project layout:
// contracts/ Solidity source files
// scripts/ deployment scripts (JS/TS)
// test/ test files (Chai/Mocha)
// ignition/ Hardhat Ignition modules (declarative deploy)
// Common commands:
// npx hardhat compile
// npx hardhat test
// npx hardhat run scripts/deploy.ts --network sepolia
// npx hardhat node // start local node
// npx hardhat console // interactive REPLPruebas en Hardhat
Las pruebas de Hardhat usan Mocha + Chai + ethers.js. getSigners() devuelve cuentas de prueba con ETH. connect(addr) envía una tx desde una cuenta concreta. Aserciones: igualdad (equal), reverts (revertedWith), eventos (emit + withArgs). TypeChain genera automáticamente tipos de TypeScript a partir de tus ABIs, dándote autocompletado y comprobaciones en compilación. Ejecuta las pruebas con 'npx hardhat test'.
// test/Token.test.ts
import { expect } from "chai";
import { ethers } from "hardhat";
import { Token } from "../typechain-types";
describe("Token", () => {
let token: Token;
let owner: any, addr1: any;
beforeEach(async () => {
[owner, addr1] = await ethers.getSigners();
const Factory = await ethers.getContractFactory("Token");
token = await Factory.deploy(1000);
await token.waitForDeployment();
});
it("assigns initial supply to owner", async () => {
expect(await token.balanceOf(owner.address)).to.equal(1000);
});
it("transfers tokens between accounts", async () => {
await token.transfer(addr1.address, 100);
expect(await token.balanceOf(addr1.address)).to.equal(100);
});
it("reverts on insufficient balance", async () => {
await expect(
token.connect(addr1).transfer(owner.address, 1)
).to.be.revertedWith("insufficient");
});
it("emits Transfer event", async () => {
await expect(token.transfer(addr1.address, 100))
.to.emit(token, "Transfer")
.withArgs(owner.address, addr1.address, 100);
});
});
// Run: npx hardhat test
// TypeChain generates typed contract bindings in typechain-types/.Configuración de Foundry
Foundry (forge) es un toolkit rápido basado en Rust donde las pruebas se escriben en el propio Solidity — sin necesidad de JavaScript/TypeScript. Instálalo vía foundryup. Herramientas clave: forge (build, test, script), cast (CLI para llamadas RPC), anvil (nodo local), chisel (REPL de Solidity). Es más rápido que Hardhat e incluye fuzz testing integrado. Las dependencias son git submodules bajo lib/. La configuración vive en foundry.toml.
// Foundry: Rust-based, fast Solidity dev toolkit
// Install: curl -L https://foundry.paradigm.xyz | bash
// foundryup
// Init: forge init my-project
// Project layout:
// src/ Solidity sources (Default = src/Contract.sol)
// test/ Solidity tests (*.t.sol)
// script/ Deployment scripts (*.s.sol)
// lib/ Dependencies (git submodules, e.g. forge-std, openzeppelin)
// Commands:
// forge build // compile
// forge test // run tests
// forge test -vvv // verbose (shows console logs)
// forge coverage // code coverage
// forge script script/Deploy.s.sol --rpc-url $RPC --broadcast
// Foundry config (foundry.toml):
// [profile.default]
// src = "src"
// out = "out"
// libs = ["lib"]
// solc = "0.8.19"
// optimizer = true
// optimizer_runs = 200
// Why Foundry?
// - Tests are written IN Solidity (no JS/TS context switch)
// - Extremely fast (parallelized, cached)
// - Built-in fuzzing and invariant testing
// - Cast/anvil/chisel CLI tools includedPruebas en Foundry (Solidity)
Las pruebas de Foundry son contratos Solidity que extienden forge-std/Test. Usa assertEq, assertTrue, etc. para las aserciones. Los cheatcodes (vm.*) manipulan el EVM: vm.prank suplanta msg.sender, vm.warp fija el tiempo, vm.deal acuña ETH, vm.expectRevert asegura fallos. Las pruebas fuzz (testFuzz_*) generan automáticamente entradas aleatorias dentro de restricciones (vm.assume). Las pruebas de invariantes (testInvariant_*) ejecutan secuencias aleatorias para encontrar invariantes rotos.
// test/Token.t.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Token.sol";
contract TokenTest is Test {
Token public token;
address owner = address(this);
address user = address(0x1);
function setUp() public {
token = new Token(1000);
}
function testInitialSupply() public view {
assertEq(token.balanceOf(owner), 1000);
}
function testTransfer() public {
token.transfer(user, 100);
assertEq(token.balanceOf(user), 100);
}
function testRevertOnInsufficient() public {
vm.expectRevert("insufficient");
token.transfer(user, 99999);
}
// Fuzz test: 'x' is randomized by the framework
function testFuzzTransfer(uint256 x) public {
vm.assume(x <= 1000);
token.transfer(user, x);
assertEq(token.balanceOf(user), x);
}
// Cheatcodes (vm.*):
// vm.prank(addr) // next call from addr
// vm.startPrank(addr) // all subsequent calls from addr
// vm.warp(timestamp) // set block.timestamp
// vm.roll(blockNum) // set block.number
// vm.deal(addr, 1 ether) // give ETH to addr
// vm.expectRevert(...) // assert next call reverts
// vm.expectEmit(...) // assert next call emits event
}
// Run: forge test -vvvFragmentos de Solidity relacionados
Copy-paste ready code for common tasks.
Fundamentos de Contratos
Definir un contrato básico con estado y funciones.
Funciones y Visibilidad
Visibilidad de funciones, payable y valores de retorno.
Modifier y Control de Acceso
Reutilizar lógica de validación con modifier.
Eventos y Logs
Emitir eventos para listeners off-chain.
Mapping, Struct y Storage Anidado
Agrupar datos con struct, buscar por clave con mapping.
Herencia, Abstract e Interface
Reutilizar lógica con herencia; definir contratos con abstract e interface.
Payable, receive y fallback (Flujos de ETH)
Recibir ETH vía funciones payable y hooks receive/fallback.
Reentrancia y Checks-Effects-Interactions
Endurecer contratos contra el ataque más común a smart contracts.
Was this helpful?