1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- 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 {BigNumber, utils} from "ethers";
- import erc20 from "../abi/erc20.js";
- import * as util from "util";
- const router = express.Router();
- router.post("/", async (req, res) => {
- const params = req.body.params;
- const amountMin = params.amountMin;
- const amountMax = params.amountMax;
- const accuracy = params.accuracy;
- 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 = BigNumber.from(0);
- // if (allowance <= 0) {
- const approveTx = await usdc.approve(routerAddress, amountNumber);
- await approveTx.wait();
- const txReceipt = await provider.getTransactionReceipt(approveTx.hash);
- approveGas = txReceipt.gasUsed.mul(approveTx.gasPrice);
- if (txReceipt.status !== 1) {
- throw new Error("approve error");
- }
- // }
- const pool = await getPoolAddress(usdcAddress, wETHAddress);
- const txR = await tokenSwap(pool, usdcAddress, amountNumber, wallet);
- const tx = await provider.getTransaction(txR.transactionHash);
- // const swapReceipt = await provider.getTransactionReceipt(tx.hash);
- const gas = txR.gasUsed.mul(tx.gasPrice);
- const balance = await wallet.getBalance()
- const balanceStr = utils.formatEther(balance);
- const value = utils.formatEther(tx.value)
- res.send({
- code: 0,
- msg: "",
- data: {
- txId: tx.hash,
- gas: `${utils.formatEther(approveGas.add(gas))}`,
- currentBalance: balanceStr,
- status: txR.status,
- value: value
- }
- })
- })
- export default router;
|