如何使用Golang正确发送RPC调用来获取智能合约所有者?

Zul*_*din 2 json-rpc go ethereum smartcontracts go-ethereum

更新

\n\n

由于我无法使用此问题中的方法来实现此目的,因此我创建了自己的库来执行相同的操作(链接)。它不依赖于 go-ethereum 包,而是使用普通net/http包来执行 JSON RPC 请求。

\n\n

我仍然想知道我在下面的方法中做错了什么。

\n\n
\n\n

定义

\n\n
    \n
  • 所有者=与类型public签订合同的变量address
  • \n
  • 合约= 有所有者的智能合约
  • \n
\n\n

这是获取合同所有者的curl 请求。我设法找到了主人。(JSON RPC 文档

\n\n
curl localhost:8545 -X POST \\\n--header \'Content-type: application/json\' \\\n--data \'{"jsonrpc":"2.0", "method":"eth_call", "params":[{"to": "0x_MY_CONTRACT_ADDRESS", "data": "0x8da5cb5b"}, "latest"], "id":1}\'\n\n{"jsonrpc":"2.0","id":1,"result":"0x000000000000000000000000_OWNER"}\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是当我尝试在 Golang 中复制它(下面的代码)时,出现json:cannot unmarshal string into Go value of type main.response错误。(我使用的 go-ethereum 代码

\n\n
package main\n\nimport (\n    "fmt"\n    "log"\n    "os"\n\n    "github.com/ethereum/go-ethereum/rpc"\n)\n\nfunc main() {\n    client, err := rpc.DialHTTP(os.Getenv("RPC_SERVER"))\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer client.Close()\n\n    type request struct {\n        To   string `json:"to"`\n        Data string `json:"data"`\n    }\n\n    type response struct {\n        Result string\n    }\n\n    req := request{"0x_MY_CONTRACT_ADDRESS", "0x8da5cb5b"}\n    var resp response\n    if err := client.Call(&resp, "eth_call", req, "latest"); err != nil {\n        log.Fatal(err)\n    }\n\n    fmt.Printf("%v\\n", resp)\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我在这里错过了什么?

\n\n

预期结果:

\n\n

字符串格式的地址。例如0x3ab17372b25154400738C04B04f755321bB5a94b

\n\n

P/S \xe2\x80\x94 我知道abigen并且我知道使用 abigen 可以更好、更容易地做到这一点。但我试图在不使用 abigen 方法的情况下解决这个特定问题。

\n

use*_*796 7

您可以使用go-ethereum/ ethclient最好地解决问题:

package main

import (
    "context"
    "log"

    "github.com/ethereum/go-ethereum"
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, _ := ethclient.Dial("https://mainnet.infura.io")
    defer client.Close()

    contractAddr := common.HexToAddress("0xCc13Fc627EFfd6E35D2D2706Ea3C4D7396c610ea")
    callMsg := ethereum.CallMsg{
        To:   &contractAddr,
        Data: common.FromHex("0x8da5cb5b"),
    }

    res, err := client.CallContract(context.Background(), callMsg, nil)
    if err != nil {
        log.Fatalf("Error calling contract: %v", err)
    }
    log.Printf("Owner: %s", common.BytesToAddress(res).Hex())
}
Run Code Online (Sandbox Code Playgroud)