Solidity – How to Make Use of Arbitrary Bytes Array in Solidity

solidity

I'm implementing an ERC-721 contract that supports the function:

safeTransferFrom(address from, address to, uint256 tokenId, bytes data)

The last parameter of this function is an arbitrary byte array. I imagine most implementations of this function ignore this parameter, but I am interested in using it. Specifically, I want to pass two additional uint256 fields in this parameter and decode them within the contract. How can I achieve this? For example:

function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) public {
    (uint256 startDate, uint256 endDate) = decode(data);
    // etc...
}

In the above example, I'm asking how to implement the decode function.

Best Answer

You can use abi.decode() function of solidity to extract your uint256 values.

Reference: abi.decoder in solidity

First make the bytes data using in the script, or using web3:

var data = await abi.encode(11111111,2222222);

Then extract those uint256 in solidity:

function Name(bytes memory data) public pure returns(uint8 number1, uint256 number2) {
    
        (number1, number2) = abi.decode(data, (uint8, uint256));

    }

And this should do the trick!