I'm trying to read from and write to a mapping of structs using inline assembly.
getValues()
is an example of how I'm able to read something from storage. I can read the first two values using and()
and shr()
. But how do I read the next values within struct?
The code in writeTo()
is able to write to a mapping(uint => uint)
. But I cant figure out how to write to a slot in a struct within a mapping(uint => Struct)
.
What values should be hashed for sstore()
to write to correct location? (whatever location that might be, but I assume getting the answer to how to jump to next slot within the struct using shr()
(?) might answer that question)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
contract Assemble2{
mapping(uint => Info) infos;
struct Info{
uint128 level;
uint128 amount;
uint128 num;
uint128 time;
address sender;
}
constructor(){
infos[0] = Info(
2,3, 4,5, msg.sender
);
}
function getValues(uint _id) public view returns(uint a, uint b, uint c, uint d, address e){
Info storage info = infos[_id];
assembly {
let w := sload(info.slot)
a := and(w, 0xfff) // gets first value in first slot
b := shr(128, w) // gets second value in first slot
//c := shr(?, w) // how to jump to next slot and get first value?
//d := shr(?, w) // how to jump to next slot and get second value?
//e := shr(?, w) // how to jump to third slot and get first value?
}
}
function writeTo(uint _id) public {
Info storage info = infos[_id];
uint newLevel = 10;
assembly {
mstore(0, newLevel)
mstore(32, info.slot)
// how to include position within struct?
// do I somehow hash the sload with the pointer to the position?
// let w := sload(info.slot)
// b := shr(128, w)
let hash := keccak256(0,64)
sstore(hash,2)
}
}
}