Локальная сеть и форкинг
Тестовые среды
«Локальная сеть и форкинг» — бесплатный урок Web3 & DApp Development Fundamentals на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Web3 & DApp Development Fundamentals, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Web3 & DApp Development Fundamentals содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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 nodeThis prints 20 funded accounts with their private keys and listens on http://127.0.0.1:8545.
npx hardhat nodeThe 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
testorrunwithout--network. State is discarded after. - Standalone — started with
npx hardhat nodeand 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 nodestarts 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
blockNumberfor reproducibility and caching. - Special RPC methods impersonate accounts, advance time, mine blocks, and reset state.
Часто задаваемые вопросы
Урок «Локальная сеть и форкинг» бесплатный?
Да — полный текст урока «Локальная сеть и форкинг» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Web3 & DApp Development Fundamentals, подпишись на CoddyKit PRO. Курс Web3 & DApp Development Fundamentals содержит 4 уроков всего.
Чему я научусь в уроке «Локальная сеть и форкинг»?
Тестовые среды Ты практикуешь Web3 & DApp Development Fundamentals с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Web3 & DApp Development Fundamentals?
Предыдущий опыт не требуется. Web3 & DApp Development Fundamentals на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Локальная сеть и форкинг»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Web3 & DApp Development Fundamentals?
Да. Каждый урок Web3 & DApp Development Fundamentals включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Настройка Hardhat
- Компиляция контрактов
- Скрипты и задачи
- Локальная сеть и форкинг