Skip to content

Commit

Permalink
Merge pull request #33 from sotatek-dev/chore/unit-test-crawler
Browse files Browse the repository at this point in the history
chore: remove hard code
  • Loading branch information
Sotatek-ThinhNguyen2 authored Sep 6, 2024
2 parents 045660b + bac52b9 commit fa95737
Show file tree
Hide file tree
Showing 15 changed files with 68 additions and 37 deletions.
2 changes: 0 additions & 2 deletions src/config/common.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ function getEthBridgeStartBlock(configService: ConfigService) {
}

async function initializeEthContract(configService: ConfigService) {
const callerName = new Error().stack?.split('\n')[2]?.trim();
console.log(`initializeEthContract called by: ${callerName || 'unknown'}`);
const [rpcEthService, address, _startBlock] = await Promise.all([
createRpcEthService(configService),
getEthBridgeAddress(configService),
Expand Down
16 changes: 16 additions & 0 deletions src/constants/api.constant.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
export const COMMOM_CONFIG_TIP = 0.5;
export const COMMON__CONFIG_DAILY_QUOTA = 500;

export enum EDirection {
ASC = 'ASC',
DESC = 'DESC',
}

export enum ERole {
MINA_ADMIN = 'Mina Admin',
EVM_ADMIN = 'EVM Admin',
}

export enum EAsset {
ETH = 'ETH',
MINA = 'MINA',
WETH = 'WETH',
}

export const JWT_TOKEN_EXPIRE_DURATION = '1d';
8 changes: 7 additions & 1 deletion src/constants/blockchain.constant.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export const DEFAULT_DECIMAL_PLACES = 6;

export const DEFAULT_ADDRESS_PREFIX = '0x';
export const DECIMAL_BASE = 10;
export enum ENetworkName {
ETH = 'eth',
MINA = 'mina',
Expand All @@ -22,3 +23,8 @@ export enum ETokenPairStatus {
ENABLE = 'enable',
DISABLE = 'disable',
}

export enum EMinaChainEnviroment {
TESTNET = 'testnet',
MAINNET = 'mainnet',
}
5 changes: 3 additions & 2 deletions src/core/base-repository.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Repository, SelectQueryBuilder } from 'typeorm';

import { EDirection } from '@constants/api.constant';
import { ETableName } from '@constants/entity.constant';

import { IPagination } from '@shared/interfaces/pagination.interface';
Expand Down Expand Up @@ -31,7 +32,7 @@ export abstract class BaseRepository<E> extends Repository<E> {
}
if (data.sortBy) {
if (!selections || selections?.includes(`${this.alias}.${data.sortBy}`)) {
queryBuilder.orderBy(`${this.alias}.${data.sortBy}`, data.direction || 'ASC');
queryBuilder.orderBy(`${this.alias}.${data.sortBy}`, data.direction || EDirection.ASC);
}
}
return queryBuilder;
Expand All @@ -56,7 +57,7 @@ export abstract class BaseRepository<E> extends Repository<E> {

if (data.sortBy) {
if (!selections || selections?.includes(`${this.alias}.${data.sortBy}`)) {
queryBuilder.orderBy(`${this.alias}.${data.sortBy}`, data.direction || 'ASC');
queryBuilder.orderBy(`${this.alias}.${data.sortBy}`, data.direction || EDirection.ASC);
}
}

Expand Down
8 changes: 5 additions & 3 deletions src/database/seeds/common_config.seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import * as dotenv from 'dotenv';
import { DataSource } from 'typeorm';
import { Seeder, SeederFactoryManager } from 'typeorm-extension';

import { COMMOM_CONFIG_TIP, COMMON__CONFIG_DAILY_QUOTA, EAsset } from '@constants/api.constant';

import { CommonConfig } from '@modules/crawler/entities/common-config.entity';

export default class CommonConfigSeeder implements Seeder {
Expand All @@ -10,9 +12,9 @@ export default class CommonConfigSeeder implements Seeder {
const repository = dataSource.getRepository(CommonConfig);
await repository.insert(
new CommonConfig({
tip: 0.5,
dailyQuota: 500,
asset: 'ETH',
tip: COMMOM_CONFIG_TIP,
dailyQuota: COMMON__CONFIG_DAILY_QUOTA,
asset: EAsset.ETH,
}),
);
}
Expand Down
6 changes: 4 additions & 2 deletions src/database/seeds/super_admin.seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import * as dotenv from 'dotenv';
import { DataSource } from 'typeorm';
import { Seeder, SeederFactoryManager } from 'typeorm-extension';

import { ERole } from '@constants/api.constant';

import { User } from '@modules/users/entities/user.entity';

export default class SuperAdminSeeder implements Seeder {
Expand All @@ -11,11 +13,11 @@ export default class SuperAdminSeeder implements Seeder {
const listAdmin = [
{
walletAddress: process.env.ADMIN_ADDRESS_EVM,
name: 'admin evm',
name: ERole.EVM_ADMIN,
},
{
walletAddress: process.env.ADMIN_ADDRESS_MINA,
name: 'admin mina',
name: ERole.MINA_ADMIN,
},
];

Expand Down
9 changes: 5 additions & 4 deletions src/database/seeds/token_pairs.seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as dotenv from 'dotenv';
import { DataSource } from 'typeorm';
import { Seeder, SeederFactoryManager } from 'typeorm-extension';

import { EAsset } from '@constants/api.constant';
import { ENetworkName, ETokenPairStatus } from '@constants/blockchain.constant';

import { TokenPair } from '@modules/users/entities/tokenpair.entity';
Expand All @@ -14,8 +15,8 @@ export default class TokenPairsSeeder implements Seeder {
{
fromChain: ENetworkName.ETH,
toChain: ENetworkName.MINA,
fromSymbol: 'ETH',
toSymbol: 'WETH',
fromSymbol: EAsset.ETH,
toSymbol: EAsset.WETH,
fromAddress: process.env.ETH_TOKEN_BRIDGE_ADDRESS,
toAddress: process.env.MINA_TOKEN_BRIDGE_ADDRESS,
fromDecimal: 18,
Expand All @@ -26,8 +27,8 @@ export default class TokenPairsSeeder implements Seeder {
{
fromChain: ENetworkName.MINA,
toChain: ENetworkName.ETH,
fromSymbol: 'WETH',
toSymbol: 'ETH',
fromSymbol: EAsset.WETH,
toSymbol: EAsset.ETH,
fromAddress: process.env.MINA_TOKEN_BRIDGE_ADDRESS,
toAddress: process.env.ETH_TOKEN_BRIDGE_ADDRESS,
fromDecimal: 9,
Expand Down
3 changes: 2 additions & 1 deletion src/modules/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { PassportModule } from '@nestjs/passport';
import { UserRepository } from 'database/repositories/user.repository';
import { CustomRepositoryModule } from 'nestjs-typeorm-custom-repository';

import { JWT_TOKEN_EXPIRE_DURATION } from '@constants/api.constant';
import { EEnvKey } from '@constants/env.constant';

import { UsersModule } from '@modules/users/users.module';
Expand All @@ -24,7 +25,7 @@ import { JwtStrategy } from './strategies/jwt.strategy';
({
secret: configService.get(EEnvKey.JWT_SECRET_KEY),
signOptions: {
expiresIn: '1d',
expiresIn: JWT_TOKEN_EXPIRE_DURATION,
},
}) as JwtModuleOptions,
inject: [ConfigService],
Expand Down
9 changes: 5 additions & 4 deletions src/modules/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import { Logger } from 'log4js';
import Client from 'mina-signer';
import { toChecksumAddress } from 'web3-utils';

import { EEnvKey } from '@constants/env.constant';
import { EMinaChainEnviroment } from '@constants/blockchain.constant';
import { EEnvironments, EEnvKey } from '@constants/env.constant';
import { EError } from '@constants/error.constant';

import { User } from '@modules/users/entities/user.entity';
Expand Down Expand Up @@ -87,9 +88,9 @@ export class AuthService {
}

private async validateSignatureMina(address: string, signature) {
let client = new Client({ network: 'mainnet' });
if (process.env.NODE_ENV !== 'production') {
client = new Client({ network: 'testnet' });
let client = new Client({ network: EMinaChainEnviroment.MAINNET });
if (process.env.NODE_ENV !== EEnvironments.PRODUCTION) {
client = new Client({ network: EMinaChainEnviroment.TESTNET });
}

const signer = {
Expand Down
13 changes: 7 additions & 6 deletions src/modules/crawler/batch.tokenprice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ConfigService } from '@nestjs/config';
import axios from 'axios';
import { TokenPriceRepository } from 'database/repositories/token-price.repository';

import { EAsset } from '@constants/api.constant';
import { EEnvKey } from '@constants/env.constant';

import { TokenPrice } from './entities';
Expand All @@ -24,19 +25,19 @@ export class BatchJobGetPriceToken {
const result = await axios.get(apiUrl, { headers });

result?.data?.data.forEach(async e => {
if (e.symbol == 'MINA') {
const tokenMina = await this.tokenPriceRepository.getTokenPriceBySymbol('MINA');
if (e.symbol == EAsset.MINA) {
const tokenMina = await this.tokenPriceRepository.getTokenPriceBySymbol(EAsset.MINA);
if (!tokenMina) {
this.tokenPriceRepository.save(new TokenPrice({ symbol: 'MINA', priceUsd: e.quote.USD.price || 1 }));
this.tokenPriceRepository.save(new TokenPrice({ symbol: EAsset.MINA, priceUsd: e.quote.USD.price || 1 }));
} else {
tokenMina.priceUsd = e.quote.USD.price;
tokenMina.save();
}
}
if (e.symbol == 'ETH') {
const tokenMina = await this.tokenPriceRepository.getTokenPriceBySymbol('ETH');
if (e.symbol == EAsset.ETH) {
const tokenMina = await this.tokenPriceRepository.getTokenPriceBySymbol(EAsset.ETH);
if (!tokenMina) {
this.tokenPriceRepository.save(new TokenPrice({ symbol: 'ETH', priceUsd: e.quote.USD.price || 2300 }));
this.tokenPriceRepository.save(new TokenPrice({ symbol: EAsset.ETH, priceUsd: e.quote.USD.price || 2300 }));
} else {
tokenMina.priceUsd = e.quote.USD.price;
tokenMina.save();
Expand Down
3 changes: 2 additions & 1 deletion src/modules/crawler/crawler.evmbridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Logger } from 'log4js';
import { DataSource, QueryRunner } from 'typeorm';
import { EventData } from 'web3-eth-contract';

import { EAsset } from '@constants/api.constant';
import { EEventName, EEventStatus, ENetworkName } from '@constants/blockchain.constant';
import { EEnvKey } from '@constants/env.constant';

Expand Down Expand Up @@ -115,7 +116,7 @@ export class BlockchainEVMCrawler {
amountReceived: event.returnValues.amount,
tokenReceivedAddress: event.returnValues.token,
protocolFee: event.returnValues.fee,
tokenReceivedName: 'ETH',
tokenReceivedName: EAsset.ETH,
});

return {
Expand Down
9 changes: 5 additions & 4 deletions src/modules/crawler/crawler.minabridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { Logger } from 'log4js';
import { Field, Mina, PublicKey, UInt32 } from 'o1js';
import { DataSource, QueryRunner } from 'typeorm';

import { EEventName, EEventStatus, ENetworkName } from '@constants/blockchain.constant';
import { EAsset } from '@constants/api.constant';
import { DEFAULT_ADDRESS_PREFIX, EEventName, EEventStatus, ENetworkName } from '@constants/blockchain.constant';
import { EEnvKey } from '@constants/env.constant';

import { CrawlContract, EventLog } from '@modules/crawler/entities';
Expand Down Expand Up @@ -86,7 +87,7 @@ export class SCBridgeMinaCrawler {
txHashUnlock: event.event.transactionInfo.transactionHash,
amountReceived: event.event.data.amount.toString(),
tokenReceivedAddress: event.event.data.tokenAddress,
tokenReceivedName: 'WETH',
tokenReceivedName: EAsset.WETH,
});

return {
Expand All @@ -96,15 +97,15 @@ export class SCBridgeMinaCrawler {

public async handlerLockEvent(event, queryRunner: QueryRunner) {
const field = Field.from(event.event.data.receipt.toString());
const receiveAddress = '0x' + field.toBigInt().toString(16);
const receiveAddress = DEFAULT_ADDRESS_PREFIX + field.toBigInt().toString(16);

const eventUnlock = {
senderAddress: event.event.data.locker,
amountFrom: event.event.data.amount.toString(),
tokenFromAddress: this.configService.get(EEnvKey.MINA_TOKEN_BRIDGE_ADDRESS),
networkFrom: ENetworkName.MINA,
networkReceived: ENetworkName.ETH,
tokenFromName: 'WETH',
tokenFromName: EAsset.WETH,
tokenReceivedAddress: this.configService.get(EEnvKey.ETH_TOKEN_BRIDGE_ADDRESS),
txHashLock: event.event.transactionInfo.transactionHash,
receiveAddress: receiveAddress,
Expand Down
6 changes: 3 additions & 3 deletions src/modules/crawler/sender.evmbridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { CommonConfigRepository } from 'database/repositories/common-configurati
import { EventLogRepository } from 'database/repositories/event-log.repository';
import { TokenPairRepository } from 'database/repositories/token-pair.repository';

import { EEventStatus, ENetworkName } from '@constants/blockchain.constant';
import { DECIMAL_BASE, EEventStatus, ENetworkName } from '@constants/blockchain.constant';
import { EError } from '@constants/error.constant';

import { ETHBridgeContract } from '@shared/modules/web3/web3.service';
Expand Down Expand Up @@ -46,8 +46,8 @@ export class SenderEVMBridge {
}

const amountReceive = BigNumber(amountFrom)
.dividedBy(BigNumber(10).pow(tokenPair.fromDecimal))
.multipliedBy(BigNumber(10).pow(tokenPair.toDecimal))
.dividedBy(BigNumber(DECIMAL_BASE).pow(tokenPair.fromDecimal))
.multipliedBy(BigNumber(DECIMAL_BASE).pow(tokenPair.toDecimal))
.toString();

const isPassDailyQuota = await this.isPassDailyQuota(senderAddress, tokenPair.fromDecimal);
Expand Down
6 changes: 3 additions & 3 deletions src/modules/crawler/sender.minabridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { TokenPriceRepository } from 'database/repositories/token-price.reposito
import { Logger } from 'log4js';
import { AccountUpdate, fetchAccount, Mina, PrivateKey, PublicKey, UInt64 } from 'o1js';

import { EEventStatus, ENetworkName } from '@constants/blockchain.constant';
import { DECIMAL_BASE, EEventStatus, ENetworkName } from '@constants/blockchain.constant';
import { EEnvKey } from '@constants/env.constant';
import { EError } from '@constants/error.constant';

Expand Down Expand Up @@ -65,8 +65,8 @@ export class SenderMinaBridge {
}

const amountReceiveConvert = BigNumber(amountFrom)
.dividedBy(BigNumber(10).pow(tokenPair.fromDecimal))
.multipliedBy(BigNumber(10).pow(tokenPair.toDecimal))
.dividedBy(BigNumber(DECIMAL_BASE).pow(tokenPair.fromDecimal))
.multipliedBy(BigNumber(DECIMAL_BASE).pow(tokenPair.toDecimal))
.toString();
const protocolFeeAmount = calculateFee(
amountReceiveConvert,
Expand Down
2 changes: 1 addition & 1 deletion src/modules/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export class UsersService {
tokenPair.toAddress,
addDecimal(0, tokenPair.toDecimal),
1,
'0xb3Edf83eA590F44f5c400077EBd94CCFE10E4Bb0', // TODO: remove hard code
process.env.ADMIN_ADDRESS_EVM,
0,
);
}
Expand Down

0 comments on commit fa95737

Please sign in to comment.