Documentation
¶
Index ¶
- Constants
- Variables
- func BuildContractInputData(contract abi.ABI, name string, args ...interface{}) ([]byte, error)
- func BuildPrivateKeyFromHex(privateKeyHex string) (*ecdsa.PrivateKey, error)
- func BuildPrivateKeyFromMnemonic(mnemonic string) (*ecdsa.PrivateKey, error)
- func BuildPrivateKeyFromMnemonicAndAccountId(mnemonic string, accountId uint32) (*ecdsa.PrivateKey, error)
- func DecodeRawTxHex(rawTx string) (*types.Transaction, error)
- func GeneratePrivateKey() (*ecdsa.PrivateKey, error)
- func GetABI(abiStr string) (abi.ABI, error)
- func GetContractMethodId(method string) string
- func GetEventTopic(event string) string
- func GetHexPrivateKey(privateKey *ecdsa.PrivateKey) string
- func GetHexPublicKey(privateKey *ecdsa.PrivateKey) string
- func GetMaxUint256() *big.Int
- func IsValidAddress(iAddress interface{}) bool
- func NewTx(to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, ...) (*types.Transaction, error)
- func NewTxWithHexData(to common.Address, nonce, gasLimit uint64, gasPrice, value *big.Int, ...) (*types.Transaction, error)
- func PrivateKeyToAddress(privateKey *ecdsa.PrivateKey) common.Address
- func PublicKeyBytesToAddress(publicKey []byte) common.Address
- func ToDecimal(iValue interface{}, decimals int) decimal.Decimal
- func ToWei(iAmount interface{}, decimals int) *big.Int
- func VerifySignature(address string, data, signature []byte) bool
- type EtherProvider
- type EtherWallet
- type Kit
- func (k *Kit) FilterEventLogs(ctx context.Context, contractAddress *common.Address, eventSignature string, ...) ([]types.Log, error)
- func (k *Kit) GetContractBytecode(ctx context.Context, address common.Address) (string, error)
- func (k *Kit) GetLatestBlock(ctx context.Context) (*types.Block, error)
- func (k *Kit) InvokeContract(ctx context.Context, contractAddress common.Address, contractAbi abi.ABI, ...) (common.Hash, error)
- func (k *Kit) InvokeContractWithABIString(ctx context.Context, contractAddress common.Address, abiJSON string, ...) (common.Hash, error)
- func (k *Kit) IsContract(ctx context.Context, address common.Address) (bool, error)
- func (k *Kit) SendTx(ctx context.Context, to common.Address, nonce, gasLimit uint64, ...) (common.Hash, error)
- func (k *Kit) SendTxAndWait(ctx context.Context, to common.Address, nonce, gasLimit uint64, ...) (*types.Receipt, error)
- func (k *Kit) SendTxWithHexInput(ctx context.Context, to common.Address, nonce, gasLimit uint64, ...) (common.Hash, error)
- func (k *Kit) SendTxWithHexInputAndWait(ctx context.Context, to common.Address, nonce, gasLimit uint64, ...) (*types.Receipt, error)
- func (k *Kit) SignMessage(ctx context.Context, message []byte) ([]byte, error)
- func (k *Kit) StaticCall(ctx context.Context, contractAddress common.Address, contractAbi abi.ABI, ...) ([]interface{}, error)
- func (k *Kit) StaticCallWithABIString(ctx context.Context, contractAddress common.Address, abiJSON string, ...) ([]interface{}, error)
- func (k *Kit) TransferEther(ctx context.Context, to common.Address, valueInEther float64) (common.Hash, error)
- func (k *Kit) TransferEtherAndWait(ctx context.Context, to common.Address, valueInEther float64, ...) (*types.Receipt, error)
- func (k *Kit) VerifyMessage(ctx context.Context, message, signature []byte) bool
- func (k *Kit) WaitForReceipt(ctx context.Context, txHash common.Hash, timeout time.Duration) (*types.Receipt, error)
- func (k *Kit) WaitForReceiptWithInterval(ctx context.Context, txHash common.Hash, timeout time.Duration, ...) (*types.Receipt, error)
- type NetworkConfig
- type Provider
- func (p *Provider) Close()
- func (p *Provider) EstimateGas(ctx context.Context, from, to common.Address, nonce uint64, ...) (uint64, error)
- func (p *Provider) FilterLogs(ctx context.Context, contractAddress *common.Address, eventTopic common.Hash, ...) ([]types.Log, error)
- func (p *Provider) GetBlockByHash(ctx context.Context, blkHash common.Hash) (*types.Block, error)
- func (p *Provider) GetBlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error)
- func (p *Provider) GetBlockNumber(ctx context.Context) (uint64, error)
- func (p *Provider) GetChainID(ctx context.Context) (*big.Int, error)
- func (p *Provider) GetContractBytecode(ctx context.Context, address common.Address) (string, error)
- func (p *Provider) GetEthClient() *ethclient.Client
- func (p *Provider) GetFromAddress(tx *types.Transaction) (common.Address, error)
- func (p *Provider) GetNetworkID(ctx context.Context) (*big.Int, error)
- func (p *Provider) GetRpcClient() *rpc.Client
- func (p *Provider) GetSuggestGasPrice(ctx context.Context) (*big.Int, error)
- func (p *Provider) GetTransactionByHash(ctx context.Context, txHash common.Hash) (tx *types.Transaction, isPending bool, err error)
- func (p *Provider) GetTransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
- func (p *Provider) IsContractAddress(ctx context.Context, address common.Address) (bool, error)
- type Wallet
- func (w *Wallet) BuildTxOpts(ctx context.Context, value, nonce, gasPrice *big.Int) (*bind.TransactOpts, error)
- func (w *Wallet) CallContract(ctx context.Context, blockNumber *big.Int, from *common.Address, ...) ([]interface{}, error)
- func (w *Wallet) CloseWallet()
- func (w *Wallet) GetAddress() common.Address
- func (w *Wallet) GetBalance(ctx context.Context) (*big.Int, error)
- func (w *Wallet) GetClient() *ethclient.Client
- func (w *Wallet) GetEthProvider() EtherProvider
- func (w *Wallet) GetNonce(ctx context.Context) (uint64, error)
- func (w *Wallet) GetPrivateKey() *ecdsa.PrivateKey
- func (w *Wallet) NewTx(ctx context.Context, to common.Address, nonce, gasLimit uint64, ...) (*types.Transaction, error)
- func (w *Wallet) NewTxWithHexInput(ctx context.Context, to common.Address, nonce, gasLimit uint64, ...) (*types.Transaction, error)
- func (w *Wallet) SendSignedTx(ctx context.Context, signedTx *types.Transaction) (common.Hash, error)
- func (w *Wallet) SendTx(ctx context.Context, to common.Address, nonce, gasLimit uint64, ...) (common.Hash, error)
- func (w *Wallet) SendTxWithHexInput(ctx context.Context, to common.Address, nonce, gasLimit uint64, ...) (common.Hash, error)
- func (w *Wallet) SignTx(ctx context.Context, tx *types.Transaction) (*types.Transaction, error)
- func (w *Wallet) Signature(data []byte) ([]byte, error)
Constants ¶
const ( MainnetChainID = 1 GoerliChainID = 5 SepoliaChainID = 11155111 PolygonChainID = 137 BSCChainID = 56 ArbitrumChainID = 42161 OptimismChainID = 10 AvalancheChainID = 43114 FantomChainID = 250 )
网络链ID常量
const ( DefaultGasLimit = 21000 // ETH 转账默认 gas limit ContractGasLimit = 200000 // 合约调用默认 gas limit DefaultGasPrice = 20000000000 // 20 Gwei MaxGasPrice = 1000000000000 // 1000 Gwei MinGasPrice = 1000000000 // 1 Gwei )
Gas 相关常量
const ( ERC20TransferGasLimit = 65000 ERC20ApproveGasLimit = 50000 UniswapSwapGasLimit = 300000 )
常用 Gas Limit
const ( DefaultTimeout = 30 BlockConfirmationTime = 12 // 以太坊平均出块时间 FastConfirmationTime = 15 // 快速确认超时 SafeConfirmationTime = 180 // 安全确认超时 )
时间相关常量 (秒)
const ( Wei = 1 GWei = 1000000000 Ether = 1000000000000000000 )
以太坊单位常量
const ( EthDecimals = 18 USDCDecimals = 6 USDTDecimals = 6 DefaultDecimals = 18 )
默认小数位数
const ( // 零地址 ZeroAddress = "0x0000000000000000000000000000000000000000" // 原生代币地址 (用于表示 ETH/BNB/MATIC 等) NativeTokenAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" )
常用地址
const ( ERC20TransferMethodID = "0xa9059cbb" ERC20TransferFromMethodID = "0x23b872dd" ERC20ApproveMethodID = "0x095ea7b3" ERC20BalanceOfMethodID = "0x70a08231" ERC20TotalSupplyMethodID = "0x18160ddd" )
ERC20 常用方法选择器
const ( ERC20TransferEventTopic = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" ERC20ApprovalEventTopic = "0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925" )
ERC20 常用事件主题
const ( // DefaultWaitInterval 默认等待交易确认的轮询间隔 DefaultWaitInterval = time.Second )
Kit 相关常量
const (
ZeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000"
)
常用哈希
Variables ¶
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 常量
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") )
标准错误定义
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
PublicKeyBytesToAddress 从公钥字节转换为以太坊地址 以太坊地址是从公钥派生出来的:对公钥进行 Keccak256 哈希,然后取后 20 字节 参数说明:
- publicKey: 公钥字节(通常包含 0x04 前缀,长度为 65 字节)
返回:
- common.Address: 派生出的以太坊地址
注意:
- 公钥字节的第一个字节(0x04)会被移除,然后对剩余 64 字节进行哈希
- 哈希结果的后 20 字节即为地址
func ToDecimal ¶
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 ¶
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 ¶
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
NewKit 创建以太坊开发工具包 参数说明:
- hexPk: 十六进制私钥字符串(带或不带 0x 前缀)
- rawUrl: 以太坊节点 RPC URL(如 "https://eth-mainnet.g.alchemy.com/v2/your-api-key")
返回:
- *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
NewKitWithGeneratedKey 创建以太坊开发工具包(自动生成随机私钥) 适用于不需要导入已有私钥的场景,如测试、临时钱包等 会自动生成一个随机私钥并创建对应的 Kit 实例 参数说明:
- rawUrl: 以太坊节点 RPC URL(如 "https://eth-mainnet.g.alchemy.com/v2/your-api-key")
返回:
- *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
GetContractBytecode 获取合约字节码 返回合约在链上的字节码(十六进制字符串,带 0x 前缀) 参数说明:
- ctx: 上下文对象
- address: 合约地址
返回:
- string: 合约字节码(十六进制字符串,如 "0x608060405234801561001057600080fd5b50...")
- error: 如果查询失败则返回错误
func (*Kit) GetLatestBlock ¶ added in v1.2.0
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
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
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
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 ¶
NewProvider 创建新的以太坊提供者实例 连接到指定的以太坊节点 RPC URL 参数说明:
- rawUrl: 以太坊节点 RPC URL(如 "https://eth-mainnet.g.alchemy.com/v2/your-api-key" 或 "http://localhost:8545")
返回:
- *Provider: 创建的 Provider 实例
- error: 如果连接失败则返回错误
func NewProviderWithChainId ¶
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 ¶
GetBlockByHash 根据区块哈希获取区块信息 通过区块哈希查询完整的区块信息,包括区块头和所有交易 参数说明:
- ctx: 上下文对象
- blkHash: 区块哈希
返回:
- *types.Block: 区块对象,包含区块头、交易列表等信息
- error: 如果查询失败则返回错误
func (*Provider) GetBlockByNumber ¶
GetBlockByNumber 根据区块号获取区块信息 通过区块号查询完整的区块信息,包括区块头和所有交易 参数说明:
- ctx: 上下文对象
- number: 区块号(nil 表示最新区块)
返回:
- *types.Block: 区块对象,包含区块头、交易列表等信息
- error: 如果查询失败则返回错误
func (*Provider) GetBlockNumber ¶
GetBlockNumber 获取最新区块号 返回当前链上的最新(最新打包的)区块号 参数说明:
- ctx: 上下文对象
返回:
- uint64: 最新区块号
- error: 如果查询失败则返回错误
func (*Provider) GetChainID ¶
GetChainID 获取链 ID 链 ID 用于 EIP-155 签名,防止重放攻击 如果已缓存链 ID,则直接返回;否则查询链上并缓存 参数说明:
- ctx: 上下文对象
返回:
- *big.Int: 链 ID(如主网为 1,Goerli 为 5)
- error: 如果查询失败则返回错误
func (*Provider) GetContractBytecode ¶
GetContractBytecode 根据合约地址获取字节码 返回合约在链上的字节码(十六进制字符串,带 0x 前缀) 参数说明:
- ctx: 上下文对象
- address: 合约地址
返回:
- string: 合约字节码(十六进制字符串,如 "0x608060405234801561001057600080fd5b50...")
- error: 如果查询失败则返回错误
注意:如果地址不是合约(普通地址),返回的字节码为空字符串
func (*Provider) GetEthClient ¶
GetEthClient 获取以太坊客户端实例 返回底层的 ethclient.Client,可用于执行底层操作 返回:
- *ethclient.Client: 以太坊客户端实例
func (*Provider) GetFromAddress ¶
GetFromAddress 从交易中提取发送地址 通过解析交易签名来获取发送者地址(交易签名者的地址) 参数说明:
- tx: 交易对象
返回:
- common.Address: 发送地址
- error: 如果提取失败则返回错误(如签名无效)
func (*Provider) GetNetworkID ¶
GetNetworkID 获取网络 ID 网络 ID 用于标识不同的网络(主网、测试网等) 参数说明:
- ctx: 上下文对象
返回:
- *big.Int: 网络 ID
- error: 如果查询失败则返回错误
func (*Provider) GetRpcClient ¶
GetRpcClient 获取 RPC 客户端实例 返回底层的 rpc.Client,可用于执行底层 RPC 调用 返回:
- *rpc.Client: RPC 客户端实例
func (*Provider) GetSuggestGasPrice ¶
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: 如果查询失败则返回错误(交易未打包时会返回错误)
type Wallet ¶
type Wallet struct {
// contains filtered or unexported fields
}
Wallet 以太坊钱包实现 封装了私钥、地址和提供者,提供钱包管理、交易构建、签名和发送等功能
func NewWallet ¶
NewWallet 创建新的钱包实例 从十六进制私钥字符串创建钱包,并连接到指定的以太坊节点 参数说明:
- hexPk: 十六进制私钥字符串(带或不带 0x 前缀)
- rawUrl: 以太坊节点 RPC URL(如 "https://eth-mainnet.g.alchemy.com/v2/your-api-key")
返回:
- *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) GetBalance ¶
GetBalance 获取账户余额 返回账户的本位币余额(单位为 Wei) 参数说明:
- ctx: 上下文对象
返回:
- *big.Int: 余额(单位为 Wei)
- error: 如果查询失败则返回错误
func (*Wallet) GetEthProvider ¶
func (w *Wallet) GetEthProvider() EtherProvider
GetEthProvider 获取以太坊提供者实例 返回:
- EtherProvider: 以太坊提供者接口
func (*Wallet) GetNonce ¶
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: 如果签名失败则返回错误