8

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?

cy23
  • 354
  • 1
  • 3
  • 12
  • Change `String(0.11 * 1000000000000000000)` to `"11e+17"`, or use `BigNumber` (or explain in your question how exactly you have tried using `BigNumber`). –  Feb 02 '22 at 12:21
  • BTW, not sure what you're expecting from `eth_sendTransaction`, but the result of that transaction should be a simple transaction hash, not an amount of ETH or anything like that. Converting that hash into a numeric value is pretty meaningless. –  Feb 02 '22 at 12:23

5 Answers5

8

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)
mahdikmg
  • 833
  • 2
  • 6
  • 13
5

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("1", "ether");

The code above converts 1 ether to equivalent Wei.

John Doe
  • 87
  • 1
  • 9
5

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

import { ethers } from "ethers";
const WeiToEther = ethers.utils.formatEther(weiValue)

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")
});
Aun Shahbaz Awan
  • 559
  • 7
  • 10
2

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

value: Number(ether * 1e18).toString(16)
zonay
  • 1,453
  • 9
  • 17
0

A good suggestion found in ethersJS documentation is using such

ethers.utils.parseEther("1")
Qudusayo
  • 1,026
  • 9
  • 15