Search code examples
pythonblockchainethereumsolidityweb3py

web3.py return from a get function in strange format


i'm developing a python app. This app is just to get data from the blockchain. In web3.js it all works good, but i need to do it in python (the client wants a python app). It all works almost good; The script does what it needs to do, but when calling the get function i get a strange output (using the get function on remix or web3.js whit a nodeJs api that i wrote works just perfect) :

D:\pytoh\b_get\Scripts\python.exe C:/Users/Alessandro/PycharmProjects/pytoh/b_get/bget.py
True
[(b'\xe9:=\xd87/\x98\x00\xe4\x89\xe3\x8eb[c\x9cj\xc4\xa3\xa2b\x1d\x9a\xf0%\x1d\xdaB\xb7\xd9\xc4\xe3', 
b'\xe9:=\xd87/\x98\x00\xe4\x89\xe3\x8eb[c\x9cj\xc4\xa3\xa2b\x1d\x9a\xf0%\x1d\xdaB\xb7\xd9\xc4\xe3')]

Process finished with exit code 0

The output that i need is like this (i don't understand why the py output is like that):[0xe93a3dd8372f9800e489e38e625b639c6ac4a3a2621d9af0251dda42b7d9c4e3,0xe93a3dd8372f9800e489e38e625b639c6ac4a3a2621d9af0251dda42b7d9c4e3]

The python script is simple (i'm still writing it):

import json
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:7545'))
print(w3.isConnected())
with open("ABI.json") as f:
  info_json = json.load(f)
abi = info_json["output"]["abi"]

 address = "0x1305ef6377fe8cB7C6dD7Eb2B6cAD83A34fC7503"
 get = w3.eth.contract(address=address, abi=abi) 
 result=get.functions.getUser("0xe93a3dd8372f9800e489e38e
                       625b639c6ac4a3a2621d9af0251dda42b7d9c4e3").call()
 print(result)

And this is the smart contract that the client wrote:

pragma solidity ^0.4.26;
pragma experimental ABIEncoderV2;

contract crud{
  address owner;
  constructor() public{
  owner = msg.sender;
}
modifier onlyOwner () {
   require(msg.sender == owner);
    _;
}
struct user{
    bytes32 hash_json;
    bytes32 hash_corso;
}
 mapping (bytes32 => user[]) public users;

 
 function setUser(bytes32 _hash, bytes32 _hash_json, bytes32 _hash_corso) onlyOwner  public {
     user memory usr;
     usr.hash_json=_hash_json;
     usr.hash_corso= _hash_corso;
     users[_hash].push(usr);
 }
 
 function getUser(bytes32 _hash) view public returns (user[] memory) {
     return users[_hash];
 }

 }

Thank for your help!


Solution

  • The result is a byte array. When you print it, it converts control characters to hex but prints readable characters.

    To get a full hex string, try this:

    result = bytearray([22,32,7,67,14,87,90])  # for testing
    hxstr = "".join(["{:02x}".format(v) for v in result])
    print("0x"+hxstr)
    

    Output

    0x162007430e575a