Draining Connection. 4040

I was able to run eth_estimateGas call for test now with different parameters, what function did you call there in particular?

In my script, I’m not using moralis SDK. I’m using just the web soket to connect the bsc.
Here is the lines I used now to estimate gas price and gas cost, separately:

const tx = BscFlashArb1.methods.startArbitrage(
                  addresses.tokens.DAI,
                  addresses.tokens.WBNB,
                  AMOUNT_DAI_WEI,
                  0
                );

                const gasPrice = await web3.eth.getGasPrice();

                const gasCost = await tx.estimateGas({from: admin});

                console.log(`gas price: ${gasPrice}, gas cost: ${gasCost}`);

this is on a lower level than what you have there, it is not Moralis SDK :slight_smile:

on what line it fails?
web3.eth.getGasPrice() or tx.estimateGas ?

It estimates gas price correctly.
It fails to estimate the gas cost and returns an error: Error: Returned error: execution reverted: Unauthorized

what kind of web socket url are you using? archive, non archive?
that Unauthorized error sounds like it is trying to run a node command that is not on a whitelist of supported commands

I’m using a non archive node.

and you are doing this on bsc, right?
if you use process.env.BSC_WSS_URL for gas estimation then it works?

I tried it now: same error! :open_mouth:
I really didn’t expect that.
I will try to make a transaction to see the actual gas cost. Then I will increase it by some percentage and hard code it in the script to see what will happen.
Thank you for your help. I’m very grateful.

in the script I made a mistake. in the ```
// arbitrage borrowing WBNB

AMOUNT_WBNB_WEI is an array. the wright value is AMOUNT_WBNB_WEI[1]

also having the same issue here, let me know if you find out the solution

thanks

I found out that the issue depends on BSC. No matter which wss you are using you will always have that issue.
In the binance chain (not binance smart chain but binance chain) documentation there is some thing similar. When you are connected to binance chain via wss, you will be disconnected after 30 minutes. If you want to maintain the connection you have to include in your code a line of code they provided, to ask every 30 minutes to maintain the connection.
I guess, they imported this future or issue into BSC.
The solution I found is to create a reset function which will reconnect when the connection fails.

2 Likes

can you share with me this reset function? thank you

1 Like

can you please share us the line of code and where to place it on the flashloan arbitrage script

`require(“dotenv”).config();
const Web3 = require(“web3”);
const abis = require("./abis");
const { mainnet: addresses } = require("./addresses");
// const { testnet: addresses } = require("./addresses"); added for testing on testnet
const Flashloan = require("./build/contracts/FlashSwap.json");

const web3 = new Web3(
new Web3.providers.WebsocketProvider(process.env.WSS_URL)
);

const provider = new Web3.providers.WebsocketProvider(process.env.WSS_URL);
provider.on(‘error’, e => console.error(‘WSS Error’, e));
provider.on(‘end’, e => console.error(‘WSS End’, e));

const { address: admin } = web3.eth.accounts.wallet.add(
process.env.PRIVATE_KEY
);

const flashloanBUSD = “50000”;
const flashloanWBNB = “500”;
const amountInBUSD = web3.utils.toBN(web3.utils.toWei(flashloanBUSD));
const amountInWBNB = web3.utils.toBN(web3.utils.toWei(flashloanWBNB));

const ApeSwap = new web3.eth.Contract(
abis.apeSwap.router,
addresses.apeSwap.router
);

const PancakeSwap = new web3.eth.Contract(
abis.pancakeSwap.router,
addresses.pancakeSwap.router
);

