0

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));

1 Answer 1

1

You can remove the negative sign by using Math.abs(). Since the USDC value is in 6-decimal format and WETH value is in 18-decimal format as per their respective token contracts, so the USDC value needs to be converted to 18-decimals as well in order to calculate the price by dividing.

The revised portion of the code would be:

const usdcDecimals = 6;

// Removing negative sign by using Math.abs()
const absoluteUsdcValue = Math.abs(amount0In);  // Needs to be converted in Wei as USDC is having 6-decimals
const absoluteWethValue = Math.abs(amount1In);  // Already in Wei as WETH is having 18-decimals

// Converting USDC value to Wei (i.e., 18-decimals)
const usdcValueInEther = parseFloat(absoluteUsdcValue) / Math.pow(10, usdcDecimals);
const usdcValueInWei = parseFloat(web3.utils.toWei(usdcValueInEther.toString(), 'ether'));

// Calculate the price
const price = BigNumber(absoluteWethValue).div(BigNumber(usdcValueInWei)).toString(10); // Price in WETH per USDC 

console.log(`Current WETH/USDC Price: ${price} WETH per USDC`);
console.log(`1 USDC = ${price} WETH`);
console.log(`1 WETH = ${BigNumber(1).div(price).toString()} WETH`);

Output:

enter image description here

2
  • thank you sir . Commented Apr 7 at 1:10
  • You're welcome @shakilkhan. Kindly please accept the answer if it solved your problem. Thanks. Commented Apr 7 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.