Skip to content

Commit

Permalink
fix: use output address from hub pool events (#490)
Browse files Browse the repository at this point in the history
  • Loading branch information
amateima authored Oct 25, 2024
1 parent 2b9d62d commit 9eea690
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 40 deletions.
13 changes: 12 additions & 1 deletion src/modules/deposit/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { DepositFixture } from "./adapter/db/deposit-fixture";
import { EtlController } from "./entry-point/http/etl-controller";
import { RewardModule } from "../rewards/module";
import { OpReward } from "../rewards/model/op-reward.entity";
import { SetPoolRebalanceRouteEvent } from "../web3/model/SetPoolRebalanceRouteEvent.entity";
import { Block } from "../web3/model/block.entity";

@Module({})
export class DepositModule {
Expand All @@ -18,7 +20,16 @@ export class DepositModule {
providers: [DepositService, DepositFixture],
exports: [DepositService],
controllers: [],
imports: [TypeOrmModule.forFeature([Deposit, OpReward]), AppConfigModule, RewardModule.forRoot(moduleOptions)],
imports: [
TypeOrmModule.forFeature([
Block,
Deposit,
OpReward,
SetPoolRebalanceRouteEvent,
]),
AppConfigModule,
RewardModule.forRoot(moduleOptions),
],
};

if (moduleOptions.runModes.includes(RunMode.Normal) || moduleOptions.runModes.includes(RunMode.Test)) {
Expand Down
42 changes: 41 additions & 1 deletion src/modules/deposit/service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BadRequestException, CACHE_MANAGER, Inject, Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Brackets, DataSource, In, Repository } from "typeorm";
import { Brackets, DataSource, In, LessThanOrEqual, Repository } from "typeorm";
import { utils } from "ethers";
import { Cache } from "cache-manager";
import BigNumber from "bignumber.js";
Expand All @@ -22,7 +22,9 @@ import {
} from "./entry-point/http/dto";
import { formatDeposit } from "./utils";
import { RewardService } from "../rewards/services/reward-service";
import { Block } from "../web3/model/block.entity";
import { ChainIds } from "../web3/model/ChainId";
import { SetPoolRebalanceRouteEvent } from "../web3/model/SetPoolRebalanceRouteEvent.entity";

export const DEPOSITS_STATS_CACHE_KEY = "deposits:stats";

Expand All @@ -34,11 +36,49 @@ export class DepositService {
constructor(
private appConfig: AppConfig,
@InjectRepository(Deposit) private depositRepository: Repository<Deposit>,
@InjectRepository(Block) private blockRepository: Repository<Block>,
@InjectRepository(SetPoolRebalanceRouteEvent)
private setPoolRebalanceRouteRepository: Repository<SetPoolRebalanceRouteEvent>,
@Inject(CACHE_MANAGER) private cacheManager: Cache,
private dataSource: DataSource,
private rewardService: RewardService,
) {}

public async deriveOutputTokenAddress(
originChainId: number,
inputTokenAddress: string,
destinationChainId: number,
quoteTimestamp: number) {
const quoteDatetime = new Date(quoteTimestamp * 1000);
const inputTokenRebalanceRoute = await this.setPoolRebalanceRouteRepository.findOne({
where: {
destinationChainId: originChainId,
destinationToken: inputTokenAddress,
date: LessThanOrEqual(quoteDatetime),
},
order: {
blockNumber: "DESC",
},
});
const l1Token = inputTokenRebalanceRoute.l1Token;
const outputTokenRebalanceRoute = await this.setPoolRebalanceRouteRepository.findOne({
where: {
destinationChainId,
l1Token,
date: LessThanOrEqual(quoteDatetime),
},
order: {
blockNumber: "DESC",
},
});

if (!outputTokenRebalanceRoute) {
throw new Error(`Output token not found for ${l1Token} on chain ${destinationChainId}`);
}

return outputTokenRebalanceRoute.destinationToken;
}

public async getCachedGeneralStats() {
let data = await this.cacheManager.get(DEPOSITS_STATS_CACHE_KEY);

Expand Down
15 changes: 13 additions & 2 deletions src/modules/scraper/adapter/messaging/BlocksEventsConsumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Logger } from "@nestjs/common";
import { Job } from "bull";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository, QueryFailedError } from "typeorm";
import { BigNumber, Event } from "ethers";
import { BigNumber, ethers, Event } from "ethers";

import { EthProvidersService } from "../../../web3/services/EthProvidersService";
import {
Expand All @@ -17,6 +17,7 @@ import {
SpeedUpEventsV3QueueMessage,
} from ".";
import { Deposit } from "../../../deposit/model/deposit.entity";
import { DepositService } from "../../../deposit/service";
import { ScraperQueuesService } from "../../service/ScraperQueuesService";
import {
FundsDepositedEvent2,
Expand Down Expand Up @@ -46,6 +47,7 @@ export class BlocksEventsConsumer {
@InjectRepository(Deposit) private depositRepository: Repository<Deposit>,
private scraperQueuesService: ScraperQueuesService,
private appConfig: AppConfig,
private depositService: DepositService,
) {}

@Process({ concurrency: 20 })
Expand Down Expand Up @@ -421,6 +423,15 @@ export class BlocksEventsConsumer {
const feePct = inputAmount.eq(0) ? BigNumber.from(0) : wei.sub(outputAmount.mul(wei).div(inputAmount));
const txReceipt = await this.providers.getCachedTransactionReceipt(chainId, transactionHash);
const swapToken = swapEvent ? await this.providers.getCachedToken(chainId, swapEvent.args.swapToken) : undefined;
const outputTokenAddress =
outputToken === ethers.constants.AddressZero
? await this.depositService.deriveOutputTokenAddress(
chainId,
inputToken,
destinationChainId.toNumber(),
quoteTimestamp,
)
: outputToken;
let trueDepositor = depositor;
let exclusivityDeadlineDate = undefined;

Expand All @@ -447,7 +458,7 @@ export class BlocksEventsConsumer {
//relayerFeePct = realizedLpFeePct + (gasFeePct + capitalCostFeePct)(old usage of relayerFeePct)
// v3 properties
outputAmount: outputAmount.toString(),
outputTokenAddress: outputToken,
outputTokenAddress,
fillDeadline: new Date(fillDeadline * 1000),
quoteTimestamp: new Date(quoteTimestamp * 1000),
exclusivityDeadline: exclusivityDeadlineDate,
Expand Down
50 changes: 14 additions & 36 deletions src/modules/scraper/adapter/messaging/TokenDetailsConsumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,12 @@ import { Logger } from "@nestjs/common";
import { Job } from "bull";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { ethers } from "ethers";

import { ScraperQueue, TokenDetailsQueueMessage, TokenPriceQueueMessage } from ".";
import { Deposit } from "../../../deposit/model/deposit.entity";
import { EthProvidersService } from "../../../web3/services/EthProvidersService";
import { ScraperQueuesService } from "../../service/ScraperQueuesService";
import { Token } from "../../../web3/model/token.entity";
import { ChainIds } from "../../../web3/model/ChainId";

@Processor(ScraperQueue.TokenDetails)
export class TokenDetailsConsumer {
Expand All @@ -36,41 +34,22 @@ export class TokenDetailsConsumer {
let outputToken: Token | undefined = undefined;

if (deposit.outputTokenAddress) {
if (deposit.outputTokenAddress === ethers.constants.AddressZero) {
let outputTokenSymbol: string;

if (destinationChainId === ChainIds.base && inputToken.symbol === "USDC") {
outputTokenSymbol = "USDbC";
} else if (sourceChainId === ChainIds.base && inputToken.symbol === "USDbC") {
outputTokenSymbol = "USDC";
} else if (destinationChainId === ChainIds.blast && inputToken.symbol === "DAI") {
outputTokenSymbol = "USDB";
} else if (sourceChainId === ChainIds.blast && inputToken.symbol === "USDB") {
outputTokenSymbol = "DAI";
} else {
outputTokenSymbol = inputToken.symbol;
try {
outputToken = await this.ethProvidersService.getCachedToken(destinationChainId, deposit.outputTokenAddress);
} catch (error) {
// stop if output token doesn't exist
if (
error?.code === "CALL_EXCEPTION" &&
["name()", "symbol()", "decimals()"].includes(error?.method)
) {
this.logger.log(`Output token ${destinationChainId} ${deposit.outputTokenAddress} doesn't exist for deposit ${depositId}`);
return;
}
outputToken = await this.tokenRepository.findOne({
where: { chainId: destinationChainId, symbol: outputTokenSymbol },
});
} else {
try {
outputToken = await this.ethProvidersService.getCachedToken(destinationChainId, deposit.outputTokenAddress);
} catch (error) {
// stop if output token doesn't exist
if (
error?.code === "CALL_EXCEPTION" &&
["name()", "symbol()", "decimals()"].includes(error?.method)
) {
this.logger.log(`Output token ${destinationChainId} ${deposit.outputTokenAddress} doesn't exist for deposit ${depositId}`);
return;
}
if (error?.code === "CALL_EXCEPTION" && error?.reason?.includes("reverted without a reason")) {
this.logger.log(`Output token ${destinationChainId} ${deposit.outputTokenAddress} doesn't exist for deposit ${depositId}`);
return;
}
throw error;
if (error?.code === "CALL_EXCEPTION" && error?.reason?.includes("reverted without a reason")) {
this.logger.log(`Output token ${destinationChainId} ${deposit.outputTokenAddress} doesn't exist for deposit ${depositId}`);
return;
}
throw error;
}
}

Expand All @@ -81,7 +60,6 @@ export class TokenDetailsConsumer {
{
tokenId: inputToken.id,
outputTokenId: outputToken ? outputToken.id : null,
outputTokenAddress: outputToken ? outputToken.address : deposit.outputTokenAddress,
},
);
await this.scraperQueuesService.publishMessage<TokenPriceQueueMessage>(ScraperQueue.TokenPrice, {
Expand Down

0 comments on commit 9eea690

Please sign in to comment.