Skip to content

Commit

Permalink
minor change plus prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
franzns committed Nov 17, 2023
1 parent 3cf1cfc commit e9b230a
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 139 deletions.
44 changes: 21 additions & 23 deletions modules/pool/lib/pool-on-chain-data.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { formatFixed } from '@ethersproject/bignumber';
import { Chain, PrismaPoolType } from '@prisma/client';
import { isSameAddress } from '@balancer-labs/sdk';
import { prisma } from '../../../prisma/prisma-client';
import { isStablePool } from './pool-utils';
import { isComposableStablePool, isStablePool } from './pool-utils';
import { TokenService } from '../../token/token.service';
import { prismaBulkExecuteOperations } from '../../../prisma/prisma-util';
import { fetchOnChainPoolState } from './pool-onchain-state';
Expand All @@ -25,9 +25,7 @@ const SUPPORTED_POOL_TYPES: PrismaPoolType[] = [
];

export class PoolOnChainDataService {
constructor(
private readonly tokenService: TokenService,
) {}
constructor(private readonly tokenService: TokenService) {}

private get options() {
return {
Expand All @@ -36,7 +34,7 @@ export class PoolOnChainDataService {
yieldProtocolFeePercentage: networkContext.data.balancer.yieldProtocolFeePercentage,
gyroConfig: networkContext.data.gyro?.config,
composableStableFactories: networkContext.data.balancer.composableStablePoolFactories,
}
};
}

public async updateOnChainStatus(poolIds: string[]): Promise<void> {
Expand All @@ -61,15 +59,15 @@ export class PoolOnChainDataService {

const { isPaused, isInRecoveryMode } = state[pool.id];
const data = pool.dynamicData;
if (data && data.isPaused !== isPaused && data.isInRecoveryMode !== isInRecoveryMode) {
if (data && (data.isPaused !== isPaused || data.isInRecoveryMode !== isInRecoveryMode)) {
operations.push(
prisma.prismaPoolDynamicData.update({
where: { id_chain: { id: pool.id, chain: this.options.chain } },
data: {
isPaused,
isInRecoveryMode,
},
})
}),
);
}
}
Expand Down Expand Up @@ -99,20 +97,20 @@ export class PoolOnChainDataService {
const gyroPools = filteredPools.filter((pool) => pool.type.includes('GYRO'));
const poolsWithComposableStableType = filteredPools.map((pool) => ({
...pool,
type: (
pool.factory && this.options.composableStableFactories.includes(pool.factory)
? 'COMPOSABLE_STABLE'
: pool.type
) as PrismaPoolType | 'COMPOSABLE_STABLE',
type: (isComposableStablePool(pool) ? 'COMPOSABLE_STABLE' : pool.type) as
| PrismaPoolType
| 'COMPOSABLE_STABLE',
}));

const tokenPrices = await this.tokenService.getTokenPrices();
const onchainResults = await fetchOnChainPoolData(poolsWithComposableStableType, this.options.vaultAddress, 1024);
const gyroFees = await (
this.options.gyroConfig
? fetchOnChainGyroFees(gyroPools, this.options.gyroConfig, 1024)
: Promise.resolve({} as { [address: string]: string })
const onchainResults = await fetchOnChainPoolData(
poolsWithComposableStableType,
this.options.vaultAddress,
1024,
);
const gyroFees = await (this.options.gyroConfig
? fetchOnChainGyroFees(gyroPools, this.options.gyroConfig, 1024)
: Promise.resolve({} as { [address: string]: string }));

const operations = [];
for (const pool of filteredPools) {
Expand All @@ -133,7 +131,7 @@ export class PoolOnChainDataService {
where: { id_chain: { id: pool.id, chain: this.options.chain } },
create: { id: pool.id, chain: this.options.chain, poolId: pool.id, amp, blockNumber },
update: { amp, blockNumber },
})
}),
);
}
}
Expand Down Expand Up @@ -163,7 +161,7 @@ export class PoolOnChainDataService {
blockNumber,
},
update: { upperTarget, lowerTarget, blockNumber },
})
}),
);
}
}
Expand Down Expand Up @@ -198,7 +196,7 @@ export class PoolOnChainDataService {
protocolYieldFee: yieldProtocolFeePercentage,
blockNumber,
},
})
}),
);
}

