Skip to content

Commit

Permalink
Merge pull request #104 from sotatek-dev/fix/history-user
Browse files Browse the repository at this point in the history
feat: add tip and gas fee for event logs
  • Loading branch information
Sotatek-TanHoang authored Sep 27, 2024
2 parents 56d637e + f4cd80f commit 1da5dec
Show file tree
Hide file tree
Showing 9 changed files with 94 additions and 71 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm';

export class CreateFeeColumnEventLogs1727426782955 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
return queryRunner.addColumns('event_logs', [
new TableColumn({
name: 'tip',
type: 'varchar',
isNullable: true,
}),
new TableColumn({
name: 'gas_fee',
type: 'varchar',
isNullable: true,
}),
]);
}

public async down(queryRunner: QueryRunner): Promise<void> {
return queryRunner.dropColumns('event_logs', ['tip', 'gas_fee']);
}
}
2 changes: 2 additions & 0 deletions src/database/repositories/event-log.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ export class EventLogRepository extends BaseRepository<EventLog> {
protocolFee?: string;
errorDetail?: string;
txHashUnlock?: string;
gasFee?: string;
tip?: string;
}) {
return this.createQueryBuilder(`${this.alias}`)
.update(EventLog)
Expand Down
6 changes: 6 additions & 0 deletions src/modules/crawler/entities/event-logs.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ export class EventLog extends BaseEntityIncludeTime {
@Column({ name: 'protocol_fee', type: 'varchar', nullable: true })
protocolFee: string;

@Column({ name: 'gas_fee', type: 'varchar', nullable: true })
gasFee: string;

@Column({ type: 'varchar', nullable: true })
tip: string;

@Column({ name: 'event', type: 'varchar', enum: EEventName, nullable: false })
event: EEventName;

Expand Down
31 changes: 11 additions & 20 deletions src/modules/crawler/sender.evmbridge.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import BigNumber from 'bignumber.js/bignumber.mjs';
import { BigNumber } from 'bignumber.js';
// import BigNumber from 'bignumber.js/bignumber.mjs';
import { ethers } from 'ethers';
import { Logger } from 'log4js';

Expand All @@ -14,7 +15,7 @@ import { MultiSignatureRepository } from '../../database/repositories/multi-sign
import { TokenPairRepository } from '../../database/repositories/token-pair.repository.js';
import { LoggerService } from '../../shared/modules/logger/logger.service.js';
import { ETHBridgeContract } from '../../shared/modules/web3/web3.service.js';
import { addDecimal, calculateFee } from '../../shared/utils/bignumber.js';
import { addDecimal, calculateFee, calculateTip } from '../../shared/utils/bignumber.js';
import { EventLog } from './entities/event-logs.entity.js';
import { MultiSignature } from './entities/multi-signature.entity.js';

Expand Down Expand Up @@ -58,18 +59,13 @@ export class SenderEVMBridge {
await this.updateLogStatusWithRetry(dataLock, EEventStatus.FAILED, EError.OVER_DAILY_QUOTA);
return;
}
// const gasFee = await this.ethBridgeContract.getEstimateGas(
// tokenReceivedAddress,
// BigNumber(amountReceive),
// txHashLock,
// receiveAddress,
// 0,
// );
const protocolFee = calculateFee(
amountReceived,
addDecimal(this.configService.get(EEnvKey.GAS_FEE_EVM), this.configService.get(EEnvKey.DECIMAL_TOKEN_EVM)),
configTip.tip,
// fee and received amount.
const gasFeeEth = addDecimal(
this.configService.get(EEnvKey.GAS_FEE_EVM),
this.configService.get(EEnvKey.DECIMAL_TOKEN_EVM),
);
const protocolFee = calculateFee(amountReceived, gasFeeEth, configTip.tip);
// call unlock function
const result = await this.ethBridgeContract.unlock(
tokenReceivedAddress,
BigNumber(amountReceived),
Expand All @@ -87,6 +83,8 @@ export class SenderEVMBridge {
errorDetail: null,
protocolFee,
amountReceived: BigNumber(amountReceived).minus(protocolFee).toFixed(0).toString(),
gasFee: gasFeeEth,
tip: calculateTip(amountReceived, gasFeeEth, configTip.tip).toFixed(0).toString(),
});
} else {
await this.handleError(result.error, dataLock);
Expand Down Expand Up @@ -116,13 +114,6 @@ export class SenderEVMBridge {
return;
}

// const gasFee = await this.ethBridgeContract.getEstimateGas(
// tokenReceivedAddress,
// BigNumber(amountReceive),
// txHashLock,
// receiveAddress,
// 0,
// );
const protocolFee = calculateFee(
amountReceived,
addDecimal(this.configService.get(EEnvKey.GAS_FEE_EVM), this.configService.get(EEnvKey.DECIMAL_TOKEN_EVM)),
Expand Down
33 changes: 21 additions & 12 deletions src/modules/crawler/sender.minabridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { EventLogRepository } from '../../database/repositories/event-log.reposi
import { MultiSignatureRepository } from '../../database/repositories/multi-signature.repository.js';
import { TokenPairRepository } from '../../database/repositories/token-pair.repository.js';
import { LoggerService } from '../../shared/modules/logger/logger.service.js';
import { addDecimal, calculateFee } from '../../shared/utils/bignumber.js';
import { addDecimal, calculateFee, calculateTip } from '../../shared/utils/bignumber.js';
import { TokenPair } from '../users/entities/tokenpair.entity.js';
import { CommonConfig } from './entities/common-config.entity.js';
import { MultiSignature } from './entities/multi-signature.entity.js';
Expand Down Expand Up @@ -69,24 +69,27 @@ export class SenderMinaBridge {
tokenPair: TokenPair,
config: CommonConfig,
amountFrom: string,
): { amountReceived: string; protocolFeeAmount: string } {
): { amountReceived: string; protocolFeeAmount: string; tipAmount: string; gasFeeMina: string } {
// convert decimal from ETH to MINA
const amountReceiveConvert = BigNumber(amountFrom)
.dividedBy(BigNumber(DECIMAL_BASE).pow(tokenPair.fromDecimal))
.multipliedBy(BigNumber(DECIMAL_BASE).pow(tokenPair.toDecimal))
.toString();
const gasFeeMina = addDecimal(
this.configService.get(EEnvKey.GASFEEMINA),
this.configService.get(EEnvKey.DECIMAL_TOKEN_MINA),
);
// calc fee follow MINA decimal.
const protocolFeeAmount = BigNumber(
calculateFee(
amountReceiveConvert,
addDecimal(this.configService.get(EEnvKey.GASFEEMINA), this.configService.get(EEnvKey.DECIMAL_TOKEN_MINA)),
config.tip,
),
)
const protocolFeeAmount = BigNumber(calculateFee(amountReceiveConvert, gasFeeMina, config.tip))
.toFixed(0)
.toString();
const amountReceived = BigNumber(amountReceiveConvert).minus(protocolFeeAmount).toFixed(0).toString();
return { amountReceived, protocolFeeAmount };
return {
amountReceived,
protocolFeeAmount,
tipAmount: calculateTip(amountReceiveConvert, gasFeeMina, config.tip).toFixed(0).toString(),
gasFeeMina,
};
}
public async handleUnlockMina() {
let dataLock, configTip;
Expand Down Expand Up @@ -123,7 +126,11 @@ export class SenderMinaBridge {
});
return;
}
const { amountReceived, protocolFeeAmount } = this.getAmountReceivedAndFee(tokenPair, configTip, amountFrom);
const { amountReceived, protocolFeeAmount, gasFeeMina, tipAmount } = this.getAmountReceivedAndFee(
tokenPair,
configTip,
amountFrom,
);

const result = await this.callUnlockFunction(amountReceived, id, receiveAddress);
// Update status eventLog when call function unlock
Expand All @@ -134,8 +141,10 @@ export class SenderMinaBridge {
status: EEventStatus.PROCESSING,
errorDetail: result.error,
txHashUnlock: result.data,
amountReceived: BigNumber(amountReceived).minus(protocolFeeAmount).toFixed(0).toString(),
amountReceived,
protocolFee: protocolFeeAmount,
gasFee: gasFeeMina,
tip: tipAmount,
});
} else {
await this.eventLogRepository.updateStatusAndRetryEvenLog({
Expand Down
42 changes: 18 additions & 24 deletions src/modules/crawler/tests/evm-sender.spec.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,30 @@
import { ConfigModule, ConfigService } from '@nestjs/config';
import { ConfigModule } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Test, TestingModule } from '@nestjs/testing';
import { ConfigurationModule } from 'config/config.module.js';
import { EAsset } from 'constants/api.constant.js';
import { EEventName, EEventStatus, ENetworkName, ETokenPairStatus } from 'constants/blockchain.constant.js';
import { CommonConfigRepository } from 'database/repositories/common-configuration.repository';
import { CrawlContractRepository } from 'database/repositories/crawl-contract.repository';
import { EventLogRepository } from 'database/repositories/event-log.repository';
import { MultiSignatureRepository } from 'database/repositories/multi-signature.repository';
import { TokenPairRepository } from 'database/repositories/token-pair.repository';
import { TokenPair } from 'modules/users/entities/tokenpair.entity.js';
import { LoggerService } from 'shared/modules/logger/logger.service.js';
import { Web3Module } from 'shared/modules/web3/web3.module.js';
import { ETHBridgeContract } from 'shared/modules/web3/web3.service.js';
import { DataSource, QueryRunner } from 'typeorm';
import { DataSource } from 'typeorm';

import { EventLog } from '../entities';
import { CommonConfig } from '../entities/common-config.entity';
import { MultiSignature } from '../entities/multi-signature.entity';
import { SenderEVMBridge } from '../sender.evmbridge';
import { ConfigurationModule } from '../../../config/config.module.js';
import { EAsset } from '../../../constants/api.constant.js';
import { EEventName, EEventStatus, ENetworkName, ETokenPairStatus } from '../../../constants/blockchain.constant.js';
import { CommonConfigRepository } from '../../../database/repositories/common-configuration.repository.js';
import { CrawlContractRepository } from '../../../database/repositories/crawl-contract.repository.js';
import { EventLogRepository } from '../../../database/repositories/event-log.repository.js';
import { MultiSignatureRepository } from '../../../database/repositories/multi-signature.repository.js';
import { TokenPairRepository } from '../../../database/repositories/token-pair.repository.js';
import { TokenPair } from '../../../modules/users/entities/tokenpair.entity.js';
import { LoggerService } from '../../../shared/modules/logger/logger.service.js';
import { Web3Module } from '../../../shared/modules/web3/web3.module.js';
import { ETHBridgeContract } from '../../../shared/modules/web3/web3.service.js';
import { CommonConfig } from '../entities/common-config.entity.js';
import { EventLog } from '../entities/index.js';
import { MultiSignature } from '../entities/multi-signature.entity.js';
import { SenderEVMBridge } from '../sender.evmbridge.js';

let senderEVMBridge: SenderEVMBridge;
let dataSource: DataSource;
let queryRunner: QueryRunner;
let eventLogRepository: EventLogRepository;
let commonConfigRepository: CommonConfigRepository;
let tokenPairRepository: TokenPairRepository;
let multiSignatureRepository: MultiSignatureRepository;
let loggerService: LoggerService;
let newEthBridgeContract: ETHBridgeContract;
// Mock objects
const mockJwtService = {
Expand Down Expand Up @@ -103,13 +100,10 @@ beforeEach(async () => {

newEthBridgeContract = module.get<ETHBridgeContract>(ETHBridgeContract);
senderEVMBridge = module.get<SenderEVMBridge>(SenderEVMBridge);
dataSource = module.get<DataSource>(DataSource);
queryRunner = dataSource.createQueryRunner();
eventLogRepository = module.get<EventLogRepository>(EventLogRepository);
commonConfigRepository = module.get<CommonConfigRepository>(CommonConfigRepository);
tokenPairRepository = module.get<TokenPairRepository>(TokenPairRepository);
multiSignatureRepository = module.get<MultiSignatureRepository>(MultiSignatureRepository);
loggerService = module.get<LoggerService>(LoggerService);
});

describe('handleValidateUnlockTxEVM', () => {
Expand Down
16 changes: 6 additions & 10 deletions src/modules/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export class UsersService {
}

async getProtocolFee({ pairId }: GetProtocolFeeBodyDto) {
let gasFee;
let gasFee, decimal;
const [tokenPair, configTip] = await Promise.all([
this.dataSource.getRepository(TokenPair).findOne({
where: { id: pairId },
Expand All @@ -81,17 +81,13 @@ export class UsersService {
]);

if (tokenPair.toChain == ENetworkName.MINA) {
gasFee = addDecimal(
this.configService.get(EEnvKey.GAS_FEE_EVM),
this.configService.get(EEnvKey.DECIMAL_TOKEN_EVM),
);
decimal = this.configService.get(EEnvKey.DECIMAL_TOKEN_EVM);
gasFee = addDecimal(this.configService.get(EEnvKey.GAS_FEE_EVM), decimal);
} else {
gasFee = addDecimal(
this.configService.get(EEnvKey.GASFEEMINA),
this.configService.get(EEnvKey.DECIMAL_TOKEN_MINA),
);
decimal = this.configService.get(EEnvKey.DECIMAL_TOKEN_MINA);
gasFee = addDecimal(this.configService.get(EEnvKey.GASFEEMINA), decimal);
}

return { gasFee, tipRate: configTip.tip };
return { gasFee, tipRate: configTip.tip, decimal };
}
}
11 changes: 7 additions & 4 deletions src/shared/utils/bignumber.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import BigNumber from 'bignumber.js/bignumber.mjs';
// import BigNumber from 'bignumber.js/bignumber.mjs';
import { BigNumber } from 'bignumber.js';
import { isNumber, isNumberString } from 'class-validator';

export const addDecimal = (value: string | number, decimal: number) => {
if (!isNumber(value) && !isNumberString(value)) return '0';
return BigNumber(value).multipliedBy(BigNumber(10).pow(decimal)).toFixed().toString();
};

export const calculateFee = (amount: string, gasFee: string | number, tipPercent: number) => {
const tip = BigNumber(amount)
export const calculateTip = (amount: string, gasFee: string | number, tipPercent: number): BigNumber => {
return BigNumber(amount)
.minus(BigNumber(gasFee))
.multipliedBy(tipPercent * 10)
.dividedBy(1000);
};
export const calculateFee = (amount: string, gasFee: string | number, tipPercent: number) => {
const tip = calculateTip(amount, gasFee, tipPercent);
return BigNumber(gasFee).plus(tip).toFixed(0, BigNumber.ROUND_UP);
};
2 changes: 1 addition & 1 deletion src/shared/utils/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,4 @@ export const getVariableName = <TResult>(getVar: () => TResult): string => {

export const nullToZero = (value: string | number) => (value ? value.toString() : '0');
export const isDevelopmentEnvironment = () =>
[EEnvironments.LOCAL].includes(process.env[EEnvKey.NODE_ENV] as EEnvironments);
[EEnvironments.LOCAL, EEnvironments.DEV].includes(process.env[EEnvKey.NODE_ENV] as EEnvironments);

0 comments on commit 1da5dec

Please sign in to comment.