A tutorial that teaches how to optimize the size of your smart contracts using Hardhat.
hardhat-contract-sizer
plugin that helps you analyze and optimize the size of your smart contracts.
npm install -D hardhat-contract-sizer
.
Then, import hardhat-contract-sizer
in hardhat.config.ts
:
Lock.sol
.
Run npx hardhat size-contracts
, which is a task added to Hardhat once you set up and configure the hardhat-contract-sizer
plugin.
You are then able to see:
hardhat-contract-sizer
plugin, since it show you the size of your contracts.
Calculator.sol
and ScientificCalculator.sol
, with the following:
npx hardhat size-contracts
again and you should be able to see:
ScientificCalculator
is bigger than Calculator
. This is because ScientificCalculator
is inheriting the contract Calculator
, which means all of its functionality and code is available in ScientificCalculator
and that will influence its size.
ScientificCalculator
:
npx hardhat size-contracts
command, you should be able to see:
Computer
that contains a function called executeProcess
:
executeProcess
function of Computer
requires certain functionality of Calculator
and a new contract called Printer
:
Computer
to access both functionalities is to inherit; however, as all of these contracts continue adding functionality, the size of the code will also increase. You will reach the contract size issue at some point, since you are copying the entire functionality into your contract. You can better allow that functionality to be kept with their specific contracts and if the Computer
requires to access that functionality, you could call the Calculator
and Printer
contracts.
But in this example, there is a process that must call both Calculator
and Printer
:
Computer
contract is very small but still has the capability to access all the functionality of Printer
and Calculator
.
Although this will reduce the size of each contract, the costs of this are discussed more deeply in the Gas Optimization article.
Calculator
library only. Then, you would have the following:
Computer
is:
Calculator
library for uint256
and how in the executeProcess
function, you can now use the add
function from the Calculator
library in all of the uint256
.
If you run the npx hardhat size-contracts
command, you then get:
Calculator
library functions and you will then have:
Overall, the optimizer tries to simplify complicated expressions, which reduces both code size and execution cost.You can enable the solidity optimizer in hardhat by simply adding the following to the
hardhat.config.ts
file:
runs
. If you run the contract sizer command again, you will see the following:
runs
parameter value to 1000:
runs
value the more efficient during execution but more expensive during deployment. You can read more in the Solidity documentation.