etherkit

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 17, 2025 License: MIT Imports: 23 Imported by: 0

README

go-ether-kit

Go Version

go-ether-kit 是一个功能强大的以太坊及 EVM 兼容网络开发工具包,提供简洁易用的 API 来进行链上交互、钱包管理和智能合约操作。

✨ 特性

  • 🔐 钱包管理:支持私钥、助记词、随机生成等多种方式创建账户
  • 🌐 网络连接:轻松连接以太坊主网、测试网及其他 EVM 兼容网络
  • 💰 交易操作:完整的交易构建、签名、发送流程
  • 📄 智能合约:合约调用、事件监听、ABI 处理
  • 🪙 代币支持:内置 ERC20 代币操作支持
  • 🔧 实用工具:单位转换、地址验证、签名验证等
  • ⚡ 自动化:自动计算 nonce、gas price 等参数
  • 🔍 链上查询:区块、交易、余额等数据查询

📦 安装

go get github.com/guanzhenxing/go-ether-kit

🚀 快速开始

创建钱包连接
package main

import (
    "fmt"
    "log"
    "github.com/guanzhenxing/go-ether-kit"
)

func main() {
    // 使用私钥创建钱包
    privateKey := "your_private_key_here"
    rpcURL := "https://eth-mainnet.g.alchemy.com/v2/your-api-key"
    
    wallet, err := etherkit.NewWallet(privateKey, rpcURL)
    if err != nil {
        log.Fatal(err)
    }
    defer wallet.CloseWallet()
    
    // 获取账户地址
    address := wallet.GetAddress()
    fmt.Printf("钱包地址: %s\n", address.Hex())
    
    // 获取余额
    balance, err := wallet.GetBalance()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("ETH 余额: %s\n", etherkit.ToDecimal(balance, etherkit.EthDecimals))
}
发送 ETH 转账
func sendETH(wallet *etherkit.Wallet) {
    toAddress := common.HexToAddress("0x742F35Cc6634C0532925a3b8D6dA2e")
    amount := etherkit.ToWei("0.1", etherkit.EthDecimals) // 0.1 ETH
    
    txHash, err := wallet.SendTx(
        toAddress,     // 收款地址
        0,             // nonce (0 表示自动计算)
        0,             // gasLimit (0 表示自动估算)
        nil,           // gasPrice (nil 表示自动获取)
        amount,        // 转账金额
        nil,           // 交易数据
    )
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("交易哈希: %s\n", txHash.Hex())
}
ERC20 代币操作
import (
    "github.com/guanzhenxing/go-ether-kit/contracts/erc20"
)

func transferToken(wallet *etherkit.Wallet) {
    tokenAddress := common.HexToAddress("0xA0b86a33E6411b6dE9C80e7F8DeD6c") // USDC 地址
    
    // 创建 ERC20 合约实例
    token, err := erc20.NewIERC20(tokenAddress, wallet.GetClient())
    if err != nil {
        log.Fatal(err)
    }
    
    // 构建交易选项
    opts, err := wallet.BuildTxOpts(
        big.NewInt(0),    // value
        nil,              // nonce (自动计算)
        nil,              // gasPrice (自动获取)
    )
    if err != nil {
        log.Fatal(err)
    }
    
    // 转账代币
    toAddress := common.HexToAddress("0x742F35Cc6634C0532925a3b8D6dA2e")
    amount := etherkit.ToWei("100", etherkit.USDCDecimals) // 100 USDC
    
    tx, err := token.Transfer(opts, toAddress, amount)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("代币转账交易: %s\n", tx.Hash().Hex())
}
智能合约调用
func callContract(wallet *etherkit.Wallet) {
    contractAddress := common.HexToAddress("0x...")
    abiString := `[{"inputs":[],"name":"totalSupply","outputs":[{"type":"uint256"}],"type":"function"}]`
    
    // 获取合约 ABI
    contractAbi, err := etherkit.GetABI(abiString)
    if err != nil {
        log.Fatal(err)
    }
    
    // 调用合约方法 (只读)
    result, err := wallet.CallContract(contractAddress, contractAbi, "totalSupply")
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("总供应量: %v\n", result[0])
}

📚 API 文档

