A tutorial that teaches how to optimize the gas usage of your smart contracts using Hardhat.
npm install -D hardhat-gas-reporter
.
Then, import hardhat-gas-reporter
in hardhat.config.ts
:
hardhat.config.ts
file:
Store
with the following settings:
Store.test.ts
in order to test the gas reporter plugin. The test file should contain the following:
npx hardhat test
. The following report appears:
addItem
and the deployment costs.
Store
contract, you can identify certain variables that are only set during the creation of the contract. This means that an opportunity is possible to turn those variables into immutable, since immutable variables can still be assigned at construction time.
If you modify the Store
contract to:
Store
smart contract, you have the following:
Id
of the Item
struct and the id
used in the mapping are similar. You can avoid duplicating this information by removing the id of the Item
struct.
The contract looks like:
Store
smart contract. However, you can go further and instead of storing the items in a mapping
, you can simply emit events
and use the events as a cheap form of storage.
For instance, you can modify the contract to look like:
ItemCreated
event, which reduces the gas costs for deployment and execution:
ItemCreated
events emitted by the contract.
require
s and use custom errors. For instance, you can do the following: