Skip to content

Commit

Permalink
Merge pull request #139 from balancer-labs/types-refactor
Browse files Browse the repository at this point in the history
Strengthen type checking + general refactor of types
  • Loading branch information
John Grant authored Sep 14, 2021
2 parents 53cfea0 + 7a939a2 commit 9602fa4
Show file tree
Hide file tree
Showing 76 changed files with 43,142 additions and 22,965 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@rollup/plugin-node-resolve": "^13.0.4",
"@rollup/plugin-typescript": "^8.2.5",
"@types/chai": "^4.2.10",
"@types/lodash.clonedeep": "^4.5.6",
"@types/mocha": "^7.0.2",
"@types/node": "^14.0.20",
"@typescript-eslint/eslint-plugin": "^4.29.2",
Expand Down
6 changes: 3 additions & 3 deletions src/formatSwaps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const formatSequence = (
? swap.tokenInDecimals
: swap.tokenOutDecimals;

amountScaled = scale(bnum(swap.swapAmount), scalingFactor)
amountScaled = scale(bnum(swap.swapAmount as string), scalingFactor)
.decimalPlaces(0, 1)
.toString();
}
Expand Down Expand Up @@ -102,10 +102,10 @@ export function formatSwaps(

const { tokenInDecimals } = swaps[0].find(
(swap) => swap.tokenIn === tokenIn
);
) as Swap;
const { tokenOutDecimals } = swaps[0].find(
(swap) => swap.tokenOut === tokenOut
);
) as Swap;

