I have a function from a library:
function sliceUint(bytes bs, uint start)
internal pure
returns (uint)
{
require(bs.length >= start + 32, "slicing out of range");
uint x;
assembly {
x := mload(add(bs, add(0x20, start)))
}
return x;
}
the purpose of which is it takes bytes-encoded parameter and converts it to a uint. The reason I need this is because I need to interact with a contract function that has a bytes calldata _extra
parameter that will call back to my contract with. I need to pass in a uint256 in the initial call, then decode with sliceuint on the callback so I can recover it.
If I understand the assembly right, it's loading into x, from the bytes bs variable, but from an offset of 0x20+start.
My question is:
- How do I convert from a uint256 to bytes in Solidity to feed to the function?
- How do I convert from a uint256 to bytes in Web3.js for same?
In web3.js I have tried:
web3.eth.abi.encodeParameter('bytes', 1337)
'0x000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000020539000000000000000000000000000000000000000000000000000000000000'
and passed that to the bytes parameter of my function. It usually reverts with an error that I may have tried to access an array out of bounds or didn't provide enough gas (I provided enough gas.)
If I try to follow what the sliceUint function does, it seems like it's pulling from the wrong place (0x80 looks like the right place) so what am I doing wrong am I encoding wrong, calling sliceUint wrong?
await tester.sliceUint(web3.eth.abi.encodeParameter('uint256', 1337), 0)
and this seems to convert correctly. Still errors out when I pass the bytes through the contract.