openzeppelin-contracts
openzeppelin-contracts copied to clipboard
Add new Bytes utility to decode `bytes memory`
🧐 Motivation
Decode data which was packed by abi.encodePacked()
into a bytes memory
https://github.com/ethereum/solidity/issues/6919
📝 Details
- Convert
bytes memory
tobytes32[]
- Read sub
bytes memory
of inputbytes memeory
- Read
uint256
,uint160
,uint128
,uint64
,uint32
,uint16
of inputbytes memory
at a given offset.
Please check #3998 for the detail, the pr is in WIP
. I will complete the rest after this discussion is resolved.
How will this work, given that the encoded type is ambigious?
Are you going to create a library?
uint256 offset = 0;
(uint256 myVar, uint256 newOffset) = decodePackedUint256(bytes)
Here is an example of Bytes.sol
, my implementation could be found in #3998
pragma solidity ^0.8.0;
import "./Bytes.sol";
contract EncodingTx {
using Bytes for bytes;
function encodeTransaction(address from, address to, uint256 value, uint64 nonce)
public pure returns (bytes memory) {
return abi.encodePacked(from, to, nonce, value);
}
function decodeTransaction(bytes memory input)
external pure returns(address from, address to, uint256 value, uint64 nonce){
uint256 offset;
uint160 uintAddress;
(uintAddress, offset) = input.readUint160(0);
from = address(uintAddress);
(uintAddress, offset) = input.readUint160(offset);
to = address(uintAddress);
(nonce, offset) = input.readUint64(offset);
(value, offset) = input.readUint256(offset);
}
}
There already exist quite a few Bytes
libraries.
The first one that comes to mind is this one.
There is also the RLP reader that is used by polygon's FX Portal.
I'm not sure we want to start yet another library for bytes manipulation. If we do, we'll need serious reasons to do so, and that start by studying the existing alternative. Unless there is something we can do better, I'm not sure why we should dedicate ressources to this.
This library provide the minimal utility to unpack the data which was packed by abi.encodePacked()
. I'm preparing a PR in #3998.