Last active
August 9, 2022 15:07
-
-
Save ItsCuzzo/e61070401ef9e2332f744f0435509077 to your computer and use it in GitHub Desktop.
Understanding mappings in Solidity using assembly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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