Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: dynamic vault address retrieval #3

Merged
merged 6 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion balancer-js/examples/data/alfajores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const sdk = new BalancerSDK({
},
});

const { pools, tokenPrices } = sdk.data;
const { tokenPrices } = sdk.data;
async function main() {
console.log(
await tokenPrices.find('0x1d4c35c3f4a91103ba323fe2f4c3f6ebef531c11')
Expand Down
2 changes: 1 addition & 1 deletion balancer-js/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kolektivo-labs/sdk",
"version": "0.0.1-beta",
"version": "0.0.2-beta",
"description": "JavaScript SDK for interacting with the Balancer Protocol V2",
"license": "GPL-3.0-only",
"homepage": "https://github.com/balancer-labs/balancer-sdk#readme",
Expand Down
15 changes: 15 additions & 0 deletions balancer-js/src/lib/constants/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ import addressesByNetwork from './addresses.json';

export const balancerVault = '0xBA12222222228d8Ba445958a75a0704d566BF2C8';

export const vaultAddresses: Record<number, string> = {
[Network.MAINNET]: balancerVault,
[Network.POLYGON]: balancerVault,
[Network.ARBITRUM]: balancerVault,
[Network.GOERLI]: balancerVault,
[Network.OPTIMISM]: balancerVault,
[Network.GNOSIS]: balancerVault,
[Network.FANTOM]: balancerVault,
[Network.BASE]: balancerVault,
[Network.ZKEVM]: balancerVault,
[Network.AVALANCHE]: balancerVault,
[Network.SEPOLIA]: balancerVault,
[Network.ALFAJORES]: '0xf2D39dd1b3e991f23d8a61bABb1c13873640873F',
};

// Info fetched using npm package slot20
export const BPT_SLOT = 0;
export const BPT_DECIMALS = 18;
Expand Down
18 changes: 15 additions & 3 deletions balancer-js/src/modules/graph/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Zero, WeiPerEther } from '@ethersproject/constants';
import { BalancerError, BalancerErrorCode } from '@/balancerErrors';
import { isSameAddress, parsePoolInfo } from '@/lib/utils';
import { _downscaleDown } from '@/lib/utils/solidityMaths';
import { Pool, PoolAttribute, PoolType } from '@/types';
import { BalancerNetworkConfig, Pool, PoolAttribute, PoolType } from '@/types';

import { Findable } from '../data/types';
import { PoolTypeConcerns } from '../pools/pool-type-concerns';
Expand Down Expand Up @@ -62,7 +62,16 @@ exitActions.set(PoolType.Weighted, 'exitPool');
exitActions.set(PoolType.ComposableStable, 'exitPool');

export class PoolGraph {
constructor(private pools: Findable<Pool, PoolAttribute>) {}
private pools: Findable<Pool, PoolAttribute>;
private chainId: number;

constructor(
pools: Findable<Pool, PoolAttribute>,
networkConfig: BalancerNetworkConfig
) {
this.pools = pools;
this.chainId = networkConfig.chainId;
}

async buildGraphFromRootPool(
poolId: string,
Expand Down Expand Up @@ -136,7 +145,10 @@ export class PoolGraph {

const tokenTotal = this.getTokenTotal(pool);
// Spot price service
const { spotPriceCalculator } = PoolTypeConcerns.from(pool.poolType);
const { spotPriceCalculator } = PoolTypeConcerns.from(
pool.poolType,
this.chainId
);
const spotPrices: SpotPrices = {};
let decimals = 18;
// Spot price of a path is product of the sp of each pool in path. We calculate the sp for each pool token here to use as required later.
Expand Down
26 changes: 21 additions & 5 deletions balancer-js/src/modules/liquidity/liquidity.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { Findable, Pool, PoolToken, Price } from '@/types';
import {
BalancerNetworkConfig,
Findable,
Pool,
PoolToken,
Price,
} from '@/types';
import { PoolAttribute } from '../data';
import { PoolTypeConcerns } from '../pools/pool-type-concerns';
import { BigNumber } from '@ethersproject/bignumber';
Expand All @@ -12,10 +18,19 @@ export interface PoolBPTValue {
}

export class Liquidity {
private pools: Findable<Pool, PoolAttribute>;
private tokenPrices: Findable<Price>;
private chainId: number;

constructor(
private pools: Findable<Pool, PoolAttribute>,
private tokenPrices: Findable<Price>
) {}
pools: Findable<Pool, PoolAttribute>,
tokenPrices: Findable<Price>,
networkConfig: BalancerNetworkConfig
) {
this.pools = pools;
this.tokenPrices = tokenPrices;
this.chainId = networkConfig.chainId;
}

async getLiquidity(pool: Pool): Promise<string> {
// Remove any tokens with same address as pool as they are pre-printed BPT
Expand Down Expand Up @@ -82,7 +97,8 @@ export class Liquidity {
// }

const tokenLiquidity = PoolTypeConcerns.from(
pool.poolType
pool.poolType,
this.chainId
).liquidity.calcTotal(nonPoolTokensWithUpdatedPrice);

const parsedTokenLiquidity = parseFixed(tokenLiquidity, SCALE);
Expand Down
6 changes: 5 additions & 1 deletion balancer-js/src/modules/pools/apr/apr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,11 @@ export class PoolApr {
*/
private async totalLiquidity(pool: Pool): Promise<string> {
try {
const liquidityService = new Liquidity(this.pools, this.tokenPrices);
const liquidityService = new Liquidity(
this.pools,
this.tokenPrices,
BALANCER_NETWORK_CONFIG[pool.chainId as Network]
);
const liquidity = await liquidityService.getLiquidity(pool);
return liquidity;
} catch (err) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
JoinPoolDecodedAttributes,
JoinPoolRequestDecodedAttributes,
} from '@/modules/pools/factory/types';
import { balancerVault, networkAddresses } from '@/lib/constants/config';
import { networkAddresses } from '@/lib/constants/config';
import { AssetHelpers, getRandomBytes32 } from '@/lib/utils';
import { PoolFactory } from '@/modules/pools/factory/pool-factory';
import { ComposableStablePoolEncoder } from '@/pool-composable-stable';
Expand All @@ -23,10 +23,12 @@ import { Contract } from '@ethersproject/contracts';
import { ContractInstances } from '@/modules/contracts/contracts.module';
import { BytesLike } from '@ethersproject/bytes';
import { ComposableStablePoolInterface } from '@/contracts/ComposableStablePool';
import { getVault } from '@/modules/sdk.helpers';

export class ComposableStableFactory implements PoolFactory {
private wrappedNativeAsset: string;
private contracts: ContractInstances;
private balancerVault: string;

constructor(
networkConfig: BalancerNetworkConfig,
Expand All @@ -35,6 +37,7 @@ export class ComposableStableFactory implements PoolFactory {
const { tokens } = networkAddresses(networkConfig.chainId);
this.wrappedNativeAsset = tokens.wrappedNativeAsset;
this.contracts = contracts;
this.balancerVault = getVault(networkConfig.chainId);
}

/**
Expand Down Expand Up @@ -226,7 +229,7 @@ export class ComposableStableFactory implements PoolFactory {
const { functionName, data } = this.encodeInitJoinFunctionData(params);

return {
to: balancerVault,
to: this.balancerVault,
functionName,
data,
attributes,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { JsonRpcProvider, TransactionReceipt } from '@ethersproject/providers';

import { Vault__factory } from '@/contracts/factories/Vault__factory';
import { WeightedPoolFactory__factory } from '@/contracts/factories/WeightedPoolFactory__factory';
import { balancerVault, networkAddresses } from '@/lib/constants/config';
import { networkAddresses } from '@/lib/constants/config';
import {
AssetHelpers,
findEventInReceiptLogs,
Expand All @@ -27,10 +27,12 @@ import { WeightedPool__factory } from '@/contracts';
import { SolidityMaths } from '@/lib/utils/solidityMaths';
import { BalancerError, BalancerErrorCode } from '@/balancerErrors';
import { WeightedPoolInterface } from '@/contracts/WeightedPool';
import { getVault } from '@/modules/sdk.helpers';

export class WeightedFactory implements PoolFactory {
private wrappedNativeAsset: string;
private contracts: ContractInstances;
private balancerVault: string;

constructor(
networkConfig: BalancerNetworkConfig,
Expand All @@ -39,6 +41,7 @@ export class WeightedFactory implements PoolFactory {
const { tokens } = networkAddresses(networkConfig.chainId);
this.wrappedNativeAsset = tokens.wrappedNativeAsset;
this.contracts = contracts;
this.balancerVault = getVault(networkConfig.chainId);
}

/**
Expand Down Expand Up @@ -207,7 +210,7 @@ export class WeightedFactory implements PoolFactory {
const { functionName, data } = this.encodeInitJoinFunctionData(params);

return {
to: balancerVault,
to: this.balancerVault,
functionName,
data,
attributes,
Expand Down
30 changes: 23 additions & 7 deletions balancer-js/src/modules/pools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,17 @@ export class Pools implements Findable<PoolWithMethods> {
);
this.liquidityService = new Liquidity(
repositories.pools,
repositories.tokenPrices
repositories.tokenPrices,
networkConfig
);
this.simulationService = new Simulation(
networkConfig,
this.repositories.poolsForSimulations
);
this.graphService = new PoolGraph(this.repositories.poolsOnChain);
this.graphService = new PoolGraph(
this.repositories.poolsOnChain,
networkConfig
);
this.joinService = new Join(
this.graphService,
networkConfig,
Expand Down Expand Up @@ -116,7 +120,7 @@ export class Pools implements Findable<PoolWithMethods> {
let queries: Queries.ParamsBuilder;
let methods;
try {
concerns = PoolTypeConcerns.from(pool.poolType);
concerns = PoolTypeConcerns.from(pool.poolType, networkConfig.chainId);
methods = {
buildJoin: (
joiner: string,
Expand Down Expand Up @@ -350,7 +354,10 @@ export class Pools implements Findable<PoolWithMethods> {
userAddress: string;
slippage: string;
}): JoinPoolAttributes {
const concerns = PoolTypeConcerns.from(pool.poolType);
const concerns = PoolTypeConcerns.from(
pool.poolType,
this.networkConfig.chainId
);

if (!concerns)
throw `buildJoin for poolType ${pool.poolType} not implemented`;
Expand Down Expand Up @@ -381,7 +388,10 @@ export class Pools implements Findable<PoolWithMethods> {
shouldUnwrapNativeAsset?: boolean;
singleTokenOut?: string;
}): ExitExactBPTInAttributes {
const concerns = PoolTypeConcerns.from(pool.poolType);
const concerns = PoolTypeConcerns.from(
pool.poolType,
this.networkConfig.chainId
);
if (!concerns || !concerns.exit.buildExitExactBPTIn)
throw `buildExit for poolType ${pool.poolType} not implemented`;

Expand Down Expand Up @@ -411,7 +421,10 @@ export class Pools implements Findable<PoolWithMethods> {
slippage: string;
toInternalBalance?: boolean;
}): ExitExactBPTInAttributes {
const concerns = PoolTypeConcerns.from(pool.poolType);
const concerns = PoolTypeConcerns.from(
pool.poolType,
this.networkConfig.chainId
);
if (!concerns || !concerns.exit.buildRecoveryExit)
throw `buildRecoveryExit for poolType ${pool.poolType} not implemented`;

Expand Down Expand Up @@ -518,7 +531,10 @@ export class Pools implements Findable<PoolWithMethods> {
bptAmount: string;
isJoin: boolean;
}): string {
const concerns = PoolTypeConcerns.from(pool.poolType);
const concerns = PoolTypeConcerns.from(
pool.poolType,
this.networkConfig.chainId
);
return concerns.priceImpactCalculator.calcPriceImpact(
pool,
tokenAmounts.map(BigInt),
Expand Down
39 changes: 24 additions & 15 deletions balancer-js/src/modules/pools/pool-type-concerns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,34 @@ import { BalancerError, BalancerErrorCode } from '@/balancerErrors';
import { isLinearish } from '@/lib/utils';
import { FX } from '@/modules/pools/pool-types/fx.module';
import { Gyro } from '@/modules/pools/pool-types/gyro.module';
import { getNetworkConfig } from '../sdk.helpers';

/**
* Wrapper around pool type specific methods.
*
* Returns a class instance of a type specific method handlers.
*/
export class PoolTypeConcerns {
constructor(
config: BalancerSdkConfig,
public weighted = new Weighted(),
public stable = new Stable(),
public composableStable = new ComposableStable(),
public metaStable = new MetaStable(),
public stablePhantom = new StablePhantom(),
public linear = new Linear()
) {}
public weighted: Weighted;
public stable: Stable;
public composableStable: ComposableStable;
public metaStable: MetaStable;
public stablePhantom: StablePhantom;
public linear: Linear;

constructor(config: BalancerSdkConfig) {
const networkConfig = getNetworkConfig(config);
this.weighted = new Weighted(networkConfig.chainId);
this.stable = new Stable(networkConfig.chainId);
this.composableStable = new ComposableStable(networkConfig.chainId);
this.metaStable = new MetaStable(networkConfig.chainId);
this.stablePhantom = new StablePhantom();
this.linear = new Linear(networkConfig.chainId);
}

static from(
poolType: PoolType
poolType: PoolType,
chainId: number
):
| Weighted
| Stable
Expand All @@ -38,7 +47,7 @@ export class PoolTypeConcerns {
// Calculate spot price using pool type
switch (poolType) {
case 'ComposableStable': {
return new ComposableStable();
return new ComposableStable(chainId);
}
case 'FX': {
return new FX();
Expand All @@ -49,22 +58,22 @@ export class PoolTypeConcerns {
return new Gyro();
}
case 'MetaStable': {
return new MetaStable();
return new MetaStable(chainId);
}
case 'Stable': {
return new Stable();
return new Stable(chainId);
}
case 'StablePhantom': {
return new StablePhantom();
}
case 'Investment':
case 'LiquidityBootstrapping':
case 'Weighted': {
return new Weighted();
return new Weighted(chainId);
}
default: {
// Handles all Linear pool types
if (isLinearish(poolType)) return new Linear();
if (isLinearish(poolType)) return new Linear(chainId);
throw new BalancerError(BalancerErrorCode.UNSUPPORTED_POOL_TYPE);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,17 @@ import {
} from './concerns/types';

export class ComposableStable implements PoolType {
constructor(
public exit: ExitConcern = new ComposableStablePoolExit(),
public liquidity: LiquidityConcern = new StablePoolLiquidity(),
public spotPriceCalculator: SpotPriceConcern = new PhantomStablePoolSpotPrice(),
public priceImpactCalculator: PriceImpactConcern = new StablePoolPriceImpact(),
public join: JoinConcern = new ComposableStablePoolJoin()
) {}
public exit: ExitConcern;
public liquidity: LiquidityConcern;
public spotPriceCalculator: SpotPriceConcern;
public priceImpactCalculator: PriceImpactConcern;
public join: JoinConcern;

constructor(chainId: number) {
this.exit = new ComposableStablePoolExit(chainId);
this.liquidity = new StablePoolLiquidity();
this.spotPriceCalculator = new PhantomStablePoolSpotPrice();
this.priceImpactCalculator = new StablePoolPriceImpact();
this.join = new ComposableStablePoolJoin(chainId);
}
}
Loading
Loading