【问题标题】:How do I accurately convert ETH to WEI when sending transaction?发送交易时如何准确地将ETH转换为WEI?
【发布时间】:2022-08-20 16:58:23
【问题描述】:

我正在尝试将ETH 从一个帐户发送到另一个帐户,但从ETHWEI 的转换一直让我头疼。在这种情况下,我尝试发送0.11 ETH,但在确认窗口中,我收到了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

  • String(0.11 * 1000000000000000000) 更改为\"11e+17\",或使用BigNumber(或在您的问题中解释您究竟如何尝试使用BigNumber)。
  • 顺便说一句,不确定您对eth_sendTransaction 的期望是什么,但该交易的结果应该是一个简单的交易哈希,而不是一定数量的 ETH 或类似的东西。将该散列转换为数值是毫无意义的。

标签: blockchain ethereum metamask


【解决方案1】:

我更喜欢使用web3 utils 来获得更简洁的代码并防止出现意外错误,这样您就可以编写以下代码:

value: "0x" + Web3.utils.toBN(Web3.utils.toWei("0.11", "ether")).toString(16)

【讨论】:

    【解决方案2】:

    你正在用吗ethers.js里面安全帽?如果是,要将以太币转换为 Wei,您可以使用ethers.utils如下:

    const { ethers } = require("hardhat");    
    let ethersToWei = ethers.utils.parseUnits(1000000.toString(), "ether");
    

    上面的代码将一百万个以太币转换为等值的 Wei。

    【讨论】:

      【解决方案3】:

      或者,这是一个没有Web3 utils 的单线解决方案:

      value: Number(ether * 1e18).toString(16)
      

      【讨论】:

      • 请问ether是什么?
      • 以太坊的数量。
      猜你喜欢
      • 2023-03-12
      • 2023-01-13
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 2018-01-13
      • 2022-11-04
      相关资源
      最近更新 更多