Provider (网络提供者)
// 创建网络连接
provider, err := etherkit.NewProvider("https://eth-mainnet.g.alchemy.com/v2/your-api-key")
provider, err := etherkit.NewProviderWithChainId("https://polygon-rpc.com", 137)

// 基本查询
chainID, err := provider.GetChainID()
blockNumber, err := provider.GetBlockNumber() 
gasPrice, err := provider.GetSuggestGasPrice()
block, err := provider.GetBlockByNumber(big.NewInt(123456))
receipt, err := provider.GetTransactionReceipt(txHash)
Signer (签名器)
// 多种创建方式
signer, err := etherkit.NewSigner()                              // 随机生成
signer, err := etherkit.NewSignerFromHexPrivateKey("0x...")      // 私钥
signer, err := etherkit.NewSignerFromMnemonic("word1 word2...")  // 助记词

// 获取账户信息  
address := signer.GetAddress()
privateKey := signer.GetPrivateKey()
Wallet (钱包)
// 创建钱包
wallet, err := etherkit.NewWallet(privateKey, rpcURL)

// 账户操作
address := wallet.GetAddress()
balance, err := wallet.GetBalance()
nonce, err := wallet.GetNonce()

// 交易操作
tx, err := wallet.NewTx(toAddr, nonce, gasLimit, gasPrice, value, data)
txHash, err := wallet.SendTx(toAddr, nonce, gasLimit, gasPrice, value, data)
signedTx, err := wallet.SignTx(tx)
工具函数
// 单位转换
wei := etherkit.ToWei("1.5", etherkit.EthDecimals)     // 1.5 ETH 转 wei
eth := etherkit.ToDecimal(wei, etherkit.EthDecimals)   // wei 转 ETH

// 地址验证
isValid := etherkit.IsValidAddress("0x...")

// 签名验证  
isValid := etherkit.VerifySignature(address, data, signature)

// 合约工具
methodID := etherkit.GetContractMethodId("transfer(address,uint256)")
eventTopic := etherkit.GetEventTopic("Transfer(address,address,uint256)")

// 常量使用
chainID := etherkit.MainnetChainID  // 主网链ID
gasPrice := etherkit.DefaultGasPriceBig  // 默认Gas价格

📁 项目结构

go-ether-kit/
├── provider.go        # 网络连接和查询
├── signer.go          # 账户和签名管理
├── wallet.go          # 钱包操作
├── address.go         # 地址相关工具
├── crypto.go          # 加密相关功能
├── contract.go        # 智能合约工具
├── transaction.go     # 交易相关功能
├── convert.go         # 单位转换工具
├── constants.go       # 常量定义
├── errors.go          # 错误定义
├── contracts/         # 智能合约绑定
│   └── erc20/        # ERC20 合约
│       └── erc20.go
├── examples/          # 使用示例
│   ├── basic/        # 基础功能示例
│   ├── erc20/        # ERC20 操作示例
│   ├── advanced/     # 高级功能示例
│   └── README.md
├── *_test.go         # 单元测试文件
├── go.mod
├── go.sum
├── Makefile          # 构建和开发工具
├── LICENSE
└── README.md

🚀 最新改进 (v2.0)

项目结构优化
  • ✅ 扁平化包结构 - 代码直接位于根目录,无需子包导入
  • ✅ 模块化文件组织 - 按功能拆分为专门文件
  • ✅ 统一错误处理 - 标准化错误定义和处理
  • ✅ 丰富的常量库 - 预定义网络、Gas、地址等常量
代码质量提升
  • ✅ 完整单元测试 - 全面的测试覆盖
  • ✅ 详细使用示例 - 基础、ERC20、高级功能示例
  • ✅ 性能基准测试 - 关键功能性能监控
  • ✅ 标准化命名 - 更符合Go语言习惯
开发体验改善
  • ✅ Makefile 工具 - 完整的开发和构建工具链
  • ✅ 丰富文档 - 详细的API文档和使用指南
  • ✅ 错误提示优化 - 清晰的错误信息和调试支持

🌐 支持的网络

网络名称 Chain ID 符号 区块时间 确认数
Ethereum Mainnet 1 ETH 12s 12
Goerli Testnet 5 ETH 12s 3
Sepolia Testnet 11155111 ETH 12s 3
Polygon 137 MATIC 2s 20
BSC 56 BNB 3s 15
Arbitrum One 42161 ETH - -
Optimism 10 ETH - -

