错误:事务已恢复:函数调用无法执行

sim*_*mon 0 solidity nft hardhat

我目前在一个 nft 市场工作,希望对每笔销售收取 2.5% 的费用。我已经在线阅读和研究了如何计算坚固性百分比,并在这方面取得了成功,但问题是结果是一个巨大的数字,即 2.5 * 150/100 应该返回 3.75 但我得到这个数字: 3750000000000000000000000000000000000

我的测试

const auctionPrice = ethers.utils.parseUnits("1", "ether");

const [_, userAddress] = await ethers.getSigners();
    let fee = (2.5 * auctionPrice) / 100;
    const commission = ethers.utils.parseUnits(fee.toString(), "ether");
    let commissionValue = commission.toString();

    console.log(commission.toString());
    console.log(fee);

    await market
      .connect(userAddress)
      .createMarketSale(nftContractAddress, 1, commissionValue, {
        value: auctionPrice,
      });
Run Code Online (Sandbox Code Playgroud)

结果

250000000000000000000000000000000

 1 failing

  1) NFTMarket
       Should create and execute market sales:
     Error: Transaction reverted: function call failed to execute
      at NFTMarket.createMarketSale (contracts/NFTMarket.sol:165)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)
      at runNextTicks (node:internal/process/task_queues:65:3)
      at listOnTimeout (node:internal/timers:526:9)
      at processTimers (node:internal/timers:500:7)
      at HardhatNode._mineBlockWithPendingTxs (node_modules\hardhat\src\internal\hardhat-network\provider\node.ts:1602:23)
      at HardhatNode.mineBlock (node_modules\hardhat\src\internal\hardhat-network\provider\node.ts:435:16)
      at EthModule._sendTransactionAndReturnHash (node_modules\hardhat\src\internal\hardhat-network\provider\modules\eth.ts:1494:18)
Run Code Online (Sandbox Code Playgroud)

所以我的问题是有什么方法可以将这个数字(3750000000000000000000000000000000000)变成小数或整数?我已经搜索过,但在网上找不到任何谈论此问题的内容

小智 5

其实你的计算没有问题。问题是函数的使用ethers.utils.parseUnits()

让我们先快速回顾一下:

在幕后,以太坊中的所有交易均以wei以太币的最小面额支付。因此,如果您向某个合约发送 1 ETH,您实际上发送了 1,000,000,000,000,000,000 wei,因为 1 ETH = 10^18 wei。

你的代码

在测试中,当你使用该功能时ethers.utils.parseUnits("1", "ether"),你实际上是在说“我想发送 1 ETH,所以请将这 1 ETH 转换为 wei,让我的生活更轻松”。然后这个函数只是将 18 个零添加到“1”字符串中。

最后,当您执行计算时(2.5 * auctionPrice) / 100,结果已经采用正确的格式。所以你不必perseUnits再次调用,因为你添加了更多的 18 个零!=D