douren5898
2018-06-05 20:15
浏览 162
已采纳

Golang Web3松露

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...

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douhu3424 2018-06-06 05:47
    已采纳

    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

    点赞 打赏 评论
  • duanqiao1880 2018-06-05 20:43

    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
    ", votes)
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题