go - 如何使用 Golang 正确发送 RPC 调用以获取智能合约所有者?
问题描述
更新
由于我无法使用这个问题中的方法来实现这一点,因此我创建了自己的库来做同样的事情(链接)。它不依赖 go-ethereum 包,而是使用普通net/http
包进行 JSON RPC 请求。
我仍然很想知道我在下面的方法中做错了什么。
定义:
- 所有者=类型
public
合同中的变量address
- 合约= 拥有所有者的智能合约
这是获取合约所有者的 curl 请求。我设法得到了主人。(JSON RPC 文档)
curl localhost:8545 -X POST \
--header 'Content-type: application/json' \
--data '{"jsonrpc":"2.0", "method":"eth_call", "params":[{"to": "0x_MY_CONTRACT_ADDRESS", "data": "0x8da5cb5b"}, "latest"], "id":1}'
{"jsonrpc":"2.0","id":1,"result":"0x000000000000000000000000_OWNER"}
但是当我尝试在 Golang(下面的代码)中复制它时,我得到了json: cannot unmarshal string into Go value of type main.response错误。(我使用的 go-ethereum 代码)
package main
import (
"fmt"
"log"
"os"
"github.com/ethereum/go-ethereum/rpc"
)
func main() {
client, err := rpc.DialHTTP(os.Getenv("RPC_SERVER"))
if err != nil {
log.Fatal(err)
}
defer client.Close()
type request struct {
To string `json:"to"`
Data string `json:"data"`
}
type response struct {
Result string
}
req := request{"0x_MY_CONTRACT_ADDRESS", "0x8da5cb5b"}
var resp response
if err := client.Call(&resp, "eth_call", req, "latest"); err != nil {
log.Fatal(err)
}
fmt.Printf("%v\n", resp)
}
我在这里错过了什么?
预期结果:
字符串格式的地址。例如0x3ab17372b25154400738C04B04f755321bB5a94b
P/S — 我知道abigen并且我知道使用 abigen 做这件事会更好、更容易。但我试图在不使用 abigen 方法的情况下解决这个特定问题。
解决方案
您可以使用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())
}
推荐阅读
- android - 从我的启动器应用程序中显示当前正在运行的应用程序的对话框
- php - 如何通过windo.location.href中的值传递两个变量并在codeigniter视图页面中访问它们
- tensorflow - 如何同时在 CPU 和 GPU 上运行 Keras?
- php - php - 下拉框值无法插入 MySQL
- webpack-4 - webpack4 sideEffects:false 导致编译错误
- javascript - React / Redux 组件获取未使用的参数
- python - GDAL:写入 zip 存档
- accessibility - 如果在“标签”内,屏幕阅读器(iOS 中的 VoiceOver)会忽略“alt”
- android - Firebase Crashlytics 与 UncaughtExceptionHandler
- r - 如何在 R 中不创建替换矩阵?