0

I am using this Ethereum Go Client and trying to call and get the response of a Smart Contract function.

The function in the smart contract is very simple (for testing now):

  function getVotesForImgIds() external view returns(uint32){
    return 12345;
  }

I am using truffle to deploy the contract:

truffle compile
truffle migrate

My Go server is very basic too, here is the important part in the main func:

abi := getVotesContractJson()["abi"] //works fine

jsonAbi, err := json.Marshal(abi)
if err != nil {
    log.Fatal(err)
}

var connection = web3.NewWeb3(providers.NewHTTPProvider("127.0.0.1:8545", 10, false))
contract, err := connection.Eth.NewContract(string(jsonAbi))
if err != nil {
    log.Fatal(err)
}
//contract works

transaction := new(dto.TransactionParameters)
transaction.Gas = big.NewInt(4000000)

result, err := contract.Call(transaction, "getVotesForImgIds")
if result != nil && err == nil {
    fmt.Println("result: ", result)
    // -------------------->
    //this will print: result:  &{87 2.0 0x0 <nil> }
} else {
    log.Fatal("call error:", err)
}

Why does this result in &{87 2.0 0x0 <nil> } ? How can I get the real value returned by the smart contract? I tried all the result.ToInt() etc. already...

TylerH
  • 20,799
  • 66
  • 75
  • 101
bergben
  • 1,385
  • 1
  • 16
  • 35

2 Answers2

1

You are not setting the contract address in your go file: https://github.com/regcostajr/go-web3/blob/master/test/eth/eth-contract_test.go#L75

regcostajr
  • 170
  • 2
0

The client library returns a DTO struct which is why you can see a bunch of fields printed in the output.

Looks like the ToInt() receiver tries to cast to int64 whereas your contract returns unint32. Try casting the result to unint32 explicitly.

if result != nil && err == nil {
    res := result.ToString()
    votes, err := strconv.ParseUint(res, 10, 32)
    if err != nil {
        // do something with error
    }
    fmt.Printf("result: %d\n", votes)
}
stacksonstacks
  • 8,613
  • 6
  • 28
  • 44
  • Thank you for that idea. Unfortunately it prints 0 for votes. I was guessing that it is because of the DTO Struct. The ToString() sets res to 0x0. Neither of the structs values makes sense to be 12345 as the smart contract function would return... – bergben Jun 05 '18 at 21:06