1

I have a contract in Solidity with a function that returns a (nested) struct. Using Python on the client side I can call the function using my geth node and it returns output as a hex string. How do I decode this to a string in Python? (And eventually to a dict) How is it encoded?

When I try this: (h is the hex string)

>>> bytes.fromhex(h[2:]).decode('utf-8')

I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 313: invalid continuation byte'

Simplified solidity code:

struct StructB {
     uint256 a;
     uint256 b;
}
struct StructC {
     uint256 a;
     uint256 b;
}
struct StructA {
    uint256 a;
    uint256 b;
    StructB structB;
    StructC structC;

}

contract MyContract {
     function myFunction() external returns (StructA memory result) {
           result.a = 0;
           result.b = 1;
           result.structA.a = 0;
           result.structA.b = 1;
           result.structB.a = 0;
           result.structB.b = 1;

     }
     return result;
}


1 Answer 1

0

You can decode a hex string to a string using bytes.fromhex('hexstring').decode('utf-8')

See:

https://stackoverflow.com/questions/3283984/decode-hex-string-in-python-3

https://www.adamsmith.haus/python/answers/how-to-decode-a-hex-string-in-python

3
  • If I do that with the output string I received, I get this error: >>> bytes.fromhex(h).decode('utf-8') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: non-hexadecimal number found in fromhex() arg at position 1 Then when I try this: >>> bytes.fromhex(h[2:]).decode('utf-8') I get: Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 313: invalid continuation byte'
    – Quint
    Oct 17, 2022 at 16:09
  • You need to remove the first "0x" from the string for the first ValueError. Oct 17, 2022 at 16:14
  • Yes, I know. the I get the second error about position 313
    – Quint
    Oct 17, 2022 at 16:18

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.