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

Redeploy #146

Merged
merged 7 commits into from
Oct 15, 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
2 changes: 1 addition & 1 deletion .cache/tokenprices-10.json

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

167 changes: 80 additions & 87 deletions src/EventHandlers/Pool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import { Pool, Pool_Swap, Pool_Sync, Pool_Mint, Pool_Burn } from "generated";
import { Token, LiquidityPoolNew, User } from "./../src/Types.gen";
import { normalizeTokenAmountTo1e18 } from "./../Helpers";
import { multiplyBase1e18 } from "./../Maths";
import {
getLiquidityPoolSnapshotByInterval,
} from "./../IntervalSnapshots";
import { getLiquidityPoolSnapshotByInterval } from "./../IntervalSnapshots";
import { SnapshotInterval } from "./../CustomTypes";
import { toChecksumAddress, TokenIdByChain } from "../Constants";
import { set_whitelisted_prices } from "../PriceOracle";
Expand Down Expand Up @@ -42,107 +40,105 @@ Pool.Burn.handler(async ({ event, context }) => {
context.Pool_Burn.set(entity);
});

Pool.Fees.handler(async ({ event, context }) => {
const currentLiquidityPool = await context.LiquidityPoolNew.get(
toChecksumAddress(event.srcAddress)
);
Pool.Fees.handlerWithLoader({
loader: async ({ event, context }) => {
const currentLiquidityPool = await context.LiquidityPoolNew.get(
event.srcAddress
);

if (currentLiquidityPool == undefined) return;
if (currentLiquidityPool == undefined) return null;

// load the token entities
const token0Instance = await context.Token.get(
currentLiquidityPool.token0_id
);
const token1Instance = await context.Token.get(
currentLiquidityPool.token1_id
);
const [token0Instance, token1Instance] = await Promise.all([
context.Token.get(currentLiquidityPool.token0_id),
context.Token.get(currentLiquidityPool.token1_id),
]);

if (token0Instance == undefined || token1Instance == undefined) {
console.error("Token instances not found.", {
token0_id: currentLiquidityPool.token0_id,
token1_id: currentLiquidityPool.token1_id,
chainId: event.chainId,
});
return { currentLiquidityPool, token0Instance, token1Instance };
},
handler: async ({ event, context, loaderReturn }) => {
if (!loaderReturn) return;

console.error(
"Token instances not found. They are required fields for LiquidityPoolEntity"
);
return;
}
const { currentLiquidityPool, token0Instance, token1Instance } =
loaderReturn;

if (token0Instance == undefined || token1Instance == undefined) {
console.error("Token instances not found.", {
token0_id: currentLiquidityPool.token0_id,
token1_id: currentLiquidityPool.token1_id,
chainId: event.chainId,
});
return;
}
if (token0Instance == undefined || token1Instance == undefined) {
console.error("Token instances not found.", {
token0_id: currentLiquidityPool.token0_id,
token1_id: currentLiquidityPool.token1_id,
chainId: event.chainId,
});
return;
}

// Normalize swap amounts to 1e18
let normalizedFeeAmount0Total = normalizeTokenAmountTo1e18(
event.params.amount0,
Number(token0Instance.decimals)
);
let normalizedFeeAmount1Total = normalizeTokenAmountTo1e18(
event.params.amount1,
Number(token1Instance.decimals)
);
// Normalize swap amounts to 1e18
let normalizedFeeAmount0Total = normalizeTokenAmountTo1e18(
event.params.amount0,
Number(token0Instance.decimals)
);
let normalizedFeeAmount1Total = normalizeTokenAmountTo1e18(
event.params.amount1,
Number(token1Instance.decimals)
);

// Calculate amounts in USD
let normalizedFeeAmount0TotalUsd = multiplyBase1e18(
normalizedFeeAmount0Total,
token0Instance.pricePerUSDNew
);
let normalizedFeeAmount1TotalUsd = multiplyBase1e18(
normalizedFeeAmount1Total,
token1Instance.pricePerUSDNew
);
// Create a new instance of LiquidityPool to be updated in the DB
const liquidityPoolInstance: LiquidityPoolNew = {
...currentLiquidityPool,
totalFees0: currentLiquidityPool.totalFees0 + normalizedFeeAmount0Total,
totalFees1: currentLiquidityPool.totalFees1 + normalizedFeeAmount1Total,
totalFeesUSD:
currentLiquidityPool.totalFeesUSD +
normalizedFeeAmount0TotalUsd +
normalizedFeeAmount1TotalUsd,
lastUpdatedTimestamp: new Date(event.block.timestamp * 1000),
};
// Update the LiquidityPoolEntity in the DB
context.LiquidityPoolNew.set(liquidityPoolInstance);
// Calculate amounts in USD
let normalizedFeeAmount0TotalUsd = multiplyBase1e18(
normalizedFeeAmount0Total,
token0Instance.pricePerUSDNew
);
let normalizedFeeAmount1TotalUsd = multiplyBase1e18(
normalizedFeeAmount1Total,
token1Instance.pricePerUSDNew
);
// Create a new instance of LiquidityPool to be updated in the DB
const liquidityPoolInstance: LiquidityPoolNew = {
...currentLiquidityPool,
totalFees0: currentLiquidityPool.totalFees0 + normalizedFeeAmount0Total,
totalFees1: currentLiquidityPool.totalFees1 + normalizedFeeAmount1Total,
totalFeesUSD:
currentLiquidityPool.totalFeesUSD +
normalizedFeeAmount0TotalUsd +
normalizedFeeAmount1TotalUsd,
lastUpdatedTimestamp: new Date(event.block.timestamp * 1000),
};
// Update the LiquidityPoolEntity in the DB
context.LiquidityPoolNew.set(liquidityPoolInstance);
},
});

Pool.Swap.handlerWithLoader({
loader: async ({ event, context }) => {
const liquidityPoolNew = await context.LiquidityPoolNew.get(
toChecksumAddress(event.srcAddress)
);
const [liquidityPoolNew, toUser] = await Promise.all([
context.LiquidityPoolNew.get(event.srcAddress),
context.User.get(event.params.to),
]);

if (liquidityPoolNew == undefined) return null;

const token0Instance = await context.Token.get(liquidityPoolNew.token0_id);
const token1Instance = await context.Token.get(liquidityPoolNew.token1_id);

if (token0Instance == undefined || token1Instance == undefined)
throw new Error(
"Token instances not found. They are required fields for LiquidityPoolEntity"
);
const [token0Instance, token1Instance, isLiquidityPool] = await Promise.all(
[
context.Token.get(liquidityPoolNew.token0_id),
context.Token.get(liquidityPoolNew.token1_id),
context.LiquidityPoolNew.get(event.params.to),
]
);

// if the swap `to` is a liquidityPool, then we won't count
// it as a unique user.
const to_address = toChecksumAddress(event.params.to);
const toUser = await context.User.get(to_address);
const isLiquidityPool =
(await context.LiquidityPoolNew.get(to_address)) != undefined;
if (token0Instance == undefined || token1Instance == undefined) {
// Commenting out error as overwhelming console.
// console.log("Token instances not found.", {
// token0_id: liquidityPoolNew.token0_id,
// token1_id: liquidityPoolNew.token1_id,
// chainId: event.chainId,
// });
return null;
}

return {
liquidityPoolNew,
token0Instance,
token1Instance,
to_address,
to_address: event.params.to,
toUser,
isLiquidityPool,
isLiquidityPool: isLiquidityPool != undefined,
};
},
handler: async ({ event, context, loaderReturn }) => {
Expand Down Expand Up @@ -239,9 +235,7 @@ Pool.Swap.handlerWithLoader({
});

Pool.Sync.handler(async ({ event, context }) => {
const liquidityPoolNew = await context.LiquidityPoolNew.get(
toChecksumAddress(event.srcAddress).toString()
);
const liquidityPoolNew = await context.LiquidityPoolNew.get(event.srcAddress);

if (liquidityPoolNew == undefined) return;

Expand Down Expand Up @@ -335,5 +329,4 @@ Pool.Sync.handler(async ({ event, context }) => {
context.LiquidityPoolHourlySnapshot.set(liquidityPoolHourlySnapshotInstance);
context.LiquidityPoolDailySnapshot.set(liquidityPoolDailySnapshotInstance);
context.LiquidityPoolWeeklySnapshot.set(liquidityPoolWeeklySnapshotInstance);

});
115 changes: 55 additions & 60 deletions src/EventHandlers/PoolFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,72 +11,67 @@ PoolFactory.PoolCreated.contractRegister(({ event, context }) => {
context.addPool(event.params.pool);
});

PoolFactory.PoolCreated.handler(async ({ event, context }) => {
const poolToken0 = await context.Token.get(
TokenIdByChain(event.params.token0, event.chainId)
);
const poolToken1 = await context.Token.get(
TokenIdByChain(event.params.token1, event.chainId)
);
PoolFactory.PoolCreated.handlerWithLoader({
loader: async ({ event, context }) => {
const [poolToken0, poolToken1] = await Promise.all([
context.Token.get(TokenIdByChain(event.params.token0, event.chainId)),
context.Token.get(TokenIdByChain(event.params.token1, event.chainId)),
]);

// Create an array to store the token symbols for pool naming later
let poolTokenSymbols: string[] = [];
return { poolToken0, poolToken1 };
},
handler: async ({ event, context, loaderReturn }) => {
const { poolToken0, poolToken1 } = loaderReturn;

// Create a mapping of poolToken to its address
let poolTokenAddressMappings: TokenEntityMapping[] = [
{ address: event.params.token0, tokenInstance: poolToken0 },
{ address: event.params.token1, tokenInstance: poolToken1 },
];
let poolTokenSymbols: string[] = [];
let poolTokenAddressMappings: TokenEntityMapping[] = [
{ address: event.params.token0, tokenInstance: poolToken0 },
{ address: event.params.token1, tokenInstance: poolToken1 },
];

// Iterating over each token
for (let poolTokenAddressMapping of poolTokenAddressMappings) {
if (poolTokenAddressMapping.tokenInstance == undefined) {
// If token entity is undefined fetch the token details.
const { symbol: tokenSymbol } = await getErc20TokenDetails(
poolTokenAddressMapping.address,
event.chainId
);

// Push the token symbol to the poolTokenSymbols array
poolTokenSymbols.push(tokenSymbol);
} else {
// If token entity exists, then push the token symbol to the poolTokenSymbols array
poolTokenSymbols.push(poolTokenAddressMapping.tokenInstance.symbol);
for (let poolTokenAddressMapping of poolTokenAddressMappings) {
if (poolTokenAddressMapping.tokenInstance == undefined) {
const { symbol: tokenSymbol } = await getErc20TokenDetails(
poolTokenAddressMapping.address,
event.chainId
);
poolTokenSymbols.push(tokenSymbol);
} else {
poolTokenSymbols.push(poolTokenAddressMapping.tokenInstance.symbol);
}
}
}

// Create a new instance of LiquidityPoolEntity to be updated in the DB
const pool: LiquidityPoolNew = {
id: event.params.pool.toString(),
chainID: BigInt(event.chainId),
name: generatePoolName(
poolTokenSymbols[0],
poolTokenSymbols[1],
event.params.stable
),
token0_id: TokenIdByChain(event.params.token0, event.chainId),
token1_id: TokenIdByChain(event.params.token1, event.chainId),
isStable: event.params.stable,
reserve0: 0n,
reserve1: 0n,
totalLiquidityUSD: 0n,
totalVolume0: 0n,
totalVolume1: 0n,
totalVolumeUSD: 0n,
totalFees0: 0n,
totalFees1: 0n,
totalFeesUSD: 0n,
numberOfSwaps: 0n,
token0Price: 0n,
token1Price: 0n,
totalEmissions: 0n,
totalEmissionsUSD: 0n,
totalBribesUSD: 0n,
lastUpdatedTimestamp: new Date(event.block.timestamp * 1000),
};
const pool: LiquidityPoolNew = {
id: event.params.pool,
chainID: BigInt(event.chainId),
name: generatePoolName(
poolTokenSymbols[0],
poolTokenSymbols[1],
event.params.stable
),
token0_id: TokenIdByChain(event.params.token0, event.chainId),
token1_id: TokenIdByChain(event.params.token1, event.chainId),
isStable: event.params.stable,
reserve0: 0n,
reserve1: 0n,
totalLiquidityUSD: 0n,
totalVolume0: 0n,
totalVolume1: 0n,
totalVolumeUSD: 0n,
totalFees0: 0n,
totalFees1: 0n,
totalFeesUSD: 0n,
numberOfSwaps: 0n,
token0Price: 0n,
token1Price: 0n,
totalEmissions: 0n,
totalEmissionsUSD: 0n,
totalBribesUSD: 0n,
lastUpdatedTimestamp: new Date(event.block.timestamp * 1000),
};

// Create the LiquidityPoolEntity in the DB
context.LiquidityPoolNew.set(pool);
context.LiquidityPoolNew.set(pool);
},
});

PoolFactory.SetCustomFee.handler(async ({ event, context }) => {
Expand Down
Loading
Loading