Skip to content

Commit

Permalink
remove lambda sor, workaround tilted gyro pools (#1131)
Browse files Browse the repository at this point in the history
  • Loading branch information
franzns authored Oct 31, 2024
1 parent cbbb4df commit a197c10
Show file tree
Hide file tree
Showing 12 changed files with 70 additions and 504 deletions.
5 changes: 5 additions & 0 deletions .changeset/modern-moles-pay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'backend': patch
---

remove old sor lambda and add workaround for multiple paths
18 changes: 0 additions & 18 deletions config/fantom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,24 +118,6 @@ export default <NetworkData>{
],
},
avgBlockSpeed: 1,
sor: {
env: {
main: {
url: 'https://2bz6hsr2y54svqgow7tbwwsrta0icouy.lambda-url.ca-central-1.on.aws/',
maxPools: 8,
forceRefresh: false,
gasPrice: BigNumber.from(10),
swapGas: BigNumber.from('1000000'),
},
canary: {
url: 'https://mep53ds2noe6rhicd67q7raqhq0dkupc.lambda-url.eu-central-1.on.aws/',
maxPools: 8,
forceRefresh: false,
gasPrice: BigNumber.from(10),
swapGas: BigNumber.from('1000000'),
},
},
},
ybAprConfig: {
sftmx: {
tokens: {
Expand Down
18 changes: 0 additions & 18 deletions config/optimism.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,24 +76,6 @@ export default <NetworkData>{
excludedFarmIds: [],
},
avgBlockSpeed: 1,
sor: {
env: {
main: {
url: 'https://nplks2oknz5lhxn6kpgxbfrxgm0hzicm.lambda-url.ca-central-1.on.aws/',
maxPools: 8,
forceRefresh: false,
gasPrice: BigNumber.from(10),
swapGas: BigNumber.from('1000000'),
},
canary: {
url: 'https://svlitjilcr5qtp7iolimlrlg7e0ipupj.lambda-url.eu-central-1.on.aws/',
maxPools: 8,
forceRefresh: false,
gasPrice: BigNumber.from(10),
swapGas: BigNumber.from('1000000'),
},
},
},
ybAprConfig: {
aave: {
v3: {
Expand Down
9 changes: 0 additions & 9 deletions modules/network/network-config-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,15 +134,6 @@ export interface NetworkData {
avgBlockSpeed: number;
sor?: {
poolIdsToExclude?: string[];
env?: {
[key in DeploymentEnv]?: {
url: string;
maxPools: number;
forceRefresh: boolean;
gasPrice: BigNumber;
swapGas: BigNumber;
};
};
};
datastudio?: {
[key in DeploymentEnv]: {
Expand Down
45 changes: 45 additions & 0 deletions modules/sor/sor-debug.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,49 @@ describe('sor debugging', () => {
}
expect(parseFloat(swaps.returnAmount)).toBeGreaterThan(0);
}, 5000000);

it('sor v2 fantom gyro', async () => {
const chain = Chain.FANTOM;

const chainId = Object.keys(chainIdToChain).find((key) => chainIdToChain[key] === chain) as string;
initRequestScopedContext();
setRequestScopedContextValue('chainId', chainId);
//only do once before starting to debug
// await PoolController().syncOnchainDataForPoolsV2(chain, [
// '0xff236989201b0f2691c3208af68d15c6d79ce8a7000200000000000000000903',
// ]);
// await PoolController().updateLiquidityValuesForActivePools(chain);

const SFTMX = '0xd7028092c830b5c8fce061af2e593413ebbc1fc1';
const WFTM = '0x21be370d5312f44cb42ce377bc9b8a0cef1a4c83';
const LUDWIG = '0xe6cc4d855b4fd4a9d02f46b9adae4c5efb1764b5';

const swaps = await sorService.getSorSwaps({
chain,
tokenIn: WFTM,
tokenOut: SFTMX,
swapType: 'EXACT_IN',
swapAmount: '800',
// queryBatchSwap: false,
// useProtocolVersion: 3,
// callDataInput: {
// receiver: '0xb5e6b895734409Df411a052195eb4EE7e40d8696',
// sender: '0xb5e6b895734409Df411a052195eb4EE7e40d8696',
// slippagePercentage: '0.1',
// },
swapOptions: {
maxPools: 8,
},
});

for (const route of swaps.routes) {
for (const hop of route.hops) {
if (hop.pool.id === '0xff236989201b0f2691c3208af68d15c6d79ce8a7000200000000000000000903') {
console.log(`ECLP`);
}
}
}
expect(parseFloat(swaps.returnAmount)).toBeGreaterThan(0);
console.log(swaps.returnAmount);
}, 5000000);
});
132 changes: 2 additions & 130 deletions modules/sor/sor.service.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
import {
GqlSorGetSwapPaths,
GqlSorGetSwapsResponse,
GqlSorSwapType,
QuerySorGetSwapPathsArgs,
QuerySorGetSwapsArgs,
} from '../../schema';
import { sorV1BeetsService } from './sorV1Beets/sorV1Beets.service';
import { sorV2Service } from './sorV2/sorPathService';
import { GetSwapsInput, GetSwapsV2Input as GetSwapPathsInput, SwapResult } from './types';
import { Chain } from '@prisma/client';
import { formatUnits, parseUnits } from '@ethersproject/units';
import { tokenService } from '../token/token.service';
import { GetSwapsV2Input as GetSwapPathsInput } from './types';
import { getToken, getTokenAmountHuman, swapPathsZeroResponse, zeroResponse } from './utils';
import { AllNetworkConfigsKeyedOnChain } from '../network/network-config';

Expand Down Expand Up @@ -107,7 +102,7 @@ export class SorService {
// args.swapAmount is HumanScale
const amount = await getTokenAmountHuman(amountToken, args.swapAmount, args.chain!);

const swapResult = await this.getComparingSwap({
const swapResult = await sorV2Service.getSwapResult({
chain: args.chain!,
swapAmount: amount,
swapOptions: args.swapOptions,
Expand All @@ -129,129 +124,6 @@ export class SorService {
}
}

private async getComparingSwap(input: GetSwapsInput) {
const v1Start = +new Date();
const swapV1 = await sorV1BeetsService.getSwapResult(input);
const v1Time = +new Date() - v1Start;

const v2Start = +new Date();
const swapV2 = await sorV2Service.getSwapResult(input);
const v2Time = +new Date() - v2Start;

const version = this.getBestSwap(swapV1, swapV2, input.swapType);

await this.logResult(
version,
swapV1,
swapV2,
input.swapType,
input.tokenIn,
input.tokenOut,
input.chain,
v1Time,
v2Time,
);

if (!version) return null;

return version === 'V1' ? swapV1 : swapV2;
}

/**
* Find best swap result for V1 vs V2 and return in CowSwap API format. Log if V1 wins.
* @param v1
* @param v2
* @param swapType
* @returns
*/
private getBestSwap(v1: SwapResult, v2: SwapResult, swapType: GqlSorSwapType, debugOut = false) {
// Useful for comparing
if (debugOut) {
console.log(`------ DEBUG`);
console.log(v1);
console.log(v2);
}

if (!v1.isValid && !v2.isValid) return null;

let isV1 = false;
if (!v1.isValid || !v2.isValid) {
isV1 = v1.isValid ? true : false;
} else if (swapType === 'EXACT_IN') {
if (v2.outputAmount < v1.outputAmount) {
isV1 = true;
}
} else {
if (v2.inputAmount > v1.inputAmount) {
isV1 = true;
}
}

if (isV1 === true) {
return 'V1';
}

return 'V2';
}

private async logResult(
version: string | null,
v1: SwapResult,
v2: SwapResult,
swapType: GqlSorSwapType,
assetIn: string,
assetOut: string,
chain: Chain,
v1Time: number,
v2Time: number,
) {
if (!version) return;

let v1ResultAmount = v1.inputAmount;
let v2ResultAmount = v2.inputAmount < 0 ? -v2.inputAmount : v2.inputAmount;
let tradeAmount = v1.outputAmount;
let userToken = assetOut;
let resultToken = assetIn;
if (swapType === 'EXACT_IN') {
v1ResultAmount = v1.outputAmount;
v2ResultAmount = v2.outputAmount < 0 ? -v2.outputAmount : v2.outputAmount;
tradeAmount = v1.inputAmount;
userToken = assetIn;
resultToken = assetOut;
}

const fp = (a: bigint, d: number) => Number(formatUnits(String(a), d));
const bn = (a: string, d: number) => BigInt(String(parseUnits(a, d)));
const prismaToken = await tokenService.getToken(resultToken, chain);
const decimals = prismaToken ? prismaToken.decimals : 18; // most probably native asset
let v2Perf =
version === 'V1'
? 1 - fp(v1ResultAmount, decimals) / fp(v2ResultAmount, decimals) // negative perf means V1 is better
: fp(v2ResultAmount, decimals) / fp(v1ResultAmount, decimals) - 1; // positive perf means V2 is better

v2Perf = Math.max(-1, Math.min(1, v2Perf));
let diffN = fp(v2ResultAmount, decimals) - fp(v1ResultAmount, decimals);
let diff = bn(diffN.toFixed(decimals), decimals);
let bestResultAmount = version === 'V1' ? v1ResultAmount : v2ResultAmount;

console.log(
[
'SOR_RESULT',
v1Time,
v2Time,
chain,
version,
swapType,
userToken,
resultToken,
String(tradeAmount),
String(bestResultAmount),
String(diff),
v2Perf.toFixed(8),
].join(','),
);
}

private async getBestSwapPathVersion(input: Omit<GetSwapPathsInput, 'protocolVersion'>) {
const swapBalancerV2 = await sorV2Service.getSorSwapPaths({ ...input, protocolVersion: 2 });
const swapBalancerV3 = await sorV2Service.getSorSwapPaths({ ...input, protocolVersion: 3 });
Expand Down
Loading

0 comments on commit a197c10

Please sign in to comment.