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

publish to prod #1269

Merged
merged 3 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# backend

## 1.26.5

### Patch Changes

- e81774e: fix syncing v3 changed pools
- 8768e95: handle custom morpho rewards

## 1.26.4

### Patch Changes
Expand Down
16 changes: 12 additions & 4 deletions modules/controllers/pool-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,17 +231,19 @@ export function PoolController(tracer?: any) {
*/
async syncChangedPoolsV3(chain: Chain) {
const {
subgraphs: { balancerV3 },
balancer: {
v3: { vaultAddress, routerAddress },
},
} = config[chain];

// Guard against unconfigured chains
if (!vaultAddress) {
if (!vaultAddress || !balancerV3) {
throw new Error(`Chain not configured: ${chain}`);
}

const viemClient = getViemClient(chain);
const subgraphClient = getVaultSubgraphClient(balancerV3);

const lastSyncBlock = await getLastSyncedBlock(chain, PrismaLastBlockSyncedCategory.POOLS_V3);
const fromBlock = lastSyncBlock + 1;
Expand All @@ -259,9 +261,14 @@ export function PoolController(tracer?: any) {
where: { chain, protocolVersion: 3 },
});

const changedPools = await getChangedPoolsV3(vaultAddress, viemClient, BigInt(fromBlock), BigInt(toBlock));
// RPC for some reason isn't working, maybe event signatures are wrong?
// const changedPools = await getChangedPoolsV3(vaultAddress, viemClient, BigInt(fromBlock), BigInt(toBlock));
const changedPoolsIds = await subgraphClient
.getAllInitializedPools({
_change_block: { number_gte: fromBlock },
})
.then((pools) => pools.map((pool) => pool.id.toLowerCase()));

const changedPoolsIds = changedPools.map((id) => id.toLowerCase());
const poolsToSync = pools.filter((pool) => changedPoolsIds.includes(pool.id.toLowerCase())); // only sync pools that are in the database
if (poolsToSync.length === 0) {
return [];
Expand All @@ -274,7 +281,8 @@ export function PoolController(tracer?: any) {
chain,
);

await upsertLastSyncedBlock(chain, PrismaLastBlockSyncedCategory.POOLS_V3, toBlock);
// Leaving safety margin for reorgs
await upsertLastSyncedBlock(chain, PrismaLastBlockSyncedCategory.POOLS_V3, toBlock - 10n);

return poolsToSync.map(({ id }) => id);
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const query = gql`
network
}
state {
apy
fee
netApy
}
}
Expand All @@ -25,6 +27,8 @@ type Vault = {
network: 'ethereum' | 'base';
};
state: {
apy: number;
fee: number;
netApy: number;
};
};
Expand Down Expand Up @@ -56,7 +60,7 @@ export class MorphoAprHandler implements AprHandler {
.map((vault) => [
vault.address.toLowerCase(),
{
apr: vault.state.netApy,
apr: vault.state.apy * (1 - vault.state.fee),
group: this.group,
isIbYield: true,
},
Expand Down
65 changes: 49 additions & 16 deletions modules/pool/lib/apr-data-sources/yb-tokens-apr.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import { tokenService } from '../../../token/token.service';
import { collectsYieldFee, tokenCollectsYieldFee } from '../pool-utils';
import { YbAprConfig } from '../../../network/apr-config-types';

const MORPHO_TOKEN = '0x58d97b57bb95320f9a05dc918aef65434969c2b2';
const MORPHO_RATE = 0.07605350252138458;

export class YbTokensAprService implements PoolAprService {
private ybTokensAprHandlers: YbAprHandlers;
private underlyingMap: { [wrapper: string]: string } = {};
Expand All @@ -31,7 +34,14 @@ export class YbTokensAprService implements PoolAprService {

public async updateAprForPools(pools: PrismaPoolWithTokens[]): Promise<void> {
const operations: any[] = [];
const tokenPrices = await tokenService.getTokenPrices(pools[0].chain);
const chains = Array.from(new Set(pools.map((pool) => pool.chain)));
const tokenPrices = await tokenService.getCurrentTokenPrices(chains).then((prices) =>
Object.fromEntries(
prices.map((price) => {
return [price.tokenAddress, price.price];
}),
),
);
const aprs = await this.fetchYieldTokensApr();
const poolsWithYbTokens = pools.filter((pool) => {
return pool.tokens.find((token) => {
Expand Down Expand Up @@ -63,35 +73,34 @@ export class YbTokensAprService implements PoolAprService {
continue;
}

for (const token of pool.tokens) {
const tokenAprs = pool.tokens.map((token) => {
const tokenApr = aprs.get(token.address);
if (!tokenApr) {
continue;
}

const tokenPrice = tokenService.getPriceForToken(tokenPrices, token.address, pool.chain);
const tokenBalance = token.balance;

const tokenLiquidity = tokenPrice * parseFloat(tokenBalance || '0');
const tokenPercentageInPool = tokenLiquidity / totalLiquidity;
return {
...token,
...tokenApr,
share: (parseFloat(token.balance) * tokenPrices[token.address]) / totalLiquidity,
};
});

if (!tokenApr || !tokenPercentageInPool) {
for (const token of tokenAprs) {
if (!token.apr || !token.share) {
continue;
}

let userApr = tokenApr.apr * tokenPercentageInPool;
let userApr = token.apr * token.share;

// AAVE + LST case, we need to apply the underlying token APR on top of the AAVE market APR
const aaveUnderlying = this.underlyingMap[token.address];
if (aaveUnderlying) {
const underlyingTokenApr = aprs.get(aaveUnderlying);
if (underlyingTokenApr) {
userApr = ((1 + tokenApr.apr) * (1 + underlyingTokenApr.apr) - 1) * tokenPercentageInPool;
userApr = ((1 + token.apr) * (1 + underlyingTokenApr.apr) - 1) * token.share;
}
}

let fee = 0;
if (collectsYieldFee(pool) && tokenCollectsYieldFee(token) && pool.dynamicData) {
const fee =
fee =
pool.type === 'META_STABLE'
? parseFloat(pool.dynamicData.protocolSwapFee || '0')
: pool.protocolVersion === 3
Expand All @@ -111,12 +120,36 @@ export class YbTokensAprService implements PoolAprService {
poolId: pool.id,
title: `${token.token.symbol} APR`,
apr: userApr,
group: tokenApr.group as PrismaPoolAprItemGroup,
group: token.group as PrismaPoolAprItemGroup,
type: yieldType,
rewardTokenAddress: token.address,
rewardTokenSymbol: token.token.symbol,
};

// Custom APR for MORPHO vaults, hardcoding, because it's complicated to get it from the API
if (data.group === PrismaPoolAprItemGroup.MORPHO) {
const morphoTokensShare = tokenAprs
.filter((t) => t.group === 'MORPHO')
.reduce((acc, t) => acc + t.share, 0);
const morphoId = `${pool.id}-morpho`;
const morphoData = {
...data,
id: morphoId,
apr: MORPHO_RATE * morphoTokensShare,
type: PrismaPoolAprType.IB_YIELD,
title: 'MORPHO APR',
rewardTokenAddress: MORPHO_TOKEN,
rewardTokenSymbol: 'MORPHO',
};
operations.push(
prisma.prismaPoolAprItem.upsert({
where: { id_chain: { id: morphoId, chain: pool.chain } },
create: morphoData,
update: morphoData,
}),
);
}

operations.push(
prisma.prismaPoolAprItem.upsert({
where: { id_chain: { id: itemId, chain: pool.chain } },
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "backend",
"version": "1.26.4",
"version": "1.26.5",
"description": "Backend service for Beethoven X and Balancer",
"repository": "https://github.com/balancer/backend",
"author": "Beethoven X",
Expand Down
Loading