blockchainethereummetamask

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


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?


Solution

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