Web3 & DApp Development Fundamentals · Lección

Red local y forking

Entornos de prueba

Lección 4 de 413 pasos

Red local y forking es una lección gratuita de Web3 & DApp Development Fundamentals en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Web3 & DApp Development Fundamentals, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Web3 & DApp Development Fundamentals incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

The Hardhat Network

Hardhat ships with a built-in local Ethereum network designed for development. It runs in-memory, mines blocks instantly, and gives you funded test accounts.

  • No real ETH or gas costs.
  • Deterministic accounts you can reuse.
  • Rich error messages and stack traces.

Starting a Local Node

Run a standalone JSON-RPC server so wallets and front-ends can connect:

npx hardhat node

This prints 20 funded accounts with their private keys and listens on http://127.0.0.1:8545.

npx hardhat node

The localhost Network

To target the running node, define a localhost network in your config:

module.exports = { solidity: "0.8.24", networks: { localhost: { url: "http://127.0.0.1:8545" }, }, };

Then deploy with npx hardhat run scripts/deploy.js --network localhost.

module.exports = {
  solidity: "0.8.24",
  networks: {
    localhost: { url: "http://127.0.0.1:8545" },
  },
};

In-Process vs Standalone

There are two ways to use the Hardhat Network:

  • In-process — a fresh network spun up automatically when you run test or run without --network. State is discarded after.
  • Standalone — started with npx hardhat node and kept alive for external connections.

What Is Forking

Forking creates a local copy of a real network (like Ethereum mainnet) at a given block. You get all the on-chain state — deployed contracts, balances, token data — but can experiment freely.

This is perfect for testing against live protocols such as Uniswap or Aave without spending real funds.

Configuring a Fork

Enable forking by pointing the Hardhat network at an archive RPC URL:

module.exports = { networks: { hardhat: { forking: { url: "https://mainnet.example-rpc.io/KEY", }, }, }, };

You typically need an archive node provider for full historical state.

module.exports = {
  networks: {
    hardhat: {
      forking: {
        url: "https://mainnet.example-rpc.io/KEY",
      },
    },
  },
};

Pinning a Block Number

For reproducible tests, pin the fork to a specific block:

forking: { url: "https://mainnet.example-rpc.io/KEY", blockNumber: 19000000, }

Pinning keeps state stable and lets Hardhat cache responses, so tests run faster and never drift as the chain advances.

forking: {
  url: "https://mainnet.example-rpc.io/KEY",
  blockNumber: 19000000,
}

Impersonating Accounts

On a fork you can act as any address — even one you do not own — to test flows like a whale moving tokens:

await hre.network.provider.request({ method: "hardhat_impersonateAccount", params: ["0xWhaleAddress"], }); const whale = await hre.ethers.getSigner("0xWhaleAddress");
await hre.network.provider.request({
  method: "hardhat_impersonateAccount",
  params: ["0xWhaleAddress"],
});
const whale = await hre.ethers.getSigner("0xWhaleAddress");

Time and Block Manipulation

The local network exposes special RPC methods to control time and blocks, useful for testing vesting or auctions:

// Advance time by 1 day await hre.network.provider.send("evm_increaseTime", [86400]); // Mine a new block await hre.network.provider.send("evm_mine");
// Advance time by 1 day
await hre.network.provider.send("evm_increaseTime", [86400]);
// Mine a new block
await hre.network.provider.send("evm_mine");

Resetting State

You can reset the fork back to a clean snapshot between tests:

await hre.network.provider.request({ method: "hardhat_reset", params: [], });

This restores the original forked state without restarting the process, keeping test runs isolated.

await hre.network.provider.request({
  method: "hardhat_reset",
  params: [],
});

Snapshots and Reverts

Beyond a full reset, you can take lightweight snapshots and revert to them, which is how test fixtures work under the hood:

const id = await hre.network.provider.send("evm_snapshot"); // ... run some transactions ... await hre.network.provider.send("evm_revert", [id]);

Each snapshot id can be reverted to once.

const id = await hre.network.provider.send("evm_snapshot");
// ... run some transactions ...
await hre.network.provider.send("evm_revert", [id]);

Quick Check

Test your understanding of local networks and forking.

Recap

You learned to run and fork local networks.

  • npx hardhat node starts a standalone JSON-RPC node with funded accounts.
  • The in-process network is used automatically for tests and discarded after.
  • Forking copies live mainnet state locally for safe experimentation.
  • Pin blockNumber for reproducibility and caching.
  • Special RPC methods impersonate accounts, advance time, mine blocks, and reset state.
Gratis para empezar

Aprende Web3 & DApp Development Fundamentals con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
29
Lecciones
105

Preguntas frecuentes

¿La lección «Red local y forking» es gratis?

Sí — el texto completo de «Red local y forking» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Web3 & DApp Development Fundamentals, actualiza a CoddyKit PRO. El curso de Web3 & DApp Development Fundamentals incluye 4 lecciones en total.

¿Qué aprenderé en «Red local y forking»?

Entornos de prueba Practicas Web3 & DApp Development Fundamentals con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Web3 & DApp Development Fundamentals?

No se requiere experiencia previa. Web3 & DApp Development Fundamentals en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Red local y forking»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Web3 & DApp Development Fundamentals?

Sí. Cada lección de Web3 & DApp Development Fundamentals incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Configuración de Hardhat
  2. Compilación de contratos
  3. Scripts y tareas
  4. Red local y forking
← Volver a Web3 & DApp Development Fundamentals