swapUsdcForEth.js 2.1 KB

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