Prechádzať zdrojové kódy

fix: Exception in floating-point calculation

wren 1 rok pred
rodič
commit
4e0fd14447

+ 8 - 6
js-runtime/src/script/zksync2/sync/swapUsdcForEth.js

@@ -2,8 +2,9 @@ import express from "express";
 import mathUtil from "../../utils/mathUtil.js";
 import {Contract, Provider, Wallet} from "zksync-web3";
 import {tokenSwap, getPoolAddress, wETHAddress, usdcAddress, routerAddress} from "./swap.js";
-import {utils} from "ethers";
+import {BigNumber, utils} from "ethers";
 import erc20 from "../abi/erc20.js";
+import * as util from "util";
 
 const router = express.Router();
 router.post("/", async (req, res) => {
@@ -11,18 +12,19 @@ router.post("/", async (req, res) => {
     const amountMin = params.amountMin;
     const amountMax = params.amountMax;
     const accuracy = params.accuracy;
-    const amountNumber = mathUtil.getRandomNumber(amountMin, amountMax, accuracy) * 1000000;
+    const amountNumber = BigNumber.from(mathUtil.getRandomNumber(amountMin, amountMax, accuracy) * 1000000);
+
     const signer = req.body.wallet;
     const provider = new Provider('https://mainnet.era.zksync.io');
     const wallet = new Wallet(signer.privateKey, provider);
     const usdc = new Contract(usdcAddress, erc20, wallet);
     // const allowance = await usdc.allowance(signer.address, routerAddress);
-    let approveGas = 0;
+    let approveGas = BigNumber.from(0);
     // if (allowance <= 0) {
     const approveTx = await usdc.approve(routerAddress, amountNumber);
     await approveTx.wait();
     const txReceipt = await provider.getTransactionReceipt(approveTx.hash);
-    approveGas = utils.formatEther((txReceipt.gasUsed * approveTx.gasPrice).toFixed(0));
+    approveGas = txReceipt.gasUsed.mul(approveTx.gasPrice);
     if (txReceipt.status !== 1) {
         throw new Error("approve error");
     }
@@ -31,7 +33,7 @@ router.post("/", async (req, res) => {
     const txR = await tokenSwap(pool, usdcAddress, amountNumber, wallet);
     const tx = await provider.getTransaction(txR.transactionHash);
     // const swapReceipt = await provider.getTransactionReceipt(tx.hash);
-    const gas = utils.formatEther((txR.gasUsed * tx.gasPrice).toFixed(0));
+    const gas = txR.gasUsed.mul(tx.gasPrice);
     const balance = await wallet.getBalance()
     const balanceStr = utils.formatEther(balance);
     const value = utils.formatEther(tx.value)
@@ -40,7 +42,7 @@ router.post("/", async (req, res) => {
         msg: "",
         data: {
             txId: tx.hash,
-            gas: `${parseFloat(approveGas + "") + parseFloat(gas)}`,
+            gas: `${utils.formatEther(approveGas.add(gas))}`,
             currentBalance: balanceStr,
             status: txR.status,
             value: value