发送交易时如何将 ETH 准确转换为 WEI?
How do I accurately convert ETH to WEI when sending transaction?
我正在尝试将 ETH
从一个帐户发送到另一个帐户,但是从 ETH
到 WEI
的转换一直让我头疼。在这种情况下,我尝试发送 0.11 ETH
,但在确认 window 中,我收到的是 313.59464925 ETH
。
// 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));
我也试过使用 BigNumber 但它没有解决问题,我想我搞砸了。如何准确地将 ETH
转换为 WEI
?
我更喜欢使用 web3 utils 来获得更简洁的代码并防止意外错误,因此您可以这样写:
value: "0x" + Web3.utils.toBN(Web3.utils.toWei("0.11", "ether")).toString(16)
或者,这是一个没有 Web3 utils
的单线解决方案:
value: Number(ether * 1e18).toString(16)
我正在尝试将 ETH
从一个帐户发送到另一个帐户,但是从 ETH
到 WEI
的转换一直让我头疼。在这种情况下,我尝试发送 0.11 ETH
,但在确认 window 中,我收到的是 313.59464925 ETH
。
// 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));
我也试过使用 BigNumber 但它没有解决问题,我想我搞砸了。如何准确地将 ETH
转换为 WEI
?
我更喜欢使用 web3 utils 来获得更简洁的代码并防止意外错误,因此您可以这样写:
value: "0x" + Web3.utils.toBN(Web3.utils.toWei("0.11", "ether")).toString(16)
或者,这是一个没有 Web3 utils
的单线解决方案:
value: Number(ether * 1e18).toString(16)