CY2*_*Y23 9 blockchain ethereum metamask
我正在尝试从一个帐户发送到另一个帐户,但从到 的ETH转换一直让我头疼。在这种情况下,我尝试发送,但在确认窗口中,我收到了。ETHWEI0.11 ETH313.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));
Run Code Online (Sandbox Code Playgroud)
我也尝试过使用BigNumber但它不能解决问题,我想我把事情搞砸了。如何准确转换ETH为WEI?
我更喜欢使用web3 utils来获得更清晰的代码并防止意外错误,因此您可以编写以下内容:
value: "0x" + Web3.utils.toBN(Web3.utils.toWei("0.11", "ether")).toString(16)
Run Code Online (Sandbox Code Playgroud)
在 ES6 中使用节点模块 ethers,您可以将 Wei 转换为 Ether,如下所示:
import { ethers } from "ethers";
const WeiToEther = ethers.utils.formatEther(weiValue)Run Code Online (Sandbox Code Playgroud)
将以太币兑换成 Wei 如下:
import { ethers } from "ethers";
const EtherToWei = ethers.utils.parseUnits("0.11","ether")Run Code Online (Sandbox Code Playgroud)
并将以太传递给你的函数:
contract.yourFunction({
value: ethers.utils.parseUnits("0.11","ether")
});Run Code Online (Sandbox Code Playgroud)
您是否将ethers.js与安全帽一起使用?如果是,要将 Ether 转换为 Wei,您可以使用ethers.utils,如下所示:
const { ethers } = require("hardhat");
let ethersToWei = ethers.utils.parseUnits("1", "ether");
Run Code Online (Sandbox Code Playgroud)
上面的代码将 1 以太转换为等值的 Wei。
| 归档时间: |
|
| 查看次数: |
18317 次 |
| 最近记录: |