Search code examples
goethereumtrufflego-ethereum

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


Solution

  • 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