Skip to content

Commit

Permalink
redo output for b-sdk input
Browse files Browse the repository at this point in the history
  • Loading branch information
franzns committed Feb 8, 2024
1 parent 4c5bf83 commit 3ff07c1
Show file tree
Hide file tree
Showing 6 changed files with 66 additions and 34 deletions.
26 changes: 20 additions & 6 deletions modules/sor/sor.gql
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ extend type Query {
"""
Get swap quote from the SOR v2 for the V2 vault
"""
sorV2GetSwaps(
sorGetSwapPaths(
"""
The Chain to query
"""
Expand All @@ -26,10 +26,11 @@ extend type Query {
swapType: GqlSorSwapType!
swapAmount: BigDecimal! #expected in human readable form
queryBatchSwap: Boolean #run queryBatchSwap to update with onchain values, default: true
): GqlSorGetSwaps!
useVaultVersion: Int #defaults that it gets the best swap from v2 and v3, can force to use only one vault version
): GqlSorGetSwapPaths!
}

type GqlSorGetSwaps {
type GqlSorGetSwapPaths {
vaultVersion: Int!
"""
The token address of the tokenIn provided
Expand All @@ -39,9 +40,8 @@ type GqlSorGetSwaps {
The token address of the tokenOut provided
"""
tokenOut: String!
tokenAddresses: [String!]!
swapType: GqlSorSwapType!
swaps: [GqlSorSwap!]!
swaps: [GqlSorSwap!]! #used by cowswap
paths: [GqlSorPath!]! #used by b-sdk
tokenInAmount: AmountHumanReadable!
tokenOutAmount: AmountHumanReadable!
swapAmount: AmountHumanReadable!
Expand All @@ -54,6 +54,19 @@ type GqlSorGetSwaps {
priceImpact: AmountHumanReadable!
}

type GqlSorPath {
vaultVersion: Int!
pools: [String]! #list of pool Ids
tokens: [Token]!
outputAmountRaw: String!
inputAmountRaw: String!
}

type Token {
address: String!
decimals: Int!
}

enum GqlSorSwapType {
EXACT_IN
EXACT_OUT
Expand Down Expand Up @@ -119,6 +132,7 @@ type GqlSorGetSwapsResponse {
priceImpact: AmountHumanReadable!
}

#used by cowswap
type GqlSorSwap {
poolId: String!
assetInIndex: Int!
Expand Down
4 changes: 2 additions & 2 deletions modules/sor/sor.resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ const balancerSdkResolvers: Resolvers = {

return sorService.getSorSwaps(args);
},
sorV2GetSwaps: async (parent, args, context) => {
return sorService.getSorV2Swaps(args);
sorGetSwapPaths: async (parent, args, context) => {
return sorService.getSorSwapPaths(args);
},
},
};
Expand Down
12 changes: 6 additions & 6 deletions modules/sor/sor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import {
GqlSorSwapType,
GqlSorGetSwapsResponse,
QuerySorGetSwapsArgs,
GqlSorGetSwaps,
QuerySorV2GetSwapsArgs,
QuerySorGetSwapPathsArgs,
GqlSorGetSwapPaths,
} from '../../schema';
import { sorV1BeetsService } from './sorV1Beets/sorV1Beets.service';
import { sorV2Service } from './sorV2/sorV2.service';
Expand All @@ -12,15 +12,15 @@ import * as Sentry from '@sentry/node';
import { Chain } from '@prisma/client';
import { parseUnits, formatUnits } from '@ethersproject/units';
import { tokenService } from '../token/token.service';
import { getToken, getTokenAmountHuman, zeroResponse, zeroResponseV2 } from './utils';
import { getToken, getTokenAmountHuman, zeroResponse, swapPathsZeroResponse } from './utils';

export class SorService {
async getSorV2Swaps(args: QuerySorV2GetSwapsArgs): Promise<GqlSorGetSwaps> {
async getSorSwapPaths(args: QuerySorGetSwapPathsArgs): Promise<GqlSorGetSwapPaths> {
console.log('getSorSwaps args', JSON.stringify(args));
const tokenIn = args.tokenIn.toLowerCase();
const tokenOut = args.tokenOut.toLowerCase();
const amountToken = args.swapType === 'EXACT_IN' ? tokenIn : tokenOut;
const emptyResponse = zeroResponseV2(args.swapType, args.tokenIn, args.tokenOut);
const emptyResponse = swapPathsZeroResponse(args.tokenIn, args.tokenOut);

// check if tokens addresses exist
try {
Expand All @@ -44,7 +44,7 @@ export class SorService {
// args.swapAmount is HumanScale
const amount = await getTokenAmountHuman(amountToken, args.swapAmount, args.chain!);

return sorV2Service.getSorSwaps({
return sorV2Service.getSorSwapPaths({
chain: args.chain!,
swapAmount: amount,
swapType: args.swapType,
Expand Down
24 changes: 22 additions & 2 deletions modules/sor/sorV2/beetsHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BatchSwapStep, NATIVE_ADDRESS, SingleSwap, SwapKind, ZERO_ADDRESS } from '@balancer/sdk';
import { GqlPoolMinimal, GqlSorSwapRoute, GqlSorSwapRouteHop } from '../../../schema';
import { BatchSwapStep, NATIVE_ADDRESS, SingleSwap, Swap, SwapKind, ZERO_ADDRESS } from '@balancer/sdk';
import { GqlPoolMinimal, GqlSorPath, GqlSorSwapRoute, GqlSorSwapRouteHop } from '../../../schema';
import { formatFixed } from '@ethersproject/bignumber';
import path from 'path';

export function mapRoutes(
swaps: BatchSwapStep[] | SingleSwap,
Expand All @@ -22,6 +23,25 @@ export function mapRoutes(
return paths.map((p) => mapBatchSwap(p, amountIn, amountOut, kind, assets, pools));
}

export function mapPaths(swap: Swap): GqlSorPath[] {
const paths: GqlSorPath[] = [];

for (const path of swap.paths) {
paths.push({
vaultVersion: 2,
inputAmountRaw: path.inputAmount.amount.toString(),
outputAmountRaw: path.outputAmount.amount.toString(),
tokens: path.tokens.map((token) => ({
address: token.address,
decimals: token.decimals,
})),
pools: path.pools.map((pool) => pool.id),
});
}

return paths;
}

export function mapBatchSwap(
swaps: BatchSwapStep[],
amountIn: string,
Expand Down
26 changes: 12 additions & 14 deletions modules/sor/sorV2/sorV2.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { GqlSorGetSwaps, GqlSorSwap, GqlSorSwapType } from '../../../schema';
import { GqlSorGetSwapPaths, GqlSorSwap, GqlSorSwapType } from '../../../schema';
import { Chain } from '@prisma/client';
import { PrismaPoolWithDynamic, prismaPoolWithDynamic } from '../../../prisma/prisma-types';
import { prisma } from '../../../prisma/prisma-client';
Expand All @@ -12,9 +12,9 @@ import { Address, formatUnits, parseUnits } from 'viem';
import { sorGetSwapsWithPools } from './lib/static';
import { SwapResultV2 } from './swapResultV2';
import { poolService } from '../../pool/pool.service';
import { mapRoutes } from './beetsHelpers';
import { mapPaths, mapRoutes } from './beetsHelpers';
import { replaceZeroAddressWithEth } from '../../web3/addresses';
import { getToken, zeroResponseV2 } from '../utils';
import { getToken, swapPathsZeroResponse } from '../utils';
import { BatchSwapStep, SingleSwap, Swap, SwapKind, TokenAmount } from '@balancer/sdk';
import { Token } from 'graphql';

Expand Down Expand Up @@ -66,16 +66,16 @@ export class SorV2Service implements SwapService {
}
}

public async getSorSwaps(input: GetSwapsV2Input, maxNonBoostedPathDepth = 4): Promise<GqlSorGetSwaps> {
public async getSorSwapPaths(input: GetSwapsV2Input, maxNonBoostedPathDepth = 4): Promise<GqlSorGetSwapPaths> {
const swap = await this.getSwap(input, maxNonBoostedPathDepth);
const emptyResponse = zeroResponseV2(input.swapType, input.tokenIn, input.tokenOut);
const emptyResponse = swapPathsZeroResponse(input.tokenIn, input.tokenOut);

if (!swap) {
return emptyResponse;
}

try {
return this.mapToSorSwaps(swap!, input.chain, input.queryBatchSwap ? input.queryBatchSwap : true);
return this.mapToSorSwapPaths(swap!, input.chain, input.queryBatchSwap ? input.queryBatchSwap : true);
} catch (err: any) {
console.log(`Error Retrieving QuerySwap`, err);
Sentry.captureException(err.message, {
Expand Down Expand Up @@ -136,7 +136,7 @@ export class SorV2Service implements SwapService {
}
}

public async mapToSorSwaps(swap: Swap, chain: Chain, queryFirst = false): Promise<GqlSorGetSwaps> {
public async mapToSorSwapPaths(swap: Swap, chain: Chain, queryFirst = false): Promise<GqlSorGetSwapPaths> {
if (!queryFirst) return this.mapSwapToSorGetSwaps(swap, swap.inputAmount, swap.outputAmount);
else {
const rpcUrl = AllNetworkConfigsKeyedOnChain[chain].data.rpcUrl;
Expand All @@ -153,7 +153,7 @@ export class SorV2Service implements SwapService {
swap: Swap,
inputAmount: TokenAmount,
outputAmount: TokenAmount,
): Promise<GqlSorGetSwaps> {
): Promise<GqlSorGetSwapPaths> {
const priceImpact = swap.priceImpact.decimal.toFixed(4);
let poolIds: string[];
if (swap.isBatchSwap) {
Expand Down Expand Up @@ -187,6 +187,8 @@ export class SorV2Service implements SwapService {
swap.swapKind,
);

const paths = mapPaths(swap);

for (const route of routes) {
route.tokenInAmount = ((inputAmount.amount * BigInt(parseUnits(`${0.5}`, 6))) / 1000000n).toString();
route.tokenOutAmount = (
Expand All @@ -196,11 +198,11 @@ export class SorV2Service implements SwapService {
}

return {
vaultVersion: 2,
paths: paths,
swaps: this.mapSwaps(swap.swaps, swap.assets),
tokenAddresses: swap.assets,
tokenIn: replaceZeroAddressWithEth(inputAmount.token.address),
tokenOut: replaceZeroAddressWithEth(outputAmount.token.address),
swapType: this.mapSwapKindToSwapType(swap.swapKind),
tokenInAmount: inputAmount.amount.toString(),
tokenOutAmount: outputAmount.amount.toString(),
swapAmount: formatUnits(swapAmount.amount, swapAmount.token.decimals),
Expand All @@ -224,10 +226,6 @@ export class SorV2Service implements SwapService {
return swapType === 'EXACT_IN' ? SwapKind.GivenIn : SwapKind.GivenOut;
}

private mapSwapKindToSwapType(kind: SwapKind): GqlSorSwapType {
return kind === SwapKind.GivenIn ? 'EXACT_IN' : 'EXACT_OUT';
}

private mapSwaps(swaps: BatchSwapStep[] | SingleSwap, assets: string[]): GqlSorSwap[] {
if (Array.isArray(swaps)) {
return swaps.map((swap) => {
Expand Down
8 changes: 4 additions & 4 deletions modules/sor/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { tokenService } from '../token/token.service';
import { Chain } from '@prisma/client';
import { AllNetworkConfigsKeyedOnChain, chainToIdMap } from '../network/network-config';
import { GqlSorGetSwaps, GqlSorGetSwapsResponse, GqlSorSwapType } from '../../schema';
import { GqlSorGetSwapPaths, GqlSorGetSwapsResponse, GqlSorSwapType } from '../../schema';
import { replaceZeroAddressWithEth } from '../web3/addresses';
import { Address } from 'viem';
import { NATIVE_ADDRESS, Token, TokenAmount } from '@balancer/sdk';
Expand Down Expand Up @@ -37,13 +37,13 @@ export const getToken = async (tokenAddr: string, chain: Chain): Promise<Token>
}
};

export const zeroResponseV2 = (swapType: GqlSorSwapType, tokenIn: string, tokenOut: string): GqlSorGetSwaps => {
export const swapPathsZeroResponse = (tokenIn: string, tokenOut: string): GqlSorGetSwapPaths => {
return {
tokenAddresses: [],
swaps: [],
paths: [],
vaultVersion: 2,
tokenIn: replaceZeroAddressWithEth(tokenIn),
tokenOut: replaceZeroAddressWithEth(tokenOut),
swapType,
tokenInAmount: '0',
tokenOutAmount: '0',
swapAmount: '0',
Expand Down

0 comments on commit 3ff07c1

Please sign in to comment.