Skip to content

Commit

Permalink
v3 actions
Browse files Browse the repository at this point in the history
  • Loading branch information
gmbronco committed Mar 4, 2024
1 parent be534a3 commit 7383bdf
Show file tree
Hide file tree
Showing 41 changed files with 1,195 additions and 720 deletions.
6 changes: 3 additions & 3 deletions codegen.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ generates:
schema: ${V3_SUBGRAPH}
plugins:
- schema-ast
modules/subgraphs/balancer-v3-pools/generated/types.ts:
modules/sources/subgraphs/balancer-v3-pools/generated/types.ts:
schema: ${V3_POOLS_SUBGRAPH}
documents: 'modules/subgraphs/balancer-v3-pools/*.graphql'
documents: 'modules/sources/subgraphs/balancer-v3-pools/*.graphql'
plugins:
- typescript
- typescript-operations
Expand All @@ -33,7 +33,7 @@ generates:
BigInt: string
Bytes: string
BigDecimal: string
modules/subgraphs/balancer-v3-pools/generated/balancer-v3-pools-schema.graphql:
modules/sources/subgraphs/balancer-v3-pools/generated/balancer-v3-pools-schema.graphql:
schema: ${V3_POOLS_SUBGRAPH}
plugins:
- schema-ast
Expand Down
2 changes: 1 addition & 1 deletion config/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Chain } from '@prisma/client';
import { sepoliaConfig } from './sepolia';
import sepoliaConfig from './sepolia';
import { NetworkData } from '../modules/network/network-config-types';

export default {
Expand Down
2 changes: 1 addition & 1 deletion config/sepolia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { BigNumber } from 'ethers';
import { env } from '../app/env';
import { NetworkData } from '../modules/network/network-config-types';

export const sepoliaConfig: NetworkData = {
export default <NetworkData>{
chain: {
slug: 'sepolia',
id: 11155111,
Expand Down
69 changes: 0 additions & 69 deletions modules/actions/pool/add-pools-from-subgraph.test.ts

This file was deleted.

117 changes: 0 additions & 117 deletions modules/actions/pool/add-pools-from-subgraph.ts

This file was deleted.

11 changes: 2 additions & 9 deletions modules/actions/pool/get-changed-pools.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,9 @@
import { Chain, Prisma, PrismaLastBlockSyncedCategory, PrismaPoolType } from '@prisma/client';
import { Chain, PrismaLastBlockSyncedCategory } from '@prisma/client';
import { prisma } from '../../../prisma/prisma-client';
import { tokenService } from '../../token/token.service';
import { fetchPoolTokenInfo, fetchPoolTokenRates } from '../../sources/contracts';
import { ViemClient } from '../../sources/viem-client';
import { fetchPoolData } from '../../sources/contracts/fetch-pool-data';
import { formatEther, formatUnits, parseUnits } from 'viem';
import { isSameAddress } from '@balancer-labs/sdk';
import { prismaBulkExecuteOperations } from '../../../prisma/prisma-util';
import { getPoolBalanceChanged } from '../../sources/logs/get-pool-balance-changed';
import { start } from 'repl';
import { getSwaps } from '../../sources/logs';
import _ from 'lodash';
import { ViemClient } from '../../sources/types';

/**
* Get all pool IDs of pools that have emitted a poolBalanceChanged event
Expand Down
113 changes: 113 additions & 0 deletions modules/actions/pool/sync-join-exits-v2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { Chain, PoolEventType } from '@prisma/client';
import { prisma } from '../../../prisma/prisma-client';
import { formatUnits } from 'viem';
import type { BalancerSubgraphService } from '../../subgraphs/balancer-subgraph/balancer-subgraph.service';
import { JoinExit_OrderBy, OrderDirection } from '../../subgraphs/balancer-subgraph/generated/balancer-subgraph-types';

/**
* Time helper to round timestamp to the nearest hour
*/
const roundToHour = (timestamp: number) => Math.floor(timestamp / 3600) * 3600;

const isFulfilled = <T>(input: PromiseSettledResult<T>): input is PromiseFulfilledResult<T> =>
input.status === 'fulfilled';

/**
* Get the join and exit events from the subgraph and store them in the database
*
* @param vaultSubgraphClient
*/
export const syncJoinExitsV2 = async (v2SubgraphClient: BalancerSubgraphService, chain: Chain) => {
const vaultVersion = 2;

// Get latest event from the DB
const latestEvent = await prisma.poolEvent.findFirst({
where: {
chain: chain,
vaultVersion,
},
orderBy: {
blockTimestamp: 'desc',
},
});

// Get events
const { joinExits } = await v2SubgraphClient.getPoolJoinExits({
first: 1000,
where: {
timestamp_gte: Number(latestEvent?.blockTimestamp || 0),
},
orderBy: JoinExit_OrderBy.Timestamp,
orderDirection: OrderDirection.Desc,
});

// Store only the events that are not already in the DB
const existingEvents = await prisma.poolEvent.findMany({
where: {
id: { in: joinExits.map((event) => event.id) },
chain: chain,
vaultVersion,
},
});

const events = joinExits.filter((event) => !existingEvents.some((existing) => existing.id === event.id));

// Prepare DB entries
const dbEntries = (
await Promise.allSettled(
events.map(async (event) => {
// TODO: Calculate USD amounts with token prices at the time of the event
// 🚨 Reading from the DB in a loop – will get slow with a large events volume
const prices = await prisma.prismaTokenPrice.findMany({
where: {
tokenAddress: { in: event.pool.tokensList },
timestamp: roundToHour(Number(event.timestamp)), // 🚨 Assuming all prices are available hourly
chain: chain,
},
include: {
token: true,
},
});

const usd = event.pool.tokensList.map((address, index) => {
const price = prices.find((price) => price.tokenAddress === address);
return {
address: address,
amount: event.amounts[index],
amountUsd:
Number(formatUnits(BigInt(event.amounts[index]), price?.token?.decimals ?? 18)) *
(price?.price || 0), // TODO: check USD amount
};
});

return {
id: event.id, // tx + logIndex
tx: event.tx,
type: event.type === 'Join' ? PoolEventType.JOIN : PoolEventType.EXIT,
poolId: event.pool.id,
chain: chain,
userAddress: event.sender,
blockNumber: Number(event.block),
blockTimestamp: Number(event.timestamp),
logPosition: Number(event.id.substring(66)),
amountUsd: usd.reduce((acc, token) => acc + Number(token.amountUsd), 0),
payload: {
tokens: usd,
},
};
}),
)
)
.filter(isFulfilled)
.map((result) => result.value);

// Create entries and skip duplicates
await prisma.poolEvent.createMany({
data: dbEntries,
skipDuplicates: true,
});

// TODO: do we need a separate function to update prices? If so, we should be syncing events first, then running a price on them

return 'ok';
};
Loading

0 comments on commit 7383bdf

Please sign in to comment.