我正在創(chuàng)建一系列非常容易理解的文章,這些文章既解釋了我所做的事情,也讓我重寫從舊的混亂黑客到希望更清潔版本的所有內容。
使測試環(huán)境成為可能的單個主要組件是構建在geth源庫中的模擬后端。模擬的后端是一個geth-ethereum虛擬機,您可以初始化、提交事務、密封塊,實際上,將其視為私有區(qū)塊鏈節(jié)點。
因此讓我們從一個極其簡單的例子開始——創(chuàng)建一個模擬區(qū)塊鏈,其中一個賬戶持有特定數量的以太。我通常使用一個名為getclient的函數來連接到我正在使用的后端。
我們使用memorykeys庫中的getaddress返回一個綁定到角色的地址?!?〕〔2〕
我們使用etherutils庫中的strtoether返回一個表示ether值的大int值a字符串[3]
var baseClient *backends.SimulatedBackend
func getClient() (client *backends.SimulatedBackend, err error) {
if baseClient != nil {
return baseClient, nil
}
funds, _ := etherUTIls.StrToEther(“10000.0”)
baseClient = backends.NewSimulatedBackend(core.GenesisAlloc{
getAddress(“banker”): {Balance: funds},
}, 8000000)
return baseClient, nil
}
我們現在有一個后端系統,有一個賬戶(我稱之為銀行家),余額為10000以太。
你可以用下面的代碼進行操作
func main() {
client, err := getClient()
if err != nil {
log.Fatal(err)
}
bal, err := client.BalanceAt(context.Background(), getAddress(“banker”), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(etherUTIls.EtherToStr(bal))
}
假設您已添加GETH,memorykeys和etherUTIls,您的環(huán)境現在應該為您設置導入,您將看到顯示10k以太的余額
go run sbe.go keyUTIls.go
10000.000000000000000000