Expand Down Expand Up @@ -253,7 +251,7 @@ export class PoolOnChainDataService {
poolToken.address === pool.address
? 0
: this.tokenService.getPriceForToken(tokenPrices, poolToken.address) *
parseFloat(balance),
parseFloat(balance),
},
update: {
blockNumber,
Expand All @@ -264,9 +262,9 @@ export class PoolOnChainDataService {
poolToken.address === pool.address
? 0
: this.tokenService.getPriceForToken(tokenPrices, poolToken.address) *
parseFloat(balance),
parseFloat(balance),
},
})
}),
);
}
}
Expand Down
105 changes: 44 additions & 61 deletions modules/pool/lib/pool-onchain-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ interface PoolInput {
address: string;
type: PrismaPoolType | 'COMPOSABLE_STABLE';
tokens: {
address: string,
address: string;
token: {
decimals: number,
}
decimals: number;
};
}[];
version: number;
}
Expand Down Expand Up @@ -79,20 +79,21 @@ const getTotalSupplyFn = (type: PoolInput['type'], version: number) => {
if (['LINEAR', 'PHANTOM_STABLE'].includes(type)) {
return 'getVirtualSupply';
} else if (
type === 'COMPOSABLE_STABLE'
|| (type === 'WEIGHTED' && version > 1)
|| (type === 'GYROE' && version > 1)
|| (type === 'UNKNOWN' && version > 1)) {
type === 'COMPOSABLE_STABLE' ||
(type === 'WEIGHTED' && version > 1) ||
(type === 'GYROE' && version > 1) ||
(type === 'UNKNOWN' && version > 1)
) {
return 'getActualSupply';
} else {
return 'totalSupply';
}
}
};

