准备好solc和abigen工具,可以参考使用go-ethereum操作简单智能合约
项目完整代码git地址
项目目录
➜ erc20_demo tree -L 2
.
├── UTC--2020-06-23T12-24-37.353894000Z--e0380828902269bfbce6b056ae3bfce8d52fd6a8
├── contracts
│ ├── ERC20Token.go
│ ├── ERC20Token.sol
├── deploy.go
├── go.mod
└── go.sum
准备一份合约文件,这里参考OpenZeppelin模版写的简单版,仅用于测试。
contracts/ERC20Token.sol
确保solc命令可用后执行后生成ERC20Token.go文件(pkg指的是ERC20Token.go的package):
abigen -sol contracts/ERC20Token.sol -pkg contracts -out contracts/ERC20Token.go
调用DeployERC20Token方法部署合约,初始化200000000个代币,name为PokeCoin,缩写PKC。
data, _ := ioutil.ReadFile(key)
auth, err := bind.NewTransactor(strings.NewReader(string(data)), "123456")
if err != nil {
log.Fatalf("Failed to create authorized transactor:%v \n", err)
}
address, _, _, err := contracts.DeployERC20Token(
auth,
blockchain,
big.NewInt(200000000),
"PokeCoin",
"PKC",
)
if err != nil {
log.Fatalf("deploy %v \n", err)
}
fmt.Printf("Contract pending deploy:0x%x \n", address)
运行后得到一个合约地址和pending交易状态,部署成功。
Contract pending deploy:0x367c02fe50380b36477f5bfa1701a3a06e393f17
在geth终端上运行miner.start()挖矿后,调用BalanceOf方法查询在合约上的代币余额,得到余额200000000。
accountBalance, err := contract.BalanceOf(nil, common.HexToAddress("0xf490774d9b87f4d379c2a789e5755156c1c370bc"))
if err != nil {
log.Fatalf("get Balances err: %v \n", err)
}
fmt.Println(accountBalance)
签名后生成转账交易,用当前账户auth.From的余额给一个新的账户转520个代币。
tx, err := contract.Transfer(&bind.TransactOpts{
From: auth.From,
Signer: auth.Signer,
Value: nil,
}, common.HexToAddress("0xf490774d9b87f4d379c2a789e5755156c1c370bc"), big.NewInt(520))
if err != nil {
log.Fatalf("TransferFrom err: %v \n", err)
}
fmt.Printf("tx sent: %s \n", tx.Hash().Hex())
得到一个tx交易记录。
tx sent: 0x6fbf00c5acb12cc07ef89eafcb1c5f57652ab7c74fd156f822280b49df4cdd44
挖矿后再次查询两个用户的余额。
var accountBalance = big.NewInt(0)
if accountBalance, err = contract.BalanceOf(nil, auth.From); err != nil {
log.Fatalf("get Balances err: %v \n", err)
}
fmt.Println(accountBalance)
if accountBalance, err = contract.BalanceOf(nil, common.HexToAddress("0xf490774d9b87f4d379c2a789e5755156c1c370bc")); err != nil {
log.Fatalf("get Balances err: %v \n", err)
}
fmt.Println(accountBalance)
发现为199999480和520,转账成功
➜ erc20_demo go run deploy.go
199999480
520
参考:
https://goethereumbook.org/zh
https://github.com/OpenZeppelin