Skip to content

Instantly share code, notes, and snippets.

@vasinl124
Forked from BlockmanCodes/listen.js
Created May 15, 2023 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasinl124/0f773bf69e5ad40b1813b070d2be580a to your computer and use it in GitHub Desktop.
Save vasinl124/0f773bf69e5ad40b1813b070d2be580a to your computer and use it in GitHub Desktop.
Uniswap V2, V3, Sushiswap: listen for swaps
const ethers = require('ethers')
const v3PoolArtifact = require("@uniswap/v3-core/artifacts/contracts/UniswapV3Pool.sol/UniswapV3Pool.json")
const v2PairArtifact = require('@uniswap/v2-periphery/build/IUniswapV2Pair.json')
const USDC_ETH_V3 = '0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640'
const ETH_USDT_V2 = '0x0d4a11d5eeaac28ec3f61d100daf4d40471f1852'
const ETH_USDT_SUSHI = '0x06da0fd433c1a5d7a4faa01111c044910a184553'
sqrtToPrice = (sqrt) => {
const numerator = sqrt ** 2
const denominator = 2 ** 192
let ratio = numerator / denominator
const decimalShift = Math.pow(10, -12)
ratio = ratio * decimalShift
return ratio
}
ratio0ToPrice = (amount0In, amount1Out) => 1/(Number(amount0In)/Number(amount1Out)/10**12)
ratio1ToPrice = (amount1In, amount0Out) => Number(amount1In)/Number(amount0Out)*10**12
const provider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/abc')
const v3Pool = new ethers.Contract(USDC_ETH_V3, v3PoolArtifact.abi, provider)
const v2Pair = new ethers.Contract(ETH_USDT_V2, v2PairArtifact.abi, provider)
const sushiPair = new ethers.Contract(ETH_USDT_SUSHI, v2PairArtifact.abi, provider)
v3Pool.on('Swap', (sender, recipient, amount0, amount1, sqrtPriceX96) => {
const ratio = sqrtToPrice(String(sqrtPriceX96))
console.log(
'Uni V3', '|',
'pair:', 'ETH/USDC', '|',
'sender:', sender, '|',
'ratio:', 1/ratio,
)
})
v2Pair.on('Swap', (sender, amount0In, amount1In, amount0Out, amount1Out, to) => {
console.log(
'Uni V2', '|',
'pair:', 'ETH/USDT', '|',
'sender:', sender, '|',
'ratio0:', ratio0ToPrice(amount0In, amount1Out),
'ratio1:', ratio1ToPrice(amount1In, amount0Out),
)
})
sushiPair.on('Swap', (sender, amount0In, amount1In, amount0Out, amount1Out, to) => {
console.log(
'Sushi', '|',
'pair:', 'ETH/USDT', '|',
'sender:', sender, '|',
'ratio0:', ratio0ToPrice(amount0In, amount1Out),
'ratio1:', ratio1ToPrice(amount1In, amount0Out),
)
})
{
"name": "01",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@uniswap/v2-periphery": "^1.1.0-beta.0",
"@uniswap/v3-core": "^1.0.1",
"dotenv": "^16.0.3",
"ethers": "^6.3.0",
"hardhat": "^2.14.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment