Skip to content

Instantly share code, notes, and snippets.

@ItsCuzzo
Last active August 9, 2022 15:07
Show Gist options
  • Save ItsCuzzo/e61070401ef9e2332f744f0435509077 to your computer and use it in GitHub Desktop.
Save ItsCuzzo/e61070401ef9e2332f744f0435509077 to your computer and use it in GitHub Desktop.
Understanding mappings in Solidity using assembly.
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.15;
contract AsmMapping {
mapping(uint256 => uint256) private _map;
/// @dev Set some dummy data to begin with.
constructor() {
_map[0] = 2;
_map[1] = 8;
}
/// @dev Function used to set a `key` and `value` pairing in asm.
function set(uint256 key, uint256 value) external {
assembly {
/// Store the concatenation of `key` and `_map.slot` in scratch space.
mstore(0x00, key)
mstore(0x20, _map.slot)
/// Store `value` in storage at the calculated storage slot.
sstore(keccak256(0x00, 64), value)
}
}
/// @dev Function used to retrieve the value at `_map[key]`.
function map(uint256 key) external view returns (uint256) {
assembly {
/// Store the concatenation of `key` and `_map.slot` in scratch space.
mstore(0x00, key)
mstore(0x20, _map.slot)
/// Store the value at the calculated storage slot in memory at fmp offset.
mstore(0x40, sload(keccak256(0x00, 64)))
/// Return a single word from fmp offset.
return(0x40, 32)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment