etherkit

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2025 License: MIT Imports: 24 Imported by: 0

README

go-evm-kit

Go Version

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

✨ 特性

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

📦 安装

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

🚀 快速开始

方式1:使用 Kit(推荐)⭐

Kit 是最便捷的使用方式,所有方法可以直接调用。

package main

import (
    "context"
    "fmt"
    "log"
    "time"
    "github.com/guanzhenxing/go-evm-kit"
)

func main() {
    privateKey := "your_private_key_here"
    rpcURL := "https://eth-mainnet.g.alchemy.com/v2/your-api-key"
    
    // 创建 Kit
    kit, err := etherkit.NewKit(privateKey, rpcURL)
    if err != nil {
        log.Fatal(err)
    }
    defer kit.CloseWallet()
    
    ctx := context.Background()
    
    // 所有方法直接调用 - 简洁明了!
    address := kit.GetAddress()                    // 来自 Signer
    chainID, _ := kit.GetChainID(ctx)              // 来自 Provider
    balance, _ := kit.GetBalance(ctx)              // 来自 Wallet
    ethBalance, _ := kit.GetBalanceInEther(ctx)    // 增强功能
    
    fmt.Printf("地址: %s\n", address.Hex())
    fmt.Printf("Chain ID: %s\n", chainID)
    fmt.Printf("余额: %s Wei (%.6f ETH)\n", balance, ethBalance)
    
    // 发送交易并等待确认(增强功能)
    toAddress := common.HexToAddress("0x...")
    receipt, err := kit.SendTxAndWait(
        ctx, toAddress, 
        0, 0, nil,              // nonce, gasLimit, gasPrice 自动计算
        big.NewInt(1000000),    // value
        nil,                    // data
        30*time.Second,         // 超时时间
    )
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("交易已确认,状态: %d\n", receipt.Status)
}
方式2:使用原始 Wallet
package main

import (
    "context"
    "fmt"
    "log"
    "github.com/guanzhenxing/go-evm-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()
    
    ctx := context.Background()
    
    // 获取账户地址
    address := wallet.GetAddress()
    fmt.Printf("钱包地址: %s\n", address.Hex())
    
    // 获取余额
    balance, err := wallet.GetBalance(ctx)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("ETH 余额: %s\n", etherkit.ToDecimal(balance, etherkit.EthDecimals))
}
发送 ETH 转账
func sendETH(wallet *etherkit.Wallet) {
    ctx := context.Background()
    toAddress := common.HexToAddress("0x742F35Cc6634C0532925a3b8D6dA2e")
    amount := etherkit.ToWei("0.1", etherkit.EthDecimals) // 0.1 ETH
    
    txHash, err := wallet.SendTx(
        ctx,           // context
        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 (
    "context"
    "github.com/guanzhenxing/go-evm-kit/contracts/erc20"
)

func transferToken(wallet *etherkit.Wallet) {
    ctx := context.Background()
    tokenAddress := common.HexToAddress("0xA0b86a33E6411b6dE9C80e7F8DeD6c") // USDC 地址
    
    // 创建 ERC20 合约实例
    token, err := erc20.NewIERC20(tokenAddress, wallet.GetClient())
    if err != nil {
        log.Fatal(err)
    }
    
    // 构建交易选项
    opts, err := wallet.BuildTxOpts(
        ctx,              // context
        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) {
    ctx := context.Background()
    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)
    }
    
    // 调用合约方法 (只读)
    // 使用最新区块,不设置 from 和 value
    result, err := wallet.CallContract(ctx, nil, nil, nil, 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)

// 基本查询(需要 context)
ctx := context.Background()
chainID, err := provider.GetChainID(ctx)
blockNumber, err := provider.GetBlockNumber(ctx) 
gasPrice, err := provider.GetSuggestGasPrice(ctx)
block, err := provider.GetBlockByNumber(ctx, big.NewInt(123456))
receipt, err := provider.GetTransactionReceipt(ctx, txHash)
私钥和地址工具函数
// 多种方式生成/导入私钥
privateKey, err := etherkit.GeneratePrivateKey()                              // 随机生成
privateKey, err := etherkit.BuildPrivateKeyFromHex("0x...")                   // 从十六进制
privateKey, err := etherkit.BuildPrivateKeyFromMnemonic("word1 word2...")     // 从助记词

// 获取地址
address := etherkit.PrivateKeyToAddress(privateKey)

// 获取私钥的十六进制字符串
hexPk := etherkit.GetHexPrivateKey(privateKey)
Wallet (钱包)
// 创建钱包
wallet, err := etherkit.NewWallet(privateKey, rpcURL)

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

// 直接调用 Provider 的方法(需要两步)
chainID, err := wallet.GetEthProvider().GetChainID(ctx)
blockNum, err := wallet.GetEthProvider().GetBlockNumber(ctx)

// 直接调用钱包方法
address := wallet.GetAddress()
privateKey := wallet.GetPrivateKey()

// 交易操作
tx, err := wallet.NewTx(ctx, toAddr, nonce, gasLimit, gasPrice, value, data)
txHash, err := wallet.SendTx(ctx, toAddr, nonce, gasLimit, gasPrice, value, data)
signedTx, err := wallet.SignTx(ctx, tx)
Kit (开发工具包) ⭐

推荐使用! 提供最便捷的 API,所有方法可直接调用,无需通过 GetEthProvider()。

// 创建 Kit
kit, err := etherkit.NewKit(privateKey, rpcURL)

// ========== 所有方法都可以直接调用 ==========

// 钱包方法(来自 Wallet)
address := kit.GetAddress()                // 获取地址
pk := kit.GetPrivateKey()                  // 获取私钥
balance, err := kit.GetBalance(ctx)        // 获取余额
nonce, err := kit.GetNonce(ctx)           // 获取 nonce

// Provider 方法(无需 GetEthProvider())
chainID, err := kit.GetChainID(ctx)        // 获取链 ID
blockNum, err := kit.GetBlockNumber(ctx)   // 获取区块高度
receipt, err := kit.GetTransactionReceipt(ctx, txHash)  // 获取交易回执

// 发送交易
txHash, err := kit.SendTx(ctx, toAddr, 0, 0, nil, value, nil)

// ========== 增强功能 ==========

// 1. 以太币单位的余额
ethBalance, err := kit.GetBalanceInEther(ctx)
fmt.Printf("余额: %.6f ETH\n", ethBalance)

// 2. 便捷的以太币转账
txHash, err := kit.TransferEther(ctx, toAddr, 0.1)  // 转 0.1 ETH

// 3. 发送交易并等待确认
receipt, err := kit.SendTxAndWait(
    ctx, toAddr, 
    0, 0, nil,           // nonce, gasLimit, gasPrice 自动计算
    value, data,
    30*time.Second,      // 超时时间
)

// 4. 等待交易确认(带超时)
receipt, err := kit.WaitForReceipt(ctx, txHash, 30*time.Second)

// 5. 一次性获取链信息
chainID, networkID, blockNum, err := kit.GetChainInfo(ctx)

// 6. 简化的合约调用
result, err := kit.CallContractSimple(
    ctx, 
    contractAddr,
    abiJSON,        // JSON 字符串
    "balanceOf",
    myAddress,
)

对比表格:

功能 Wallet Kit
调用 Provider 方法 wallet.GetEthProvider().GetChainID(ctx) kit.GetChainID(ctx) ✅
获取地址/私钥 wallet.GetAddress() kit.GetAddress() ✅
获取 ETH 余额 手动转换 Wei kit.GetBalanceInEther(ctx) ✅
等待交易确认 手动轮询 kit.WaitForReceipt(ctx, hash, timeout) ✅
转账以太币 手动转换单位 kit.TransferEther(ctx, to, 0.1) ✅
工具函数
// 单位转换
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-evm-kit/
├── provider.go        # Provider 层 - 链交互
├── wallet.go          # Wallet 层 - 完整钱包功能
├── kit.go             # Kit 层 - 最便捷的工具包
├── crypto.go          # 加密工具(私钥、签名、地址)
├── convert.go         # 单位转换工具
├── contract.go        # 合约工具
├── transaction.go     # 交易工具
├── address.go         # 地址相关工具
├── constants.go       # 常量定义
├── errors.go          # 错误定义
├── contracts/         # 智能合约绑定
│   └── erc20/        # ERC20 合约
├── examples/          # 使用示例
│   └── kit/          # Kit 使用示例
├── *_test.go         # 单元测试文件
├── go.mod
├── go.sum
├── Makefile          # 构建和开发工具
├── LICENSE
└── README.md

🏗️ 架构设计

设计理念

go-evm-kit 采用简洁实用的设计理念,专注于提供便捷的以太坊开发工具,而不是构建复杂的抽象层。

核心架构
crypto.go (工具函数)
   ├─ GeneratePrivateKey()
   ├─ BuildPrivateKeyFromHex()
   └─ PrivateKeyToAddress()
      ↓
provider.go (链交互)
   ├─ GetChainID()
   ├─ GetBlockNumber()
   └─ GetTransactionReceipt()
      ↓
wallet.go (完整钱包)
   ├─ privateKey, address (私钥/地址)
   ├─ Provider (链交互)
   └─ SendTx(), SignTx()
      ↓
kit.go (推荐使用) ⭐
   ├─ *Wallet (嵌入)
   ├─ EtherProvider (嵌入接口)
   └─ 增强功能
三层架构
层级 文件 用途 何时使用
Provider provider.go 链交互查询 只需要查询链数据,不需要私钥
Wallet wallet.go 完整钱包功能 需要发送交易、签名等完整功能
Kit ⭐ kit.go 最便捷的工具包 推荐使用 - 所有方法直接调用
设计决策

为什么将私钥直接放在 Wallet 中?

  1. 简化架构 - 移除不必要的 Signer 抽象层
  2. 开发工具定位 - 专注于 99% 的开发场景,不需要支持硬件钱包等复杂场景
  3. 更直观 - Wallet(钱包)本身就应该包含私钥和地址
  4. 易于维护 - 更少的接口和类型

为什么推荐使用 Kit?

  1. 最简单 - 所有方法直接调用,无需 GetEthProvider()
  2. 最强大 - 包含所有功能 + 增强功能
  3. 最实用 - 覆盖 99% 的使用场景
扩展性

虽然架构简化了,但仍保持良好的扩展性:

// 自定义 Provider(添加缓存)
type CachedProvider struct {
    *Provider
    cache Cache
}

// 基于 Kit 扩展(DeFi 功能)
type DeFiKit struct {
    *Kit
}

func (dk *DeFiKit) SwapTokens(...) error {
    // 实现 DeFi 操作
}

🚀 最佳实践

1. 优先使用 Kit(推荐)
// ✅ 推荐 - 最简单的使用方式
kit, _ := NewKit(privateKey, rpcURL)
balance, _ := kit.GetBalance(ctx)
chainID, _ := kit.GetChainID(ctx)  // 直接调用,无需 GetEthProvider()
2. 只读场景使用 Provider
// ✅ 只需要查询链数据时
provider, _ := NewProvider(rpcURL)
blockNum, _ := provider.GetBlockNumber(ctx)
3. 复杂场景使用 Wallet
// ✅ 需要自定义逻辑时
privateKey, _ := BuildPrivateKeyFromHex(hexPk)
provider, _ := NewProvider(rpcURL)
wallet, _ := NewWalletWithComponents(privateKey, provider)

🆕 最新改进

v2.0 - 架构简化
  • ✅ 简化架构 - 移除 Signer 抽象层,从 4 层减少到 3 层
  • ✅ Kit 工具包 - 提供最便捷的 API,所有方法直接调用
  • ✅ 更少的文件 - 核心只有 3 个文件:provider.go、wallet.go、kit.go
  • ✅ 更易理解 - Wallet 直接包含私钥和地址,概念更清晰
代码质量
  • ✅ 完整单元测试 - 覆盖率 34%+
  • ✅ 详细使用示例 - examples/kit 完整示例
  • ✅ 标准化命名 - 符合 Go 语言习惯

🌐 支持的网络

网络名称 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 (
	// DefaultWaitInterval 默认等待交易确认的轮询间隔
	DefaultWaitInterval = time.Second
)

Kit 相关常量

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 构建合约调用的输入数据 将函数名和参数打包成合约调用所需的字节数据 参数说明:

  • contract: 合约 ABI 对象
  • name: 函数名(如 "transfer", "balanceOf")
  • args: 函数参数(按函数定义顺序传入)

返回:

  • []byte: 合约调用数据(包含函数选择器和编码后的参数)
  • error: 如果打包失败则返回错误(如参数类型不匹配、参数数量不对等)

示例:

  • data, err := BuildContractInputData(abi, "transfer", toAddress, amount)
  • data, err := BuildContractInputData(abi, "balanceOf", userAddress)

func BuildPrivateKeyFromHex

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

BuildPrivateKeyFromHex 从十六进制字符串构建私钥对象 将十六进制私钥字符串转换为 ECDSA 私钥对象 参数说明:

  • privateKeyHex: 十六进制私钥字符串(带或不带 0x 前缀)

返回:

  • *ecdsa.PrivateKey: ECDSA 私钥对象
  • error: 如果格式无效则返回错误

示例:

  • pk, err := BuildPrivateKeyFromHex("abc123...") // 不带 0x 前缀
  • pk, err := BuildPrivateKeyFromHex("0xabc123...") // 带 0x 前缀

func BuildPrivateKeyFromMnemonic

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

BuildPrivateKeyFromMnemonic 从助记词构建私钥对象(默认账户) 使用 BIP-44 标准从助记词派生私钥,使用默认账户索引(0) 参数说明:

  • mnemonic: BIP-39 助记词字符串(12 或 24 个单词)

返回:

  • *ecdsa.PrivateKey: ECDSA 私钥对象
  • error: 如果助记词无效或派生失败则返回错误

注意:

  • 使用 BIP-44 标准路径:m/44'/60'/0'/0/0(以太坊主网,第一个账户)
  • 如果需要其他账户,使用 BuildPrivateKeyFromMnemonicAndAccountId

func BuildPrivateKeyFromMnemonicAndAccountId

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

BuildPrivateKeyFromMnemonicAndAccountId 从助记词和账户索引构建私钥对象 使用 BIP-44 标准从助记词派生指定账户的私钥 参数说明:

  • mnemonic: BIP-39 助记词字符串(12 或 24 个单词)
  • accountId: 账户索引(0 表示第一个账户,1 表示第二个账户,以此类推)

返回:

  • *ecdsa.PrivateKey: ECDSA 私钥对象
  • error: 如果助记词无效或派生失败则返回错误

注意:

  • 使用 BIP-44 标准路径:m/44'/60'/0'/0/{accountId}(以太坊主网)
  • 同一个助记词配合不同的 accountId 可以生成不同的私钥和地址
  • 这是 HD 钱包的标准做法,允许从一个助记词管理多个账户

func DecodeRawTxHex

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

DecodeRawTxHex 解析原始交易十六进制字符串 将 RLP 编码的原始交易数据解码为交易对象 参数说明:

  • rawTx: 原始交易的十六进制字符串(RLP 编码,带或不带 0x 前缀)

返回:

  • *types.Transaction: 解析后的交易对象
  • error: 如果解析失败则返回错误(如格式无效、RLP 编码错误等)

使用场景:

  • 从其他系统接收原始交易数据并解析
  • 从链上获取原始交易并重新构建交易对象

func GeneratePrivateKey

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

GeneratePrivateKey 生成新的随机私钥 使用加密安全的随机数生成器创建 ECDSA 私钥 适用于创建新钱包的场景

返回:

  • *ecdsa.PrivateKey: 新生成的 ECDSA 私钥
  • error: 如果生成失败则返回错误

注意:

  • 请妥善保存生成的私钥,丢失私钥将无法恢复钱包
  • 生成的私钥是随机的,每次调用都会创建新的私钥

func GetABI

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

GetABI 从 ABI JSON 字符串中解析 ABI 对象 ABI(Application Binary Interface)定义了合约的接口,包括函数签名、事件等 参数说明:

  • abiStr: ABI JSON 字符串(完整的合约 ABI 或单个函数的 ABI)

返回:

  • abi.ABI: 解析后的 ABI 对象,可用于合约调用
  • error: 如果 JSON 格式无效则返回错误

示例:

  • abiStr := `[{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"type":"function"}]`
  • abiObj, err := GetABI(abiStr)

func GetContractMethodId

func GetContractMethodId(method string) string

GetContractMethodId 获取合约方法的函数选择器(method ID) 函数选择器是函数签名的 Keccak256 哈希的前 4 字节,用于标识要调用的函数 参数说明:

  • method: 函数签名字符串,格式为 "函数名(参数类型1,参数类型2,...)" 例如:"transfer(address,uint256)"、"balanceOf(address)"

返回:

  • string: 函数选择器(十六进制字符串,带 0x 前缀,如 "0xa9059cbb")

示例:

  • GetContractMethodId("transfer(address,uint256)") // 返回 "0xa9059cbb"
  • GetContractMethodId("balanceOf(address)") // 返回 "0x70a08231"

func GetEventTopic

func GetEventTopic(event string) string

GetEventTopic 获取事件的 topic(事件签名的哈希) 事件的 topic 是事件签名的 Keccak256 哈希,用于在日志中识别事件 参数说明:

  • event: 事件签名字符串,格式为 "事件名(参数类型1,参数类型2,...)" 例如:"Transfer(address,address,uint256)"、"Approval(address,address,uint256)"

返回:

  • string: 事件 topic(十六进制字符串,带 0x 前缀)

示例:

  • GetEventTopic("Transfer(address,address,uint256)") // 返回 "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"

func GetHexPrivateKey

func GetHexPrivateKey(privateKey *ecdsa.PrivateKey) string

GetHexPrivateKey 获取私钥的十六进制字符串表示 将私钥转换为十六进制字符串,不包含 0x 前缀 参数说明:

  • privateKey: ECDSA 私钥对象

返回:

  • string: 私钥的十六进制字符串(不包含 0x 前缀,如 "abc123...")

示例:

  • hexPk := GetHexPrivateKey(privateKey) // 返回 "abc123..."

func GetHexPublicKey

func GetHexPublicKey(privateKey *ecdsa.PrivateKey) string

GetHexPublicKey 获取公钥的十六进制字符串表示 将私钥对应的公钥转换为十六进制字符串,不包含 0x 前缀和 0x04 前缀 参数说明:

  • privateKey: ECDSA 私钥对象

返回:

  • string: 公钥的十六进制字符串(不包含 0x 和 0x04 前缀)

注意:

  • 公钥的完整格式通常包含 0x04 前缀(表示未压缩格式)
  • 此方法返回的是去掉 0x04 前缀后的公钥

func GetMaxUint256

func GetMaxUint256() *big.Int

GetMaxUint256 获取 uint256 的最大值 返回 2^256 - 1,这是 Solidity 中 uint256 类型能表示的最大值 常用于 ERC20 代币的 approve 操作,表示无限授权

返回:

  • *big.Int: uint256 的最大值(2^256 - 1)

示例:

  • maxUint := GetMaxUint256()
  • txHash, err := kit.InvokeContract(ctx, tokenAddr, abi, "approve", 0, 0, nil, nil, spenderAddr, maxUint)

func IsValidAddress

func IsValidAddress(iAddress interface{}) bool

IsValidAddress 验证是否是有效的以太坊地址 验证地址格式是否正确(必须以 0x 开头,后跟 40 个十六进制字符) 参数说明:

  • iAddress: 要验证的地址,可以是 string 或 common.Address 类型

返回:

  • bool: true 表示地址格式有效,false 表示格式无效

示例:

  • IsValidAddress("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb") // 返回 true
  • IsValidAddress("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb") // 返回 false(长度不对)

func NewTx

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

NewTx 创建新的交易对象 构建一个以太坊交易,使用传统交易类型(Legacy Transaction) 参数说明:

  • to: 接收地址(合约地址或普通地址,nil 表示合约部署)
  • nonce: 交易 nonce(用于防止重放攻击)
  • gasLimit: Gas 限制(交易最多消耗的 gas)
  • gasPrice: Gas 价格(单位为 Wei)
  • value: 转账金额(单位为 Wei,nil 表示不转账)
  • data: 交易数据(合约调用数据或 nil)

返回:

  • *types.Transaction: 交易对象(未签名)
  • error: 如果创建失败则返回错误

注意:

  • 此方法创建的是传统交易类型,不支持 EIP-1559 的动态 gas 费用
  • 交易需要签名后才能发送

func NewTxWithHexData

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

NewTxWithHexData 基于十六进制数据创建交易对象 与 NewTx 类似,但接受十六进制字符串作为交易数据 参数说明:

  • to: 接收地址
  • nonce: 交易 nonce
  • gasLimit: Gas 限制
  • gasPrice: Gas 价格(单位为 Wei)
  • value: 转账金额(单位为 Wei,nil 表示不转账)
  • hexData: 十六进制交易数据(带或不带 0x 前缀)

返回:

  • *types.Transaction: 交易对象(未签名)
  • error: 如果创建失败则返回错误(如十六进制格式无效)

func PrivateKeyToAddress

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

PrivateKeyToAddress 从私钥派生以太坊地址 以太坊地址是从私钥对应的公钥派生出来的 参数说明:

  • privateKey: ECDSA 私钥对象

返回:

  • common.Address: 派生出的以太坊地址

注意:

  • 同一个私钥总是对应同一个地址
  • 地址是从公钥的 Keccak256 哈希的后 20 字节派生出来的

func PublicKeyBytesToAddress

func PublicKeyBytesToAddress(publicKey []byte) common.Address

PublicKeyBytesToAddress 从公钥字节转换为以太坊地址 以太坊地址是从公钥派生出来的:对公钥进行 Keccak256 哈希,然后取后 20 字节 参数说明:

  • publicKey: 公钥字节(通常包含 0x04 前缀,长度为 65 字节)

返回:

  • common.Address: 派生出的以太坊地址

注意:

  • 公钥字节的第一个字节(0x04)会被移除,然后对剩余 64 字节进行哈希
  • 哈希结果的后 20 字节即为地址

func ToDecimal

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

ToDecimal 将最小单位(如 Wei)转换为带小数位的数值 将链上的最小单位(如 Wei、Satoshi 等)转换为可读的小数形式 参数说明:

  • iValue: 要转换的值,可以是 string(十进制字符串)或 *big.Int
  • decimals: 小数位数(如以太币为 18,USDT 为 6)

返回:

  • decimal.Decimal: 转换后的十进制数值(保留完整精度)

示例:

  • ToDecimal("1000000000000000000", 18) // 1 ETH = 1.0
  • ToDecimal("1000000", 6) // 1 USDT = 1.0
  • balance := big.NewInt(500000000000000000) // 0.5 ETH
  • ToDecimal(balance, 18) // 0.5

func ToWei

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

ToWei 将带小数位的数值转换为最小单位(如 Wei) 将可读的小数形式转换为链上的最小单位(如 Wei、Satoshi 等) 参数说明:

  • iAmount: 要转换的数值,可以是 string、float64、int64、int、decimal.Decimal 或 *decimal.Decimal
  • decimals: 小数位数(如以太币为 18,USDT 为 6)

返回:

  • *big.Int: 转换后的最小单位值(如 Wei)

示例:

  • ToWei(1.5, 18) // 1.5 ETH = 1500000000000000000 Wei
  • ToWei("0.1", 18) // 0.1 ETH = 100000000000000000 Wei
  • ToWei(100, 6) // 100 USDT = 100000000 (最小单位)

func VerifySignature

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

VerifySignature 验证签名是否由指定地址创建 验证给定的数据和签名是否由指定地址对应的私钥签名 参数说明:

  • address: 用于签名的地址(十六进制字符串,带或不带 0x 前缀)
  • data: 原始数据(字节)
  • signature: 签名数据(65 字节,包含 r、s、v)

返回:

  • bool: true 表示签名有效(由指定地址创建),false 表示签名无效

注意:

  • 会对数据进行 Keccak256 哈希,然后验证签名
  • 签名格式必须是 65 字节(r、s 各 32 字节,v 1 字节)

Types

type EtherProvider

type EtherProvider interface {
	// GetEthClient 获取以太坊客户端实例
	// 返回底层的 ethclient.Client,可用于执行底层操作
	GetEthClient() *ethclient.Client
	// GetRpcClient 获取 RPC 客户端实例
	// 返回底层的 rpc.Client,可用于执行底层 RPC 调用
	GetRpcClient() *rpc.Client
	// Close 关闭客户端连接
	// 释放所有底层资源,包括 ethclient 和 rpc client
	Close()
	// GetNetworkID 获取网络 ID
	// 参数说明:
	//   - ctx: 上下文对象
	// 返回:
	//   - *big.Int: 网络 ID
	//   - error: 如果查询失败则返回错误
	GetNetworkID(ctx context.Context) (*big.Int, error)
	// GetChainID 获取链 ID
	// 参数说明:
	//   - ctx: 上下文对象
	// 返回:
	//   - *big.Int: 链 ID(如主网为 1,Goerli 为 5)
	//   - error: 如果查询失败则返回错误
	GetChainID(ctx context.Context) (*big.Int, error)
	// GetBlockByHash 根据区块哈希获取区块信息
	// 参数说明:
	//   - ctx: 上下文对象
	//   - hash: 区块哈希
	// 返回:
	//   - *types.Block: 区块对象,包含区块头、交易列表等信息
	//   - error: 如果查询失败则返回错误
	GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error)
	// GetBlockByNumber 根据区块号获取区块信息
	// 参数说明:
	//   - ctx: 上下文对象
	//   - number: 区块号(nil 表示最新区块)
	// 返回:
	//   - *types.Block: 区块对象,包含区块头、交易列表等信息
	//   - error: 如果查询失败则返回错误
	GetBlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error)
	// GetBlockNumber 获取最新区块号
	// 参数说明:
	//   - ctx: 上下文对象
	// 返回:
	//   - uint64: 最新区块号
	//   - error: 如果查询失败则返回错误
	GetBlockNumber(ctx context.Context) (uint64, error)
	// GetSuggestGasPrice 获取建议的 Gas 价格
	// 返回网络建议的 Gas 价格(单位为 Wei)
	// 参数说明:
	//   - ctx: 上下文对象
	// 返回:
	//   - *big.Int: 建议的 Gas 价格(单位为 Wei)
	//   - error: 如果查询失败则返回错误
	GetSuggestGasPrice(ctx context.Context) (*big.Int, error)
	// GetTransactionByHash 根据交易哈希获取交易信息
	// 参数说明:
	//   - ctx: 上下文对象
	//   - hash: 交易哈希
	// 返回:
	//   - tx: 交易对象
	//   - isPending: 交易是否还在待处理状态
	//   - error: 如果查询失败则返回错误
	GetTransactionByHash(ctx context.Context, hash common.Hash) (tx *types.Transaction, isPending bool, err error)
	// GetTransactionReceipt 根据交易哈希获取交易收据
	// 交易收据包含交易执行结果、gas 使用情况、日志等信息
	// 参数说明:
	//   - ctx: 上下文对象
	//   - txHash: 交易哈希
	// 返回:
	//   - *types.Receipt: 交易收据,包含交易状态、gas 使用等信息
	//   - error: 如果查询失败则返回错误
	GetTransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
	// GetContractBytecode 获取合约字节码
	// 返回合约在链上的字节码(十六进制字符串,带 0x 前缀)
	// 参数说明:
	//   - ctx: 上下文对象
	//   - address: 合约地址
	// 返回:
	//   - string: 合约字节码(十六进制字符串)
	//   - error: 如果查询失败则返回错误
	GetContractBytecode(ctx context.Context, address common.Address) (string, error)
	// IsContractAddress 检查地址是否为合约地址
	// 通过检查地址的代码长度来判断是否为合约(合约代码长度 > 0)
	// 参数说明:
	//   - ctx: 上下文对象
	//   - address: 要检查的地址
	// 返回:
	//   - bool: true 表示是合约地址,false 表示是普通地址
	//   - error: 如果查询失败则返回错误
	IsContractAddress(ctx context.Context, address common.Address) (bool, error)
	// EstimateGas 估算交易所需的 Gas 数量
	// 通过模拟交易执行来估算 gas 消耗
	// 参数说明:
	//   - ctx: 上下文对象
	//   - from: 发送地址
	//   - to: 接收地址(合约地址或普通地址)
	//   - nonce: 交易 nonce
	//   - gasPrice: Gas 价格(nil 表示不设置)
	//   - value: 转账金额(nil 表示不转账)
	//   - data: 交易数据(合约调用数据或 nil)
	// 返回:
	//   - uint64: 估算的 Gas 数量
	//   - error: 如果估算失败则返回错误
	EstimateGas(ctx context.Context, from, to common.Address, nonce uint64, gasPrice, value *big.Int, data []byte) (uint64, error)
	// GetFromAddress 从交易中提取发送地址
	// 通过解析交易签名来获取发送者地址
	// 参数说明:
	//   - tx: 交易对象
	// 返回:
	//   - common.Address: 发送地址
	//   - error: 如果提取失败则返回错误
	GetFromAddress(tx *types.Transaction) (common.Address, error)
	// FilterLogs 查询事件日志
	// 用于查询指定区块范围内的事件日志,支持按合约地址、事件签名和 indexed 参数进行过滤
	// 参数说明:
	//   - ctx: 上下文对象
	//   - contractAddress: 合约地址(nil 表示查询所有合约)
	//   - eventTopic: 事件签名 topic(如 GetEventTopic("Transfer(address,address,uint256)"))
	//   - fromBlock: 起始区块号(nil 表示从最新区块开始)
	//   - toBlock: 结束区块号(nil 表示到最新区块)
	//   - indexedTopics: 可选的 indexed 参数过滤(nil 表示不过滤,每个元素对应一个 indexed 参数)
	// 返回:
	//   - []types.Log: 事件日志列表,用户需要自行解析 Data 和 Topics
	//   - error: 如果查询失败则返回错误
	FilterLogs(ctx context.Context, contractAddress *common.Address, eventTopic common.Hash, fromBlock, toBlock *big.Int, indexedTopics []common.Hash) ([]types.Log, error)
}

