• Stars
    star
    129
  • Rank 279,178 (Top 6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A JS module for keeping track of the latest Ethereum block by polling an ethereum provider

eth-block-tracker

This module walks the Ethereum blockchain, keeping track of the latest block. It uses a web3 provider as a data source and will continuously poll for the next block.

Installation

yarn add eth-block-tracker

or

npm install eth-block-tracker

Usage

const createInfuraProvider = require('eth-json-rpc-infura');
const { PollingBlockTracker } = require('eth-block-tracker');

const provider = createInfuraProvider({
  network: 'mainnet',
  projectId: process.env.INFURA_PROJECT_ID,
});
const blockTracker = new PollingBlockTracker({ provider });

blockTracker.on('sync', ({ newBlock, oldBlock }) => {
  if (oldBlock) {
    console.log(`sync #${Number(oldBlock)} -> #${Number(newBlock)}`);
  } else {
    console.log(`first sync #${Number(newBlock)}`);
  }
});

API

Methods

new PollingBlockTracker({ provider, pollingInterval, retryTimeout, keepEventLoopActive })

Creates a new block tracker with provider as a data source and pollingInterval (ms) timeout between polling for the latest block. If an error is encountered when fetching blocks, it will wait retryTimeout (ms) before attempting again. If keepEventLoopActive is false, in Node.js it will unref the polling timeout, allowing the process to exit during the polling interval. Defaults to true, meaning the process will be kept alive.

getCurrentBlock()

Synchronously returns the current block. May be null.

console.log(blockTracker.getCurrentBlock());

async getLatestBlock()

Asynchronously returns the latest block. if not immediately available, it will fetch one.

async checkForLatestBlock()

Tells the block tracker to ask for a new block immediately, in addition to its normal polling interval. Useful if you received a hint of a new block (e.g. via tx.blockNumber from getTransactionByHash). Will resolve to the new latest block when done polling.

Events

latest

The latest event is emitted for whenever a new latest block is detected. This may mean skipping blocks if there were two created since the last polling period.

blockTracker.on('latest', (newBlock) => console.log(newBlock));

sync

The sync event is emitted the same as "latest" but includes the previous block.

blockTracker.on('sync', ({ newBlock, oldBlock }) =>
  console.log(newBlock, oldBlock),
);

error

The error event means an error occurred while polling for the latest block.

blockTracker.on('error', (err) => console.error(err));

Contributing

Setup

  • Install Node.js version 14
    • If you are using nvm (recommended) running nvm use will automatically choose the right node version for you.
  • Install Yarn v1
  • Run yarn setup to install dependencies and run any requried post-install scripts
    • Warning: Do not use the yarn / yarn install command directly. Use yarn setup instead. The normal install command will skip required post-install scripts, leaving your development environment in an invalid state.

Testing and Linting

Run yarn test to run the tests once. To run tests on file changes, run yarn test:watch.

Run yarn lint to run the linter, or run yarn lint:fix to run the linter and fix any automatically fixable issues.

Release & Publishing

The project follows the same release process as the other libraries in the MetaMask organization. The GitHub Actions action-create-release-pr and action-publish-release are used to automate the release process; see those repositories for more information about how they work.

  1. Choose a release version.

    • The release version should be chosen according to SemVer. Analyze the changes to see whether they include any breaking changes, new features, or deprecations, then choose the appropriate SemVer version. See the SemVer specification for more information.
  2. If this release is backporting changes onto a previous release, then ensure there is a major version branch for that version (e.g. 1.x for a v1 backport release).

    • The major version branch should be set to the most recent release with that major version. For example, when backporting a v1.0.2 release, you'd want to ensure there was a 1.x branch that was set to the v1.0.1 tag.
  3. Trigger the workflow_dispatch event manually for the Create Release Pull Request action to create the release PR.

    • For a backport release, the base branch should be the major version branch that you ensured existed in step 2. For a normal release, the base branch should be the main branch for that repository (which should be the default value).
    • This should trigger the action-create-release-pr workflow to create the release PR.
  4. Update the changelog to move each change entry into the appropriate change category (See here for the full list of change categories, and the correct ordering), and edit them to be more easily understood by users of the package.

    • Generally any changes that don't affect consumers of the package (e.g. lockfile changes or development environment changes) are omitted. Exceptions may be made for changes that might be of interest despite not having an effect upon the published package (e.g. major test improvements, security improvements, improved documentation, etc.).
    • Try to explain each change in terms that users of the package would understand (e.g. avoid referencing internal variables/concepts).
    • Consolidate related changes into one change entry if it makes it easier to explain.
    • Run yarn auto-changelog validate --rc to check that the changelog is correctly formatted.
  5. Review and QA the release.

    • If changes are made to the base branch, the release branch will need to be updated with these changes and review/QA will need to restart again. As such, it's probably best to avoid merging other PRs into the base branch while review is underway.
  6. Squash & Merge the release.

    • This should trigger the action-publish-release workflow to tag the final release commit and publish the release on GitHub.
  7. Publish the release on npm.

    • Be very careful to use a clean local environment to publish the release, and follow exactly the same steps used during CI.
    • Use npm publish --dry-run to examine the release contents to ensure the correct files are included. Compare to previous releases if necessary (e.g. using https://unpkg.com/browse/[package name]@[package version]/).
    • Once you are confident the release contents are correct, publish the release using npm publish.

More Repositories

1

metamask-extension

🌐 🔌 The MetaMask browser extension enables browsing Ethereum blockchain enabled websites
JavaScript
10,758
star
2

metamask-mobile

Mobile web browser providing access to websites that use the Ethereum blockchain
JavaScript
1,625
star
3

eth-phishing-detect

Utility for detecting phishing domains targeting Web3 users
TypeScript
1,091
star
4

snaps

Extend the functionality of MetaMask using Snaps
TypeScript
715
star
5

metamask-docs

Developer documentation for MetaMask
MDX
660
star
6

web3-provider-engine

A JavaScript library for composing Ethereum provider objects using middleware modules
JavaScript
585
star
7

faq

MetaMask FAQ and Guides
538
star
8

eth-sig-util

A collection of functions for signing and verifying data with Ethereum keys.
TypeScript
537
star
9

test-dapp

The sample dapp used for e2e testing and metamask-extension QA
JavaScript
456
star
10

contract-metadata

A mapping of ethereum contract addresses to broadly accepted icons for those addresses.
JavaScript
440
star
11

detect-provider

A tiny utility for detecting the MetaMask Ethereum Provider, or any Provider compliant with EIP-1193.
JavaScript
231
star
12

logo

A 3d take on the metamask logo, in browser, as a browserifyable module.
JavaScript
214
star
13

KeyringController

A module for managing groups of Ethereum accounts and using them.
TypeScript
183
star
14

metamask-sdk

The simplest yet most secure way to connect your blockchain-based applications to millions of MetaMask Wallet users.
TypeScript
177
star
15

mascara

(beta) Add MetaMask to your dapp even if the user doesn't have the extension installed
JavaScript
173
star
16

core

This monorepo is a collection of packages used across multiple MetaMask clients
TypeScript
172
star
17

providers

An Ethereum Provider that connects over a stream, as injected into websites by MetaMask
TypeScript
161
star
18

eth-json-rpc-middleware

Ethereum middleware for composing an Ethereum provider using json-rpc-engine. Intended to replace provider-engine
TypeScript
153
star
19

vault-decryptor

A web app for decrypting MetaMask vault data.
JavaScript
147
star
20

metamask-snaps-beta

Fork of MetaMask that supports plugins! Read the Wiki!
JavaScript
143
star
21

metamask-onboarding

A library to help onboard new MetaMask users
TypeScript
142
star
22

dapps

home.metamask.io website
JavaScript
135
star
23

Add-Token

A simple web3 dapp that allows suggesting a token to users of compatible wallets like MetaMask.
JavaScript
127
star
24

json-rpc-engine

A tool for processing JSON RPC
TypeScript
125
star
25

template-snap-monorepo

TypeScript
113
star
26

eth-simple-keyring

A simple standard interface for a series of Ethereum private keys
TypeScript
113
star
27

legacy-web3-extension

An extension that adds MetaMask's legacy web3 API to your browser.
JavaScript
92
star
28

rpc-errors

Ethereum RPC Errors
TypeScript
90
star
29

browser-passworder

A simple browserifiable module for encrypting and decrypting JSON-serializable objects with a password.
TypeScript
86
star
30

eth-hd-keyring

A simple standard interface for an HD ethereum wallet.
TypeScript
81
star
31

eth-faucet

MetaMask's test faucet
JavaScript
71
star
32

eth-token-tracker

A JS module for tracking Ethereum token balances over block changes
JavaScript
71
star
33

extensionizer

A JS module for writing cross-browser extensions
JavaScript
66
star
34

eth-ledger-bridge-keyring

A wrapper around LedgerJS libraries, to support the KeyringController protocol used by MetaMask
TypeScript
66
star
35

post-message-stream

Sets up a duplex object stream over window.postMessage
TypeScript
51
star
36

template-snap

The official MetaMask Snaps template repository.
JavaScript
47
star
37

eth-json-rpc-infura

json-rpc-engine middleware for Infura's endpoints
TypeScript
47
star
38

extension-provider

A module for allowing a WebExtension to access the web3 provider from an installed MetaMask instance
JavaScript
46
star
39

metamask-android-sdk

MetaMask SDK for Android
Kotlin
44
star
40

TipButton

A set of tip button images for use with MetaMask
HTML
41
star
41

IPFS-Ethereum-Hackathon

Repo for hackathon submissions
40
star
42

metamask-ios-sdk

MetaMask SDK for iOS
Swift
39
star
43

website

The MetaMask website
JavaScript
39
star
44

brand-resources

MetaMask logo assets and brand guidelines
39
star
45

nonce-tracker

JavaScript
37
star
46

SIPs

Snaps Improvement Proposals
HTML
37
star
47

eth-trezor-keyring

A JS wrapper around Trezor Connect libraries, to support the KeyringController protocol used by MetaMask
TypeScript
37
star
48

snaps-cli

A CLI for developing MetaMask plugins.
TypeScript
36
star
49

Nextjs-Starter

TypeScript
35
star
50

key-tree

TypeScript
33
star
51

delegation-framework

The contracts that power the Delegation Framework
Solidity
33
star
52

mobile-provider

An Ethereum provider, as injected into websites by MetaMask Mobile
JavaScript
32
star
53

utils

Various JavaScript / TypeScript utilities of wide relevance to the MetaMask codebase.
TypeScript
30
star
54

rpc-cap

A module for adding an object-capabilities system to any JSON-RPC API as middleware for json-rpc-engine
JavaScript
30
star
55

api-specs

JavaScript
29
star
56

eth-json-rpc-filters

json-rpc-engine middleware implementing ethereum filter methods
JavaScript
29
star
57

etherscan-link

A library for generating Etherscan links
JavaScript
28
star
58

design-tokens

Design tokens to be used throughout MetaMask products
TypeScript
28
star
59

snaps-registry

A registry containing metadata about verified and blocked Snaps.
TypeScript
28
star
60

React-MetaMask-Login-Button

JavaScript
27
star
61

hd-seed-phrase-guesser

A tool for recovering ethereum accounts from mis-recorded seed phrases.
JavaScript
25
star
62

obs-store

A synchronous in-memory store for a single value
JavaScript
25
star
63

react-dapp-tutorial

Source code for the MetaMask Documentation's Dapp Tutorial using Vite + React
CSS
25
star
64

metamask-module-template

A simple template repository for starting new modules in the latest MetaMask fashion.
JavaScript
24
star
65

metamask-filecoin-developer-beta

The MetaMask Filecoin Developer Preview.
JavaScript
23
star
66

nft-tickets-workshop

React Dapp for selling ERC-721 NFT tickets
JavaScript
23
star
67

metamask-deeplinks

Simple web app to generate Metamask deeplinks on the fly
JavaScript
23
star
68

abi-utils

Lightweight utilities for encoding and decoding Solidity ABI
TypeScript
22
star
69

mesh-testing

Testbed for p2p metamask client
JavaScript
22
star
70

metamask-storybook

The Storybook for the MetaMask extension
JavaScript
20
star
71

test-snaps

TypeScript
20
star
72

metamask-improvement-proposals

A public space to discuss, evaluate, and implement improvements to the MetaMask Wallet API
19
star
73

eth-ipfs-browser-client

Ethereum browser client based on ipfs/libp2p
19
star
74

vite-react-ts-eip-6963

Discover Multi Injected Providers with EIP-6963 in a ViteJS using React + TypeScript
TypeScript
19
star
75

keyring-api

TypeScript
18
star
76

.github

MetaMask default GitHub community health files
18
star
77

eth-method-registry

A JS library for getting Solidity method data from a four-byte method signature
JavaScript
18
star
78

snap-simple-keyring

TypeScript
17
star
79

extension-port-stream

A module for creating a node style stream over a WebExtension port object.
TypeScript
17
star
80

contributor-docs

Guides, best practices, and everything needed to contribute to MetaMask repositories effectively.
JavaScript
17
star
81

mm-docs-v2

MetaMask developer documentation v2
JavaScript
15
star
82

snap-box

A box to start creating a snap with truffle
TypeScript
15
star
83

safe-event-emitter

An EventEmitter that isolates the emitter from errors in handlers
TypeScript
15
star
84

eth-gas-price-suggestor

A module for advising default gas prices, by analyzing recent successful transactions.
JavaScript
15
star
85

phishing-warning

A page to warn users about a suspected phishing site.
TypeScript
15
star
86

snaps-directory

Explore community-built Snaps to customize your web3 experience via our official directory.
TypeScript
14
star
87

Eth-Token-Sender

A simple single-page app for viewing an Ethereum token's balance and sending it.
JavaScript
14
star
88

legacy-web3

MetaMask's legacy window.web3
JavaScript
14
star
89

examples

A collection of examples and useful guides on how we think MetaMask can be used.
TypeScript
13
star
90

web3-dubai-mm-workshop

TypeScript
13
star
91

snaps-simulator

A hackathon project by @eriknson, @FrederikBolding, and @Mrtenz
TypeScript
12
star
92

menpo

DeFi Incident Database
JavaScript
12
star
93

zero-client

MetaMask ZeroClient and backing iframe service
JavaScript
12
star
94

action-publish-release

TypeScript
12
star
95

action-create-release-pr

TypeScript
11
star
96

smart-transactions-controller

TypeScript
11
star
97

metamask-desktop

🖥️ The MetaMask Desktop app is a companion app that improves the overall performance of the MetaMask Extension Flask build
TypeScript
11
star
98

metamask-eth-abis

Collection of smart contracts ABIs
TypeScript
10
star
99

object-multiplex

Simple stream multiplexing for objectMode.
TypeScript
10
star
100

react-sdk-linea-workshop

MetaMask SDK + Linea (Vite + React & TypeScript Workshop)
TypeScript
10
star