概述: 用Go加载和初始化智能合约的教程。
加载智能合约
这写章节需要了解如何将智能合约的ABI编译成Go的合约文件。如果你还没看, 前先读上一个章节 。
一旦使用abigen
工具将智能合约的ABI编译为Go包,下一步就是调用“New”方法,其格式为“New
address := common.HexToAddress("0x147B8eb97fD247D06C4006D269c90C1908Fb5D54")
instance, err := store.NewStore(address, client)
if err != nil {
log.Fatal(err)
}
_ = instance // we'll be using this in the 下个章节
完整代码
Commands
solc --abi Store.sol
solc --bin Store.sol
abigen --bin=Store_sol_Store.bin --abi=Store_sol_Store.abi --pkg=store --out=Store.go
pragma solidity ^0.4.24;
contract Store {
event ItemSet(bytes32 key, bytes32 value);
string public version;
mapping (bytes32 => bytes32) public items;
constructor(string _version) public {
version = _version;
}
function setItem(bytes32 key, bytes32 value) external {
items[key] = value;
emit ItemSet(key, value);
}
}
package main
import (
"fmt"
"log"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
store "./contracts" // for demo
)
func main() {
client, err := ethclient.Dial("https://rinkeby.infura.io")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x147B8eb97fD247D06C4006D269c90C1908Fb5D54")
instance, err := store.NewStore(address, client)
if err != nil {
log.Fatal(err)
}
fmt.Println("contract is loaded")
_ = instance
}
solc version used for these examples
$ solc --version
0.4.24+commit.e67f0147.Emscripten.clang
最后编辑: kuteng 文档更新时间: 2021-10-19 16:44 作者:kuteng