High gas fees can destroy an NFT mint’s momentum. Learn the architectural decisions, Solidity optimizations, and deployment strategies needed to minimize transaction costs for both you and your minters.
Introduction: Why Gas Optimization Matters
On Ethereum and EVM-compatible networks, gas costs are directly tied to user experience. Inefficient contracts lead to failed transactions, gas wars, and frustrated collectors. Optimizing an NFT smart contract is not just about saving a few dollars—it can be the difference between a sold-out drop and an abandoned mint.
In this guide, we will walk through the full lifecycle of designing, coding, testing, and deploying a production-ready, gas-optimized ERC-721 collection.
1. Architectural Choices: ERC-721 vs. ERC-721A
The standard OpenZeppelin ERC721Enumerable implementation tracks token balances and owners using multiple storage slots, causing batch minting costs to scale linearly ($O(N)$).
For drops where users might mint more than one token per transaction, Azuki’s ERC-721A standard is the industry benchmark. It achieves near-constant gas costs ($O(1)$) for batch mints by:
- Deferred Balance Updates: Writing the owner address once for the first token in a batch, leaving subsequent tokens implicitly owned until transferred.
- Removing Redundant State: Storing balance and ownership in tightly packed data structures rather than updating multiple mappings per mint.
2. Key Solidity Optimization Techniques
Use Custom Errors Instead of Require Strings
Starting with Solidity 0.8.4, custom errors save substantial deployment and execution gas by replacing verbose revert strings with 4-byte error selectors.
// Bad: Expensive string stored in bytecode and returned on revert
require(msg.value >= PRICE, "Insufficient funds sent");
// Good: Cheap 4-byte selector
error InsufficientFunds();
if (msg.value < PRICE) revert InsufficientFunds();
Implement Merkle Trees for Allowlisting
Storing hundreds or thousands of allowlisted addresses in contract storage via mappings requires an expensive setup transaction (thousands of SSTORE operations). Instead, compute a Merkle Root off-chain, store a single 32-byte bytes32 root on-chain, and have minters submit cryptographic proofs with their mint transactions.
Storage Packing and Variable Sizing
EVM storage operates in 32-byte (256-bit) slots. Packing smaller variables together reduces the number of SSTORE and SLOAD opcodes executed:
// Packed into a single 256-bit slot
struct CollectionConfig {
uint64 mintPrice; // 8 bytes
uint32 maxSupply; // 4 bytes
uint32 maxPerWallet; // 4 bytes
bool isPublicMintActive; // 1 byte
}
Cache Storage Reads in Memory
Reading from storage (SLOAD) costs up to 2,100 gas for a cold read, whereas reading from memory (MLOAD) costs 3 gas. If you access a state variable multiple times inside a loop or function, copy it to a local memory variable first.
3. The Gas-Optimized Contract
Below is a production-grade template using ERC721A, MerkleProof verification, custom errors, and packed configuration state.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "erc721a/contracts/ERC721A.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
error SaleInactive();
error ExceedsMaxSupply();
error ExceedsMaxPerWallet();
error InsufficientPayment();
error InvalidAllowlistProof();
error WithdrawFailed();
contract OptimizedNFT is ERC721A, Ownable {
uint256 public constant MAX_SUPPLY = 10000;
uint256 public constant MINT_PRICE = 0.05 ether;
uint256 public constant MAX_PER_TX = 5;
bytes32 public merkleRoot;
bool public publicMintOpen;
bool public allowlistMintOpen;
string private baseTokenURI;
constructor(
string memory baseURI_,
bytes32 merkleRoot_
) ERC721A("OptimizedNFT", "OPT") Ownable(msg.sender) {
baseTokenURI = baseURI_;
merkleRoot = merkleRoot_;
}
function allowlistMint(uint256 quantity, bytes32[] calldata proof) external payable {
if (!allowlistMintOpen) revert SaleInactive();
if (_totalMinted() + quantity > MAX_SUPPLY) revert ExceedsMaxSupply();
if (msg.value < MINT_PRICE * quantity) revert InsufficientPayment();
bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(msg.sender))));
if (!MerkleProof.verify(proof, merkleRoot, leaf)) revert InvalidAllowlistProof();
_mint(msg.sender, quantity);
}
function publicMint(uint256 quantity) external payable {
if (!publicMintOpen) revert SaleInactive();
if (quantity > MAX_PER_TX) revert ExceedsMaxPerWallet();
if (_totalMinted() + quantity > MAX_SUPPLY) revert ExceedsMaxSupply();
if (msg.value < MINT_PRICE * quantity) revert InsufficientPayment();
_mint(msg.sender, quantity);
}
function _baseURI() internal view override returns (string memory) {
return baseTokenURI;
}
function setBaseURI(string calldata newBaseURI) external onlyOwner {
baseTokenURI = newBaseURI;
}
function setMerkleRoot(bytes32 newRoot) external onlyOwner {
merkleRoot = newRoot;
}
function setSaleState(bool publicState, bool allowlistState) external onlyOwner {
publicMintOpen = publicState;
allowlistMintOpen = allowlistState;
}
function withdraw() external onlyOwner {
(bool success, ) = payable(owner()).call{value: address(this).balance}("");
if (!success) revert WithdrawFailed();
}
}
4. Compiler Configuration
Fine-tuning the Solidity compiler settings is essential for balancing deployment cost with transaction-level execution cost.
Hardhat Configuration (hardhat.config.js)
module.exports = {
solidity: {
version: "0.8.20",
settings: {
optimizer: {
enabled: true,
runs: 200 // Higher runs = cheaper function execution, higher deployment gas
},
viaIR: true // Enables intermediate representation pipeline for deep optimizations
}
}
};
Foundry Configuration (foundry.toml)
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc_version = "0.8.20"
optimizer = true
optimizer_runs = 200
via_ir = true
Tip: If minters are sensitive to execution gas, increase runs to 1000 or 10000. This will slightly increase your deployment cost but reduces the transaction cost across all future mints.
5. Profiling Gas Usage Before Deployment
Never deploy to mainnet without auditing your gas benchmarks. Use established developer tool plugins to generate gas usage reports:
- Foundry: Run
forge test --gas-reportto generate an instant CLI breakdown of gas consumed by individual functions. - Hardhat: Integrate
hardhat-gas-reporterto output transaction costs translated to current USD fiat values.
6. Deployment Walkthrough
Step 1: Generate Off-Chain Metadata & Merkle Root
Host metadata JSON files on decentralized storage (IPFS or Arweave). Prepare the allowlist array in Node.js, compute the Merkle root using merkletreejs, and keep the generated tree accessible for frontend dApps to supply proofs.
Step 2: Dry Run on a Testnet
Deploy the contract to Sepolia using Foundry or Hardhat:
# Deploy via Foundry
forge create --rpc-url $SEPOLIA_RPC_URL \
--private-key $PRIVATE_KEY \
src/OptimizedNFT.sol:OptimizedNFT \
--constructor-args "ipfs://CID/" 0xYourMerkleRootHere \
--verify --etherscan-api-key $ETHERSCAN_API_KEY
Step 3: Verification and Production Deployment
Deploy to mainnet during low-traffic periods (track the Ethereum gas tracker to target <15 Gwei). Verify the contract source immediately on block explorers to maintain transparency with collectors.
Conclusion: The Gas Optimization Checklist
- Use ERC-721A when batch minting is a requirement.
- Replace string-based reverts with custom errors.
- Implement Merkle Trees instead of on-chain allowlist mappings.
- Pack storage structs and declare fixed variables as constant or immutable.
- Enable viaIR and optimize compiler runs.
- Benchmark with gas reports before executing mainnet transactions.