swapUsdcForEth.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import express from "express";
  2. import mathUtil from "../../utils/mathUtil.js";
  3. import {Contract, Provider, Wallet} from "zksync-web3";
  4. import {tokenSwap, getPoolAddress, wETHAddress, usdcAddress, routerAddress} from "./swap.js";
  5. import {utils} from "ethers";
  6. import erc20 from "../abi/erc20.js";
  7. const router = express.Router();
  8. router.post("/", async (req, res) => {
  9. const params = req.body.params;
  10. const amountMin = params.amountMin;
  11. const amountMax = params.amountMax;
  12. const accuracy = params.accuracy;
  13. const amountNumber = mathUtil.getRandomNumber(amountMin, amountMax, accuracy) * 1000000;
  14. const signer = req.body.wallet;
  15. const provider = new Provider('https://mainnet.era.zksync.io');
  16. const wallet = new Wallet(signer.privateKey, provider);
  17. const usdc = new Contract(usdcAddress, erc20, wallet);
  18. // const allowance = await usdc.allowance(signer.address, routerAddress);
  19. let approveGas = 0;
  20. // if (allowance <= 0) {
  21. const approveTx = await usdc.approve(routerAddress, amountNumber);
  22. await approveTx.wait();
  23. const txReceipt = await provider.getTransactionReceipt(approveTx.hash);
  24. approveGas = utils.formatEther((txReceipt.gasUsed * approveTx.gasPrice).toFixed(0));
  25. if (txReceipt.status !== 1) {
  26. throw new Error("approve error");
  27. }
  28. // }
  29. const pool = await getPoolAddress(usdcAddress, wETHAddress);
  30. const txR = await tokenSwap(pool, usdcAddress, amountNumber, wallet);
  31. const tx = await provider.getTransaction(txR.transactionHash);
  32. // const swapReceipt = await provider.getTransactionReceipt(tx.hash);
  33. const gas = utils.formatEther((txR.gasUsed * tx.gasPrice).toFixed(0));
  34. const balance = await wallet.getBalance()
  35. const balanceStr = utils.formatEther(balance);
  36. const value = utils.formatEther(tx.value)
  37. res.send({
  38. code: 0,
  39. msg: "",
  40. data: {
  41. txId: tx.hash,
  42. gas: `${parseFloat(approveGas + "") + parseFloat(gas)}`,
  43. currentBalance: balanceStr,
  44. status: txR.status,
  45. value: value
  46. }
  47. })
  48. })
  49. export default router;