使用预定义常量:

// 直接使用链ID常量
provider := etherkit.NewProviderWithChainId(rpcURL, etherkit.MainnetChainID)

// 获取网络配置
config := etherkit.NetworkConfigs[etherkit.PolygonChainID]
fmt.Printf("网络: %s, 符号: %s\n", config.Name, config.Symbol)

🔧 高级用法

批量操作
// 批量查询余额
addresses := []common.Address{addr1, addr2, addr3}
for _, addr := range addresses {
    balance, _ := provider.GetEthClient().BalanceAt(context.Background(), addr, nil)
    fmt.Printf("地址 %s 余额: %s ETH\n", addr.Hex(), etherkit.ToDecimal(balance, 18))
}
事件监听
// 监听 ERC20 Transfer 事件
query := ethereum.FilterQuery{
    Addresses: []common.Address{tokenAddress},
    Topics: [][]common.Hash{
        {common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef")},
    },
}

logs := make(chan types.Log)
sub, err := provider.GetEthClient().SubscribeFilterLogs(context.Background(), query, logs)
if err != nil {
    log.Fatal(err)
}

for {
    select {
    case err := <-sub.Err():
        log.Fatal(err)
    case vLog := <-logs:
        fmt.Printf("发现 Transfer 事件: %s\n", vLog.TxHash.Hex())
    }
}

🤝 贡献

欢迎提交 Issue 和 Pull Request!

  1. Fork 项目
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 打开 Pull Request

📄 许可证

本项目基于 MIT 许可证开源 - 查看 LICENSE 文件了解详情。

🔗 相关资源

📞 支持

如有问题或建议,请:


⭐ 如果这个项目对你有帮助,请给个 Star!

Documentation

Index

Constants

View Source
const (
	MainnetChainID   = 1
	GoerliChainID    = 5
	SepoliaChainID   = 11155111
	PolygonChainID   = 137
	BSCChainID       = 56
	ArbitrumChainID  = 42161
	OptimismChainID  = 10
	AvalancheChainID = 43114
	FantomChainID    = 250
)

网络链ID常量

View Source
const (
	DefaultGasLimit  = 21000         // ETH 转账默认 gas limit
	ContractGasLimit = 200000        // 合约调用默认 gas limit
	DefaultGasPrice  = 20000000000   // 20 Gwei
	MaxGasPrice      = 1000000000000 // 1000 Gwei
	MinGasPrice      = 1000000000    // 1 Gwei
)

Gas 相关常量

View Source
const (
	ERC20TransferGasLimit = 65000
	ERC20ApproveGasLimit  = 50000
	UniswapSwapGasLimit   = 300000
)

常用 Gas Limit

View Source
const (
	DefaultTimeout        = 30
	BlockConfirmationTime = 12  // 以太坊平均出块时间
	FastConfirmationTime  = 15  // 快速确认超时
	SafeConfirmationTime  = 180 // 安全确认超时
)

时间相关常量 (秒)

View Source
const (
	Wei   = 1
	GWei  = 1000000000
	Ether = 1000000000000000000
)

以太坊单位常量

View Source
const (
	EthDecimals     = 18
	USDCDecimals    = 6
	USDTDecimals    = 6
	DefaultDecimals = 18
)

默认小数位数

View Source
const (
	// 零地址
	ZeroAddress = "0x0000000000000000000000000000000000000000"
	// 原生代币地址 (用于表示 ETH/BNB/MATIC 等)
	NativeTokenAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"
)

常用地址

View Source
const (
	ERC20TransferMethodID     = "0xa9059cbb"
	ERC20TransferFromMethodID = "0x23b872dd"
	ERC20ApproveMethodID      = "0x095ea7b3"
	ERC20BalanceOfMethodID    = "0x70a08231"
	ERC20TotalSupplyMethodID  = "0x18160ddd"
)

ERC20 常用方法选择器

View Source
const (
	ERC20TransferEventTopic = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
	ERC20ApprovalEventTopic = "0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925"
)

ERC20 常用事件主题

View Source
const (
	ZeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000"
)

常用哈希

Variables

View Source
var (
	BigInt0   = big.NewInt(0)
	BigInt1   = big.NewInt(1)
	BigInt2   = big.NewInt(2)
	BigInt10  = big.NewInt(10)
	BigInt100 = big.NewInt(100)

	// Gas 价格常量
	DefaultGasPriceBig = big.NewInt(DefaultGasPrice)
	MinGasPriceBig     = big.NewInt(MinGasPrice)
	MaxGasPriceBig     = big.NewInt(MaxGasPrice)

	// Gas limit 常量
	DefaultGasLimitBig       = big.NewInt(DefaultGasLimit)
	ContractGasLimitBig      = big.NewInt(ContractGasLimit)
	ERC20TransferGasLimitBig = big.NewInt(ERC20TransferGasLimit)
	ERC20ApproveGasLimitBig  = big.NewInt(ERC20ApproveGasLimit)

	// 单位转换常量
	WeiPerEther = big.NewInt(Ether)
	WeiPerGWei  = big.NewInt(GWei)
)

常用 big.Int 常量

View Source
var (
	// 网络相关错误
	ErrNetworkConnection = errors.New("failed to connect to ethereum network")
	ErrInvalidRPCURL     = errors.New("invalid RPC URL")
	ErrNetworkTimeout    = errors.New("network request timeout")

	// 地址相关错误
	ErrInvalidAddress = errors.New("invalid ethereum address")
	ErrZeroAddress    = errors.New("address cannot be zero address")

	// 私钥相关错误
	ErrInvalidPrivateKey = errors.New("invalid private key")
	ErrInvalidMnemonic   = errors.New("invalid mnemonic phrase")
	ErrInvalidKeyFormat  = errors.New("invalid key format")

	// 交易相关错误
	ErrInsufficientFunds = errors.New("insufficient funds for transaction")
	ErrInvalidGasPrice   = errors.New("invalid gas price")
	ErrInvalidGasLimit   = errors.New("invalid gas limit")
	ErrInvalidNonce      = errors.New("invalid nonce")
	ErrTransactionFailed = errors.New("transaction execution failed")

	// 合约相关错误
	ErrContractCall           = errors.New("contract call failed")
	ErrInvalidABI             = errors.New("invalid contract ABI")
	ErrInvalidContractAddress = errors.New("invalid contract address")

	// 签名相关错误
	ErrSignatureFailed             = errors.New("signature generation failed")
	ErrInvalidSignature            = errors.New("invalid signature")
	ErrSignatureVerificationFailed = errors.New("signature verification failed")

	// 钱包相关错误
	ErrWalletClosed        = errors.New("wallet connection is closed")
	ErrInvalidWalletConfig = errors.New("invalid wallet configuration")
)

标准错误定义

View Source
var NetworkConfigs = map[int64]NetworkConfig{
	MainnetChainID: {
		ChainID:       MainnetChainID,
		Name:          "Ethereum Mainnet",
		Symbol:        "ETH",
		BlockTime:     12,
		Confirmations: 12,
	},
	GoerliChainID: {
		ChainID:       GoerliChainID,
		Name:          "Goerli Testnet",
		Symbol:        "ETH",
		BlockTime:     12,
		Confirmations: 3,
	},
	SepoliaChainID: {
		ChainID:       SepoliaChainID,
		Name:          "Sepolia Testnet",
		Symbol:        "ETH",
		BlockTime:     12,
		Confirmations: 3,
	},
	PolygonChainID: {
		ChainID:       PolygonChainID,
		Name:          "Polygon",
		Symbol:        "MATIC",
		BlockTime:     2,
		Confirmations: 20,
	},
	BSCChainID: {
		ChainID:       BSCChainID,
		Name:          "Binance Smart Chain",
		Symbol:        "BNB",
		BlockTime:     3,
		Confirmations: 15,
	},
}

预定义网络配置

Functions

func BuildContractInputData

func BuildContractInputData(contract abi.ABI, name string, args ...interface{}) ([]byte, error)

BuildContractInputData 构建合约的input data

func BuildPrivateKeyFromHex

func BuildPrivateKeyFromHex(privateKeyHex string) (*ecdsa.PrivateKey, error)

BuildPrivateKeyFromHex 从字符串私钥构建私钥对象

func BuildPrivateKeyFromMnemonic

func BuildPrivateKeyFromMnemonic(mnemonic string) (*ecdsa.PrivateKey, error)

func BuildPrivateKeyFromMnemonicAndAccountId

func BuildPrivateKeyFromMnemonicAndAccountId(mnemonic string, accountId uint32) (*ecdsa.PrivateKey, error)

BuildPrivateKeyFromMnemonicAndAccountId 从助记词获得私钥

func DecodeRawTxHex

func DecodeRawTxHex(rawTx string) (*types.Transaction, error)

DecodeRawTxHex 解析rawTx

func GeneratePrivateKey

func GeneratePrivateKey() (*ecdsa.PrivateKey, error)

GeneratePrivateKey 创建私钥

func GetABI

func GetABI(abiStr string) (abi.ABI, error)

GetABI 从abi字符串中获得ABI对象

func GetContractMethodId

func GetContractMethodId(method string) string

GetContractMethodId 获得合约的methodId 参数method,如:transfer(address,uint256)

func GetEventTopic

func GetEventTopic(event string) string

GetEventTopic 获得事件的topic。event字符串如:transfer(address,uint256)

func GetHexPrivateKey

func GetHexPrivateKey(privateKey *ecdsa.PrivateKey) string

GetHexPrivateKey 创建十六进制的私钥(不以0x开头)

func GetHexPublicKey

func GetHexPublicKey(privateKey *ecdsa.PrivateKey) string

GetHexPublicKey 从私钥中获得十六进制的公钥(不以0x和04开头)

func GetMaxUint256

func GetMaxUint256() *big.Int

GetMaxUint256 获得合约中MaxUint256

func IsValidAddress

func IsValidAddress(iAddress interface{}) bool

IsValidAddress 验证是否是十六进制地址

func NewTx

func NewTx(to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, data []byte) (*types.Transaction, error)

NewTx 新建一个tx

func NewTxWithHexData

func NewTxWithHexData(to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, hexData string) (*types.Transaction, error)

NewTxWithHexData 基于hexData构建一个Tx

func PrivateKeyToAddress

func PrivateKeyToAddress(privateKey *ecdsa.PrivateKey) common.Address

PrivateKeyToAddress 从私钥中获得地址

func PublicKeyBytesToAddress

func PublicKeyBytesToAddress(publicKey []byte) common.Address

PublicKeyBytesToAddress 公钥到地址

func ToDecimal

func ToDecimal(iValue interface{}, decimals int) decimal.Decimal

ToDecimal wei to decimals

func ToWei

func ToWei(iAmount interface{}, decimals int) *big.Int

ToWei decimals to wei

func VerifySignature

func VerifySignature(address string, data, signature []byte) bool

VerifySignature 验证签名 address: 用于签名的地址 digestHash: 用于验证的原始数据 signature: 需要进行验证的签名数据

Types

type EtherProvider

type EtherProvider interface {
	GetEthClient() *ethclient.Client
	GetRpcClient() *rpc.Client
	Close()
	GetNetworkID() (*big.Int, error)
	GetChainID() (*big.Int, error)
	GetBlockByHash(hash common.Hash) (*types.Block, error)
	GetBlockByNumber(number *big.Int) (*types.Block, error)
	GetBlockNumber() (uint64, error)
	GetSuggestGasPrice() (*big.Int, error)
	GetTransactionByHash(hash common.Hash) (tx *types.Transaction, isPending bool, err error)
	GetTransactionReceipt(txHash common.Hash) (*types.Receipt, error)
	GetContractBytecode(address common.Address) (string, error)
	IsContractAddress(address common.Address) (bool, error)
	EstimateGas(from, to common.Address, nonce uint64, gasPrice, value *big.Int, data []byte) (uint64, error)
	GetFromAddress(tx *types.Transaction) (common.Address, error)
}

EtherProvider 需要通过链上查询的,但是不需要账户的

type EtherSigner

type EtherSigner interface {
	GetAddress() common.Address
	GetPrivateKey() *ecdsa.PrivateKey
}

EtherSigner ETH账户

type EtherWallet

type EtherWallet interface {
	GetEthSigner() EtherSigner
	GetEthProvider() EtherProvider
	GetClient() *ethclient.Client
	GetAddress() common.Address
	CloseWallet()
	GetNonce() (uint64, error)
	GetBalance() (*big.Int, error)
	NewTx(to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, data []byte) (*types.Transaction, error)
	SendTx(to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, data []byte) (common.Hash, error)
	NewTxWithHexInput(to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, input string) (*types.Transaction, error)
	SendTxWithHexInput(to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, input string) (common.Hash, error)
	BuildTxOpts(value, nonce, gasPrice *big.Int) (*bind.TransactOpts, error)
	SignTx(tx *types.Transaction) (*types.Transaction, error)
	SendSignedTx(signedTx *types.Transaction) (common.Hash, error)
	Signature(data []byte) ([]byte, error)
	CallContract(contractAddress common.Address, contractAbi abi.ABI, functionName string, params ...interface{}) ([]interface{}, error)
}

EtherWallet 钱包信息

type NetworkConfig

type NetworkConfig struct {
	ChainID       int64
	Name          string
	Symbol        string
	BlockTime     int // 秒
	Confirmations int
}

网络配置

type Provider

type Provider struct {
	// contains filtered or unexported fields
}

func NewProvider

func NewProvider(rawUrl string) (*Provider, error)

func NewProviderWithChainId

func NewProviderWithChainId(rawUrl string, chainId int64) (*Provider, error)

func (*Provider) Close

func (p *Provider) Close()

Close 关闭ethClient客户端和rpcClient客户端

func (*Provider) EstimateGas

func (p *Provider) EstimateGas(from, to common.Address, nonce uint64, gasPrice, value *big.Int, data []byte) (uint64, error)

EstimateGas 预估手续费

func (*Provider) GetBlockByHash

func (p *Provider) GetBlockByHash(blkHash common.Hash) (*types.Block, error)

GetBlockByHash 根据区块Hash获得区块信息

func (*Provider) GetBlockByNumber

func (p *Provider) GetBlockByNumber(number *big.Int) (*types.Block, error)

GetBlockByNumber 根据区块号获得区块信息

func (*Provider) GetBlockNumber

func (p *Provider) GetBlockNumber() (uint64, error)

GetBlockNumber 获得最新区块

func (*Provider) GetChainID

func (p *Provider) GetChainID() (*big.Int, error)

GetChainID 获得ChainId

func (*Provider) GetContractBytecode

func (p *Provider) GetContractBytecode(address common.Address) (string, error)

GetContractBytecode 根据合约地址获得bytecode

func (*Provider) GetEthClient

func (p *Provider) GetEthClient() *ethclient.Client

GetEthClient 获得ethClient客户端

func (*Provider) GetFromAddress

func (p *Provider) GetFromAddress(tx *types.Transaction) (common.Address, error)

GetFromAddress 获得交易的fromAddress

func (*Provider) GetNetworkID

func (p *Provider) GetNetworkID() (*big.Int, error)

GetNetworkID 获得NetworkId

func (*Provider) GetRpcClient

func (p *Provider) GetRpcClient() *rpc.Client

GetRpcClient 获得rpcClient客户端

func (*Provider) GetSuggestGasPrice

func (p *Provider) GetSuggestGasPrice() (*big.Int, error)

GetSuggestGasPrice 获得建议的Gas

func (*Provider) GetTransactionByHash

func (p *Provider) GetTransactionByHash(txHash common.Hash) (tx *types.Transaction, isPending bool, err error)

GetTransactionByHash 根据txHash获得交易信息

func (*Provider) GetTransactionReceipt

func (p *Provider) GetTransactionReceipt(txHash common.Hash) (*types.Receipt, error)

GetTransactionReceipt 根据txHash获得交易Receipt

func (*Provider) IsContractAddress

func (p *Provider) IsContractAddress(address common.Address) (bool, error)

IsContractAddress 是否是合约地址。

type Signer

type Signer struct {
	// contains filtered or unexported fields
}

func NewSigner

func NewSigner() (*Signer, error)

NewSigner 创建一个默认的账号信息

func NewSignerFromHexPrivateKey

func NewSignerFromHexPrivateKey(hexPk string) (*Signer, error)

NewSignerFromHexPrivateKey 使用私钥创建一个账号信息

func NewSignerFromMnemonic

func NewSignerFromMnemonic(mnemonic string) (*Signer, error)

NewSignerFromMnemonic 使用助记词创建一个账号信息

func NewSignerFromMnemonicAndAccountId

func NewSignerFromMnemonicAndAccountId(mnemonic string, accountId uint32) (*Signer, error)

NewSignerFromMnemonicAndAccountId 使用助记词创建一个账号信息

func NewSignerFromPrivateKey

func NewSignerFromPrivateKey(pk *ecdsa.PrivateKey) (*Signer, error)

NewSignerFromPrivateKey 使用私钥创建一个账号信息

func NewSignerFromRawPrivateKey

func NewSignerFromRawPrivateKey(rawPk []byte) (*Signer, error)

NewSignerFromRawPrivateKey 使用私钥创建一个账号信息

func (*Signer) GetAddress

func (s *Signer) GetAddress() common.Address

GetAddress 获得地址

func (*Signer) GetPrivateKey

func (s *Signer) GetPrivateKey() *ecdsa.PrivateKey

GetPrivateKey 获得私钥

type Wallet

type Wallet struct {
	// contains filtered or unexported fields
}

func NewWallet

func NewWallet(hexPk string, rawUrl string) (*Wallet, error)

NewWallet 新建一个Wallet

func NewWalletWithComponents

func NewWalletWithComponents(es EtherSigner, ep EtherProvider) (*Wallet, error)

NewWalletWithComponents creates a new Wallet with given signer and provider components

func (*Wallet) BuildTxOpts

func (w *Wallet) BuildTxOpts(value, nonce, gasPrice *big.Int) (*bind.TransactOpts, error)

BuildTxOpts 构建交易的选项

func (*Wallet) CallContract

func (w *Wallet) CallContract(contractAddress common.Address, contractAbi abi.ABI, functionName string, params ...interface{}) ([]interface{}, error)

CallContract 调用合约的方法,无需创建交易

func (*Wallet) CloseWallet

func (w *Wallet) CloseWallet()

CloseWallet 关闭Wallet

func (*Wallet) GetAddress

func (w *Wallet) GetAddress() common.Address

GetAddress 获得地址

func (*Wallet) GetBalance

func (w *Wallet) GetBalance() (*big.Int, error)

GetBalance 获得本位币的约

func (*Wallet) GetClient

func (w *Wallet) GetClient() *ethclient.Client

func (*Wallet) GetEthProvider

func (w *Wallet) GetEthProvider() EtherProvider

GetEthProvider 获得EthProvider

func (*Wallet) GetEthSigner

func (w *Wallet) GetEthSigner() EtherSigner

GetEthSigner 获得EthSinger

func (*Wallet) GetNonce

func (w *Wallet) GetNonce() (uint64, error)

GetNonce 获得nonce

func (*Wallet) NewTx

func (w *Wallet) NewTx(to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, data []byte) (*types.Transaction, error)

NewTx 构建一笔交易。nonce传0表示字段计算;gasLimit传0表示字段计算;gasPrice穿nil或者big.NewInt(0)表示gasPrice自动计算。

func (*Wallet) NewTxWithHexInput

func (w *Wallet) NewTxWithHexInput(to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, input string) (*types.Transaction, error)

NewTxWithHexInput 构建一笔交易,使用0x开头的input。nonce传0表示字段计算;gasLimit传0表示字段计算;gasPrice穿nil或者big.NewInt(0)表示gasPrice自动计算。

func (*Wallet) SendSignedTx

func (w *Wallet) SendSignedTx(signedTx *types.Transaction) (common.Hash, error)

SendSignedTx 发送签名后的Tx

func (*Wallet) SendTx

func (w *Wallet) SendTx(to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, data []byte) (common.Hash, error)

SendTx 发送交易。nonce传0表示字段计算;gasLimit传0表示字段计算;gasPrice穿nil或者big.NewInt(0)表示gasPrice自动计算。

func (*Wallet) SendTxWithHexInput

func (w *Wallet) SendTxWithHexInput(to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, input string) (common.Hash, error)

SendTxWithHexInput 发送一笔交易,使用0x开头的input。nonce传0表示字段计算;gasLimit传0表示字段计算;gasPrice穿nil或者big.NewInt(0)表示gasPrice自动计算。

func (*Wallet) SignTx

func (w *Wallet) SignTx(tx *types.Transaction) (*types.Transaction, error)

SignTx 对交易进行签名

func (*Wallet) Signature

func (w *Wallet) Signature(data []byte) ([]byte, error)

Signature 生成一个签名

Directories

Path Synopsis
contracts
examples
advanced command
basic command
erc20 command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL