'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 1:[1]
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)
Solution 2:[2]
Alternatively, here is a one liner solution without Web3 utils:
value: Number(ether * 1e18).toString(16)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mahdikmg |
| Solution 2 | zonay |