EtherProvider 以太坊提供者接口 提供链上查询功能,但不需要账户信息(如私钥) 用于执行只读操作,如查询区块、交易、余额等

type EtherWallet

type EtherWallet interface {
	// GetEthProvider 获取以太坊提供者实例
	// 返回:
	//   - EtherProvider: 以太坊提供者接口
	GetEthProvider() EtherProvider
	// GetClient 获取以太坊客户端实例
	// 返回:
	//   - *ethclient.Client: 以太坊客户端
	GetClient() *ethclient.Client
	// GetAddress 获取钱包地址
	// 返回:
	//   - common.Address: 钱包地址
	GetAddress() common.Address
	// GetPrivateKey 获取私钥
	// 返回:
	//   - *ecdsa.PrivateKey: ECDSA 私钥对象
	GetPrivateKey() *ecdsa.PrivateKey
	// CloseWallet 关闭钱包连接
	// 释放所有底层资源
	CloseWallet()
	// GetNonce 获取账户的 nonce
	// nonce 用于防止交易重放,每个交易必须使用唯一的 nonce
	// 参数说明:
	//   - ctx: 上下文对象
	// 返回:
	//   - uint64: 下一个可用的 nonce
	//   - error: 如果查询失败则返回错误
	GetNonce(ctx context.Context) (uint64, error)
	// GetBalance 获取账户余额
	// 返回账户的本位币余额(单位为 Wei)
	// 参数说明:
	//   - ctx: 上下文对象
	// 返回:
	//   - *big.Int: 余额(单位为 Wei)
	//   - error: 如果查询失败则返回错误
	GetBalance(ctx context.Context) (*big.Int, error)
	// NewTx 构建一笔交易
	// 自动计算 nonce、gasLimit 和 gasPrice(如果未提供)
	// 参数说明:
	//   - ctx: 上下文对象
	//   - to: 接收地址(合约地址或普通地址)
	//   - nonce: 交易 nonce(0 表示自动计算)
	//   - gasLimit: Gas 限制(0 表示自动估算)
	//   - gasPrice: Gas 价格(nil 或 0 表示自动获取)
	//   - value: 转账金额(nil 表示不转账)
	//   - data: 交易数据(合约调用数据或 nil)
	// 返回:
	//   - *types.Transaction: 交易对象
	//   - error: 如果构建失败则返回错误
	NewTx(ctx context.Context, to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, data []byte) (*types.Transaction, error)
	// SendTx 发送交易
	// 构建、签名并发送交易,返回交易哈希
	// 参数说明:
	//   - ctx: 上下文对象
	//   - to: 接收地址(合约地址或普通地址)
	//   - nonce: 交易 nonce(0 表示自动计算)
	//   - gasLimit: Gas 限制(0 表示自动估算)
	//   - gasPrice: Gas 价格(nil 或 0 表示自动获取)
	//   - value: 转账金额(nil 表示不转账)
	//   - data: 交易数据(合约调用数据或 nil)
	// 返回:
	//   - common.Hash: 交易哈希,可用于查询交易状态
	//   - error: 如果发送失败则返回错误
	SendTx(ctx context.Context, to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, data []byte) (common.Hash, error)
	// NewTxWithHexInput 构建一笔交易,使用十六进制输入数据
	// 与 NewTx 类似,但接受十六进制字符串作为输入数据
	// 参数说明:
	//   - ctx: 上下文对象
	//   - to: 接收地址
	//   - nonce: 交易 nonce(0 表示自动计算)
	//   - gasLimit: Gas 限制(0 表示自动估算)
	//   - gasPrice: Gas 价格(nil 或 0 表示自动获取)
	//   - value: 转账金额(nil 表示不转账)
	//   - input: 十六进制输入数据(带或不带 0x 前缀)
	// 返回:
	//   - *types.Transaction: 交易对象
	//   - error: 如果构建失败则返回错误
	NewTxWithHexInput(ctx context.Context, to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, input string) (*types.Transaction, error)
	// SendTxWithHexInput 发送一笔交易,使用十六进制输入数据
	// 与 SendTx 类似,但接受十六进制字符串作为输入数据
	// 参数说明:
	//   - ctx: 上下文对象
	//   - to: 接收地址
	//   - nonce: 交易 nonce(0 表示自动计算)
	//   - gasLimit: Gas 限制(0 表示自动估算)
	//   - gasPrice: Gas 价格(nil 或 0 表示自动获取)
	//   - value: 转账金额(nil 表示不转账)
	//   - input: 十六进制输入数据(带或不带 0x 前缀)
	// 返回:
	//   - common.Hash: 交易哈希
	//   - error: 如果发送失败则返回错误
	SendTxWithHexInput(ctx context.Context, to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, input string) (common.Hash, error)
	// BuildTxOpts 构建交易的选项
	// 用于与 go-ethereum 的 bind 包配合使用,生成 TransactOpts
	// 参数说明:
	//   - ctx: 上下文对象
	//   - value: 转账金额(nil 表示不转账)
	//   - nonce: 交易 nonce(nil 或 <= 0 表示自动计算)
	//   - gasPrice: Gas 价格(nil 或 <= 0 表示自动获取)
	// 返回:
	//   - *bind.TransactOpts: 交易选项,可用于合约交互
	//   - error: 如果构建失败则返回错误
	BuildTxOpts(ctx context.Context, value, nonce, gasPrice *big.Int) (*bind.TransactOpts, error)
	// SignTx 对交易进行签名
	// 使用钱包的私钥对交易进行 EIP-155 签名
	// 参数说明:
	//   - ctx: 上下文对象
	//   - tx: 未签名的交易对象
	// 返回:
	//   - *types.Transaction: 已签名的交易对象
	//   - error: 如果签名失败则返回错误
	SignTx(ctx context.Context, tx *types.Transaction) (*types.Transaction, error)
	// SendSignedTx 发送已签名的交易
	// 将已签名的交易发送到网络
	// 参数说明:
	//   - ctx: 上下文对象
	//   - signedTx: 已签名的交易对象
	// 返回:
	//   - common.Hash: 交易哈希
	//   - error: 如果发送失败则返回错误
	SendSignedTx(ctx context.Context, signedTx *types.Transaction) (common.Hash, error)
	// Signature 对数据进行签名
	// 使用钱包的私钥对数据进行 ECDSA 签名
	// 参数说明:
	//   - data: 要签名的原始数据(字节)
	// 返回:
	//   - []byte: 签名结果(65 字节,包含 r、s、v)
	//   - error: 如果签名失败则返回错误
	Signature(data []byte) ([]byte, error)
	// CallContract 调用合约方法(静态调用,不发送交易)
	// 可以调用 view/pure 函数,也可以模拟调用非 view/pure 函数来查看执行结果
	// 参数说明:
	//   - ctx: 上下文对象
	//   - blockNumber: 区块号(nil 表示最新区块)
	//   - from: 调用者地址(nil 表示不设置)
	//   - value: 模拟转账金额(nil 表示不转账)
	//   - contractAddress: 合约地址
	//   - contractAbi: 合约 ABI 对象
	//   - functionName: 函数名
	//   - params: 函数参数(按函数定义顺序传入)
	// 返回:
	//   - []interface{}: 函数返回值数组(按函数定义顺序)
	//   - error: 如果调用失败则返回错误
	CallContract(ctx context.Context, blockNumber *big.Int, from *common.Address, value *big.Int, contractAddress common.Address, contractAbi abi.ABI, functionName string, params ...interface{}) ([]interface{}, error)
}