const defaultCalls = (
const addDefaultCallsToMulticaller = (
{ id, address, type, version }: PoolInput,
vaultAddress: string,
multicaller: Multicaller3
multicaller: Multicaller3,
) => {
multicaller.call(`${id}.poolTokens`, vaultAddress, 'getPoolTokens', [id]);
multicaller.call(`${id}.totalSupply`, address, getTotalSupplyFn(type, version));
Expand All @@ -101,59 +102,41 @@ const defaultCalls = (
multicaller.call(`${id}.protocolYieldFeePercentageCache`, address, 'getProtocolFeePercentageCache', [2]);
};

const weightedCalls = (
{ id, address }: PoolInput,
multicaller: Multicaller3
) => {
const weightedCalls = ({ id, address }: PoolInput, multicaller: Multicaller3) => {
multicaller.call(`${id}.weights`, address, 'getNormalizedWeights');
};

const lbpAndInvestmentCalls =(
{ id, address }: PoolInput,
multicaller: Multicaller3
) => {
const lbpAndInvestmentCalls = ({ id, address }: PoolInput, multicaller: Multicaller3) => {
multicaller.call(`${id}.weights`, address, 'getNormalizedWeights');
multicaller.call(`${id}.swapEnabled`, address, 'getSwapEnabled');
};

const linearCalls = (
{ id, address }: PoolInput,
multicaller: Multicaller3
) => {
const linearCalls = ({ id, address }: PoolInput, multicaller: Multicaller3) => {
multicaller.call(`${id}.targets`, address, 'getTargets');
multicaller.call(`${id}.wrappedTokenRate`, address, 'getWrappedTokenRate');
};

const stableCalls = (
{ id, address, tokens }: PoolInput,
multicaller: Multicaller3
) => {
const stableCalls = ({ id, address, tokens }: PoolInput, multicaller: Multicaller3) => {
multicaller.call(`${id}.amp`, address, 'getAmplificationParameter');

tokens.forEach(({ address: tokenAddress }, i) => {
multicaller.call(`${id}.tokenRate[${i}]`, address, 'getTokenRate', [tokenAddress]);
});
};

const metaStableCalls = (
{ id, address, tokens }: PoolInput,
multicaller: Multicaller3
) => {
const metaStableCalls = ({ id, address, tokens }: PoolInput, multicaller: Multicaller3) => {
multicaller.call(`${id}.amp`, address, 'getAmplificationParameter');

tokens.forEach(({ address: tokenAddress }, i) => {
multicaller.call(`${id}.metaPriceRateCache[${i}]`, address, 'getPriceRateCache', [tokenAddress]);
});
}
};

const gyroECalls = (
{ id, address }: PoolInput,
multicaller: Multicaller3
) => {
const gyroECalls = ({ id, address }: PoolInput, multicaller: Multicaller3) => {
multicaller.call(`${id}.tokenRates`, address, 'getTokenRates');
};

const poolTypeCalls = (type: PoolInput['type'], version = 1) => {
const addPoolTypeSpecificCallsToMulticaller = (type: PoolInput['type'], version = 1) => {
const do_nothing = () => ({});
switch (type) {
case 'WEIGHTED':
Expand Down Expand Up @@ -186,53 +169,53 @@ const parse = (result: OnchainData, decimalsLookup: { [address: string]: number
totalShares: formatEther(result.totalSupply || '0'),
weights: result.weights?.map(formatEther),
targets: result.targets?.map(String),
poolTokens: result.poolTokens ? {
tokens: result.poolTokens[0].map((token) => token.toLowerCase()),
balances: result.poolTokens[1].map((balance, i) => formatUnits(balance, decimalsLookup[result.poolTokens[0][i].toLowerCase()])),
rates: result.poolTokens[0].map((_, i) =>
result.tokenRate && result.tokenRate[i]
? formatEther(result.tokenRate[i])
: result.tokenRates && result.tokenRates[i]
? formatEther(result.tokenRates[i])
: result.metaPriceRateCache && result.metaPriceRateCache[i][0].gt(0)
? formatEther(result.metaPriceRateCache[i][0])
: undefined
)
} : { tokens: [], balances: [], rates: [] },
poolTokens: result.poolTokens
? {
tokens: result.poolTokens[0].map((token) => token.toLowerCase()),
balances: result.poolTokens[1].map((balance, i) =>
formatUnits(balance, decimalsLookup[result.poolTokens[0][i].toLowerCase()]),
),
rates: result.poolTokens[0].map((_, i) =>
result.tokenRate && result.tokenRate[i]
? formatEther(result.tokenRate[i])
: result.tokenRates && result.tokenRates[i]
? formatEther(result.tokenRates[i])
: result.metaPriceRateCache && result.metaPriceRateCache[i][0].gt(0)
? formatEther(result.metaPriceRateCache[i][0])
: undefined,
),
}
: { tokens: [], balances: [], rates: [] },
wrappedTokenRate: result.wrappedTokenRate ? formatEther(result.wrappedTokenRate) : '1.0',
rate: result.rate ? formatEther(result.rate) : '1.0',
swapEnabled: result.swapEnabled,
protocolYieldFeePercentageCache: result.protocolYieldFeePercentageCache ? formatEther(result.protocolYieldFeePercentageCache) : undefined,
protocolYieldFeePercentageCache: result.protocolYieldFeePercentageCache
? formatEther(result.protocolYieldFeePercentageCache)
: undefined,
});

export const fetchOnChainPoolData = async (
pools: PoolInput[],
vaultAddress: string,
batchSize = 1024
) => {
export const fetchOnChainPoolData = async (pools: PoolInput[], vaultAddress: string, batchSize = 1024) => {
if (pools.length === 0) {
return {};
}

const multicaller = new Multicaller3(abi, batchSize);

pools.forEach((pool) => {
defaultCalls(pool, vaultAddress, multicaller);
poolTypeCalls(pool.type, pool.version)(pool, multicaller);
addDefaultCallsToMulticaller(pool, vaultAddress, multicaller);
addPoolTypeSpecificCallsToMulticaller(pool.type, pool.version)(pool, multicaller);
});

const results = (await multicaller.execute()) as {
[id: string]: OnchainData;
};

const decimalsLookup = Object.fromEntries(
pools.flatMap((pool) =>
pool.tokens.map(({ address, token }) => [address, token.decimals])
)
pools.flatMap((pool) => pool.tokens.map(({ address, token }) => [address, token.decimals])),
);

const parsed = Object.fromEntries(
Object.entries(results).map(([key, result]) => [key, parse(result, decimalsLookup)])
Object.entries(results).map(([key, result]) => [key, parse(result, decimalsLookup)]),
);

return parsed;
Expand Down
Loading

0 comments on commit e9b230a

Please sign in to comment.