const tokenArray = getTokenAddresses(swaps);
const swapsV2: SwapV2[] = swaps.flatMap((sequence) =>
Expand Down
2 changes: 1 addition & 1 deletion src/frontendHelpers/stableHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function BPTForTokensZeroPriceImpact(
// if there were no price impact, i.e. using the spot price of tokenIn/BPT

// We need to scale down allBalances
const allBalancesDownScaled = [];
const allBalancesDownScaled: BigNumber[] = [];
for (let i = 0; i < allBalances.length; i++) {
allBalancesDownScaled.push(
allBalances[i].times(new BigNumber(10).pow(-decimals[i]))
Expand Down
2 changes: 1 addition & 1 deletion src/poolCaching/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export class PoolCacher {
newPools = cloneDeep(poolsData);
} else {
// Retrieve from URL if set otherwise use data passed in constructor
if (this.isConnectedToSubgraph()) {
if (this.poolsUrl !== null) {
newPools = await fetchSubgraphPools(this.poolsUrl);
} else {
newPools = this.pools;
Expand Down
7 changes: 4 additions & 3 deletions src/poolCaching/onchainData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export async function getOnChainBalances(
): Promise<SubgraphPoolBase[]> {
if (subgraphPools.length === 0) return subgraphPools;

const abis = Object.values(
const abis: any = Object.values(
// Remove duplicate entries using their names
Object.fromEntries(
[
Expand Down Expand Up @@ -85,7 +85,7 @@ export async function getOnChainBalances(
string,
{
amp?: string;
swapFee?: string;
swapFee: string;
weights?: string[];
poolTokens: {
tokens: string[];
Expand All @@ -111,7 +111,8 @@ export async function getOnChainBalances(
bnum(poolTokens.balances[i]),
-Number(T.decimals)
).toString();
if (subgraphPools[poolId].poolType === 'Weighted') {
if (weights) {
// Only expected for WeightedPools
T.weight = scale(bnum(weights[i]), -18).toString();
}
});
Expand Down
31 changes: 13 additions & 18 deletions src/pools/elementPool/elementPool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
PoolPairBase,
SwapTypes,
SubgraphPoolBase,
SubgraphToken,
} from '../../types';
import { getAddress } from '@ethersproject/address';
import { bnum } from '../../utils/bignumber';
Expand All @@ -19,31 +20,16 @@ import {
getTimeTillExpiry,
} from './elementMath';

export interface ElementPoolToken {
address: string;
balance: string;
decimals: string | number;
}
type ElementPoolToken = Pick<SubgraphToken, 'address' | 'balance' | 'decimals'>;

export interface ElementPoolPairData extends PoolPairBase {
id: string;
address: string;
poolType: PoolTypes;
tokenIn: string;
tokenOut: string;
balanceIn: BigNumber;
balanceOut: BigNumber;
swapFee: BigNumber;
decimalsIn: number;
decimalsOut: number;
// Element specific fields
export type ElementPoolPairData = PoolPairBase & {
totalShares: BigNumber;
expiryTime: number;
unitSeconds: number;
principalToken: string;
baseToken: string;
currentBlockTimestamp: number;
}
};

export class ElementPool implements PoolBase {
poolType: PoolTypes = PoolTypes.Element;
Expand All @@ -62,6 +48,14 @@ export class ElementPool implements PoolBase {
currentBlockTimestamp: number;

static fromPool(pool: SubgraphPoolBase): ElementPool {
if (!pool.expiryTime) throw new Error('ElementPool missing expiryTime');
if (!pool.unitSeconds)
throw new Error('ElementPool missing unitSeconds');
if (!pool.principalToken)
throw new Error('ElementPool missing principalToken');

if (!pool.baseToken) throw new Error('ElementPool missing baseToken');

return new ElementPool(
pool.id,
pool.address,
Expand Down Expand Up @@ -196,6 +190,7 @@ export class ElementPool implements PoolBase {
} else {
// token is underlying in the pool
const T = this.tokens.find((t) => t.address === token);
if (!T) throw Error('Pool does not contain this token');
T.balance = newBalance.toString();
}
}
Expand Down
1 change: 1 addition & 0 deletions src/pools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,5 @@ export function getOutputAmountSwap(
return pool._tokenInForExactTokenOut(poolPairData, amount, false);
}
}
throw Error('Unsupported swap');
}
35 changes: 9 additions & 26 deletions src/pools/metaStablePool/metaStablePool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import {
PoolBase,
PoolTypes,
SwapPairType,
PoolPairBase,
SwapTypes,
SubgraphPoolBase,
SubgraphToken,
} from '../../types';
import { getAddress } from '@ethersproject/address';
import { bnum, scale, ZERO } from '../../utils/bignumber';
Expand All @@ -17,35 +17,17 @@ import {
_derivativeSpotPriceAfterSwapExactTokenInForTokenOut,
_derivativeSpotPriceAfterSwapTokenInForExactTokenOut,
} from './metaStableMath';
import { StablePoolPairData } from 'pools/stablePool/stablePool';

export interface MetaStablePoolToken {
address: string;
balance: string;
decimals: string | number;
priceRate?: string;
}
type MetaStablePoolToken = Pick<
SubgraphToken,
'address' | 'balance' | 'decimals' | 'priceRate'
>;

export interface MetaStablePoolPairData extends PoolPairBase {
id: string;
address: string;
poolType: PoolTypes;
tokenIn: string;
tokenOut: string;
balanceIn: BigNumber;
balanceOut: BigNumber;
swapFee: BigNumber;
swapFeeScaled: BigNumber;
decimalsIn: number;
decimalsOut: number;
allBalances: BigNumber[]; // Only for stable pools
allBalancesScaled: BigNumber[]; // Only for stable pools - EVM Maths uses everything in 1e18 upscaled format and this avoids repeated scaling
invariant: BigNumber; // Only for stable pools
amp: BigNumber; // Only for stable pools
tokenIndexIn: number; // Only for stable pools
tokenIndexOut: number; // Only for stable pools
export type MetaStablePoolPairData = StablePoolPairData & {
tokenInPriceRate: BigNumber;
tokenOutPriceRate: BigNumber;
}
};

export class MetaStablePool implements PoolBase {
poolType: PoolTypes = PoolTypes.MetaStable;
Expand Down Expand Up @@ -195,6 +177,7 @@ export class MetaStablePool implements PoolBase {
} else {
// token is underlying in the pool
const T = this.tokens.find((t) => t.address === token);
if (!T) throw Error('Pool does not contain this token');
T.balance = newBalance.toString();
}
}
Expand Down
36 changes: 12 additions & 24 deletions src/pools/stablePool/stablePool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
PoolPairBase,
SwapTypes,
SubgraphPoolBase,
SubgraphToken,
} from '../../types';
import { getAddress } from '@ethersproject/address';
import { bnum, scale, ZERO } from '../../utils/bignumber';
Expand All @@ -18,31 +19,17 @@ import {
_derivativeSpotPriceAfterSwapTokenInForExactTokenOut,
} from './stableMath';

export interface StablePoolToken {
address: string;
balance: string;
decimals: string | number;
}
type StablePoolToken = Pick<SubgraphToken, 'address' | 'balance' | 'decimals'>;

export interface StablePoolPairData extends PoolPairBase {
id: string;
address: string;
poolType: PoolTypes;
tokenIn: string;
tokenOut: string;
balanceIn: BigNumber;
balanceOut: BigNumber;
swapFee: BigNumber;
swapFeeScaled: BigNumber;
decimalsIn: number;
decimalsOut: number;
allBalances: BigNumber[]; // Only for stable pools
allBalancesScaled: BigNumber[]; // Only for stable pools - EVM Maths uses everything in 1e18 upscaled format and this avoids repeated scaling
invariant: BigNumber; // Only for stable pools
amp: BigNumber; // Only for stable pools
tokenIndexIn: number; // Only for stable pools
tokenIndexOut: number; // Only for stable pools
}
export type StablePoolPairData = PoolPairBase & {
swapFeeScaled: BigNumber; // EVM Maths uses everything in 1e18 upscaled format and this avoids repeated scaling
allBalances: BigNumber[];
allBalancesScaled: BigNumber[]; // EVM Maths uses everything in 1e18 upscaled format and this avoids repeated scaling
invariant: BigNumber;
amp: BigNumber;
tokenIndexIn: number;
tokenIndexOut: number;
};

export class StablePool implements PoolBase {
poolType: PoolTypes = PoolTypes.Stable;
Expand Down Expand Up @@ -175,6 +162,7 @@ export class StablePool implements PoolBase {
} else {
// token is underlying in the pool
const T = this.tokens.find((t) => t.address === token);
if (!T) throw Error('Pool does not contain this token');
T.balance = newBalance.toString();
}
}
Expand Down
39 changes: 15 additions & 24 deletions src/pools/weightedPool/weightedPool.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getAddress } from '@ethersproject/address';
import { bnum, scale, ZERO, ONE } from '../../utils/bignumber';
import { bnum, scale, ZERO } from '../../utils/bignumber';
import { BigNumber } from '../../utils/bignumber';
import * as SDK from '@georgeroman/balancer-v2-pools';
import {
Expand All @@ -9,6 +9,8 @@ import {
PoolPairBase,
SwapTypes,
SubgraphPoolBase,
SubgraphToken,
NoNullableField,
} from '../../types';
import {
_exactTokenInForTokenOut,
Expand All @@ -19,27 +21,15 @@ import {
_derivativeSpotPriceAfterSwapTokenInForExactTokenOut,
} from './weightedMath';

export interface WeightedPoolToken {
address: string;
balance: string;
decimals: string | number;
weight?: string;
}
export type WeightedPoolToken = Pick<
NoNullableField<SubgraphToken>,
'address' | 'balance' | 'decimals' | 'weight'
>;

export interface WeightedPoolPairData extends PoolPairBase {
id: string;
address: string;
poolType: PoolTypes;
tokenIn: string;
tokenOut: string;
balanceIn: BigNumber;
balanceOut: BigNumber;
weightIn: BigNumber; // Weights are only defined for weighted pools
weightOut: BigNumber; // Weights are only defined for weighted pools
swapFee: BigNumber;
decimalsIn: number;
decimalsOut: number;
}
export type WeightedPoolPairData = PoolPairBase & {
weightIn: BigNumber;
weightOut: BigNumber;
};

export class WeightedPool implements PoolBase {
poolType: PoolTypes = PoolTypes.Weighted;
Expand All @@ -63,7 +53,7 @@ export class WeightedPool implements PoolBase {
pool.swapFee,
pool.totalWeight,
pool.totalShares,
pool.tokens,
pool.tokens as WeightedPoolToken[],
pool.tokensList
);
}
Expand All @@ -86,7 +76,7 @@ export class WeightedPool implements PoolBase {
this.totalWeight = bnum(totalWeight);
}

setTypeForSwap(type: SwapPairType) {
setTypeForSwap(type: SwapPairType): void {
this.swapPairType = type;
}

Expand Down Expand Up @@ -131,7 +121,7 @@ export class WeightedPool implements PoolBase {
// inverse of the slippage. It is proportional to the token balances in the
// pool but also depends on the shape of the invariant curve.
// As a standard, we define normalized liquidity in tokenOut
getNormalizedLiquidity(poolPairData: WeightedPoolPairData) {
getNormalizedLiquidity(poolPairData: WeightedPoolPairData): BigNumber {
return poolPairData.balanceOut
.times(poolPairData.weightIn)
.div(poolPairData.weightIn.plus(poolPairData.weightOut));
Expand All @@ -156,6 +146,7 @@ export class WeightedPool implements PoolBase {
} else {
// token is underlying in the pool
const T = this.tokens.find((t) => t.address === token);
if (!T) throw Error('Pool does not contain this token');
T.balance = newBalance.toString();
}
}
Expand Down
Loading

0 comments on commit 9602fa4

Please sign in to comment.