Untitled
unknown
plain_text
3 years ago
8.1 kB
8
Indexable
import axios from 'axios';
import { BigNumber } from 'ethers'
import * as ethers from 'ethers';
//const axios = require('axios')
const tokens = require('./tokens');
export const desiredAmount = '1000'
export async function checkArbitrage(DesiredAmount, fromToken, toToken) {
const FromToken = tokens.tokens.filter(token => token.symbol === fromToken)[0];
const ToToken = tokens.tokens.filter(token => token.symbol === toToken)[0]
//fromAmount getting value from stableToCrypto.js function
async function getBuyPrice() {
async function getSellPrice() {
const amount = (DesiredAmount * 10 ** FromToken.decimals);
const bestSellPrice = await getBestPrice(amount, FromToken.address, ToToken.address);
const bestPrice = bestSellPrice.bestPrice
const bestDex = bestSellPrice.bestDex;
return { bestPrice, bestDex }
}
const sellObj = await getSellPrice();
const bestSellPrice = sellObj.bestPrice;
const bestSellDEX = sellObj.bestDex;
const fromAmount = bestSellPrice;
// Agregar un timeout de x segundos
await new Promise(resolve => setTimeout(resolve, 1000));
const bestBuyPrice = await getBestPrice(fromAmount, ToToken.address, FromToken.address);
const bestPrice = (bestBuyPrice.bestPrice / 10 ** FromToken.decimals).toFixed(FromToken.decimals);
const bestDex = bestBuyPrice.bestDex;
const profit = bestPrice - parseFloat(desiredAmount)
const profitPercentage = parseFloat((profit / desiredAmount * 100).toFixed(2));
const arbitrageExists = profit > 0;
console.log(`Token Pair: ${fromToken}/${toToken}, Desired Amount: ${desiredAmount}, Best DEX: ${bestDex}, Best Price: ${bestPrice}, Best Sell DEX: ${bestSellDEX}, Profit: ${profit}, Profit Percentage: ${profitPercentage}, Arbitrage Exists: ${arbitrageExists}`);
return { toToken, fromToken, desiredAmount, bestDex, bestPrice, bestSellDEX, profit, profitPercentage, arbitrageExists };
}
// Example usage
async function getBestPrice(amount, fromTokenAddress, toTokenAddress) {
async function checkNativeToken() {
let toAddress = toTokenAddress;
let fromAddress = fromTokenAddress;
if (toAddress || fromAddress === '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE') {
toAddress = (toAddress === '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE') ? '0x0000000000000000000000000000000000001010' : toAddress;
fromAddress = (fromAddress === '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE') ? '0x0000000000000000000000000000000000001010' : fromAddress;
}
else { }
return { toAddress, fromAddress }
}
async function getSlingshotPrice() {
const addresses = await checkNativeToken();
try {
const response = await axios.post('https://slingshot.finance/api/v3/trade/', {
fromAmount: amount.toString(),
from: addresses.fromAddress,
gasOptimized: false,
limit: "99",
to: addresses.toAddress,
_unsafe: false,
recipient: "0x12848cabc163d81ff286b996b88fbd1c5b370592"
});
const price = response.data.estimatedOutput;
return price;
} catch (error) {
console.log(error);
}
}
async function get1inchPrice() {
const url = 'https://api.1inch.exchange/v3.0/137/swap';
const params = {
fromTokenAddress: fromTokenAddress,
toTokenAddress: toTokenAddress,
amount: amount,
fromAddress: '0x0000000000000000000000000000000000000000',
slippage: 3,
disableEstimate: true,
};
try {
const response = await axios.get(url, { params });
const data = response.data;
if (data) {
const price = data.toTokenAmount;
return price;
}
} catch (error) {
console.log('Error getting 1INCH price:', error);
}
}
async function getOpenOceanPrice() {
const addresses = await checkNativeToken();
const URL = 'https://ethapi.openocean.finance/v2/137/quote';
const PARAMS = {
inTokenSymbol: FromToken.symbol,
inTokenAddress: addresses.fromAddress,
outTokenSymbol: ToToken.symbol,
outTokenAddress: addresses.toAddress,
amount: amount,
gasPrice: '221657952477',
slippage: '100',
disabledDexIds: '',
};
try {
const response = await axios.get(URL, { params: PARAMS });
const data = response.data;
if (data) {
const price = data.outAmount;
return price;
}
} catch (error) {
console.error(error);
throw new Error('Failed to get price from OpenOcean');
}
}
async function getParaswapPrice() {
const url = 'https://apiv5.paraswap.io/prices/';
const params = {
srcToken: fromTokenAddress,
destToken: toTokenAddress,
amount: amount,
srcDecimals: FromToken.decimals,
destDecimals: ToToken.decimals,
side: 'SELL',
network: '137',
};
try {
const response = await axios.get(url, { params });
const data = response.data;
if (data) {
const price = data.priceRoute.destAmount;
return price;
}
} catch (error) {
console.error(error);
throw new Error('Failed to get price from Paraswap');
}
}
async function getDodoPrice() {
const url = 'https://route-api.dodoex.io/dodoapi/getdodoroute';
const params = {
fromTokenAddress: fromTokenAddress,
fromTokenDecimals: FromToken.decimals,
toTokenAddress: toTokenAddress,
toTokenDecimals: ToToken.decimals,
fromAmount: amount,
userAddr: '0x0000000000000000000000000000000000000000',
estimateGas: false,
slippage: 3,
chainId: 137,
rpc: 'https://matic-mainnet-full-rpc.bwarelabs.com',
};
try {
const response = await axios.get(url, { params });
const data = response.data;
if (data) {
let price = undefined;
async function checkPrice() {
const getPrice = await data.data.resAmount
if (getBuyPrice.name === 'getBuyPrice') {
price = await (getPrice * 10 ** ToToken.decimals);
} else {
price = await (getPrice / 10 ** FromToken.decimals);
}
return price
}
const updatedPrice = await checkPrice();
const result = updatedPrice.toString();
console.log(result)
return result
}
} catch (error) {
console.log('Error getting DODO price:', error);
}
}
const getPricePromises = [
//{ name: 'Slingshot', pricePromise: await getSlingshotPrice() },
{ name: '1inch', pricePromise: await get1inchPrice() },
{ name: 'OpenOcean', pricePromise: await getOpenOceanPrice() },
{name: 'Paraswap', pricePromise: await getParaswapPrice()},
//{name: 'Dodo', pricePromise: await getDodoPrice()},
];
const allPrices = await Promise.allSettled(
getPricePromises.map(({ pricePromise }) => pricePromise)
);
const fulfilledPrices = allPrices
.filter((result) => result.status === 'fulfilled')
.map((result, index) => ({ dex: getPricePromises[index].name, value: result.value }));
console.log(fulfilledPrices)
const values = fulfilledPrices.map(({ value }) => BigNumber.from(value));
const bestPrice = values.reduce((acc, val) => acc.gt(val) ? acc : val, BigNumber.from(0)).toString();
const bestDex = fulfilledPrices.find(({ value }) => value === bestPrice)?.dex;
return { bestDex, bestPrice };
}
const result = await getBuyPrice();
return result
}
export default { checkArbitrage };Editor is loading...