76 lines
1.9 KiB
Go
76 lines
1.9 KiB
Go
package genex
|
|
|
|
import (
|
|
"context"
|
|
"math/big"
|
|
"time"
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
|
)
|
|
|
|
// GetBlock 获取区块信息
|
|
func (c *Client) GetBlock(height int64) (*BlockInfo, error) {
|
|
block, err := c.ethClient.BlockByNumber(context.Background(), big.NewInt(height))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &BlockInfo{
|
|
Height: block.Number().Int64(),
|
|
Hash: block.Hash().Hex(),
|
|
Timestamp: time.Unix(int64(block.Time()), 0),
|
|
TxCount: len(block.Transactions()),
|
|
Proposer: block.Coinbase().Hex(),
|
|
}, nil
|
|
}
|
|
|
|
// GetLatestBlock 获取最新区块
|
|
func (c *Client) GetLatestBlock() (*BlockInfo, error) {
|
|
block, err := c.ethClient.BlockByNumber(context.Background(), nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &BlockInfo{
|
|
Height: block.Number().Int64(),
|
|
Hash: block.Hash().Hex(),
|
|
Timestamp: time.Unix(int64(block.Time()), 0),
|
|
TxCount: len(block.Transactions()),
|
|
Proposer: block.Coinbase().Hex(),
|
|
}, nil
|
|
}
|
|
|
|
// GetTransaction 获取交易详情
|
|
func (c *Client) GetTransaction(hash common.Hash) (*TransactionInfo, error) {
|
|
tx, _, err := c.ethClient.TransactionByHash(context.Background(), hash)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
receipt, err := c.ethClient.TransactionReceipt(context.Background(), hash)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
status := "failed"
|
|
if receipt.Status == 1 {
|
|
status = "success"
|
|
}
|
|
return &TransactionInfo{
|
|
Hash: tx.Hash().Hex(),
|
|
BlockHeight: receipt.BlockNumber.Int64(),
|
|
From: "", // 需要从签名恢复
|
|
To: tx.To().Hex(),
|
|
Value: tx.Value(),
|
|
GasUsed: receipt.GasUsed,
|
|
Status: status,
|
|
}, nil
|
|
}
|
|
|
|
// GetStats 获取链统计
|
|
func (c *Client) GetStats() (*ChainStats, error) {
|
|
block, err := c.ethClient.BlockByNumber(context.Background(), nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &ChainStats{
|
|
BlockHeight: block.Number().Int64(),
|
|
}, nil
|
|
}
|