pub trait StorageKey: OnlyPrimitives {
// Required method
fn as_storage_bytes(&self) -> impl AsRef<[u8]>;
// Provided method
fn mapping_slot(&self, slot: U256) -> U256 { ... }
}Expand description
Trait for types that can be used as storage mapping keys.
Keys are hashed using keccak256 along with the mapping’s base slot to determine the final storage location. This trait provides the byte representation used in that hash.
§Sealed to single-word primitives
Only types that implement sealed::OnlyPrimitives (single-word types ≤32 bytes)
can be mapping keys. This prevents arrays, structs, and dynamic types from being
used as keys — matching Solidity’s restriction to value types.
§Encoding
Mapping slots are computed as keccak256(bytes32(key) | bytes32(slot)), where the
key’s raw bytes are left-padded to 32 bytes and the slot is appended in big-endian.
This differs from Solidity’s keccak256(abi.encode(key, slot)), where signed integers
are sign-extended and bytesN (N < 32) are right-padded. Per-type equivalence:
- Unsigned integers,
Address,bytes32: identical — both zero-left-pad. - Signed integers: diverges — Solidity sign-extends negative values to 32 bytes, we zero-left-pad the two’s complement representation.
bytesN(N < 32): diverges — Solidity right-pads, we left-pad.
This is not a soundness issue — there are no slot collision risks — but off-chain
tools that reconstruct storage slots using Solidity’s abi.encode rules will compute
different locations for the divergent types. View functions should be used instead.
Required Methods§
Sourcefn as_storage_bytes(&self) -> impl AsRef<[u8]>
fn as_storage_bytes(&self) -> impl AsRef<[u8]>
Returns key bytes for storage slot computation.
Provided Methods§
Sourcefn mapping_slot(&self, slot: U256) -> U256
fn mapping_slot(&self, slot: U256) -> U256
Compute storage slot for a mapping with this key.
Left-pads the key to 32 bytes, concatenates with the slot, and hashes.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.