Skip to content

Commit

Permalink
Merge pull request #597 from beethovenxfi/fix/sor
Browse files Browse the repository at this point in the history
native asset support, fixes: #587
  • Loading branch information
franzns authored Dec 14, 2023
2 parents cc0d6dc + 875bbec commit dd2c31a
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 44 deletions.
3 changes: 2 additions & 1 deletion modules/beethoven/balancer-sor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import * as Sentry from '@sentry/node';
import _ from 'lodash';
import { Logger } from '@ethersproject/logger';
import { SwapInfoRoute } from '@balancer-labs/sor';
import { NATIVE_ADDRESS, ZERO_ADDRESS } from '@balancer/sdk';

interface GetSwapsInput {
tokenIn: string;
Expand Down Expand Up @@ -331,7 +332,7 @@ export class BalancerSorService {
}

private getTokenDecimals(tokenAddress: string, tokens: PrismaToken[]): number {
if (tokenAddress === '0x0000000000000000000000000000000000000000') {
if (tokenAddress === ZERO_ADDRESS || tokenAddress === NATIVE_ADDRESS) {
return 18;
}

Expand Down
3 changes: 1 addition & 2 deletions modules/sor/sorV1Balancer/sorV1Balancer.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { GqlSorSwapType, GqlCowSwapApiResponse, GqlSorGetSwapsResponse } from '.
import { GetSwapsInput, SwapService, SwapResult } from '../types';
import { FundManagement, SwapTypes, SwapV2 } from '@balancer-labs/sdk';
import { env } from '../../../app/env';
import { networkContext } from '../../network/network-context.service';
import { AllNetworkConfigs, AllNetworkConfigsKeyedOnChain, chainToIdMap } from '../../network/network-config';
import { DeploymentEnv } from '../../network/network-config-types';

Expand All @@ -33,7 +32,7 @@ class SwapResultV1 implements SwapResult {
}
}

async getCowSwapResponse(chain = networkContext.chain, queryFirst = false): Promise<GqlCowSwapApiResponse> {
async getCowSwapResponse(chain: Chain, queryFirst = false): Promise<GqlCowSwapApiResponse> {
if (!this.isValid || this.swap === null) throw new Error('No Response - Invalid Swap');

if (queryFirst) {
Expand Down
6 changes: 3 additions & 3 deletions modules/sor/sorV2/beetsHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BatchSwapStep, SingleSwap, SwapKind } from '@balancer/sdk';
import { BatchSwapStep, NATIVE_ADDRESS, SingleSwap, SwapKind, ZERO_ADDRESS } from '@balancer/sdk';
import { GqlPoolMinimal, GqlSorSwapRoute, GqlSorSwapRouteHop } from '../../../schema';
import { formatFixed } from '@ethersproject/bignumber';

Expand Down Expand Up @@ -77,8 +77,8 @@ export function splitPaths(
if (kind === SwapKind.GivenOut) {
swapsCopy.reverse();
}
const assetInIndex = BigInt(assets.indexOf(assetIn));
const assetOutIndex = BigInt(assets.indexOf(assetOut));
const assetInIndex = BigInt(assets.indexOf(assetIn === NATIVE_ADDRESS ? ZERO_ADDRESS : assetIn));
const assetOutIndex = BigInt(assets.indexOf(assetOut === NATIVE_ADDRESS ? ZERO_ADDRESS : assetOut));
let path: BatchSwapStep[];
let paths: BatchSwapStep[][] = [];
swapsCopy.forEach((swap) => {
Expand Down
49 changes: 20 additions & 29 deletions modules/sor/sorV2/sorV2.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {
BasePool,
sorGetSwapsWithPools,
Token,
Address,
SwapKind,
sorParseRawPools,
Expand All @@ -14,30 +13,37 @@ import {
RawGyro2Pool,
RawGyro3Pool,
RawGyroEPool,
HumanAmount,
SupportedRawPoolTypes,
SingleSwap,
BatchSwapStep,
} from '@balancer/sdk';
import { GqlSorSwapType, GqlSwap, GqlSorGetSwapsResponse, GqlPoolMinimal, GqlSorSwapRoute } from '../../../schema';
import {
GqlSorSwapType,
GqlSwap,
GqlSorGetSwapsResponse,
GqlPoolMinimal,
GqlSorSwapRoute,
GqlCowSwapApiResponse,
} from '../../../schema';
import { Chain, PrismaPoolType } from '@prisma/client';
import { PrismaPoolWithDynamic, prismaPoolWithDynamic } from '../../../prisma/prisma-types';
import { prisma } from '../../../prisma/prisma-client';
import { GetSwapsInput, SwapResult, SwapService } from '../types';
import { poolService } from '../../pool/pool.service';
import { tokenService } from '../../token/token.service';
import { networkContext } from '../../network/network-context.service';
import { prisma } from '../../../prisma/prisma-client';
import { PrismaPoolWithDynamic, prismaPoolWithDynamic } from '../../../prisma/prisma-types';
import { HumanAmount, SupportedRawPoolTypes } from '@balancer/sdk';
import { BalancerSorService } from '../../beethoven/balancer-sor.service';
import { env } from '../../../app/env';
import { DeploymentEnv } from '../../network/network-config-types';
import { Cache, CacheClass } from 'memory-cache';
import { GqlCowSwapApiResponse } from '../../../schema';
import { BalancerSorService } from '../../beethoven/balancer-sor.service';
import { poolService } from '../../pool/pool.service';
import { BatchSwapStep } from '@balancer/sdk';
import { SingleSwap } from '@balancer/sdk';
import { SwapInfoRoute, SwapTypes, Swap, bnum, SwapInfoRouteHop } from '@balancer-labs/sor';
import { BigNumber } from 'ethers';
import { oldBnumScale } from '../../big-number/old-big-number';
import { mapRoutes } from './beetsHelpers';
import { poolsToIgnore } from '../constants';
import { AllNetworkConfigsKeyedOnChain, chainToIdMap } from '../../network/network-config';
import * as Sentry from '@sentry/node';
import { getToken } from '../utils';

const ALL_BASEPOOLS_CACHE_KEY = `basePools:all`;

Expand All @@ -59,7 +65,7 @@ class SwapResultV2 implements SwapResult {
}
}

async getCowSwapResponse(chain = networkContext.chain, queryFirst = false): Promise<GqlCowSwapApiResponse> {
async getCowSwapResponse(chain: Chain, queryFirst = false): Promise<GqlCowSwapApiResponse> {
if (!this.isValid || this.swap === null) throw new Error('No Response - Invalid Swap');

if (!queryFirst) return this.mapResultToCowSwap(this.swap, this.swap.inputAmount, this.swap.outputAmount);
Expand Down Expand Up @@ -278,8 +284,8 @@ export class SorV2Service implements SwapService {
): Promise<SwapResult> {
try {
const poolsFromDb = await this.getBasePools(chain);
const tIn = await this.getToken(tokenIn as Address, chain);
const tOut = await this.getToken(tokenOut as Address, chain);
const tIn = await getToken(tokenIn as Address, chain);
const tOut = await getToken(tokenOut as Address, chain);
const swapKind = this.mapSwapType(swapType);
const config = graphTraversalConfig
? {
Expand Down Expand Up @@ -321,21 +327,6 @@ export class SorV2Service implements SwapService {
}
}

/**
* Gets a b-sdk Token based off tokenAddr.
* @param address
* @param chain
* @returns
*/
private async getToken(address: Address, chain: Chain): Promise<Token> {
const token = await tokenService.getToken(address, chain);
if (!token) {
throw new Error('Unknown token: ' + address);
}
const chainId = Number(chainToIdMap[chain]);
return new Token(chainId, address, token.decimals, token.symbol);
}

private mapSwapType(swapType: GqlSorSwapType): SwapKind {
return swapType === 'EXACT_IN' ? SwapKind.GivenIn : SwapKind.GivenOut;
}
Expand Down
30 changes: 21 additions & 9 deletions modules/sor/utils.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,32 @@
import { TokenAmount, Token, Address } from '@balancer/sdk';
import { TokenAmount, Token, Address, NATIVE_ADDRESS, NATIVE_ASSETS } from '@balancer/sdk';
import { tokenService } from '../token/token.service';
import { Chain } from '@prisma/client';
import { chainToIdMap } from '../network/network-config';

export async function getTokenAmountHuman(tokenAddr: string, humanAmount: string, chain: Chain): Promise<TokenAmount> {
const chainId = Number(chainToIdMap[chain]);
const prismaToken = await tokenService.getToken(tokenAddr, chain);
if (!prismaToken) throw Error(`Missing token from tokenService ${tokenAddr}`);
const token = new Token(chainId, prismaToken.address as Address, prismaToken.decimals);
const token = await getToken(tokenAddr, chain);
return TokenAmount.fromHumanAmount(token, humanAmount as `${number}`);
}

export async function getTokenAmountRaw(tokenAddr: string, rawAmount: string, chain: Chain): Promise<TokenAmount> {
const chainId = Number(chainToIdMap[chain]);
const prismaToken = await tokenService.getToken(tokenAddr, chain);
if (!prismaToken) throw Error(`Missing token from tokenService ${tokenAddr}`);
const token = new Token(chainId, prismaToken.address as Address, prismaToken.decimals);
const token = await getToken(tokenAddr, chain);
return TokenAmount.fromRawAmount(token, rawAmount);
}

/**
* Gets a b-sdk Token based off tokenAddr.
* @param address
* @param chain
* @returns
*/
export const getToken = async (tokenAddr: string, chain: Chain): Promise<Token> => {
const chainId = Number(chainToIdMap[chain]);

if (tokenAddr === NATIVE_ADDRESS && chainId in NATIVE_ASSETS) {
return NATIVE_ASSETS[chainId as keyof typeof NATIVE_ASSETS];
} else {
const prismaToken = await tokenService.getToken(tokenAddr, chain);
if (!prismaToken) throw Error(`Missing token from tokenService ${tokenAddr}`);
return new Token(chainId, prismaToken.address as Address, prismaToken.decimals);
}
};

0 comments on commit dd2c31a

Please sign in to comment.