golang以太坊開發介紹
讀取一個賬戶的余額相當簡單。調用客戶端的BalanceAt方法,給它傳遞賬戶地址和可選的區塊號。將區塊號設置為nil將返回最新的余額。
傳區塊號能讓您讀取該區塊時的賬戶余額。區塊號必須是big.Int類型。
account_balance.go 完整代碼
package main import ( "context" "fmt" "log" "math" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://mainnet.infura.io") if err != nil { log.Fatal(err) } account := common.HexToAddress("0x71c7656ec7ab88b098defb751b7401b5f6d8976f") balance, err := client.BalanceAt(context.Background(), account, nil) if err != nil { log.Fatal(err) } fmt.Println(balance) // 25893180161173005034 blockNumber := big.NewInt(5532993) balanceAt, err := client.BalanceAt(context.Background(), account, blockNumber) if err != nil { log.Fatal(err) } fmt.Println(balanceAt) // 25729324269165216042 fbalance := new(big.Float) fbalance.SetString(balanceAt.String()) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(math.Pow10(18))) fmt.Println(ethValue) // 25.729324269165216041 pendingBalance, err := client.PendingBalanceAt(context.Background(), account) fmt.Println(pendingBalance) // 25729324269165216042 }
運行代碼查看效果
先下載需要的包(會下載到gopath里面)。
go get github.com/ethereum/go-ethereum/common
go get github.com/ethereum/go-ethereum/ethclient
注意:由於用命令下載速度很慢,容易導致部分文件下載失敗,可以去github上手動下載zip包,解壓后放在gopath相應目錄下。
如果存在的需要加-u參數進行更新,如:go get -u github.com/ethereum/go-ethereum/common
在運行go程序時,出現報錯:cannot find package "golang.org/X/crypto/sha3" in any of 或者 cannot find package "golang.org/x/net/websocket" in any of
解決方案:
git clone https://github.com/golang/crypto.git
git clone https://github.com/golang/sys.git
git clone https://github.com/golang/net.git
將下載的包放在GOPATH對應的路徑下的(\gopath\src\golang.org\X )
注意:.git隱藏文件夾,.gitattributes,.gitignore 不要拷貝過去,否則再執行其他命令就會報錯
在運行時報錯:exec: "gcc": executable file not found in %PATH%。原因是沒有安裝gcc環境造成的。解決方案:
Mac OS最快捷的獲取gcc的方法是從蘋果的網站上下載Xcode開發環境,並按說明進行安裝。一旦安裝上Xcode,你就能使用gcc了。
在Windows上安裝gcc,需要下載 MinGW 安裝。下載后按提示一步步安裝即可。
安裝完成后,在命令行輸入 gcc -v 查看安裝是否成功,如沒有成功,需要手動配置環境變量。
假設安裝在C:\MinGW目錄下,則需要在path下添加路徑C:\MinGW\bin。設置好之后,重新打開命令窗口,重新編譯Go程序,一般就可以執行了。
如果還不行,通常是由於環境變量沒有啟動造成的,需要重啟電腦測試。
如果報錯:cc1.exe: sorry, unimplemented: 64-bit mode not compiled in
原因是gcc版本不是64位的,在64位環境下無法編譯,需要將mingw32換成mingw64。
下載安裝包:http://mingw-w64.org/doku.php/download/mingw-builds 選擇x86_64版本安裝
默認安裝在 C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64
安裝完成后添加環境變量GCC_HOME,內容為上面的安裝路徑(最后這個\mingw64是安裝后加上的),在path下添加%GCC_HOME%\bin。
同時去掉32位的環境變量配置。
重新打開命令窗口,輸入 gcc -v 查看安裝是否成功
到存放代碼的文件夾下,執行運行命令:
go run account_balance.go
window下還是有很多莫名其妙的問題,版本不兼容等各種問題層出不窮。
可以考慮這個套件的方式:https://github.com/ethereum/go-ethereum/wiki/Installation-instructions-for-Windows ,但測試了下需要docker的,情況可能又更復雜了
主要參考開源文檔:https://goethereumbook.org/zh/ 更多內容請訪問該網址。