|
| 1 | +package eth |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/canopy-network/canopy/cmd/rpc/oracle/types" |
| 5 | + "github.com/canopy-network/canopy/lib" |
| 6 | + ethtypes "github.com/ethereum/go-ethereum/core/types" |
| 7 | +) |
| 8 | + |
| 9 | +var _ types.BlockI = &Block{} // Ensures *Block implements BlockI |
| 10 | + |
| 11 | +// Block represents an ethereum block that implements BlockI interface |
| 12 | +type Block struct { |
| 13 | + hash string // block hash as hex string |
| 14 | + number uint64 // block number |
| 15 | + transactions []*Transaction // array of transactions in this block |
| 16 | +} |
| 17 | + |
| 18 | +// NewBlock creates a new Block from an ethereum block |
| 19 | +func NewBlock(ethBlock *ethtypes.Block) (*Block, error) { |
| 20 | + // validate input block is not nil |
| 21 | + if ethBlock == nil { |
| 22 | + return nil, lib.ErrNilBlock() |
| 23 | + } |
| 24 | + // create new block instance |
| 25 | + block := &Block{ |
| 26 | + hash: ethBlock.Hash().Hex(), // convert block hash to hex string |
| 27 | + number: ethBlock.NumberU64(), // get block number as uint64 |
| 28 | + transactions: make([]*Transaction, 0), // initialize empty transaction slice |
| 29 | + } |
| 30 | + return block, nil // return successfully created block |
| 31 | +} |
| 32 | + |
| 33 | +// Hash returns the block hash as a string |
| 34 | +func (b *Block) Hash() string { |
| 35 | + return b.hash // return the stored block hash |
| 36 | +} |
| 37 | + |
| 38 | +// Number returns the block number |
| 39 | +func (b *Block) Number() uint64 { |
| 40 | + return b.number // return the stored block number |
| 41 | +} |
| 42 | + |
| 43 | +// Transactions returns all transactions in this block |
| 44 | +func (b *Block) Transactions() []types.TransactionI { |
| 45 | + // create slice to hold transaction interfaces |
| 46 | + txs := make([]types.TransactionI, len(b.transactions)) |
| 47 | + // convert each transaction to interface type |
| 48 | + for i, tx := range b.transactions { |
| 49 | + txs[i] = tx // assign transaction to interface slice |
| 50 | + } |
| 51 | + return txs // return slice of transaction interfaces |
| 52 | +} |
0 commit comments