Monitoring swaps on Uniswap with WebSocket endpoints
Monitoring swaps, in near real-time, as they happen on Uniswap V2 with web3.js.
Overview
Overview
This code snippet leverages new block subscriptions, enabled by the usage of a WebSocket endpoint, to watch and sift through new blocks, filter transactions that involve the Uniswap V2 router contract, and then, of which, return those that are ETH -> Token swaps.
This snippet uses one of the previous recipes on web3.js subscriptions as a base.
Environment setup
Environment setup
If you haven’t already, ensure node.js is installed.
The only dependency here is web3.js
, which you can install by running:
npm install web3
Defining web3
Defining web3
To define the web3
variable, you’ll need to first launch a Chainstack Elastic Node, in this case for Ethereum.
Navigate to the Chainstack console
Deploy an Ethereum mainnet node
Open the newly deployed node
Copy the corresponding WSS endpoint
Paste it into your Web3
constructor
Defining the Uniswap V2 constants
Defining the Uniswap V2 constants
To enable the active filtering of transactions to return ETH -> Token swaps on Uniswap V2, we’ll need to define the following:
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 theswapExactETHForTokens
method.SWAP_EXACT_ETH_FOR_FEE_TOKENS_SIGNATURE
, which is the method ID for theswapExactETHForTokensSupportingFeeOnTransferTokens
method.
Opening the subscription
Opening the subscription
Now, we’ll need to setup the subscription that we’ll use to continually query new blocks as they get confirmed on the Ethereum blockchain.
This will be defined as subscribeToNewBlocks
, and will open the newBlockHeaders
subscription in a variable called subscription
.
Creating the handler function
Creating the handler function
The final component of this code includes the defining of 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
Understanding the response
For each transaction that meets the criteria within the conditional we set in 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.