Created
June 30, 2022 21:17
-
-
Save daopunk/9a9c56de14e91fc1ae6b4f07c0bc904f to your computer and use it in GitHub Desktop.
getBytePackedVar to access variables packed into 32 byte slot in Ethereum state with ethers.js
This file contains hidden or 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
| async function getBytePackedVar(slot, contractAddress, byteShift, byteSize) { | |
| const paddedSlot = utils.hexZeroPad(slot, 32); | |
| const storageLocation = await ethers.provider.getStorageAt(contractAddress, paddedSlot); | |
| let result = ""; | |
| let altByteSize = 0; | |
| let altByteShift = 0; | |
| let check = false; | |
| if (byteSize <= 6) { | |
| return BigNumber.from(storageLocation).shr(byteShift * 4).mask(byteSize * 4 * 2).toNumber().toString(16); | |
| } else { | |
| altByteSize = byteSize - 6; | |
| altByteShift = byteShift + 12; | |
| check = true; | |
| result += await getBytePackedVar(slot, contractAddress, altByteShift, altByteSize); | |
| } | |
| if (check) { | |
| result += await getBytePackedVar(slot, contractAddress, byteShift, 6); | |
| } | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment