Компиляция контрактов
Артефакты сборки
«Компиляция контрактов» — бесплатный урок Web3 & DApp Development Fundamentals на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Web3 & DApp Development Fundamentals, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Web3 & DApp Development Fundamentals содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Compile
Solidity source code cannot run on the EVM directly. The compiler turns .sol files into bytecode and an ABI that tools and clients use.
- Bytecode — the low-level instructions deployed on-chain.
- ABI — a JSON interface describing functions and events.
The Compile Task
Hardhat compiles every contract under contracts/ with a single command:
npx hardhat compileHardhat downloads the right solc version automatically, so you do not need to install the compiler manually.
npx hardhat compileChoosing the Solidity Version
The compiler version is set in hardhat.config.js and must satisfy the pragma in your contracts:
module.exports = {
solidity: "0.8.24",
};If your contract says pragma solidity ^0.8.24;, the configured version must be compatible or compilation fails.
module.exports = {
solidity: "0.8.24",
};Build Artifacts
After compiling, Hardhat writes output to the artifacts/ folder. Each contract gets a JSON file containing:
abi— the application binary interface.bytecode— deployment bytecode.deployedBytecode— runtime bytecode.
These artifacts are what ethers.js loads to interact with your contract.
The Cache Folder
Hardhat keeps a cache/ folder to track what changed. On the next compile, only modified files are recompiled.
This incremental compilation makes large projects build quickly. If something seems stale, you can force a fresh build.
Cleaning the Build
To remove cached and generated files, run the clean task:
npx hardhat cleanThis deletes artifacts/ and cache/. Use it when you suspect a stale artifact is causing odd behavior, then recompile.
npx hardhat cleanCompiler Optimizer
The optimizer reduces gas costs and bytecode size. Enable it in the config:
module.exports = {
solidity: {
version: "0.8.24",
settings: {
optimizer: { enabled: true, runs: 200 },
},
},
};A higher runs value optimizes for frequent calls; a lower value optimizes for deployment size.
module.exports = {
solidity: {
version: "0.8.24",
settings: {
optimizer: { enabled: true, runs: 200 },
},
},
};Multiple Compiler Versions
If different contracts need different Solidity versions, list several compilers:
module.exports = {
solidity: {
compilers: [
{ version: "0.8.24" },
{ version: "0.7.6" },
],
},
};Hardhat picks a matching compiler for each file based on its pragma.
module.exports = {
solidity: {
compilers: [
{ version: "0.8.24" },
{ version: "0.7.6" },
],
},
};Reading Compiler Warnings
The compiler reports errors (which stop the build) and warnings (which do not). Common warnings include:
- Unused local variables.
- Shadowed declarations.
- Functions that could be marked
vieworpure.
Treat warnings seriously — they often hint at real bugs.
Using the ABI Later
Once compiled, you import the artifact in scripts or tests to attach to a contract:
const artifact = require("./artifacts/contracts/Greeter.sol/Greeter.json");
console.log(artifact.abi);Tools like ethers.js use this ABI to encode and decode calls correctly.
const artifact = require("./artifacts/contracts/Greeter.sol/Greeter.json");
console.log(artifact.abi);Forcing a Recompile
By default Hardhat skips files that have not changed. To rebuild everything without cleaning, pass the force flag:
npx hardhat compile --forceThis is useful after changing compiler settings, which the incremental cache may not detect on its own.
npx hardhat compile --forceQuick Check
Test your understanding of compilation in Hardhat.
Recap
You learned how Hardhat compiles contracts.
npx hardhat compilebuilds all contracts and downloads the right solc.- Artifacts (ABI + bytecode) land in
artifacts/; incremental builds usecache/. npx hardhat cleanremoves stale output.- The optimizer and multiple compiler versions are configured in
hardhat.config.js. - Always fix warnings — they often reveal bugs.
Часто задаваемые вопросы
Урок «Компиляция контрактов» бесплатный?
Да — полный текст урока «Компиляция контрактов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 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 структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Компиляция контрактов»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Web3 & DApp Development Fundamentals?
Да. Каждый урок Web3 & DApp Development Fundamentals включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Настройка Hardhat
- Компиляция контрактов
- Скрипты и задачи
- Локальная сеть и форкинг