MetaMask – web3.utils.toWei Discordancy: Addressing Ether Value Discrepancies in Notifications

metamasksendtransaction

I'm new to ethereum and when using web3.utils.toWei("1", "ether") it doesn't work properly.

const transactionParameters = {
 from: metamaskaddr,
 gasPrice: '0x09184e72a000', // customizable by user during MetaMask confirmation.
 gas: '0x2710', // customizable by user during MetaMask confirmation.
 to: '0x1e518d4dDd1f75aa884906980E59e3F40745351c', // Required except during contract publications.
 value: web3.utils.toWei("1", "ether"), // Only required to send ether to the recipient from the initiating external account.
 data:
 web3.utils.toHex(algoaddr), // Optional, but used for defining smart contract creation and interaction.
 };

 // txHash is a hex string
 // As with any RPC call, it may throw an error
 const txHash = await ethereum.request({
 method: 'eth_sendTransaction',
 params: [transactionParameters],
 });

I'm trying to create a metamask notification to send eth. When the notification appears, it isn't 1 eth, it is 4722.36648287 eth??? I am using client-side javascript.

Best Answer

I ran into the same problem because I was using an older Alchemy version of web3 which interprets the amount given to value as a hex number.

1000000000000000000 hex = 4722366482869645213696 dec.
Also see this issue: https://github.com/alchemyplatform/alchemy-web3/issues/61.

To solve it you can wrap it in a web3.utils.toHex:
value: web3.utils.toHex(web3.utils.toWei("1", "ether" ))

Related Topic