Skip to content

Instantly share code, notes, and snippets.

@daopunk
Created June 30, 2022 21:17
Show Gist options
  • Select an option

  • Save daopunk/9a9c56de14e91fc1ae6b4f07c0bc904f to your computer and use it in GitHub Desktop.

Select an option

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
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