![](/img/trans.png)
[英]How to send wei/eth to contract address? (using truffle javascript test)
[英]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)
在 Hardhat 中使用ethers.js ? 使用ethers 工具。
const { ethers } = require("hardhat");
let ethersToWei = ethers.utils.parseUnits(1000000.toString(), "ether");
上面的代码将一百万个以太币转换为等值的 Wei。
在使用节点模块 ethers 的 ES6 中,您可以将 Ethers 转换为 Wei,如下所示:
import { ethers } from "ethers"; const EtherToWei = ethers.utils.parseUnits("0.11","ether")
并将醚传递给您的 Function:
contract.yourFunction({ value: ethers.utils.parseUnits("0.11","ether") });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.