|
| 1 | +import Web3 from "web3"; |
| 2 | + |
| 3 | +const network = "mainnet"; |
| 4 | +const INFURA_PROJECT_ID = "INFURA_PROJECT_ID"; |
| 5 | +const RPC_ENDPOINT = `https://${network}.infura.io/v3/${INFURA_PROJECT_ID}`; |
| 6 | + |
| 7 | +export class EthNetwork { |
| 8 | + private web3: Web3; |
| 9 | + |
| 10 | + /** |
| 11 | + * Creates an instance of EthNetwork object. |
| 12 | + */ |
| 13 | + constructor() { |
| 14 | + this.web3 = new Web3(RPC_ENDPOINT); |
| 15 | + } |
| 16 | + |
| 17 | + /** |
| 18 | + * Get the number of the latest block on Ethereum Mainnet. |
| 19 | + * @returns latest block number. |
| 20 | + */ |
| 21 | + public getLatestBlockNumber = async () => { |
| 22 | + return await this.web3.eth.getBlockNumber(); |
| 23 | + }; |
| 24 | + |
| 25 | + /** |
| 26 | + * Fetch a block of given number or hash from the Ethereum Mainnet. |
| 27 | + * @param block number or hash of the block. |
| 28 | + * @returns a block of given number or Hash. |
| 29 | + */ |
| 30 | + public getBlock = async (block: number | string) => { |
| 31 | + return await this.web3.eth.getBlock(block); |
| 32 | + }; |
| 33 | + |
| 34 | + /** |
| 35 | + * Get the number of transaction in a block of given number or Hash. |
| 36 | + * @param block (Optional) Hash or number of the block- default is "latest". |
| 37 | + * @returns number of transactions in the block. |
| 38 | + */ |
| 39 | + public getBlockTransactionCount = async ( |
| 40 | + block: string | number = "latest" |
| 41 | + ) => { |
| 42 | + return await this.web3.eth.getBlockTransactionCount(block); |
| 43 | + }; |
| 44 | + |
| 45 | + /** |
| 46 | + * Get a specific transaction from a block of given number. |
| 47 | + * @param trxIndex index of the transaction in the block. |
| 48 | + * @param block (Optional) Hash or number of the block- default is "latest". |
| 49 | + * @returns transactions object for the required transaction. |
| 50 | + */ |
| 51 | + public getTransactionFromBlock = async ( |
| 52 | + trxIndex: number, |
| 53 | + block: string | number = "latest" |
| 54 | + ) => { |
| 55 | + return await this.web3.eth.getTransactionFromBlock(block, trxIndex); |
| 56 | + }; |
| 57 | + |
| 58 | + /** |
| 59 | + * Fetch a given number of latest blocks from Ethereum Mainnet. |
| 60 | + * @param numberOfBlocks (Optional) number of blocks to fetch. Default is `10`. |
| 61 | + */ |
| 62 | + public getLatestXBlocks = async (numberOfBlocks: number = 10) => { |
| 63 | + const latestBlock = await this.getLatestBlockNumber(); |
| 64 | + |
| 65 | + let blocks: Array<any> = []; |
| 66 | + for (let i = 0; i < numberOfBlocks; ++i) { |
| 67 | + blocks.push(await this.getBlock(latestBlock - i)); |
| 68 | + } |
| 69 | + return blocks; |
| 70 | + }; |
| 71 | +} |
0 commit comments