javascript 如何将美元转换为正确的wei进行eth交易?

pxy2qtax  于 2023-08-02  发布在  Java
关注(0)|答案(1)|浏览(100)

我得到了180亿美元的交易,我的项目是以美元计价的,所以我只需要发送正确的魏,我猜。

  1. value: web3.utils.toWei(usdAmount, 'ether'),

字符串
我已经尝试了像

  1. function usdToWei(usdAmount, ethToUsdExchangeRate) {
  2. const weiPerEth = 10 ** 18; // 1 ETH = 10^18 wei
  3. const amountInEth = usdAmount / ethToUsdExchangeRate;
  4. const amountInWei = amountInEth * weiPerEth;
  5. return amountInWei;
  6. }


但我做错了。

wtlkbnrh

wtlkbnrh1#

假设ethToUsdExchangeRate是JavaScript中的一个Number类型,它保存了以美元为单位的1 ETH的当前价格,包括小数(例如:$1234.56存储为1234.56):

  1. const ethToUsdExchangeRate = 1234.56;
  2. const usdAmount = 10;
  3. const oneUsdInWei = (10**18) / ethToUsdExchangeRate;
  4. const usdAmountInWei = oneUsdInWei * usdAmount;
  5. // returns 8100051840331779 wei (or ~0.008 ETH)
  6. console.log(usdAmountInWei);

字符串

相关问题