Monitoring swaps, in near real-time, as they happen on Uniswap V2 with web3.js.
Overview
Environment setup
web3.js
, which you can install by running:
npm install web3
Defining web3
web3
variable, you’ll need to first launch a Chainstack Elastic Node, in this case for Ethereum.Web3
constructorDefining the Uniswap V2 constants
UNISWAP_ROUTER_ADDRESS
, which as the name suggests, is the address of the V2 router.SWAP_EXACT_ETH_FOR_TOKENS_SIGNATURE
, which is the method ID of the swapExactETHForTokens
method.SWAP_EXACT_ETH_FOR_FEE_TOKENS_SIGNATURE
, which is the method ID for the swapExactETHForTokensSupportingFeeOnTransferTokens
method.Opening the subscription
subscribeToNewBlocks
, and will open the newBlockHeaders
subscription in a variable called subscription
.Creating the handler function
handleNewBlock
, our handler function that will work with the data returned by the subscription.Within this function, we’ll run a getBlock
call on the returned block number. This call specifically uses the true
flag as the second parameter, which means the getBlock
response will include transaction details for each transaction included in the specified block.These transactions will then be looped through and filtered using a conditional that checks for parity with the router address, along with the specified method IDs.Understanding the response
handleNewBlock
, a collection of strings will be printed to the console containing key information, such as the transaction ID, the address that executed the swap, and the amount of ETH being swapped.