Contract Storage Slot Calculator
Calculate storage slots for mappings and arrays in Solidity smart contracts
1. What is a storage slot?
In Ethereum smart contracts, storage is organized into 32-byte slots. Each state variable occupies a specific slot, and mappings use a calculated slot based on the key and base slot number.
2. How does it work?
For mappings, the storage slot is calculated as: keccak256(key . slot)
Where key is the mapping key (padded to 32 bytes) and slot is the base slot number of the mapping.
solidity
1// Example: Calculate slot for balances[user]
2contract ERC20 {
3 mapping(address => uint256) public balances; // slot 0
4
5 function getBalanceSlot(address user) public pure returns (bytes32) {
6 return keccak256(abi.encodePacked(user, uint256(0)));
7 }
8}Use cases
- Reading storage directly with eth_getStorageAt
- Storage proofs for L2 bridges
- Off-chain verification of contract state
- Advanced contract analysis and debugging
3. Examples
ERC-20 balance mapping
Key: 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045
Slot: 0
→ Storage Slot: 0xfca351f4d96129454cfc8ef7930b638ac71fea35eb69ee3b8d959496beb04a33NFT owner mapping (uint256 key)
Key: 1 (token ID)
Slot: 2
→ Use for mapping(uint256 => address) ownerOfNested mapping
First calculate outer mapping slot, then use result as slot for inner key
4. Source Code
typescript
1// npm install viem
2
3import { keccak256, encodePacked, pad, toHex } from 'viem';
4
5// Calculate storage slot for mapping
6function getMappingSlot(key: string, slotNumber: number): string {
7 let keyBytes: `0x${string}`;
8
9 // Handle address (20 bytes) or uint256 (32 bytes)
10 if (key.startsWith('0x')) {