搭建以太坊环境
讲解以太坊开发环境搭建,包括编译 go-ethereum、使用 clef 导入账户、同步 Sepolia 测试网数据以及通过 API 查询账户余额。
搭建以太坊环境
- 代码编译
下载go-ethereum
构建make all
构建成功如下
- 创建账户
可以通过clef来生成账户。 由于我已经存在账户,导入已经账户。 将metamask账户的私钥导入(切忌泄露)。 clef importraw file 可以看到通过私钥算出我的账户(EOA)
由于创建transaction需要签名 执行clef --chainid 11155111(Sepolia testnet) 命令
- 同步数据
geth --sepolia --authrpc.addr localhost --authrpc.port 8551 --authrpc.vhosts localhost --http --http.api eth,net (网络无法连接enode,放弃治疗)
- 接入api
查询账户余额
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)
const API_ADDRESS = "https://api-sepolia.etherscan.io/api"
const ADDRESS = "0x2578205BAfEACD598773dF05E2192efc7835c59E"
const API_KEY = "your api key"
type ether struct {
tag string `map:"tag,omitempty"`
address string `map:"address,omitempty"`
apikey string `map:"apikey,omitempty"`
}
type etherAccount struct {
ether
module string `map:"module,omitempty"`
action string `map:"action,omitempty"`
}
type etherAccountResp struct {
Status string `json:"status"`
Message string `json:"message"`
Result string `json:"result"`
}
func newEther() ether {
return ether{
tag: "latest",
address: ADDRESS,
apikey: API_KEY,
}
}
func newEtherAccount(module, action string) *etherAccount {
ether := newEther()
var account etherAccount
account.module = module
account.action = action
account.apikey = ether.apikey
account.tag = ether.tag
account.address = ether.address
return &account
}
func main() {
module := "account"
action := "balance"
account := newEtherAccount(module, action)
params := url.Values{}
params.Add("tag", account.tag)
params.Add("address", account.address)
params.Add("apikey", account.apikey)
params.Add("module", account.module)
params.Add("action", account.action)
accountUrl, _ := url.Parse(API_ADDRESS)
accountUrl.RawQuery = params.Encode()
proxy, _ := url.Parse("http://127.0.0.1:7890")
client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxy)}}
resp, err := client.Get(accountUrl.String())
if err != nil {
panic(err.Error())
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var accountResp etherAccountResp
json.Unmarshal(body, &accountResp)
fmt.Printf(" %+v ", accountResp)
}
api返回的余额
etherscan账户的余额