Search code examples
ethereumblockchainsoliditysmartcontractsethers.js

How to compare two 'wei' values?


Here is the code snippet of my smart contract:

provider = new ethers.BrowserProvider(window.ethereum);
signer = await provider.getSigner();
let contract = new ethers.Contract(NFTMarketplaceAddress, Marketplace.abi, signer);
const address = await signer.getAddress();
const balance = await provider.getBalance(address);
const priceInWei = ethers.parseEther(NFTData.price.toString());
  
console.log(balance.lt(priceInWei))

I'm trying to check whether the balance is lower than the priceInWei. That's why I'm using ethers.js library's lt function.

But the console shows my the following error:

TypeError: balance.lt is not a function

How to fix this problem?

I've tried the following technique:

console.log(balance < priceInWei)

Certainly that doesn't give me the correct output.


Solution

  • Based on the BrowserProvider in your snippet, I'm assuming you're using ethers v6.

    This version returns native JavaScript BigInt from the provider.getBalance() function as well as from the parseEther() function.

    You can simply compare the BigInt values with the < sign.

    console.log(balance < priceInWei)
    

    The FixedNumber might be used e.g. for comparing token amounts where the tokens have different number of decimals.

    Or possibly when a future version of Solidity implements returning Fixed point numbers, these returned numbers might be encoded into the FixedNumber type in ethers.js.

    But right now, it doesn't really seem to be a widely used feature.