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

aprs: adding working supply #453

Merged
merged 26 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
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 modules/network/arbitrum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ export const arbitrumNetworkConfig: NetworkConfig = {
new PhantomStableAprService(),
new BoostedPoolAprService(),
new SwapFeeAprService(arbitrumNetworkData.balancer.swapProtocolFeePercentage),
new GaugeAprService(gaugeSubgraphService, tokenService, [arbitrumNetworkData.bal!.address]),
new GaugeAprService(tokenService, [arbitrumNetworkData.bal!.address]),
],
poolStakingServices: [new GaugeStakingService(gaugeSubgraphService, arbitrumNetworkData.bal!.address)],
tokenPriceHandlers: [
Expand Down
2 changes: 1 addition & 1 deletion modules/network/avalanche.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ export const avalancheNetworkConfig: NetworkConfig = {
new PhantomStableAprService(),
new BoostedPoolAprService(),
new SwapFeeAprService(avalancheNetworkData.balancer.swapProtocolFeePercentage),
new GaugeAprService(gaugeSubgraphService, tokenService, [avalancheNetworkData.bal!.address]),
new GaugeAprService(tokenService, [avalancheNetworkData.bal!.address]),
],
poolStakingServices: [new GaugeStakingService(gaugeSubgraphService, avalancheNetworkData.bal!.address)],
tokenPriceHandlers: [
Expand Down
2 changes: 1 addition & 1 deletion modules/network/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export const baseNetworkConfig: NetworkConfig = {
new IbTokensAprService(baseNetworkData.ibAprConfig),
new BoostedPoolAprService(),
new SwapFeeAprService(baseNetworkData.balancer.swapProtocolFeePercentage),
new GaugeAprService(gaugeSubgraphService, tokenService, [baseNetworkData.bal!.address]),
new GaugeAprService(tokenService, [baseNetworkData.bal!.address]),
],
poolStakingServices: [new GaugeStakingService(gaugeSubgraphService, baseNetworkData.bal!.address)],
tokenPriceHandlers: [
Expand Down
2 changes: 1 addition & 1 deletion modules/network/gnosis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export const gnosisNetworkConfig: NetworkConfig = {
new PhantomStableAprService(),
new BoostedPoolAprService(),
new SwapFeeAprService(gnosisNetworkData.balancer.swapProtocolFeePercentage),
new GaugeAprService(gaugeSubgraphService, tokenService, [gnosisNetworkData.bal!.address]),
new GaugeAprService(tokenService, [gnosisNetworkData.bal!.address]),
],
poolStakingServices: [new GaugeStakingService(gaugeSubgraphService, gnosisNetworkData.bal!.address)],
tokenPriceHandlers: [
Expand Down
3 changes: 2 additions & 1 deletion modules/network/mainnet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export const mainnetNetworkData: NetworkData = {
gaugeControllerHelperAddress: '0x8e5698dc4897dc12243c8642e77b4f21349db97c',
balancer: {
vault: '0xba12222222228d8ba445958a75a0704d566bf2c8',
tokenAdmin: '0xf302f9f50958c5593770fdf4d4812309ff77414f',
composableStablePoolFactories: [
'0xf9ac7b9df2b3454e841110cce5550bd5ac6f875f',
'0x85a80afee867adf27b50bdb7b76da70f1e853062',
Expand Down Expand Up @@ -364,7 +365,7 @@ export const mainnetNetworkConfig: NetworkConfig = {
new PhantomStableAprService(),
new BoostedPoolAprService(),
new SwapFeeAprService(mainnetNetworkData.balancer.swapProtocolFeePercentage),
new GaugeAprService(gaugeSubgraphService, tokenService, [mainnetNetworkData.bal!.address]),
new GaugeAprService(tokenService, [mainnetNetworkData.bal!.address]),
],
poolStakingServices: [new GaugeStakingService(gaugeSubgraphService, mainnetNetworkData.bal!.address)],
tokenPriceHandlers: [
Expand Down
1 change: 1 addition & 0 deletions modules/network/network-config-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ export interface NetworkData {
gaugeControllerHelperAddress?: string;
balancer: {
vault: string;
tokenAdmin?: string;
weightedPoolV2Factories: string[];
composableStablePoolFactories: string[];
yieldProtocolFeePercentage: number;
Expand Down
2 changes: 1 addition & 1 deletion modules/network/optimism.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ export const optimismNetworkConfig: NetworkConfig = {
new PhantomStableAprService(),
new BoostedPoolAprService(),
new SwapFeeAprService(optimismNetworkData.balancer.swapProtocolFeePercentage),
new GaugeAprService(gaugeSubgraphService, tokenService, [
new GaugeAprService(tokenService, [
optimismNetworkData.beets!.address,
optimismNetworkData.bal!.address,
]),
Expand Down
2 changes: 1 addition & 1 deletion modules/network/polygon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ export const polygonNetworkConfig: NetworkConfig = {
new PhantomStableAprService(),
new BoostedPoolAprService(),
new SwapFeeAprService(polygonNetworkData.balancer.swapProtocolFeePercentage),
new GaugeAprService(gaugeSubgraphService, tokenService, [polygonNetworkData.bal!.address]),
new GaugeAprService(tokenService, [polygonNetworkData.bal!.address]),
],
poolStakingServices: [new GaugeStakingService(gaugeSubgraphService, polygonNetworkData.bal!.address)],
tokenPriceHandlers: [
Expand Down
2 changes: 1 addition & 1 deletion modules/network/zkevm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ export const zkevmNetworkConfig: NetworkConfig = {
new PhantomStableAprService(),
new BoostedPoolAprService(),
new SwapFeeAprService(zkevmNetworkData.balancer.swapProtocolFeePercentage),
new GaugeAprService(gaugeSubgraphService, tokenService, [zkevmNetworkData.bal!.address]),
new GaugeAprService(tokenService, [zkevmNetworkData.bal!.address]),
],
poolStakingServices: [new GaugeStakingService(gaugeSubgraphService, zkevmNetworkData.bal!.address)],
tokenPriceHandlers: [
Expand Down
216 changes: 115 additions & 101 deletions modules/pool/lib/apr-data-sources/ve-bal-gauge-apr.service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
/**
* This service calculates the APR for a pool based on the gauge rewards
*
* Definitions:
* The “working supply” of the gauge - the effective total LP token amount after all deposits have been boosted.
* "Working balance" is 40% of a user balance in a gauge - used only for BAL rewards on v2 gauges on child gauges or on mainnet
*/
import { PrismaPoolWithTokens } from '../../../../prisma/prisma-types';
import { PoolAprService } from '../../pool-types';
import { TokenService } from '../../../token/token.service';
Expand All @@ -6,152 +13,159 @@ import { PrismaPoolAprItem, PrismaPoolAprRange, PrismaPoolAprType } from '@prism
import { prisma } from '../../../../prisma/prisma-client';
import { prismaBulkExecuteOperations } from '../../../../prisma/prisma-util';
import { networkContext } from '../../../network/network-context.service';
import { GaugeSubgraphService } from '../../../subgraphs/gauge-subgraph/gauge-subgraph.service';

export class GaugeAprService implements PoolAprService {
private readonly MAX_VEBAL_BOOST = 2.5;

constructor(
private readonly gaugeSubgraphService: GaugeSubgraphService,
private readonly tokenService: TokenService,
private readonly primaryTokens: string[],
) {}
constructor(private readonly tokenService: TokenService, private readonly primaryTokens: string[]) {}

public getAprServiceName(): string {
return 'GaugeAprService';
}

public async updateAprForPools(pools: PrismaPoolWithTokens[]): Promise<void> {
public async updateAprForPools(pools: { id: string }[]): Promise<void> {
const operations: any[] = [];
const gauges = await this.gaugeSubgraphService.getAllGaugesWithStatus();
const tokenPrices = await this.tokenService.getTokenPrices();

const poolsExpanded = await prisma.prismaPool.findMany({
where: { chain: networkContext.chain, id: { in: pools.map((pool) => pool.id) } },
// Get the data
const tokenPrices = await this.tokenService.getTokenPrices();
const stakings = await prisma.prismaPoolStaking.findMany({
where: {
poolId: { in: pools.map((pool) => pool.id) },
type: 'GAUGE',
chain: networkContext.chain,
},
include: {
dynamicData: true,
staking: {
gauge: {
include: {
gauge: {
include: {
rewards: true,
},
},
rewards: true,
},
},
pool: {
include: {
dynamicData: true,
},
},
},
});

for (const pool of poolsExpanded) {
let gauge;
let preferredStaking;
for (const stake of pool.staking) {
if (stake.gauge?.status === 'PREFERRED') {
preferredStaking = stake;
gauge = gauges.find(
(subgraphGauge) =>
subgraphGauge.address === stake.gauge?.gaugeAddress && stake.gauge?.status === 'PREFERRED',
);
}
}
if (!gauge || !pool.dynamicData || !preferredStaking?.gauge) {
for (const stake of stakings) {
const { pool, gauge } = stake;

if (!gauge || !gauge.rewards || !pool.dynamicData || pool.dynamicData.totalShares === '0') {
continue;
}

// Get token rewards per year with data needed for the DB
const rewards = await Promise.allSettled(
gauge.rewards.map(async ({ tokenAddress, rewardPerSecond }) => {
const price = this.tokenService.getPriceForToken(tokenPrices, tokenAddress);
if (!price) {
return Promise.reject('Price not found');
}

let definition;
try {
definition = await prisma.prismaToken.findUniqueOrThrow({
where: { address_chain: { address: tokenAddress, chain: networkContext.chain } },
});
} catch (e) {
//we don't have the reward token added as a token, only happens for testing tokens
return Promise.reject('Definition not found');
}

return {
address: tokenAddress,
symbol: definition.symbol,
rewardPerYear: parseFloat(rewardPerSecond) * secondsPerYear * price,
};
}),
);

// Calculate APRs
const totalShares = parseFloat(pool.dynamicData.totalShares);
const gaugeTvl =
totalShares > 0 ? (parseFloat(gauge.totalSupply) / totalShares) * pool.dynamicData.totalLiquidity : 0;

let thirdPartyApr = 0;

for (let rewardToken of preferredStaking.gauge.rewards) {
const tokenAddress = rewardToken.tokenAddress;
let rewardTokenDefinition;
try {
rewardTokenDefinition = await prisma.prismaToken.findUniqueOrThrow({
where: { address_chain: { address: tokenAddress, chain: networkContext.chain } },
});
} catch (e) {
//we don't have the reward token added as a token, only happens for testing tokens
continue;
}
const tokenPrice = this.tokenService.getPriceForToken(tokenPrices, tokenAddress) || 0.1;
const rewardTokenPerYear = parseFloat(rewardToken.rewardPerSecond) * secondsPerYear;
const rewardTokenValuePerYear = tokenPrice * rewardTokenPerYear;
let rewardApr = gaugeTvl > 0 ? rewardTokenValuePerYear / gaugeTvl : 0;

const isThirdPartyApr = !this.primaryTokens.includes(tokenAddress.toLowerCase());
if (isThirdPartyApr) {
thirdPartyApr += rewardApr;
}
const bptPrice = pool.dynamicData.totalLiquidity / totalShares;
const gaugeTvl = totalShares > 0 ? parseFloat(gauge.totalSupply) * bptPrice : 0;
const workingSupply = parseFloat(gauge.workingSupply);
const workingSupplyTvl = ((workingSupply + 0.4) / 0.4) * bptPrice;

// apply vebal boost for BAL rewards on v2 gauges on child changes or on mainnet
if (
rewardToken.tokenAddress.toLowerCase() === networkContext.data.bal!.address.toLowerCase() &&
(preferredStaking.gauge.version === 2 || networkContext.chain === 'MAINNET')
) {
const aprItemId = `${pool.id}-${rewardTokenDefinition.symbol}-apr`;
const aprRangeId = `${pool.id}-bal-apr-range`;
const aprItems = rewards
.map((reward) => {
if (reward.status === 'rejected') {
return null;
}

const itemData = {
id: aprItemId,
const { address, symbol, rewardPerYear } = reward.value;

const itemData: PrismaPoolAprItem = {
id: `${gauge.id}-${symbol}-apr`,
chain: networkContext.chain,
poolId: pool.id,
title: `${rewardTokenDefinition.symbol} reward APR`,
apr: 0,
type: PrismaPoolAprType.NATIVE_REWARD,
title: `${symbol} reward APR`,
group: null,
apr: 0,
type: this.primaryTokens.includes(address.toLowerCase())
? PrismaPoolAprType.NATIVE_REWARD
: PrismaPoolAprType.THIRD_PARTY_REWARD,
};

const rangeData = {
id: aprRangeId,
chain: networkContext.chain,
aprItemId: aprItemId,
min: rewardApr,
max: rewardApr * this.MAX_VEBAL_BOOST,
};
// veBAL rewards have a range associated with the item
if (
address.toLowerCase() === networkContext.data.bal!.address.toLowerCase() &&
(networkContext.chain === 'MAINNET' || gauge.version === 2)
) {
let minApr = 0;
if (networkContext.chain === 'MAINNET' && workingSupplyTvl > 0) {
minApr = rewardPerYear / workingSupplyTvl;
} else if (gaugeTvl > 0) {
minApr = rewardPerYear / gaugeTvl;
}

operations.push(
prisma.prismaPoolAprItem.upsert({
where: {
id_chain: {
id: aprItemId,
chain: networkContext.chain,
},
},
update: itemData,
create: itemData,
}),
);
const aprRangeId = `${itemData.id}-range`;

const rangeData = {
id: aprRangeId,
chain: networkContext.chain,
aprItemId: itemData.id,
min: minApr,
max: minApr * this.MAX_VEBAL_BOOST,
};

return [itemData, rangeData];
} else {
itemData.apr = gaugeTvl > 0 ? rewardPerYear / gaugeTvl : 0;

return itemData;
}
})
.flat()
.filter((apr): apr is PrismaPoolAprItem | PrismaPoolAprRange => apr !== null);

// Prepare DB operations
for (const item of aprItems) {
if (item.id.includes('apr-range')) {
operations.push(
prisma.prismaPoolAprRange.upsert({
where: {
id_chain: { id: aprRangeId, chain: networkContext.chain },
id_chain: { id: item.id, chain: networkContext.chain },
},
update: rangeData,
create: rangeData,
update: item,
create: item as PrismaPoolAprRange,
}),
);
} else {
const item: PrismaPoolAprItem = {
id: `${pool.id}-${rewardTokenDefinition.symbol}-apr`,
chain: networkContext.chain,
poolId: pool.id,
title: `${rewardTokenDefinition.symbol} reward APR`,
apr: rewardApr,
type: isThirdPartyApr ? PrismaPoolAprType.THIRD_PARTY_REWARD : PrismaPoolAprType.NATIVE_REWARD,
group: null,
};
operations.push(
prisma.prismaPoolAprItem.upsert({
where: { id_chain: { id: item.id, chain: networkContext.chain } },
where: {
id_chain: { id: item.id, chain: networkContext.chain },
},
update: item,
create: item,
create: item as PrismaPoolAprItem,
}),
);
}
}
}

await prismaBulkExecuteOperations(operations, true);
}
}
Loading