Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SWA-98][FIX] - Update 1inch API config #317

Merged
merged 3 commits into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 10 additions & 24 deletions src/entities/trades/OneInch/OneInch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { BigNumber } from '@ethersproject/bignumber'
import { BaseProvider } from '@ethersproject/providers'
import { UnsignedTransaction } from '@ethersproject/transactions'
import invariant from 'tiny-invariant'
Expand Down Expand Up @@ -32,7 +31,6 @@ interface OneInchConstructorParams {
tradeType: TradeType
chainId: ChainId
approveAddress: string
estimatedGas: BigNumber
}

/**
Expand All @@ -46,7 +44,6 @@ export class OneInchTrade extends Trade {
tradeType,
chainId,
approveAddress,
estimatedGas,
}: OneInchConstructorParams) {
super({
details: undefined,
Expand All @@ -65,13 +62,12 @@ export class OneInchTrade extends Trade {
priceImpact: new Percent('0', '100'),
fee: new Percent('0', '10000'),
approveAddress,
estimatedGas,
})
}

static async getQuote(
{ amount, quoteCurrency, tradeType, maximumSlippage = defaultMaximumSlippage }: OneInchQuoteTypes,
provider?: BaseProvider
provider?: BaseProvider,
): Promise<OneInchTrade | null> {
const chainId = tryGetChainId(amount, quoteCurrency)

Expand All @@ -84,15 +80,14 @@ export class OneInchTrade extends Trade {
// Ensure the provider's chainId matches the provided currencies
invariant(
(await provider.getNetwork()).chainId == chainId,
`OneInch.getQuote: currencies chainId does not match provider's chainId`
`OneInch.getQuote: currencies chainId does not match provider's chainId`,
)

const currencyIn = amount.currency
const currencyOut = quoteCurrency

// Ensure that the currencies are present
invariant(currencyIn.address && currencyOut.address, `getQuote: Currency address is required`)
let gas

try {
//Fetch approve address
Expand All @@ -105,32 +100,24 @@ export class OneInchTrade extends Trade {
amount: amount.raw.toString(),
}

// Fetch the quote from the API
const { fromTokenAmount, toTokenAmount, estimatedGas } = await (
const { toAmount } = await (
await fetch(generateApiRequestUrl({ methodName: RequestType.QUOTE, queryParams, chainId }))
).json()
gas = estimatedGas
let fromTokenAmountApi = fromTokenAmount
let toTokenAmountApi = toTokenAmount

let toTokenAmountApi = toAmount
let fromTokenAmountApi = amount.raw.toString()
if (tradeType === TradeType.EXACT_OUTPUT) {
// Prepare the query parameters for the API request

const queryParams = {
fromTokenAddress: currencyOut.address,
toTokenAddress: currencyIn.address,
amount: toTokenAmount.toString(),
amount: toAmount.toString(),
}

const {
toTokenAmount: toTokenAmountOutput,
fromTokenAmount,
estimatedGas,
} = await (await fetch(generateApiRequestUrl({ methodName: RequestType.QUOTE, queryParams, chainId }))).json()
const { toAmount: toTokenAmountOutput } = await (
await fetch(generateApiRequestUrl({ methodName: RequestType.QUOTE, queryParams, chainId }))
).json()

fromTokenAmountApi = fromTokenAmount
toTokenAmountApi = toTokenAmountOutput
gas = estimatedGas
}

const currencyInType = tradeType === TradeType.EXACT_INPUT ? currencyIn : currencyOut
Expand All @@ -150,7 +137,6 @@ export class OneInchTrade extends Trade {
tradeType,
chainId,
approveAddress,
estimatedGas: BigNumber.from(gas),
})
} catch (error) {
console.error('OneInch.getQuote: Error fetching the quote:', error.message)
Expand Down Expand Up @@ -192,7 +178,7 @@ export class OneInchTrade extends Trade {
public async swapTransaction(options: ExtentendedTradeOptions): Promise<UnsignedTransaction> {
invariant(
this.inputAmount.currency.address && this.outputAmount.currency.address,
'OneInchTrade: Currency address is required'
'OneInchTrade: Currency address is required',
)

const queryParams = {
Expand Down
44 changes: 39 additions & 5 deletions src/entities/trades/OneInch/api.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,66 @@
import { ChainId } from '../../../constants'
import { REFFERER_ADDRESS_CHAIN_MAPPING } from '../constants'

const apiBaseUrl = (chainId: number) => 'https://api.1inch.io/v5.0/' + chainId

export enum RequestType {
QUOTE = '/quote',
SWAP = '/swap',
}

enum ApiName {
FUSION = '/fusion',
SPOT_PRICE = '/price',
SWAP = '/swap',
}

enum SubApiName {
ORDERS = '/orders',
QUOTER = '/quoter',
RELAYER = '/relayer',
}

enum ApiVersion {
FUSION = '/v1.0',
SPOT_PRICE = '/v1.1',
SWAP = '/v5.2',
}

interface ApiRequestUrlParams {
methodName: RequestType
queryParams: Record<string, string>
chainId: ChainId
}

//0.1% fee here is link to api https://docs.1inch.io/docs/aggregation-protocol/api/swap-params
interface ApiUrlConfig {
apiName: ApiName
apiVersion: ApiVersion
chainId: number
subApiName?: SubApiName | ''
}

/**
* @see https://portal.1inch.dev/documentation/swap/introduction
*/

const API_BASE_URL = process.env.REACT_APP_ONEINCH_BASE_API_URL ?? 'https://api.1inch.dev/'
const ONE_INCH_REFFERER_FEE = '0' //MIN-> 0 MAX-> 3

const getApiUrl = ({ apiName, apiVersion, chainId, subApiName = '' }: ApiUrlConfig) =>
`${API_BASE_URL}${apiName}${subApiName}${apiVersion}/${chainId}`

export function generateApiRequestUrl({ methodName, queryParams, chainId }: ApiRequestUrlParams) {
if (REFFERER_ADDRESS_CHAIN_MAPPING[chainId]) {
queryParams.referrerAddress = REFFERER_ADDRESS_CHAIN_MAPPING[chainId] ?? ''
queryParams.fee = ONE_INCH_REFFERER_FEE
}

return apiBaseUrl(chainId) + methodName + '?' + new URLSearchParams(queryParams).toString()
return (
getApiUrl({ apiName: ApiName.SWAP, apiVersion: ApiVersion.SWAP, chainId }) +
methodName +
'?' +
new URLSearchParams(queryParams).toString()
)
}

export function approveAddressUrl(chainId: ChainId) {
return apiBaseUrl(chainId) + '/approve/spender'
return getApiUrl({ apiName: ApiName.SWAP, apiVersion: ApiVersion.SWAP, chainId }) + '/approve/spender'
}
Loading