EtherWallet 以太坊钱包接口 提供钱包管理、交易构建、签名和发送等功能

type Kit added in v1.1.0

type Kit struct {
	*Wallet       // 嵌入 Wallet,获得所有钱包方法(包括 GetAddress、GetPrivateKey)
	EtherProvider // 嵌入 Provider 接口,直接调用所有 Provider 方法!
}

Kit 以太坊开发工具包,提供最便捷的使用方式 通过嵌入接口,所有 Provider 和 Wallet 的方法都可以直接调用

func NewKit added in v1.1.0

func NewKit(hexPk string, rawUrl string) (*Kit, error)

NewKit 创建以太坊开发工具包 参数说明:

返回:

  • *Kit: 创建的 Kit 实例
  • error: 如果创建失败则返回错误

func NewKitWithComponents added in v1.1.0

func NewKitWithComponents(privateKey *ecdsa.PrivateKey, ep EtherProvider) (*Kit, error)

NewKitWithComponents 使用已有组件创建 Kit 适用于已经创建好私钥和 Provider 的情况,避免重复创建 参数说明:

  • privateKey: 已存在的 ECDSA 私钥
  • ep: 已存在的 EtherProvider 实例

返回:

  • *Kit: 创建的 Kit 实例
  • error: 如果创建失败则返回错误

