4

First, I'm caling function foo() (from another contract) that returns me a uint in the form of bytes.

Then, I'm using BytesLib.toUint(foo(), 0) to retrieve the uint.

When the value is supposed to be 1, foo returns 0x0000000000000000000000000000000000000000000000000000000000000001, and BytesLib.toUint(foo(), 0) works fine.

When the value is supposed to be 2, foo returns 0x0000000000000000000000000000000000000000000000000000000000000002, and BytesLib.toUint(foo(), 0) works fine.

However, when the value is supposed to be 0, foo does not return 0x0000000000000000000000000000000000000000000000000000000000000000.

It returns 0x. And BytesLib.toUint(foo()), 0) does not work.

I would like to implement some logic to check if the value of foo() equals 0x. I've tried multiple things:

  • if (foo() == 0x) { //do something else }
  • if (foo() == "0x") { //do something else }
  • if (foo() == address(0)) { //do something else }
  • if (foo() == keccak256(0x)) { //do something else }

But all of these result in compilation errors.

How should I handle 0x?

1 Answer 1

4

0x is technically an empty byte array. In Solidity, you can't do direct comparison of bytes (or other dynamic types), so an easy way to check for this is by checking the length of the bytes, e.g. foo().length == 0.

contract Foo {
  function foo() public returns (bytes memory) {
    return bytes("");
  }
  
  function bar() public returns (bool) {
    return foo().length == 0;
  }
}

Calling foo() returns an empty byte array (0x), and calling bar() returns true as expected.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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