1

i am trying to encode a bool variable as callback data (bytes). i am doing this by using abi.encodePacked for reduced space and cost and a custom decoding function.

The issue is that after decoding, the returned variable is always true no matter what the packed encoded value is.

here is the code :

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

/** 
 * @title Ballot
 * @dev Implements voting process along with vote delegation
 */
contract TEST {
   
   function encodeBytes() public pure returns (bytes memory){
       
      bool x = false;
       return abi.encodePacked(x);
   }
   
   
   function decode(bytes memory data) public pure returns ( bool b) {
        assembly {
            b := mload(
                add(
                    data,
                    8
                )
            )

        }
    }


    function decodeAndReturn() public returns (bool){
        bytes memory packed = encodeBytes();
        return decode(packed);
    }
}

calling decodeAndReturn would return true even if the encoded variable is explicitly set to false. is the issue with my decoding function ?

1

The problem is in the decode function, you are not loading the data correctly. First, you need to determine the length of the data. This can be done using mload(data) which loads the length of data, the length is located at the first 32 bytes.

After the first 32 bytes that define the length of data, you can load the data using mload(add(data, 0x20)). Just to clarify, 0x20 is equivalent to 32 bytes.

So, your code should be the following:

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

/** 
 * @title Ballot
 * @dev Implements voting process along with vote delegation
 */
contract TEST {
   
   function encodeBytes() public pure returns (bytes memory){
      bool x = false;
      return abi.encodePacked(x);
   }
   
   
   function decode(bytes memory data) public pure returns (bool b){
        assembly {
            // Load the length of data (first 32 bytes)
            let len := mload(data)
            // Load the data after 32 bytes, so add 0x20
            b := mload(add(data, 0x20))
        }
    }


    function decodeAndReturn() public pure returns (bool){
        bytes memory packed = encodeBytes();
        return decode(packed);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.