func NewKitWithGeneratedKey added in v1.2.0

func NewKitWithGeneratedKey(rawUrl string) (*Kit, error)

NewKitWithGeneratedKey 创建以太坊开发工具包(自动生成随机私钥) 适用于不需要导入已有私钥的场景,如测试、临时钱包等 会自动生成一个随机私钥并创建对应的 Kit 实例 参数说明:

返回:

  • *Kit: 创建的 Kit 实例(包含新生成的私钥和地址)
  • error: 如果创建失败则返回错误

注意:

  • 生成的私钥是随机的,每次调用都会创建新的钱包
  • 请妥善保存生成的私钥,可通过 kit.GetPrivateKey() 获取私钥对象,或使用 GetHexPrivateKey(kit.GetPrivateKey()) 获取十六进制字符串
  • 适用于临时场景,生产环境建议使用 NewKit 导入已有私钥

func (*Kit) FilterEventLogs added in v1.2.0

func (k *Kit) FilterEventLogs(ctx context.Context, contractAddress *common.Address, eventSignature string, fromBlock, toBlock *big.Int, indexedParams []common.Hash) ([]types.Log, error)

FilterEventLogs 查询合约事件日志(便捷方法) 自动生成事件 topic,简化事件日志查询流程 参数说明:

  • ctx: 上下文对象
  • contractAddress: 合约地址(nil 表示查询所有合约)
  • eventSignature: 事件签名字符串(如 "Transfer(address,address,uint256)" 或 "MarketEntered(address,address)")
  • fromBlock: 起始区块号(nil 表示从最新区块开始)
  • toBlock: 结束区块号(nil 表示到最新区块)
  • indexedParams: 可选的 indexed 参数值(用于过滤,nil 表示不过滤) 每个元素对应事件签名中的一个 indexed 参数,例如:
  • Transfer(from, to, value) 中 from 和 to 是 indexed,可以传入 []common.Hash{fromAddr.Hash(), toAddr.Hash()}
  • MarketEntered(cToken, account) 中两个都是 indexed,可以传入 []common.Hash{cTokenAddr.Hash(), accountAddr.Hash()}

返回:

  • []types.Log: 事件日志列表,用户需要自行解析 Data 和 Topics
  • error: 如果查询失败则返回错误

使用示例:

  • 查询单个合约的事件(不过滤 indexed 参数): logs, err := kit.FilterEventLogs(ctx, &contractAddr, "MarketEntered(address,address)", fromBlock, toBlock, nil)
  • 查询所有合约的事件: logs, err := kit.FilterEventLogs(ctx, nil, "Transfer(address,address,uint256)", fromBlock, toBlock, nil)
  • 带 indexed 参数过滤: logs, err := kit.FilterEventLogs(ctx, &contractAddr, "Transfer(address,address,uint256)", fromBlock, toBlock, []common.Hash{fromAddr.Hash(), toAddr.Hash()})

