Code showing me token price in wrong format. How to solve it?
From the code I got:
1 WETH = -3.30628482e-9 USDC
1 USDC = -302454281.60057910558352924961 WETH
But the real/expected values were:
1 WETH = 3306.2848 USDC
1 USDC = 0.000302 WETH
Here's the code:
const Web3 = require('web3');
const { BigNumber } = require('bignumber.js');
const UniswapV3PoolABI = require('./abis/UniswapV3PoolABI.json');
// Pool address and pair addresses
const POOL_ADDRESS = '0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640';
const WETH_ADDRESS = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
const USDC_ADDRESS = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48';
// RPC URL
const RPC_URL = 'wss://ethereum-rpc.publicnode.com';
// Initialize Web3 with WebSocketProvider
const web3 = new Web3(new Web3.providers.WebsocketProvider(RPC_URL));
// Initialize contract
const uniswapV3PoolContract = new web3.eth.Contract(UniswapV3PoolABI, POOL_ADDRESS);
// Subscribe to Swap event
uniswapV3PoolContract.events.Swap({}, (error, event) => {
if (error) {
console.error('Error:', error);
return;
}
const { returnValues } = event;
//console.log('Event data:', returnValues);
const amount0In = new BigNumber(returnValues.amount0);
const amount1In = new BigNumber(returnValues.amount1);
//console.log('Raw amounts:');
//console.log(`Amount0: ${amount0In.toString()} WETH`);
//console.log(`Amount1: ${amount1In.toString()} USDC`);
// Check if amounts are valid
if (!amount0In.isFinite() || !amount1In.isFinite() || amount0In.isZero() || amount1In.isZero()) {
console.error('Invalid amounts:', amount0In.toString(), amount1In.toString());
return;
}
// Calculate the price
const price = amount0In.div(amount1In).toString(); // Price in WETH per USDC
//console.log(`Current WETH/USDC Price: ${price} WETH per USDC`);
console.log(`1 WETH = ${price} USDC`);
console.log(`1 USDC = ${new BigNumber(1).div(price).toString()} WETH`);
})
.on('connected', () => console.log('Connected to Ethereum node'))
.on('error', (error) => console.error('Error in contract event subscription:', error));