How do I accurately convert ETH to WEI when sending transaction?

Viewed 2783

I am trying to send ETH from one account to another but the conversion from ETH to WEI keeps giving me headaches. In this case, I am trying to send 0.11 ETH but in the confirmation window, I get 313.59464925 ETH instead.

// This is my transaction code

await window.ethereum
  .request({
    method: "eth_sendTransaction",
    params: [
        {
          from: window.ethereum.selectedAddress,
          to: "0x4dxxxxxxxxxxxxxxxxxx2dr9820C",
          value: String(0.11 * 1000000000000000000), // convert to WEI
          },
        ],
      })
  .then((result) => console.log(result))
  .catch((error) => console.log(error));

I have also tried using BigNumber but it doesn't solve the problem, I guess I'm messing something up. How do I accurately convert ETH to WEI?

4 Answers

i prefer using web3 utils to have cleaner code and prevent unexpected bugs so with that you can write this:

value: "0x" + Web3.utils.toBN(Web3.utils.toWei("0.11", "ether")).toString(16)

Are you using ethers.js with hardhat? If yes, to convert Ethers to Wei, you can use ethers.utils as follows:

const { ethers } = require("hardhat");    
let ethersToWei = ethers.utils.parseUnits(1000000.toString(), "ether");

The code above converts a million ethers to equivalent Wei.

Alternatively, here is a one liner solution without Web3 utils:

value: Number(ether * 1e18).toString(16)

In ES6 using node module ethers, you can convert Ethers to Wei as follows:

import { ethers } from "ethers";
const EtherToWei = ethers.utils.parseUnits("0.11","ether")

And to pass the ethers to your Function:

contract.yourFunction({ 
  value:  ethers.utils.parseUnits("0.11","ether")
});

Related