|
| 1 | +import { ethers } from 'ethers'; |
| 2 | +import { getCalleeAddressByCollateralType } from '../../constants/CALLEES'; |
| 3 | +import { getCollateralConfigBySymbol } from '../../constants/COLLATERALS'; |
| 4 | +import { getErc20SymbolByAddress } from '../../contracts'; |
| 5 | +import { getDecimalChainIdByNetworkType, getNetworkConfigByType } from '../../network'; |
| 6 | +import { CollateralConfig } from '../../types'; |
| 7 | +import BigNumber from '../../bignumber'; |
| 8 | +import { getTokenAddressByNetworkAndSymbol } from '../../tokens'; |
| 9 | +import { Queue } from 'async-await-queue'; |
| 10 | +import memoizee from 'memoizee'; |
| 11 | +import { convertETHtoDAI } from '../../fees'; |
| 12 | + |
| 13 | +const MAX_DELAY_BETWEEN_REQUESTS_MS = 600; |
| 14 | +const REQUEST_QUEUE = new Queue(1, MAX_DELAY_BETWEEN_REQUESTS_MS); |
| 15 | +const EXPECTED_SIGNATURE = '0x12aa3caf'; // see https://www.4byte.directory/signatures/?bytes4_signature=0x12aa3caf |
| 16 | +const SUPPORTED_1INCH_NETWORK_IDS = [1, 56, 137, 10, 42161, 100, 43114]; // see https://help.1inch.io/en/articles/5528619-how-to-use-different-networks-on-1inch |
| 17 | +const ONE_DAY_MS = 24 * 60 * 60 * 1000; |
| 18 | + |
| 19 | +export const getOneInchUrl = (chainId: number) => { |
| 20 | + return `https://api.1inch.io/v5.0/${chainId}`; |
| 21 | +}; |
| 22 | + |
| 23 | +interface Protocol { |
| 24 | + id: string; |
| 25 | + title: string; |
| 26 | + img: string; |
| 27 | + img_color: string; |
| 28 | +} |
| 29 | + |
| 30 | +interface OneInchToken { |
| 31 | + symbol: string; |
| 32 | + name: string; |
| 33 | + address: string; |
| 34 | + decimals: 0; |
| 35 | + logoURI: string; |
| 36 | +} |
| 37 | +interface OneInchSwapRepsonse { |
| 38 | + fromToken: OneInchToken; |
| 39 | + toToken: OneInchToken; |
| 40 | + toTokenAmount: string; |
| 41 | + fromTokenAmount: string; |
| 42 | + protocols: OneInchSwapRoute[]; |
| 43 | + tx: { |
| 44 | + from: string; |
| 45 | + to: string; |
| 46 | + data: string; |
| 47 | + value: string; |
| 48 | + gasPrice: string; |
| 49 | + gas: string; |
| 50 | + }; |
| 51 | +} |
| 52 | +interface LiquiditySourcesResponse { |
| 53 | + protocols: Protocol[]; |
| 54 | +} |
| 55 | +type OneInchSwapRoute = { name: string; part: number; fromTokenAddress: string; toTokenAddress: string }[][]; |
| 56 | + |
| 57 | +const executeRequestInQueue = async (url: string) => { |
| 58 | + const apiRequestSymbol = Symbol(); |
| 59 | + await REQUEST_QUEUE.wait(apiRequestSymbol); |
| 60 | + const response = await fetch(url).then(res => res.json()); |
| 61 | + REQUEST_QUEUE.end(apiRequestSymbol); |
| 62 | + return response; |
| 63 | +}; |
| 64 | + |
| 65 | +export const executeOneInchApiRequest = async ( |
| 66 | + chainId: number, |
| 67 | + endpoint: '/swap' | '/liquidity-sources', |
| 68 | + params?: Record<string, any> |
| 69 | +) => { |
| 70 | + const oneInchUrl = getOneInchUrl(chainId); |
| 71 | + const url = `${oneInchUrl}${endpoint}?${new URLSearchParams(params)}`; |
| 72 | + const response = await executeRequestInQueue(url); |
| 73 | + if (response.error) { |
| 74 | + throw new Error(`failed to receive response from oneinch: ${response.error}`); |
| 75 | + } |
| 76 | + return response; |
| 77 | +}; |
| 78 | + |
| 79 | +async function _getOneinchValidProtocols(chainId: number) { |
| 80 | + // Fetch all supported protocols except for the limit orders |
| 81 | + const response: LiquiditySourcesResponse = await executeOneInchApiRequest(chainId, '/liquidity-sources'); |
| 82 | + const protocolIds = response.protocols.map(protocol => protocol.id); |
| 83 | + return protocolIds.filter(protocolId => !protocolId.toLowerCase().includes('limit')); |
| 84 | +} |
| 85 | + |
| 86 | +export const getOneinchValidProtocols = memoizee(_getOneinchValidProtocols, { |
| 87 | + promise: true, |
| 88 | + length: 1, |
| 89 | + maxAge: ONE_DAY_MS, |
| 90 | +}); |
| 91 | + |
| 92 | +export async function getOneinchSwapParameters( |
| 93 | + network: string, |
| 94 | + collateralSymbol: string, |
| 95 | + amount: string, |
| 96 | + marketId: string, |
| 97 | + slippage = '1' |
| 98 | +): Promise<OneInchSwapRepsonse> { |
| 99 | + const isFork = getNetworkConfigByType(network).isFork; |
| 100 | + const chainId = isFork ? 1 : getDecimalChainIdByNetworkType(network); |
| 101 | + if (!isFork && !SUPPORTED_1INCH_NETWORK_IDS.includes(chainId)) { |
| 102 | + throw new Error(`1inch does not support network ${network}`); |
| 103 | + } |
| 104 | + const toTokenAddress = await getTokenAddressByNetworkAndSymbol(network, 'DAI'); |
| 105 | + const fromTokenAddress = await getTokenAddressByNetworkAndSymbol(network, collateralSymbol); |
| 106 | + const calleeAddress = getCalleeAddressByCollateralType( |
| 107 | + network, |
| 108 | + getCollateralConfigBySymbol(collateralSymbol).ilk, |
| 109 | + marketId |
| 110 | + ); |
| 111 | + // Documentation https://docs.1inch.io/docs/aggregation-protocol/api/swap-params/ |
| 112 | + const swapParams = { |
| 113 | + fromTokenAddress, |
| 114 | + toTokenAddress, |
| 115 | + fromAddress: calleeAddress, |
| 116 | + amount, |
| 117 | + slippage, |
| 118 | + allowPartialFill: false, // disable partial fill |
| 119 | + disableEstimate: true, // disable eth_estimateGas |
| 120 | + compatibilityMode: true, // always receive parameters for the `swap` call |
| 121 | + }; |
| 122 | + const oneinchResponse = await executeOneInchApiRequest(chainId, '/swap', swapParams); |
| 123 | + const functionSignature = ethers.utils.hexDataSlice(oneinchResponse.tx.data, 0, 4); // see https://docs.soliditylang.org/en/develop/abi-spec.html#function-selector |
| 124 | + if (functionSignature !== EXPECTED_SIGNATURE) { |
| 125 | + throw new Error(`Unexpected 1inch function signature: ${functionSignature}, expected: ${EXPECTED_SIGNATURE}`); |
| 126 | + } |
| 127 | + return oneinchResponse; |
| 128 | +} |
| 129 | + |
| 130 | +export async function extractPathFromSwapResponseProtocols( |
| 131 | + network: string, |
| 132 | + oneInchRoutes: OneInchSwapRoute[] |
| 133 | +): Promise<string[]> { |
| 134 | + const pathStepsResolves = await Promise.all( |
| 135 | + oneInchRoutes[0].map(async route => { |
| 136 | + return await Promise.all([ |
| 137 | + await getErc20SymbolByAddress(network, route[0].fromTokenAddress), |
| 138 | + await getErc20SymbolByAddress(network, route[0].toTokenAddress), |
| 139 | + ]); |
| 140 | + }) |
| 141 | + ); |
| 142 | + const path = [pathStepsResolves[0][0]]; |
| 143 | + for (const step of pathStepsResolves) { |
| 144 | + path.push(step[1]); |
| 145 | + } |
| 146 | + return path; |
| 147 | +} |
| 148 | + |
| 149 | +export async function getOneInchMarketData( |
| 150 | + network: string, |
| 151 | + collateral: CollateralConfig, |
| 152 | + amount: BigNumber, |
| 153 | + marketId: string |
| 154 | +) { |
| 155 | + const swapData = await getOneinchSwapParameters( |
| 156 | + network, |
| 157 | + collateral.symbol, |
| 158 | + amount.shiftedBy(collateral.decimals).toFixed(0), |
| 159 | + marketId |
| 160 | + ); |
| 161 | + const path = await extractPathFromSwapResponseProtocols(network, swapData.protocols); |
| 162 | + const calleeData = swapData.tx.data; |
| 163 | + const estimatedGas = swapData.tx.gas; |
| 164 | + const exchangeFeeEth = new BigNumber(swapData.tx.gasPrice).multipliedBy(estimatedGas); |
| 165 | + const exchangeFeeDai = await convertETHtoDAI(network, exchangeFeeEth); |
| 166 | + const to = swapData.tx.to; |
| 167 | + return { |
| 168 | + path, |
| 169 | + exchangeFeeEth, |
| 170 | + exchangeFeeDai, |
| 171 | + calleeData, |
| 172 | + to, |
| 173 | + }; |
| 174 | +} |
0 commit comments