Go语言调用智能合约
Windows环境下安装gcc环境,参见windows搭建gcc开发环境
用Go来做以太坊开发③交易
用Go来做以太坊开发④智能合约
用Go来做以太坊开发⑤事件日志
使用Go与以太坊智能合约交互
一、win开发环境
找到包的安装路径:github.com/ethereum/go-ethereum/cmd/abigen
go build -i 生成 abigen.exe
使用abigen将abi翻译成go(最好先将abigen.exe拷贝到$PATH的某个路径下)
abigen --abi xx.abi --pkg pkgname --type apiname --out xx.go
二、合并合约
https://github.com/BlockCatIO/solidity-flattener或
https://github.com/coburncoburn/SolidityFlattery.
etherscan上验证合约步骤
$ git clone https://github.com/coburncoburn/SolidityFlattery.git
$ cd SolidityFlattery
$ go get gopkg.in/natefinch/lumberjack.v2
$ go build flat.go utils.go
$ go install flat.go utils.go
$ flat --input TPToken.sol --output verify
过程中可以看到只需要输入TPToken.sol,flat就会自动寻找其依赖的合约。
其中verify为输出文件的名字,可以根据自己习惯设置。
输出文件有两个; verify.log, verify.sol,其中verify.sol就是合并好的用来在etherscan上验证的合约
三、go合约调用
- 连接eth节点
import(
"github.com/ethereum/go-ethereum/ethclient"
store "exch/contracts"
)
//ethclient连接
client, err := ethclient.Dial("https://jsonrpc.medishares.net")
if err != nil {
fmt.Println("Failed to Dial ", err)
return
}
defer client.Close()
import (
"context"
"fmt"
"log"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient")func main() {
client, err := ethclient.Dial("wss://rinkeby.infura.io/ws")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0x147B8eb97fD247D06C4006D269c90C1908Fb5D54")
query := ethereum.FilterQuery{
Addresses: []common.Address{contractAddress},
}
logs := make(chan types.Log)
sub, err := client.SubscribeFilterLogs(context.Background(), query, logs)
if err != nil {
log.Fatal(err)
}
for {
select {
case err := <-sub.Err():
log.Fatal(err)
case vLog := <-logs:
fmt.Println(vLog) // pointer to event log
}
}}