const init = async () => {
const networkId = await web3.eth.net.getId();
const flashloan = new web3.eth.Contract(
Flashloan.abi,
Flashloan.networks[networkId].address
);

web3.eth
.subscribe(“newBlockHeaders”)
.on(“data”, async (block) => {
console.log(New block received. Block # ${block.number});

  const amountsOut1 = await ApeSwap.methods
  .getAmountsIn(amountInBUSD, [
    addresses.tokens.WBNB,
    addresses.tokens.BUSD,
  ])
  .call();
const amountsOut2 = await ApeSwap.methods
  .getAmountsOut(amountInBUSD, [
    addresses.tokens.BUSD,
    addresses.tokens.WBNB,
  ])
  .call();

const amountsOut3 = await PancakeSwap.methods
  .getAmountsIn(amountInBUSD, [
    addresses.tokens.WBNB,
    addresses.tokens.BUSD,
  ])
  .call();
const amountsOut4 = await PancakeSwap.methods
  .getAmountsOut(amountInBUSD, [
    addresses.tokens.BUSD,
    addresses.tokens.WBNB,
  ])
  .call();

const amountsOut5 = await ApeSwap.methods
  .getAmountsIn(amountInWBNB, [
    addresses.tokens.BUSD,
    addresses.tokens.WBNB,
  ])
  .call();
const amountsOut6 = await ApeSwap.methods
  .getAmountsOut(amountInWBNB, [
    addresses.tokens.WBNB,
    addresses.tokens.BUSD,
  ])
  .call();

const amountsOut7 = await PancakeSwap.methods
  .getAmountsIn(amountInWBNB, [
    addresses.tokens.BUSD,
    addresses.tokens.WBNB,
  ])
  .call();
const amountsOut8 = await PancakeSwap.methods
  .getAmountsOut(amountInWBNB, [
    addresses.tokens.WBNB,
    addresses.tokens.BUSD,
  ])
  .call();

const aperesults = {
  buy: amountsOut1[0] / 10 ** 18,
  sell: amountsOut2[1] / 10 ** 18,
};
const aperesults2 = {
  buy: amountsOut5[0] / 10 ** 18,
  sell: amountsOut6[1] / 10 ** 18,
};

const pancakeresults = {
  buy: amountsOut3[0] / 10 ** 18,
  sell: amountsOut4[1] / 10 ** 18,
};
const pancakeresults2 = {
  buy: amountsOut7[0] / 10 ** 18,
  sell: amountsOut8[1] / 10 ** 18,
};

console.log(`ApeSwap ${flashloanBUSD} BUSD/WBNB `);
console.log(aperesults);

console.log(`PancakeSwap ${flashloanBUSD} BUSD/WBNB`);
console.log(pancakeresults);

console.log(`ApeSwap ${flashloanWBNB} WBNB/BUSD`);
console.log(aperesults2);

console.log(`PancakeSwap${flashloanWBNB} WBNB/BUSD `);
console.log(pancakeresults2);

  //Payback fee calc

  const pancakeBnbPrice =
    (pancakeresults.buy + pancakeresults.sell) / flashloanWBNB / 2;
  const apeswapBnbPrice =
    (aperesults.buy + aperesults.sell) / flashloanWBNB / 2;

  let pancakePaybackCalcBusd = (pancakeresults.buy / 0.997) * 10 ** 18;
  let apeswapPaybackCalcBusd = (aperesults.buy / 0.997) * 10 ** 18;
  let apePaybackCalcWbnb = (aperesults2.buy / 0.997) * 10 ** 18;
  let pancakePaybackCalcWbnb = (pancakeresults2.buy / 0.997) * 10 ** 18;

  let repayBusdPancakeFee =
    pancakePaybackCalcBusd / 10 ** 18 - pancakeresults.buy;
  let repayBusdApeswapFee =
    apeswapPaybackCalcBusd / 10 ** 18 - aperesults.buy;
  let repayWbnbPancakeFee =
    (pancakePaybackCalcWbnb / 10 ** 18 - pancakeresults2.buy) *
    pancakeBnbPrice;
  let repayWbnbApeswapFee =
    (apePaybackCalcWbnb / 10 ** 18 - aperesults2.buy) * apeswapBnbPrice;

  const gasPrice = await web3.eth.getGasPrice();
  const txCost =
    ((330000 * parseInt(gasPrice)) / 10 ** 18) * pancakeBnbPrice;

  //Profit Calc
  const profit1 =
    aperesults.sell - pancakeresults.buy - txCost - repayBusdApeswapFee;
  const profit2 =
    pancakeresults.sell - aperesults.buy - txCost - repayBusdPancakeFee;
  const profit3 =
    pancakeresults2.sell - aperesults2.buy - txCost - repayWbnbPancakeFee;
  const profit4 =
    aperesults2.sell - pancakeresults2.buy - txCost - repayWbnbApeswapFee;

  if (profit1 > 0 && profit1 > profit2) {
    console.log("Arb opportunity found!");
    console.log(`Flashloan WBNB on Apeswap at ${aperesults.buy} `);
    console.log(`Sell WBNB on PancakeSwap at ${pancakeresults.sell} `);
    console.log(`Expected cost of flashswap: ${repayBusdPancakeFee}`);
    console.log(`Expected Gas cost: ${txCost}`);
    console.log(`Expected profit: ${profit1} BUSD`);

    let tx = flashloan.methods.startArbitrage(
      addresses.tokens.WBNB, //token1
      addresses.tokens.BUSD, //token2
      amountInWBNB.toString(), //amount0
      0, //amount1
      addresses.apeSwap.factory, //apefactory
      addresses.pancakeSwap.router, //pancakerouter
      pancakePaybackCalcBusd.toString()
    );

    const data = tx.encodeABI();
    const txData = {
      from: admin,
      to: flashloan.options.address,
      data,
      gas: "330000",
      gasPrice: gasPrice,
    };
    const receipt = await web3.eth.sendTransaction(txData);
    console.log(`Transaction hash: ${receipt.transactionHash}`);
  }

  if (profit2 > 0 && profit2 > profit1) {
    console.log("Arb opportunity found!");
    console.log(`Buy WBNB from PancakeSwap at ${pancakeresults.buy} `);
    console.log(`Sell WBNB from ApeSwap at ${aperesults.sell}`);
    console.log(`Expected cost of flashswap: ${repayBusdApeswapFee}`);
    console.log(`Expected Gas cost: ${txCost}`);
    console.log(`Expected profit: ${profit2} BUSD`);

    let tx = flashloan.methods.startArbitrage(
      addresses.tokens.WBNB, //token1
      addresses.tokens.BUSD, //token2
      amountInWBNB.toString(), //amount0
      0, //amount1
      addresses.pancakeSwap.factory, //pancakefactory
      addresses.apeSwap.router, // aperouter
      apeswapPaybackCalcBusd.toString()
    );

    const data = tx.encodeABI();
    const txData = {
      from: admin,
      to: flashloan.options.address,
      data,
      gas: "330000",
      gasPrice: gasPrice,
    };
    const receipt = await web3.eth.sendTransaction(txData);
    console.log(`Transaction hash: ${receipt.transactionHash}`);
  }

  if (profit3 > 0 && profit3 > profit4) {
    console.log("Arb opportunity found!");
    console.log(`Flashloan BUSD on Apeswap at ${aperesults2.buy} `);
    console.log(`Sell BUSD on PancakeSwap at ${pancakeresults2.sell} `);
    console.log(`Expected cost of flashswap: ${repayWbnbApeswapFee}`);
    console.log(`Expected Gas cost: ${txCost}`);
    console.log(`Expected profit: ${profit3} WBNB`);

    let tx = flashloan.methods.startArbitrage(
      addresses.tokens.BUSD, //token1
      addresses.tokens.WBNB, //token2
      0, //amount0
      amountInBUSD.toString(), //amount1
      addresses.apeSwap.factory, //apefactory
      addresses.pancakeSwap.router, //pancakerouter
      apePaybackCalcWbnb.toString()
    );

    const data = tx.encodeABI();
    const txData = {
      from: admin,
      to: flashloan.options.address,
      data,
      gas: "330000",
      gasPrice: gasPrice,
    };
    const receipt = await web3.eth.sendTransaction(txData);
    console.log(`Transaction hash: ${receipt.transactionHash}`);
  }

  if (profit4 > 0 && profit4 > profit3) {
    console.log("Arb opportunity found!");
    console.log(`Flashloan BUSD on PancakeSwap at ${pancakeresults2.buy} `);
    console.log(`Sell BUSD on  at Apeswap ${aperesults2.sell} `);
    console.log(`Expected cost of flashswap: ${repayWbnbPancakeFee}`);
    console.log(`Expected Gas cost: ${txCost}`);
    console.log(`Expected profit: ${profit4} WBNB`);

    let tx = flashloan.methods.startArbitrage(
      //token1
      addresses.tokens.WBNB,
      addresses.tokens.BUSD, //token2
      0, //amount0
      amountInBUSD.toString(), //amount1
      addresses.pancakeSwap.factory, //pancakeFactory
      addresses.apeSwap.router, //apeRouter
      pancakePaybackCalcWbnb.toString()
    );

    const data = tx.encodeABI();
    const txData = {
      from: admin,
      to: flashloan.options.address,
      data,
      gas: "330000",
      gasPrice: gasPrice,
    };
    const receipt = await web3.eth.sendTransaction(txData);
    console.log(`Transaction hash: ${receipt.transactionHash}`);
  }
})
.on("error", (error) => {
  console.log(error);
});

};
init();`