Skip to content

Commit

Permalink
Move unwrapRate to prisma token
Browse files Browse the repository at this point in the history
  • Loading branch information
brunoguerios committed Dec 19, 2024
1 parent 6f38d3d commit 36d2c61
Show file tree
Hide file tree
Showing 22 changed files with 72 additions and 117 deletions.
4 changes: 0 additions & 4 deletions apps/api/gql/schema/pool.gql
Original file line number Diff line number Diff line change
Expand Up @@ -1306,10 +1306,6 @@ type GqlPoolTokenDetail {
"""
isBufferAllowed: Boolean!
"""
If it is an ERC4626 token, it represents the rate between wrapped/underlying.
"""
unwrapRate: BigDecimal!
"""
The ERC4626 review data for the token
"""
erc4626ReviewData: Erc4626ReviewData
Expand Down
4 changes: 4 additions & 0 deletions apps/api/gql/schema/token.gql
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,10 @@ type GqlToken {
"""
isBufferAllowed: Boolean!
"""
If it is an ERC4626 token, it represents the rate between wrapped/underlying.
"""
unwrapRate: BigDecimal!
"""
The ERC4626 review data for the token
"""
erc4626ReviewData: Erc4626ReviewData
Expand Down
10 changes: 5 additions & 5 deletions graphql_schema_generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2325,11 +2325,6 @@ export const schema = gql`
"""
underlyingToken: GqlToken
"""
If it is an ERC4626 token, it represents the rate between wrapped/underlying.
"""
unwrapRate: BigDecimal!
"""
The weight of the token in the pool if it is a weighted pool, null otherwise
"""
Expand Down Expand Up @@ -3226,6 +3221,11 @@ export const schema = gql`
"""
underlyingTokenAddress: String
"""
If it is an ERC4626 token, it represents the rate between wrapped/underlying.
"""
unwrapRate: BigDecimal!
"""
The website URL of the token
"""
Expand Down
3 changes: 1 addition & 2 deletions modules/actions/pool/v3/sync-pools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ import { VaultClient, getVaultClient, getPoolsClient } from '../../../sources/co
import { syncDynamicTypeDataForPools } from './type-data/sync-dynamic-type-data-for-pools';
import { ViemClient } from '../../../sources/viem-client';
import { applyOnchainDataUpdateV3 } from '../../../sources/enrichers/apply-onchain-data';
import { fetchCombinedData } from '../../../sources/contracts/v3/fetch-combined-data';

const syncVaultData = async (vaultClient: VaultClient, chain: Chain, ids: string[], blockNumber: bigint) => {
// Enrich with onchain data for all the pools
const onchainData = await fetchCombinedData(ids, chain, vaultClient, blockNumber);
const onchainData = await vaultClient.fetchPoolData(ids, blockNumber);

// Needed to get the token decimals for the USD calculations,
// Keeping it external, because we fetch these tokens in the upsert pools function
Expand Down
8 changes: 3 additions & 5 deletions modules/actions/pool/v3/upsert-pools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { prisma } from '../../../../prisma/prisma-client';
import { tokensTransformer } from '../../../sources/transformers/tokens-transformer';
import { V3JoinedSubgraphPool } from '../../../sources/subgraphs';
import { enrichPoolUpsertsUsd } from '../../../sources/enrichers/pool-upserts-usd';
import { fetchCombinedData, type VaultClient } from '../../../sources/contracts';
import { type VaultClient } from '../../../sources/contracts';
import { poolUpsertTransformerV3 } from '../../../sources/transformers/pool-upsert-transformer-v3';
import { applyOnchainDataUpdateV3 } from '../../../sources/enrichers/apply-onchain-data';
import { fetchErc4626AndUnderlyingTokenData } from '../../../sources/contracts/fetch-erc4626-token-data';
Expand All @@ -26,17 +26,15 @@ export const upsertPools = async (
blockNumber: bigint,
) => {
// Enrich with onchain data for all the pools
const onchainData = await fetchCombinedData(
const onchainData = await vaultClient.fetchPoolData(
subgraphPools.map((pool) => pool.id),
chain,
vaultClient,
blockNumber,
);

// Store pool tokens and BPT in the tokens table before creating the pools
const allTokens = tokensTransformer(subgraphPools, chain);

const { enrichedTokensWithErc4626Data } = await fetchErc4626AndUnderlyingTokenData(allTokens, getViemClient(chain));
const enrichedTokensWithErc4626Data = await fetchErc4626AndUnderlyingTokenData(allTokens, getViemClient(chain));

try {
await prisma.prismaToken.createMany({
Expand Down
2 changes: 1 addition & 1 deletion modules/actions/token/sync-erc4626-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const syncErc4626Tokens = async (viemClient: ViemClient, chain: Chain) =>
},
});

const { enrichedTokensWithErc4626Data } = await fetchErc4626AndUnderlyingTokenData(allTokens, viemClient);
const enrichedTokensWithErc4626Data = await fetchErc4626AndUnderlyingTokenData(allTokens, viemClient);

for (const token of enrichedTokensWithErc4626Data) {
await prisma.prismaToken.upsert({
Expand Down
1 change: 0 additions & 1 deletion modules/pool/lib/pool-gql-loader.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -857,7 +857,6 @@ export class PoolGqlLoaderService {
tradable: !poolToken.token.types.find((type) => type.type === 'PHANTOM_BPT' || type.type === 'BPT'),
chain: poolToken.chain,
chainId: Number(chainToIdMap[poolToken.chain]),
unwrapRate: poolToken.unwrapRate,
};
}

Expand Down
8 changes: 4 additions & 4 deletions modules/sor/sor-debug.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ describe('sor debugging', () => {
}, 5000000);

it.only('sor v3 mainnet wstETH -> waGnowstETH', async () => {
const chain = Chain.GNOSIS;
const chain = Chain.MAINNET;

const chainId = Object.keys(chainIdToChain).find((key) => chainIdToChain[key] === chain) as string;
initRequestScopedContext();
Expand All @@ -47,12 +47,12 @@ describe('sor debugging', () => {

const swaps = await sorService.getSorSwapPaths({
chain,
tokenIn: '0x773cda0cade2a3d86e6d4e30699d40bb95174ff2', // wstETH
tokenOut: '0x6c76971f98945ae98dd7d4dfca8711ebea946ea6', // waGnowstETH
tokenIn: '0xbeef01735c132ada46aa9aa4c54623caa92a64cb', // steakUSDC 18 decimals
tokenOut: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC 6 decimals
swapType: 'EXACT_IN',
swapAmount: '1',
useProtocolVersion: 3,
poolIds: ['0x272d6be442e30d7c87390edeb9b96f1e84cecd8d'], // buffer
poolIds: ['0x5dd88b3aa3143173eb26552923922bdf33f50949'], // boosted
});

console.log(swaps.returnAmount);
Expand Down
2 changes: 1 addition & 1 deletion modules/sor/sorV2/lib/poolsV3/stable/stablePool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export class StablePool implements BasePoolV3 {
tokenAmount.amount,
poolToken.index,
parseEther(poolToken.priceRate),
parseEther(poolToken.unwrapRate),
parseEther(poolToken.token.unwrapRate),
poolToken.token.underlyingTokenAddress,
),
);
Expand Down
2 changes: 1 addition & 1 deletion modules/sor/sorV2/lib/poolsV3/weighted/weightedPool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export class WeightedPoolV3 implements BasePoolV3 {
tokenAmount.amount,
poolToken.index,
parseEther(poolToken.priceRate),
parseEther(poolToken.unwrapRate),
parseEther(poolToken.token.unwrapRate),
poolToken.token.underlyingTokenAddress,
parseEther(poolToken.weight),
),
Expand Down
58 changes: 31 additions & 27 deletions modules/sources/contracts/fetch-erc4626-token-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import MinimalErc4626Abi from './abis/MinimalERC4626';
import { fetchErc20Headers } from '.';
import { multicallViem, ViemMulticallCall } from '../../web3/multicaller-viem';
import { Chain } from '@prisma/client';
import { Address, parseEther } from 'viem';
import { isSameAddress } from '@balancer/sdk';
import { formatUnits, parseEther, parseUnits } from 'viem';

interface Erc4626Data {
asset?: string;
Expand All @@ -19,17 +18,17 @@ interface Erc4626Data {
export async function fetchErc4626AndUnderlyingTokenData(
tokens: { address: string; decimals: number; name: string; symbol: string; chain: Chain }[],
viemClient: ViemClient,
): Promise<{
enrichedTokensWithErc4626Data: {
): Promise<
{
address: string;
decimals: number;
name: string;
symbol: string;
chain: Chain;
underlyingTokenAddress?: string;
}[];
unwrapRateData: { [id: string]: bigint };
}> {
unwrapRate?: string;
}[]
> {
const tokenData: {
[id: string]: {
address: string;
Expand All @@ -38,11 +37,10 @@ export async function fetchErc4626AndUnderlyingTokenData(
symbol: string;
chain: Chain;
underlyingTokenAddress?: string;
unwrapRate?: string;
};
} = {};

const unwrapRateData: { [id: string]: bigint } = {};

const calls: ViemMulticallCall[] = [];

for (const token of tokens) {
Expand All @@ -58,7 +56,7 @@ export async function fetchErc4626AndUnderlyingTokenData(
address: token.address as `0x${string}`,
abi: MinimalErc4626Abi,
functionName: 'convertToAssets',
args: [parseEther('1')],
args: [parseUnits('1', token.decimals)],
},
{
path: `${token.address}.convertToShares`,
Expand Down Expand Up @@ -123,29 +121,35 @@ export async function fetchErc4626AndUnderlyingTokenData(
name: token.name,
symbol: token.symbol,
chain: token.chain,
underlyingTokenAddress: underlyingTokenAddress,
underlyingTokenAddress,
};

unwrapRateData[token.address] = result.convertToAssets ? BigInt(result.convertToAssets) : parseEther('1');
if (underlyingTokenAddress) {
if (!tokenData[underlyingTokenAddress]) {
const underlyingTokenDetail = await fetchErc20Headers(
[underlyingTokenAddress as `0x${string}`],
viemClient,
);

if (underlyingTokenAddress && !tokenData[underlyingTokenAddress]) {
const underlyingTokenDetail = await fetchErc20Headers(
[underlyingTokenAddress as `0x${string}`],
viemClient,
);
tokenData[underlyingTokenAddress] = {
address: underlyingTokenAddress,
decimals: underlyingTokenDetail[underlyingTokenAddress].decimals,
name: underlyingTokenDetail[underlyingTokenAddress].name,
symbol: underlyingTokenDetail[underlyingTokenAddress].symbol,
chain: token.chain,
underlyingTokenAddress: undefined,
};
}

tokenData[underlyingTokenAddress] = {
address: underlyingTokenAddress,
decimals: underlyingTokenDetail[underlyingTokenAddress].decimals,
name: underlyingTokenDetail[underlyingTokenAddress].name,
symbol: underlyingTokenDetail[underlyingTokenAddress].symbol,
chain: token.chain,
underlyingTokenAddress: undefined,
const unwrapRate = result.convertToAssets
? formatUnits(BigInt(result.convertToAssets), tokenData[underlyingTokenAddress].decimals)
: '1';
tokenData[token.address] = {
...tokenData[token.address],
unwrapRate,
};

unwrapRateData[underlyingTokenAddress] = parseEther('1');
}
}

return { enrichedTokensWithErc4626Data: [...Object.values(tokenData)], unwrapRateData };
return [...Object.values(tokenData)];
}
1 change: 0 additions & 1 deletion modules/sources/contracts/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
export * from './fetch-erc20-headers';
export * from './v3/fetch-pool-type-data';
export * from './v3/fetch-pool-data';
export * from './v3/fetch-combined-data';
export * from './v3/vault-client';
export * from './v3/pools-client';
export * from './fetch-cow-amm-data';
32 changes: 0 additions & 32 deletions modules/sources/contracts/v3/fetch-combined-data.ts

This file was deleted.

24 changes: 0 additions & 24 deletions modules/sources/contracts/v3/fetch-unwrap-rates.ts

This file was deleted.

5 changes: 2 additions & 3 deletions modules/sources/enrichers/apply-onchain-data.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { formatEther, formatUnits, parseEther } from 'viem';
import { OnchainDataCowAmm, OnchainDataV3 } from '../contracts';
import { OnchainDataCowAmm, PoolDataV3 } from '../contracts';
import { Chain } from '@prisma/client';
import { PoolDynamicUpsertData, PoolUpsertData } from '../../../prisma/prisma-types';

export const applyOnchainDataUpdateV3 = (
data: Partial<PoolUpsertData> = {},
onchainPoolData: OnchainDataV3,
onchainPoolData: PoolDataV3,
allTokens: { address: string; decimals: number }[],
chain: Chain,
poolId: string,
Expand Down Expand Up @@ -48,7 +48,6 @@ export const applyOnchainDataUpdateV3 = (
...token,
balance: formatUnits(tokenData.balance ?? 0n, decimals[tokenData.address.toLocaleLowerCase()]),
priceRate: tokenData.rate ? formatEther(tokenData.rate) : '1',
unwrapRate: tokenData.unwrapRate ? tokenData.unwrapRate : 1,
balanceUSD: 0,
};
}) ||
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
Warnings:
- You are about to drop the column `unwrapRate` on the `PrismaPoolToken` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "PrismaPoolToken" DROP COLUMN "unwrapRate";

-- AlterTable
ALTER TABLE "PrismaToken" ADD COLUMN "unwrapRate" TEXT NOT NULL DEFAULT '1000000000000000000';
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "PrismaToken" ALTER COLUMN "unwrapRate" SET DEFAULT '1';
2 changes: 1 addition & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,6 @@ model PrismaPoolToken {
balanceUSD Float
weight String?
priceRate String
unwrapRate String @default("1000000000000000000")
latestFxPrice Float?
@@index([poolId, chain])
Expand Down Expand Up @@ -726,6 +725,7 @@ model PrismaToken {
underlyingTokenAddress String?
isBufferAllowed Boolean @default(true)
unwrapRate String @default("1")
walletBalances PrismaUserWalletBalance[]
stakedBalances PrismaUserStakedBalance[]
Expand Down
1 change: 0 additions & 1 deletion prisma/schema/pool.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@ model PrismaPoolToken {
balanceUSD Float
weight String?
priceRate String
unwrapRate String @default("1000000000000000000")
latestFxPrice Float?
@@index([poolId, chain])
Expand Down
1 change: 1 addition & 0 deletions prisma/schema/token.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ model PrismaToken {
underlyingTokenAddress String?
isBufferAllowed Boolean @default(true)
unwrapRate String @default("1")
walletBalances PrismaUserWalletBalance[]
stakedBalances PrismaUserStakedBalance[]
Expand Down
Loading

0 comments on commit 36d2c61

Please sign in to comment.