Skip to content

Commit

Permalink
refactor: stop passing chain to quote sources (#595)
Browse files Browse the repository at this point in the history
  • Loading branch information
0xsambugs authored Oct 21, 2024
1 parent 075b818 commit 9d5b279
Show file tree
Hide file tree
Showing 29 changed files with 156 additions and 150 deletions.
6 changes: 3 additions & 3 deletions src/services/quotes/quote-sources/0x-quote-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export class ZRXQuoteSource implements IQuoteSource<ZRXSupport, ZRXConfig, ZRXDa
async quote({
components: { fetchService },
request: {
chain,
chainId,
sellToken,
buyToken,
order,
Expand All @@ -48,7 +48,7 @@ export class ZRXQuoteSource implements IQuoteSource<ZRXSupport, ZRXConfig, ZRXDa
config,
}: QuoteParams<ZRXSupport, ZRXConfig>): Promise<SourceQuoteResponse<ZRXData>> {
const queryParams = {
chainId: chain.chainId,
chainId,
sellToken,
buyToken,
taker: takeFrom,
Expand All @@ -66,7 +66,7 @@ export class ZRXQuoteSource implements IQuoteSource<ZRXSupport, ZRXConfig, ZRXDa

const response = await fetchService.fetch(url, { timeout, headers });
if (!response.ok) {
failed(ZRX_METADATA, chain, sellToken, buyToken, await response.text());
failed(ZRX_METADATA, chainId, sellToken, buyToken, await response.text());
}
const {
transaction: { data, gas, to, value },
Expand Down
6 changes: 3 additions & 3 deletions src/services/quotes/quote-sources/1inch-quote-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class OneInchQuoteSource implements IQuoteSource<OneInchSupport, OneInchC
private async getQuote({
components: { fetchService },
request: {
chain,
chainId,
sellToken,
buyToken,
order,
Expand All @@ -84,10 +84,10 @@ export class OneInchQuoteSource implements IQuoteSource<OneInchSupport, OneInchC
includeGas: true,
};
const queryString = qs.stringify(queryParams, { skipNulls: true, arrayFormat: 'comma' });
const url = `${getUrl(config)}/${chain.chainId}/swap?${queryString}`;
const url = `${getUrl(config)}/${chainId}/swap?${queryString}`;
const response = await fetchService.fetch(url, { timeout, headers: getHeaders(config) });
if (!response.ok) {
failed(ONE_INCH_METADATA, chain, sellToken, buyToken, (await response.text()) || `Failed with status ${response.status}`);
failed(ONE_INCH_METADATA, chainId, sellToken, buyToken, (await response.text()) || `Failed with status ${response.status}`);
}
const {
dstAmount,
Expand Down
8 changes: 4 additions & 4 deletions src/services/quotes/quote-sources/balancer-quote-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class BalancerQuoteSource extends AlwaysValidConfigAndContextSource<Balan
async quote({
components: { fetchService },
request: {
chain,
chainId,
sellToken,
buyToken,
order,
Expand All @@ -55,7 +55,7 @@ export class BalancerQuoteSource extends AlwaysValidConfigAndContextSource<Balan
const query = {
query: `query {
sorGetSwapPaths(
chain: ${SUPPORTED_CHAINS[chain.chainId]}
chain: ${SUPPORTED_CHAINS[chainId]}
swapAmount: "${amount}"
swapType: ${order.type == 'sell' ? 'EXACT_IN' : 'EXACT_OUT'}
tokenIn: "${sellToken}"
Expand All @@ -82,12 +82,12 @@ export class BalancerQuoteSource extends AlwaysValidConfigAndContextSource<Balan
});

if (!quoteResponse.ok) {
failed(BALANCER_METADATA, chain, sellToken, buyToken, await quoteResponse.text());
failed(BALANCER_METADATA, chainId, sellToken, buyToken, await quoteResponse.text());
}
const quoteResult = await quoteResponse.json();

if (!quoteResult.data.sorGetSwapPaths.callData) {
failed(BALANCER_METADATA, chain, sellToken, buyToken, quoteResult);
failed(BALANCER_METADATA, chainId, sellToken, buyToken, quoteResult);
}

const {
Expand Down
6 changes: 3 additions & 3 deletions src/services/quotes/quote-sources/balmy-quote-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class BalmyQuoteSource extends AlwaysValidConfigAndContextSource<BalmySup
async quote({
components: { fetchService },
request: {
chain,
chainId,
config: { slippagePercentage, timeout, txValidFor },
accounts: { takeFrom, recipient },
order,
Expand All @@ -54,7 +54,7 @@ export class BalmyQuoteSource extends AlwaysValidConfigAndContextSource<BalmySup
config,
}: QuoteParams<BalmySupport, BalmyConfig>): Promise<SourceQuoteResponse<BalmyData>> {
const balmyUrl = config.url ?? 'https://api.balmy.xyz';
const url = `${balmyUrl}/v1/swap/networks/${chain.chainId}/quotes/balmy`;
const url = `${balmyUrl}/v1/swap/networks/${chainId}/quotes/balmy`;
const stringOrder =
order.type === 'sell' ? { type: 'sell', sellAmount: order.sellAmount.toString() } : { type: 'buy', buyAmount: order.buyAmount.toString() };
const body = {
Expand All @@ -74,7 +74,7 @@ export class BalmyQuoteSource extends AlwaysValidConfigAndContextSource<BalmySup
timeout,
});
if (!response.ok) {
failed(BALMY_METADATA, chain, request.sellToken, request.buyToken, await response.text());
failed(BALMY_METADATA, chainId, request.sellToken, request.buyToken, await response.text());
}
const {
sellAmount,
Expand Down
16 changes: 8 additions & 8 deletions src/services/quotes/quote-sources/barter-quote-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class BarterQuoteSource implements IQuoteSource<BarterSupport, BarterConf
async quote({
components: { fetchService },
request: {
chain,
chainId,
sellToken,
buyToken,
order,
Expand All @@ -54,19 +54,19 @@ export class BarterQuoteSource implements IQuoteSource<BarterSupport, BarterConf
headers['X-From'] = config.referrer.name;
}

const responseEnv = await fetchService.fetch(`https://${config.customSubdomain}.${BARTER_NETWORKS[chain.chainId]}.barterswap.xyz/env`, {
const responseEnv = await fetchService.fetch(`https://${config.customSubdomain}.${BARTER_NETWORKS[chainId]}.barterswap.xyz/env`, {
headers,
timeout,
});
if (!responseEnv.ok) {
failed(BARTER_METADATA, chain, sellToken, buyToken, await responseEnv.text());
failed(BARTER_METADATA, chainId, sellToken, buyToken, await responseEnv.text());
}

const { defaultFilters, facadeAddress } = await responseEnv.json();
const typeFilter = calculateTypeFilters({ config, defaultFilters });

const responseSwapRoute = await fetchService.fetch(
`https://${config.customSubdomain}.${BARTER_NETWORKS[chain.chainId]}.barterswap.xyz/getSwapRoute`,
`https://${config.customSubdomain}.${BARTER_NETWORKS[chainId]}.barterswap.xyz/getSwapRoute`,
{
method: 'POST',
body: JSON.stringify({ source, target, amount, typeFilter }),
Expand All @@ -76,7 +76,7 @@ export class BarterQuoteSource implements IQuoteSource<BarterSupport, BarterConf
);

if (!responseSwapRoute.ok) {
failed(BARTER_METADATA, chain, sellToken, buyToken, await responseSwapRoute.text());
failed(BARTER_METADATA, chainId, sellToken, buyToken, await responseSwapRoute.text());
}
const { outputAmount, gasEstimation } = await responseSwapRoute.json();
const minBuyAmount = subtractPercentage(outputAmount, slippagePercentage, 'up');
Expand All @@ -96,7 +96,7 @@ export class BarterQuoteSource implements IQuoteSource<BarterSupport, BarterConf
async buildTx({
components: { fetchService },
request: {
chain,
chainId,
sellToken,
buyToken,
sellAmount,
Expand Down Expand Up @@ -125,14 +125,14 @@ export class BarterQuoteSource implements IQuoteSource<BarterSupport, BarterConf
typeFilter,
};

const responseSwap = await fetchService.fetch(`https://${config.customSubdomain}.${BARTER_NETWORKS[chain.chainId]}.barterswap.xyz/swap`, {
const responseSwap = await fetchService.fetch(`https://${config.customSubdomain}.${BARTER_NETWORKS[chainId]}.barterswap.xyz/swap`, {
method: 'POST',
body: JSON.stringify(bodySwap),
timeout,
headers,
});
if (!responseSwap.ok) {
failed(BARTER_METADATA, chain, sellToken, buyToken, await responseSwap.text());
failed(BARTER_METADATA, chainId, sellToken, buyToken, await responseSwap.text());
}
const resultSwap = await responseSwap.json();
const { data, to, value } = resultSwap;
Expand Down
8 changes: 4 additions & 4 deletions src/services/quotes/quote-sources/bebop-quote-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class BebopQuoteSource implements IQuoteSource<BebopSupport, BebopConfig,
async quote({
components: { fetchService },
request: {
chain,
chainId,
sellToken,
buyToken,
order,
Expand All @@ -60,16 +60,16 @@ export class BebopQuoteSource implements IQuoteSource<BebopSupport, BebopConfig,
slippage: slippagePercentage,
};
const queryString = qs.stringify(queryParams, { skipNulls: true, arrayFormat: 'comma' });
const url = `https://api.bebop.xyz/router/${NETWORK_KEY[chain.chainId]}/v1/quote?${queryString}`;
const url = `https://api.bebop.xyz/router/${NETWORK_KEY[chainId]}/v1/quote?${queryString}`;

const headers = { 'source-auth': config.apiKey };
const response = await fetchService.fetch(url, { timeout, headers });
if (!response.ok) {
failed(BEBOP_METADATA, chain, sellToken, buyToken, await response.text());
failed(BEBOP_METADATA, chainId, sellToken, buyToken, await response.text());
}
const result: BebopResult = await response.json();
if ('error' in result) {
failed(BEBOP_METADATA, chain, sellToken, buyToken, result.error.message);
failed(BEBOP_METADATA, chainId, sellToken, buyToken, result.error.message);
}
const {
sellTokens: {
Expand Down
29 changes: 15 additions & 14 deletions src/services/quotes/quote-sources/braindex-quote-source.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { encodeFunctionData, toHex, Address as ViemAddress, Hex } from 'viem';
import { Address, Chain, ChainId, TimeString } from '@types';
import { Chains } from '@chains';
import { Address, ChainId, TimeString } from '@types';
import { Chains, getChainByKey } from '@chains';
import { calculateDeadline, isSameAddress, subtractPercentage } from '@shared/utils';
import { Addresses, Uint } from '@shared/constants';
import { BuildTxParams, QuoteParams, QuoteSourceMetadata, SourceQuoteResponse, SourceQuoteTransaction } from './types';
Expand Down Expand Up @@ -32,20 +32,20 @@ export class BrainDexQuoteSource extends AlwaysValidConfigAndContextSource<Brain
async quote({
components: { fetchService },
request: {
chain,
chainId,
sellToken,
buyToken,
order,
accounts: { takeFrom, recipient },
config: { slippagePercentage, timeout, txValidFor },
},
}: QuoteParams<BrainDexSupport>): Promise<SourceQuoteResponse<BrainDexData>> {
const mappedSellToken = mapToken(sellToken, chain);
const mappedBuyToken = mapToken(buyToken, chain);
const mappedSellToken = mapToken(sellToken, chainId);
const mappedBuyToken = mapToken(buyToken, chainId);
if (isSameAddress(mappedSellToken, mappedBuyToken)) throw new Error(`Not supported`);

const body = {
chain_id: chain.chainId,
chain_id: chainId,
amount_in: toHex(order.sellAmount),
token_in: mappedSellToken,
token_out: mappedBuyToken,
Expand All @@ -62,11 +62,11 @@ export class BrainDexQuoteSource extends AlwaysValidConfigAndContextSource<Brain
timeout,
});
if (!response.ok) {
failed(BRAINDEX_METADATA, chain, sellToken, buyToken, await response.text());
failed(BRAINDEX_METADATA, chainId, sellToken, buyToken, await response.text());
}
const { amount_out, swap_paths } = await response.json();

const router = ROUTER_ADDRESS[chain.chainId];
const router = ROUTER_ADDRESS[chainId];
const buyAmount = BigInt(amount_out);
const minBuyAmount = subtractPercentage(buyAmount, slippagePercentage, 'up');

Expand All @@ -83,16 +83,16 @@ export class BrainDexQuoteSource extends AlwaysValidConfigAndContextSource<Brain

async buildTx({
request: {
chain,
chainId,
sellToken,
buyToken,
sellAmount,
minBuyAmount,
customData: { swapPaths, txValidFor, recipient },
},
}: BuildTxParams<BrainDexConfig, BrainDexData>): Promise<SourceQuoteTransaction> {
const mappedSellToken = mapToken(sellToken, chain);
const mappedBuyToken = mapToken(buyToken, chain);
const mappedSellToken = mapToken(sellToken, chainId);
const mappedBuyToken = mapToken(buyToken, chainId);
const deadline = BigInt(calculateDeadline(txValidFor) ?? Uint.MAX_256);

let calldata: string;
Expand All @@ -118,15 +118,16 @@ export class BrainDexQuoteSource extends AlwaysValidConfigAndContextSource<Brain
});
}
return {
to: ROUTER_ADDRESS[chain.chainId],
to: ROUTER_ADDRESS[chainId],
calldata,
value,
};
}
}

function mapToken(token: Address, chain: Chain): ViemAddress {
return isSameAddress(token, Addresses.NATIVE_TOKEN) ? checksum(chain.wToken) : checksum(token);
function mapToken(token: Address, chainId: ChainId): ViemAddress {
const chain = getChainByKey(chainId);
return chain && isSameAddress(token, Addresses.NATIVE_TOKEN) ? checksum(chain.wToken) : checksum(token);
}

const ROUTER_ABI = [
Expand Down
6 changes: 3 additions & 3 deletions src/services/quotes/quote-sources/changelly-quote-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class ChangellyQuoteSource implements IQuoteSource<ChangellySupport, Chan
async quote({
components: { fetchService },
request: {
chain,
chainId,
sellToken,
buyToken,
order,
Expand All @@ -47,12 +47,12 @@ export class ChangellyQuoteSource implements IQuoteSource<ChangellySupport, Chan
takerAddress: config.disableValidation ? undefined : takeFrom,
};
const queryString = qs.stringify(queryParams, { skipNulls: true, arrayFormat: 'comma' });
const url = `https://dex-api.changelly.com/v1/${chain.chainId}/quote?${queryString}`;
const url = `https://dex-api.changelly.com/v1/${chainId}/quote?${queryString}`;

const headers = { 'X-Api-Key': config.apiKey };
const response = await fetchService.fetch(url, { timeout, headers });
if (!response.ok) {
failed(CHANGELLY_METADATA, chain, sellToken, buyToken, await response.text());
failed(CHANGELLY_METADATA, chainId, sellToken, buyToken, await response.text());
}
const { amount_out_total, estimate_gas_total, calldata, to } = await response.json();

Expand Down
12 changes: 6 additions & 6 deletions src/services/quotes/quote-sources/conveyor-quote-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export class ConveyorQuoteSource extends AlwaysValidConfigAndContextSource<Conve
async quote({
components: { fetchService },
request: {
chain,
chainId,
sellToken,
buyToken,
order,
Expand All @@ -52,7 +52,7 @@ export class ConveyorQuoteSource extends AlwaysValidConfigAndContextSource<Conve
}: QuoteParams<ConveyorSupport, ConveyorConfig>): Promise<SourceQuoteResponse<ConveyorData>> {
let referrer = '0';
if (config.referrerCodes !== 'disable') {
referrer = `${config.referrerCodes?.[chain.chainId] ?? DEFAULT_REFERRERS[chain.chainId] ?? 0}`;
referrer = `${config.referrerCodes?.[chainId] ?? DEFAULT_REFERRERS[chainId] ?? 0}`;
}

const body = {
Expand All @@ -62,7 +62,7 @@ export class ConveyorQuoteSource extends AlwaysValidConfigAndContextSource<Conve
slippage: slippagePercentage * 100,
// Note: Conveyor doesn't support swap & transfer, so the recipient must be the same as the taker address
recipient: takeFrom,
chainId: chain.chainId,
chainId,
referrer,
partner: config.referrer?.name,
forceCalldata: true,
Expand All @@ -74,16 +74,16 @@ export class ConveyorQuoteSource extends AlwaysValidConfigAndContextSource<Conve
body: JSON.stringify(body),
});
if (!response.ok) {
failed(CONVEYOR_METADATA, chain, sellToken, buyToken, await response.text());
failed(CONVEYOR_METADATA, chainId, sellToken, buyToken, await response.text());
}
const { body: result } = await response.json();
if ('errorStatus' in result && !config.disableValidation) {
// We don't have a way to disable Conveyor's validation, but we can work around it. So we will only fail
// when the validation fails, and the config didn't mark it as disabled
failed(CONVEYOR_METADATA, chain, sellToken, buyToken, JSON.stringify(result.errorStatus));
failed(CONVEYOR_METADATA, chainId, sellToken, buyToken, JSON.stringify(result.errorStatus));
}
if (!('tx' in result) && 'message' in result) {
failed(CONVEYOR_METADATA, chain, sellToken, buyToken, result.message);
failed(CONVEYOR_METADATA, chainId, sellToken, buyToken, result.message);
}

const {
Expand Down
Loading

0 comments on commit 9d5b279

Please sign in to comment.