Skip to content

Commit

Permalink
Merge pull request #1260 from ReflectiveChimp/update-1inch-api
Browse files Browse the repository at this point in the history
Support new 1inch api
  • Loading branch information
seguido authored Oct 18, 2023
2 parents 5eb06aa + 9c63e24 commit 06d738a
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 49 deletions.
28 changes: 21 additions & 7 deletions src/api/zaps/one-inch/OneInchSwapApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,16 @@ import {
} from './types';

export class OneInchSwapApi implements IOneInchSwapApi {
constructor(protected readonly baseUrl: string) {}
constructor(protected readonly baseUrl: string, protected readonly apiKey: string) {}

protected buildUrl<T extends {}>(path: string, request?: T) {
const params = request ? new URLSearchParams(request).toString() : '';
return params ? `${this.baseUrl}${path}?${params}` : `${this.baseUrl}${path}`;
let queryString: string | undefined;
if (request) {
const params = new URLSearchParams(request);
queryString = params.toString();
}

return queryString ? `${this.baseUrl}${path}?${queryString}` : `${this.baseUrl}${path}`;
}

protected async get<ResponseType extends {}, RequestType extends {}>(
Expand All @@ -25,6 +30,7 @@ export class OneInchSwapApi implements IOneInchSwapApi {
const response = await fetch(url, {
headers: {
Accept: 'application/json',
Authorization: `Bearer ${this.apiKey}`,
},
});

Expand All @@ -43,6 +49,7 @@ export class OneInchSwapApi implements IOneInchSwapApi {
const response = await fetch(url, {
headers: {
Accept: 'application/json',
Authorization: `Bearer ${this.apiKey}`,
},
});

Expand All @@ -58,20 +65,27 @@ export class OneInchSwapApi implements IOneInchSwapApi {
return proxyResponse;
}

protected addRequiredParams<T extends object>(request: T): T & { includeTokensInfo: boolean } {
return {
...request,
includeTokensInfo: true,
};
}

async getProxiedQuote(request: QuoteRequest): Promise<ProxiedResponse> {
return await this.transparentGet('/quote', request);
return await this.transparentGet('/quote', this.addRequiredParams(request));
}

async getProxiedSwap(request: SwapRequest): Promise<ProxiedResponse> {
return await this.transparentGet('/swap', request);
return await this.transparentGet('/swap', this.addRequiredParams(request));
}

async getQuote(request: QuoteRequest): Promise<QuoteResponse> {
return await this.get('/quote', request);
return await this.get('/quote', this.addRequiredParams(request));
}

async getSwap(request: SwapRequest): Promise<SwapResponse> {
return await this.get('/swap', request);
return await this.get('/swap', this.addRequiredParams(request));
}

async isHealthy(): Promise<boolean> {
Expand Down
5 changes: 3 additions & 2 deletions src/api/zaps/one-inch/RateLimitedOneInchSwapApi.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { OneInchSwapApi } from './OneInchSwapApi';
import PQueue from 'p-queue';
import { ProxiedResponse } from './types.js';

export class RateLimitedOneInchSwapApi extends OneInchSwapApi {
constructor(baseUrl: string, protected readonly queue: PQueue) {
super(baseUrl);
constructor(baseUrl: string, apiKey: string, protected readonly queue: PQueue) {
super(baseUrl, apiKey);
}

protected async get<ResponseType extends {}, RequestType extends {}>(
Expand Down
27 changes: 11 additions & 16 deletions src/api/zaps/one-inch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,15 @@ import { AnyChain, ApiChain, toApiChain, toChainId } from '../../../utils/chain'
import { OneInchPriceApi } from './OneInchPriceApi';
import { IOneInchPriceApi, IOneInchSwapApi } from './types';

const DEFAULT_API_URL = 'https://api.1inch.io';
const API_URL = process.env.ONE_INCH_API || DEFAULT_API_URL;
// With custom api endpoint we can do more requests per second
const API_QUEUE_CONFIG_CUSTOM = {
concurrency: 10,
intervalCap: 10, // 10 to 20 RPS as per 1inch for our private API
interval: 1000,
};
// Default config is really slow at 1 per 2 seconds
// Configure to just under RPS allowed by our account
const API_QUEUE_CONFIG = {
concurrency: 1,
intervalCap: 1,
interval: 2000,
concurrency: 1, // TODO change once we have enterprise account
intervalCap: 1, // TODO change once we have enterprise account
interval: 2000, // TODO change once we have enterprise account
carryoverConcurrencyCount: true,
autoStart: true,
timeout: 60 * 1000,
timeout: 30 * 1000,
throwOnTimeout: true,
...(API_URL === DEFAULT_API_URL ? {} : API_QUEUE_CONFIG_CUSTOM),
};

const swapApiByChain: Partial<Record<ApiChain, IOneInchSwapApi>> = {};
Expand All @@ -37,8 +28,12 @@ export function getOneInchSwapApi(chain: AnyChain): IOneInchSwapApi {
}

const chainId = toChainId(apiChain);
const baseUrl = `${API_URL}/v5.0/${chainId}`;
swapApiByChain[apiChain] = new RateLimitedOneInchSwapApi(baseUrl, swapApiQueue);
const baseUrl = `https://api.1inch.dev/swap/v5.2/${chainId}`;
const apiKey = process.env.ONE_INCH_API_KEY;
if (!apiKey) {
throw new Error(`ONE_INCH_API_KEY env variable is not set`);
}
swapApiByChain[apiChain] = new RateLimitedOneInchSwapApi(baseUrl, apiKey, swapApiQueue);
}

return swapApiByChain[apiChain];
Expand Down
32 changes: 10 additions & 22 deletions src/api/zaps/one-inch/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,45 +6,35 @@ export type HealthCheckResponse = {
};

export type QuoteRequest = {
fromTokenAddress: string;
toTokenAddress: string;
src: string;
dst: string;
amount: string;
fee?: string;
};

export type QuoteToken = {
address: string;
symbol: string;
name: string;
decimals: number;
logoURI: string;
name: string;
symbol: string;
tags: string[];
};

export type QuoteRoutePart = {
fromTokenAddress: string;
name: string;
part: number;
toTokenAddress: string;
};

export type QuoteResponse = {
estimatedGas: number;
fromToken: QuoteToken;
fromTokenAmount: string;
toToken: QuoteToken;
toTokenAmount: string;
protocols: QuoteRoutePart[][][];
toAmount: string;
};

export type SwapRequest = {
fromTokenAddress: string;
toTokenAddress: string;
src: string;
dst: string;
amount: string;
fromAddress: string;
from: string;
slippage: number;
fee?: string;
referrerAddress?: string;
referrer?: string;
disableEstimate?: boolean;
};

Expand All @@ -59,10 +49,8 @@ export type SwapTx = {

export type SwapResponse = {
fromToken: QuoteToken;
fromTokenAmount: string;
toToken: QuoteToken;
toTokenAmount: string;
protocols: string[];
toAmount: string;
tx: SwapTx;
};

Expand Down
4 changes: 2 additions & 2 deletions src/api/zaps/zaps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -494,8 +494,8 @@ async function getCanSwapOnOneInch(
// Don't quote wnative:wnative
const calls = tokensExcludingWnative.map(token =>
api.getQuote({
fromTokenAddress: token.address,
toTokenAddress: wnative.address,
src: token.address,
dst: wnative.address,
amount: amountInWei,
})
);
Expand Down

0 comments on commit 06d738a

Please sign in to comment.