注意:

  • 返回的日志需要用户自行解析,因为不同事件的数据结构不同
  • 解析示例(以 MarketEntered(address,address) 为例): for _, vLog := range logs { if len(vLog.Data) >= 64 { accountBytes := vLog.Data[32:64] // 第二个 address 是 account accountAddr := common.BytesToAddress(accountBytes) // 处理 accountAddr... } }

func (*Kit) GetContractBytecode added in v1.2.0

func (k *Kit) GetContractBytecode(ctx context.Context, address common.Address) (string, error)

GetContractBytecode 获取合约字节码 返回合约在链上的字节码(十六进制字符串,带 0x 前缀) 参数说明:

  • ctx: 上下文对象
  • address: 合约地址

返回:

  • string: 合约字节码(十六进制字符串,如 "0x608060405234801561001057600080fd5b50...")
  • error: 如果查询失败则返回错误

func (*Kit) GetLatestBlock added in v1.2.0

func (k *Kit) GetLatestBlock(ctx context.Context) (*types.Block, error)

GetLatestBlock 获取最新区块 获取当前链上的最新区块信息,包括区块号、时间戳、交易列表等 参数说明:

  • ctx: 上下文对象

返回:

  • *types.Block: 区块对象,包含区块头、交易列表等信息
  • error: 如果查询失败则返回错误

func (*Kit) InvokeContract added in v1.2.0

func (k *Kit) InvokeContract(ctx context.Context, contractAddress common.Address, contractAbi abi.ABI, functionName string, nonce, gasLimit uint64, gasPrice, value *big.Int, params ...interface{}) (common.Hash, error)

InvokeContract 调用合约方法并发送交易(花费 gas,会修改链上状态) 用于调用非 view/pure 函数,需要发送交易来执行 适用于转账代币、调用状态修改函数等场景 参数说明:

  • ctx: 上下文对象
  • contractAddress: 合约地址
  • contractAbi: 合约 ABI 对象
  • functionName: 函数名(如 "transfer", "approve")
  • nonce: 交易 nonce(0 表示自动计算)
  • gasLimit: Gas 限制(0 表示自动估算)
  • gasPrice: Gas 价格(nil 表示自动获取)
  • value: 转账金额(nil 表示不转账,用于 payable 函数)
  • params: 函数参数(按函数定义顺序传入)

返回:

  • common.Hash: 交易哈希,可用于查询交易状态
  • error: 如果发送失败则返回错误

func (*Kit) InvokeContractWithABIString added in v1.2.0

func (k *Kit) InvokeContractWithABIString(ctx context.Context, contractAddress common.Address, abiJSON string, functionName string, nonce, gasLimit uint64, gasPrice, value *big.Int, params ...interface{}) (common.Hash, error)

InvokeContractWithABIString 使用 ABI JSON 字符串调用合约方法并发送交易(花费 gas) 这是 InvokeContract 的便捷版本,接受 ABI JSON 字符串而不是 ABI 对象 适用于从配置文件或 API 获取 ABI 的场景 使用示例:

  • 调用转账:InvokeContractWithABIString(ctx, addr, abiJSON, "transfer", 0, 0, nil, nil, toAddress, amount)

参数说明:

  • ctx: 上下文对象
  • contractAddress: 合约地址
  • abiJSON: ABI JSON 字符串(完整的合约 ABI 或单个函数的 ABI)
  • functionName: 函数名(如 "transfer", "approve")
  • nonce: 交易 nonce(0 表示自动计算)
  • gasLimit: Gas 限制(0 表示自动估算)
  • gasPrice: Gas 价格(nil 表示自动获取)
  • value: 转账金额(nil 表示不转账,用于 payable 函数)
  • params: 函数参数(按函数定义顺序传入)

返回:

  • common.Hash: 交易哈希,可用于查询交易状态
  • error: 如果发送失败则返回错误

func (*Kit) IsContract added in v1.2.0

func (k *Kit) IsContract(ctx context.Context, address common.Address) (bool, error)

IsContract 检查地址是否为合约地址 通过检查地址的代码长度来判断是否为合约(合约代码长度 > 0) 参数说明:

  • ctx: 上下文对象
  • address: 要检查的地址

返回:

  • bool: true 表示是合约地址,false 表示是普通地址
  • error: 如果查询失败则返回错误

func (*Kit) SendTx added in v1.2.0

func (k *Kit) SendTx(ctx context.Context, to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, data []byte) (common.Hash, error)

SendTx 发送交易(不等待确认) 构建、签名并发送交易,返回交易哈希后立即返回,不等待交易打包 参数说明:

  • ctx: 上下文对象
  • to: 接收地址(合约地址或普通地址)
  • nonce: 交易 nonce(0 表示自动计算)
  • gasLimit: Gas 限制(0 表示自动估算)
  • gasPrice: Gas 价格(nil 表示自动获取)
  • value: 转账金额(nil 表示不转账)
  • data: 交易数据(合约调用数据或 nil)

返回:

  • common.Hash: 交易哈希,可用于后续查询交易状态
  • error: 如果发送失败则返回错误

注意:此方法通过嵌入的 Wallet 提供,如需等待交易确认,请使用 SendTxAndWait

func (*Kit) SendTxAndWait added in v1.1.0

func (k *Kit) SendTxAndWait(ctx context.Context, to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, data []byte, timeout time.Duration) (*types.Receipt, error)

SendTxAndWait 发送交易并等待确认 这是 SendTx 和 WaitForReceipt 的组合方法,发送交易后自动等待打包 参数说明:

  • ctx: 上下文对象
  • to: 接收地址(合约地址或普通地址)
  • nonce: 交易 nonce(0 表示自动计算)
  • gasLimit: Gas 限制(0 表示自动估算)
  • gasPrice: Gas 价格(nil 表示自动获取)
  • value: 转账金额(nil 表示不转账)
  • data: 交易数据(合约调用数据或 nil)
  • timeout: 等待超时时间(如 30*time.Second)

返回:

  • *types.Receipt: 交易收据
  • error: 如果发送失败或超时则返回错误

func (*Kit) SendTxWithHexInput added in v1.2.0

func (k *Kit) SendTxWithHexInput(ctx context.Context, to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, input string) (common.Hash, error)

SendTxWithHexInput 发送十六进制输入的交易(不等待确认) 构建、签名并发送交易,输入数据为十六进制字符串,返回交易哈希后立即返回 参数说明:

  • ctx: 上下文对象
  • to: 接收地址(合约地址或普通地址)
  • nonce: 交易 nonce(0 表示自动计算)
  • gasLimit: Gas 限制(0 表示自动估算)
  • gasPrice: Gas 价格(nil 表示自动获取)
  • value: 转账金额(nil 表示不转账)
  • input: 十六进制输入数据(带或不带 0x 前缀,如 "0x1234..." 或 "1234...")

返回:

  • common.Hash: 交易哈希,可用于后续查询交易状态
  • error: 如果发送失败则返回错误

注意:此方法通过嵌入的 Wallet 提供,如需等待交易确认,请使用 SendTxWithHexInputAndWait

func (*Kit) SendTxWithHexInputAndWait added in v1.2.0

func (k *Kit) SendTxWithHexInputAndWait(ctx context.Context, to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, input string, timeout time.Duration) (*types.Receipt, error)

SendTxWithHexInputAndWait 发送十六进制输入的交易并等待确认 这是 SendTxWithHexInput 和 WaitForReceipt 的组合方法 参数说明:

  • ctx: 上下文对象
  • to: 接收地址(合约地址或普通地址)
  • nonce: 交易 nonce(0 表示自动计算)
  • gasLimit: Gas 限制(0 表示自动估算)
  • gasPrice: Gas 价格(nil 表示自动获取)
  • value: 转账金额(nil 表示不转账)
  • input: 十六进制输入数据(带或不带 0x 前缀)
  • timeout: 等待超时时间(如 30*time.Second)

返回:

  • *types.Receipt: 交易收据
  • error: 如果发送失败或超时则返回错误

func (*Kit) SignMessage added in v1.2.0

func (k *Kit) SignMessage(ctx context.Context, message []byte) ([]byte, error)

SignMessage 对消息进行签名 使用 Kit 的私钥对消息进行 ECDSA 签名 参数说明:

  • ctx: 上下文对象(当前未使用,保留用于未来扩展)
  • message: 要签名的消息(原始字节)

返回:

  • []byte: 签名结果(65 字节,包含 r、s、v)
  • error: 如果签名失败则返回错误

func (*Kit) StaticCall added in v1.2.0

func (k *Kit) StaticCall(ctx context.Context, contractAddress common.Address, contractAbi abi.ABI, functionName string, blockNumber *big.Int, from *common.Address, value *big.Int, params ...interface{}) ([]interface{}, error)

StaticCall 静态调用合约方法(不花费 gas,不发送交易) 可以调用 view/pure 函数,也可以模拟调用非 view/pure 函数来查看执行结果 适用于读取合约状态、查询数据等场景 参数说明:

  • ctx: 上下文对象
  • contractAddress: 合约地址
  • contractAbi: 合约 ABI 对象
  • functionName: 函数名(如 "balanceOf", "totalSupply")
  • blockNumber: 区块号(nil 表示最新区块,可用于查询历史状态)
  • from: 调用者地址(nil 表示使用 Kit 的地址)
  • value: 模拟转账金额(nil 表示不转账,用于模拟 payable 函数)
  • params: 函数参数(按函数定义顺序传入)

返回:

  • []interface{}: 函数返回值数组(按函数定义顺序)
  • error: 如果调用失败则返回错误

func (*Kit) StaticCallWithABIString added in v1.2.0

func (k *Kit) StaticCallWithABIString(ctx context.Context, contractAddress common.Address, abiJSON string, functionName string, blockNumber *big.Int, from *common.Address, value *big.Int, params ...interface{}) ([]interface{}, error)

StaticCallWithABIString 使用 ABI JSON 字符串进行静态调用(不花费 gas,不发送交易) 这是 StaticCall 的便捷版本,接受 ABI JSON 字符串而不是 ABI 对象 适用于从配置文件或 API 获取 ABI 的场景 使用示例:

  • 简单调用(使用默认值):StaticCallWithABIString(ctx, addr, abiJSON, "balanceOf", nil, nil, nil, userAddress)
  • 指定区块号:StaticCallWithABIString(ctx, addr, abiJSON, "balanceOf", blockNum, nil, nil, userAddress)

参数说明:

  • ctx: 上下文对象
  • contractAddress: 合约地址
  • abiJSON: ABI JSON 字符串(完整的合约 ABI 或单个函数的 ABI)
  • functionName: 函数名(如 "balanceOf", "totalSupply")
  • blockNumber: 区块号(nil 表示最新区块)
  • from: 调用者地址(nil 表示使用 Kit 的地址)
  • value: 模拟转账金额(nil 表示不转账)
  • params: 函数参数(按函数定义顺序传入)

返回:

  • []interface{}: 函数返回值数组(按函数定义顺序)
  • error: 如果调用失败则返回错误

func (*Kit) TransferEther added in v1.1.0

func (k *Kit) TransferEther(ctx context.Context, to common.Address, valueInEther float64) (common.Hash, error)

TransferEther 转账以太币(便捷方法) 将 ETH 金额转换为 Wei 并发送交易,自动计算 nonce、gasLimit 和 gasPrice 参数说明:

  • ctx: 上下文对象
  • to: 接收地址
  • valueInEther: 转账金额(以 ETH 为单位,如 0.1 表示 0.1 ETH)

返回:

  • common.Hash: 交易哈希
  • error: 如果转账失败则返回错误

func (*Kit) TransferEtherAndWait added in v1.2.0

func (k *Kit) TransferEtherAndWait(ctx context.Context, to common.Address, valueInEther float64, timeout time.Duration) (*types.Receipt, error)

TransferEtherAndWait 转账以太币并等待确认 这是 TransferEther 和 WaitForReceipt 的组合方法 参数说明:

  • ctx: 上下文对象
  • to: 接收地址
  • valueInEther: 转账金额(以 ETH 为单位,如 0.1 表示 0.1 ETH)
  • timeout: 等待超时时间(如 30*time.Second)

返回:

  • *types.Receipt: 交易收据
  • error: 如果转账失败或超时则返回错误

func (*Kit) VerifyMessage added in v1.2.0

func (k *Kit) VerifyMessage(ctx context.Context, message, signature []byte) bool

VerifyMessage 验证消息签名 验证消息签名是否由指定的地址(Kit 的地址)签名 参数说明:

  • ctx: 上下文对象(当前未使用,保留用于未来扩展)
  • message: 原始消息(字节)
  • signature: 签名结果(65 字节)

返回:

  • bool: true 表示签名有效,false 表示签名无效

func (*Kit) WaitForReceipt added in v1.1.0

func (k *Kit) WaitForReceipt(ctx context.Context, txHash common.Hash, timeout time.Duration) (*types.Receipt, error)

WaitForReceipt 等待交易被打包,带超时控制 按指定间隔轮询交易收据,直到交易被打包或超时 参数说明:

  • ctx: 上下文对象
  • txHash: 交易哈希
  • timeout: 超时时间(如 30*time.Second)

返回:

  • *types.Receipt: 交易收据,包含交易状态、gas 使用等信息
  • error: 如果超时或查询失败则返回错误

func (*Kit) WaitForReceiptWithInterval added in v1.2.0

func (k *Kit) WaitForReceiptWithInterval(ctx context.Context, txHash common.Hash, timeout time.Duration, interval time.Duration) (*types.Receipt, error)

WaitForReceiptWithInterval 等待交易被打包,带超时控制和自定义轮询间隔 按指定间隔轮询交易收据,直到交易被打包或超时 参数说明:

  • ctx: 上下文对象
  • txHash: 交易哈希
  • timeout: 超时时间(如 30*time.Second)
  • interval: 轮询间隔(如 2*time.Second,建议不小于 1 秒以避免频繁请求)

返回:

  • *types.Receipt: 交易收据,包含交易状态、gas 使用等信息
  • error: 如果超时或查询失败则返回错误

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
}

Provider 以太坊提供者实现 封装了与以太坊节点通信的底层客户端

func NewProvider

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

NewProvider 创建新的以太坊提供者实例 连接到指定的以太坊节点 RPC URL 参数说明:

返回:

  • *Provider: 创建的 Provider 实例
  • error: 如果连接失败则返回错误

func NewProviderWithChainId

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

NewProviderWithChainId 创建新的以太坊提供者实例(指定链 ID) 预先设置链 ID,避免首次调用时查询链 ID 的网络延迟 适用于已知链 ID 的场景,可以提高性能 参数说明:

  • rawUrl: 以太坊节点 RPC URL
  • chainId: 链 ID(如主网为 1,Goerli 为 5)

返回:

  • *Provider: 创建的 Provider 实例
  • error: 如果连接失败则返回错误

func (*Provider) Close

func (p *Provider) Close()

Close 关闭客户端连接 释放所有底层资源,包括 ethclient 和 rpc client 建议在程序退出或不再使用时调用此方法

func (*Provider) EstimateGas

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

EstimateGas 估算交易所需的 Gas 数量 通过模拟交易执行来估算 gas 消耗,这对于确定交易的 gasLimit 很有用 参数说明:

  • ctx: 上下文对象
  • from: 发送地址
  • to: 接收地址(合约地址或普通地址)
  • nonce: 交易 nonce
  • gasPrice: Gas 价格(nil 表示不设置)
  • value: 转账金额(nil 表示不转账)
  • data: 交易数据(合约调用数据或 nil)

返回:

  • uint64: 估算的 Gas 数量
  • error: 如果估算失败则返回错误(如合约执行失败、余额不足等)

func (*Provider) FilterLogs added in v1.2.0

func (p *Provider) FilterLogs(ctx context.Context, contractAddress *common.Address, eventTopic common.Hash, fromBlock, toBlock *big.Int, indexedTopics []common.Hash) ([]types.Log, error)

FilterLogs 查询事件日志 用于查询指定区块范围内的事件日志,支持按合约地址、事件签名和 indexed 参数进行过滤 参数说明:

  • ctx: 上下文对象
  • contractAddress: 合约地址(nil 表示查询所有合约)
  • eventTopic: 事件签名 topic(如 GetEventTopic("Transfer(address,address,uint256)"))
  • fromBlock: 起始区块号(nil 表示从最新区块开始)
  • toBlock: 结束区块号(nil 表示到最新区块)
  • indexedTopics: 可选的 indexed 参数过滤(nil 表示不过滤,每个元素对应一个 indexed 参数)

返回:

  • []types.Log: 事件日志列表,用户需要自行解析 Data 和 Topics
  • error: 如果查询失败则返回错误

使用示例:

  • 查询单个合约的事件:FilterLogs(ctx, &contractAddr, topicHash, fromBlock, toBlock, nil)
  • 查询所有合约的事件:FilterLogs(ctx, nil, topicHash, fromBlock, toBlock, nil)
  • 带 indexed 参数过滤:FilterLogs(ctx, &contractAddr, topicHash, fromBlock, toBlock, []common.Hash{fromAddr.Hash(), toAddr.Hash()})

func (*Provider) GetBlockByHash

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

GetBlockByHash 根据区块哈希获取区块信息 通过区块哈希查询完整的区块信息,包括区块头和所有交易 参数说明:

  • ctx: 上下文对象
  • blkHash: 区块哈希

返回:

  • *types.Block: 区块对象,包含区块头、交易列表等信息
  • error: 如果查询失败则返回错误

func (*Provider) GetBlockByNumber

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

GetBlockByNumber 根据区块号获取区块信息 通过区块号查询完整的区块信息,包括区块头和所有交易 参数说明:

  • ctx: 上下文对象
  • number: 区块号(nil 表示最新区块)

返回:

  • *types.Block: 区块对象,包含区块头、交易列表等信息
  • error: 如果查询失败则返回错误

func (*Provider) GetBlockNumber

func (p *Provider) GetBlockNumber(ctx context.Context) (uint64, error)

GetBlockNumber 获取最新区块号 返回当前链上的最新(最新打包的)区块号 参数说明:

  • ctx: 上下文对象

返回:

  • uint64: 最新区块号
  • error: 如果查询失败则返回错误

func (*Provider) GetChainID

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

GetChainID 获取链 ID 链 ID 用于 EIP-155 签名,防止重放攻击 如果已缓存链 ID,则直接返回;否则查询链上并缓存 参数说明:

  • ctx: 上下文对象

返回:

  • *big.Int: 链 ID(如主网为 1,Goerli 为 5)
  • error: 如果查询失败则返回错误

func (*Provider) GetContractBytecode

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

GetContractBytecode 根据合约地址获取字节码 返回合约在链上的字节码(十六进制字符串,带 0x 前缀) 参数说明:

  • ctx: 上下文对象
  • address: 合约地址

返回:

  • string: 合约字节码(十六进制字符串,如 "0x608060405234801561001057600080fd5b50...")
  • error: 如果查询失败则返回错误

注意:如果地址不是合约(普通地址),返回的字节码为空字符串

func (*Provider) GetEthClient

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

GetEthClient 获取以太坊客户端实例 返回底层的 ethclient.Client,可用于执行底层操作 返回:

  • *ethclient.Client: 以太坊客户端实例

func (*Provider) GetFromAddress

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

GetFromAddress 从交易中提取发送地址 通过解析交易签名来获取发送者地址(交易签名者的地址) 参数说明:

  • tx: 交易对象

返回:

  • common.Address: 发送地址
  • error: 如果提取失败则返回错误(如签名无效)

func (*Provider) GetNetworkID

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

GetNetworkID 获取网络 ID 网络 ID 用于标识不同的网络(主网、测试网等) 参数说明:

  • ctx: 上下文对象

返回:

  • *big.Int: 网络 ID
  • error: 如果查询失败则返回错误

func (*Provider) GetRpcClient

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

GetRpcClient 获取 RPC 客户端实例 返回底层的 rpc.Client,可用于执行底层 RPC 调用 返回:

  • *rpc.Client: RPC 客户端实例

func (*Provider) GetSuggestGasPrice

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

GetSuggestGasPrice 获取建议的 Gas 价格 返回网络建议的 Gas 价格(单位为 Wei) 参数说明:

  • ctx: 上下文对象

返回:

  • *big.Int: 建议的 Gas 价格(单位为 Wei)
  • error: 如果查询失败则返回错误

func (*Provider) GetTransactionByHash

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

GetTransactionByHash 根据交易哈希获取交易信息 查询交易的详细信息,包括交易状态(是否已打包) 参数说明:

  • ctx: 上下文对象
  • txHash: 交易哈希

返回:

  • tx: 交易对象,包含交易的所有字段
  • isPending: 交易是否还在待处理状态(true 表示还在 mempool 中)
  • error: 如果查询失败则返回错误

func (*Provider) GetTransactionReceipt

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

GetTransactionReceipt 根据交易哈希获取交易收据 交易收据包含交易执行结果、gas 使用情况、日志等信息 注意:只有已打包的交易才有收据,待处理的交易无法获取收据 参数说明:

  • ctx: 上下文对象
  • txHash: 交易哈希

返回:

  • *types.Receipt: 交易收据,包含交易状态、gas 使用等信息
  • error: 如果查询失败则返回错误(交易未打包时会返回错误)

func (*Provider) IsContractAddress

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

IsContractAddress 检查地址是否为合约地址 通过检查地址的代码长度来判断是否为合约(合约代码长度 > 0) 参数说明:

  • ctx: 上下文对象
  • address: 要检查的地址

返回:

  • bool: true 表示是合约地址,false 表示是普通地址(EOA)
  • error: 如果查询失败则返回错误

type Wallet

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

Wallet 以太坊钱包实现 封装了私钥、地址和提供者,提供钱包管理、交易构建、签名和发送等功能

func NewWallet

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

NewWallet 创建新的钱包实例 从十六进制私钥字符串创建钱包,并连接到指定的以太坊节点 参数说明:

返回:

  • *Wallet: 创建的钱包实例
  • error: 如果创建失败则返回错误

func NewWalletWithComponents

func NewWalletWithComponents(privateKey *ecdsa.PrivateKey, ep EtherProvider) (*Wallet, error)

NewWalletWithComponents 使用已有组件创建钱包实例 适用于已经创建好私钥和 Provider 的情况,避免重复创建 参数说明:

  • privateKey: 已存在的 ECDSA 私钥
  • ep: 已存在的 EtherProvider 实例

返回:

  • *Wallet: 创建的钱包实例
  • error: 如果创建失败则返回错误

func (*Wallet) BuildTxOpts

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

BuildTxOpts 构建交易的选项 用于与 go-ethereum 的 bind 包配合使用,生成 TransactOpts 参数说明:

  • ctx: 上下文对象
  • value: 转账金额(nil 表示不转账)
  • nonce: 交易 nonce(nil 或 <= 0 表示自动计算)
  • gasPrice: Gas 价格(nil 或 <= 0 表示自动获取)

返回:

  • *bind.TransactOpts: 交易选项,可用于合约交互
  • error: 如果构建失败则返回错误

func (*Wallet) CallContract

func (w *Wallet) CallContract(ctx context.Context, blockNumber *big.Int, from *common.Address, value *big.Int, contractAddress common.Address, contractAbi abi.ABI, functionName string, params ...interface{}) ([]interface{}, error)

CallContract 调用合约方法(静态调用,不发送交易) 可以调用 view/pure 函数,也可以模拟调用非 view/pure 函数来查看执行结果 参数说明:

  • ctx: 上下文对象
  • blockNumber: 区块号(nil 表示最新区块,可用于查询历史状态)
  • from: 调用者地址(nil 表示不设置)
  • value: 模拟转账金额(nil 表示不转账,用于模拟 payable 函数)
  • contractAddress: 合约地址
  • contractAbi: 合约 ABI 对象
  • functionName: 函数名(如 "balanceOf", "totalSupply")
  • params: 函数参数(按函数定义顺序传入)

返回:

  • []interface{}: 函数返回值数组(按函数定义顺序)
  • error: 如果调用失败则返回错误

func (*Wallet) CloseWallet

func (w *Wallet) CloseWallet()

CloseWallet 关闭钱包连接 释放所有底层资源,包括 Provider 的连接 建议在程序退出或不再使用时调用此方法

func (*Wallet) GetAddress

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

GetAddress 获取钱包地址 返回:

  • common.Address: 钱包地址

func (*Wallet) GetBalance

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

GetBalance 获取账户余额 返回账户的本位币余额(单位为 Wei) 参数说明:

  • ctx: 上下文对象

返回:

  • *big.Int: 余额(单位为 Wei)
  • error: 如果查询失败则返回错误

func (*Wallet) GetClient

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

GetClient 获取以太坊客户端实例 返回:

  • *ethclient.Client: 以太坊客户端

func (*Wallet) GetEthProvider

func (w *Wallet) GetEthProvider() EtherProvider

GetEthProvider 获取以太坊提供者实例 返回:

  • EtherProvider: 以太坊提供者接口

func (*Wallet) GetNonce

func (w *Wallet) GetNonce(ctx context.Context) (uint64, error)

GetNonce 获取账户的 nonce nonce 用于防止交易重放,每个交易必须使用唯一的 nonce 返回待处理状态的 nonce(pending nonce),即下一个可用的 nonce 参数说明:

  • ctx: 上下文对象

返回:

  • uint64: 下一个可用的 nonce
  • error: 如果查询失败则返回错误

func (*Wallet) GetPrivateKey added in v1.1.0

func (w *Wallet) GetPrivateKey() *ecdsa.PrivateKey

GetPrivateKey 获取私钥 返回:

  • *ecdsa.PrivateKey: ECDSA 私钥对象

注意:请妥善保管私钥,泄露私钥将导致资产丢失

func (*Wallet) NewTx

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

NewTx 构建一笔交易 自动计算 nonce、gasLimit 和 gasPrice(如果未提供) 参数说明:

  • ctx: 上下文对象
  • to: 接收地址(合约地址或普通地址)
  • nonce: 交易 nonce(0 表示自动计算)
  • gasLimit: Gas 限制(0 表示自动估算)
  • gasPrice: Gas 价格(nil 或 big.NewInt(0) 表示自动获取)
  • value: 转账金额(nil 表示不转账)
  • data: 交易数据(合约调用数据或 nil)

返回:

  • *types.Transaction: 交易对象(未签名)
  • error: 如果构建失败则返回错误

func (*Wallet) NewTxWithHexInput

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

NewTxWithHexInput 构建一笔交易,使用十六进制输入数据 与 NewTx 类似,但接受十六进制字符串作为输入数据 参数说明:

  • ctx: 上下文对象
  • to: 接收地址
  • nonce: 交易 nonce(0 表示自动计算)
  • gasLimit: Gas 限制(0 表示自动估算)
  • gasPrice: Gas 价格(nil 或 big.NewInt(0) 表示自动获取)
  • value: 转账金额(nil 表示不转账)
  • input: 十六进制输入数据(带或不带 0x 前缀,如 "0x1234..." 或 "1234...")

返回:

  • *types.Transaction: 交易对象(未签名)
  • error: 如果构建失败则返回错误

func (*Wallet) SendSignedTx

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

SendSignedTx 发送已签名的交易 将已签名的交易发送到网络 参数说明:

  • ctx: 上下文对象
  • signedTx: 已签名的交易对象

返回:

  • common.Hash: 交易哈希
  • error: 如果发送失败则返回错误(如余额不足、nonce 错误等)

func (*Wallet) SendTx

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

SendTx 发送交易 构建、签名并发送交易,返回交易哈希 参数说明:

  • ctx: 上下文对象
  • to: 接收地址(合约地址或普通地址)
  • nonce: 交易 nonce(0 表示自动计算)
  • gasLimit: Gas 限制(0 表示自动估算)
  • gasPrice: Gas 价格(nil 或 big.NewInt(0) 表示自动获取)
  • value: 转账金额(nil 表示不转账)
  • data: 交易数据(合约调用数据或 nil)

返回:

  • common.Hash: 交易哈希,可用于查询交易状态
  • error: 如果发送失败则返回错误

func (*Wallet) SendTxWithHexInput

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

SendTxWithHexInput 发送一笔交易,使用十六进制输入数据 与 SendTx 类似,但接受十六进制字符串作为输入数据 参数说明:

  • ctx: 上下文对象
  • to: 接收地址
  • nonce: 交易 nonce(0 表示自动计算)
  • gasLimit: Gas 限制(0 表示自动估算)
  • gasPrice: Gas 价格(nil 或 big.NewInt(0) 表示自动获取)
  • value: 转账金额(nil 表示不转账)
  • input: 十六进制输入数据(带或不带 0x 前缀)

返回:

  • common.Hash: 交易哈希
  • error: 如果发送失败则返回错误

func (*Wallet) SignTx

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

SignTx 对交易进行签名 使用钱包的私钥对交易进行 EIP-155 签名(伦敦签名) 参数说明:

  • ctx: 上下文对象
  • tx: 未签名的交易对象

返回:

  • *types.Transaction: 已签名的交易对象
  • error: 如果签名失败则返回错误

func (*Wallet) Signature

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

Signature 对数据进行签名 使用钱包的私钥对数据进行 ECDSA 签名 先对数据进行 Keccak256 哈希,然后使用私钥签名 参数说明:

  • data: 要签名的原始数据(字节)

返回:

  • []byte: 签名结果(65 字节,包含 r、s、v)
  • error: 如果签名失败则返回错误

Directories

Path Synopsis
contracts
examples
kit command

Jump to

Keyboard shortcuts

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