Skip to content

Commit

Permalink
Merge pull request #206 from sotatek-dev/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
Sotatek-TanHoang authored Oct 31, 2024
2 parents c446ee8 + 2ce162f commit 1b2bf0d
Show file tree
Hide file tree
Showing 13 changed files with 119 additions and 9 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"migration:run": "npm run typeorm -- -d dist/database/data-source.js migration:run",
"migration:run-dist": "npm run typeorm -- -d dist/database/data-source.js migration:run",
"migration:run:js": "node ./node_modules/typeorm/cli.js -d dist/database/data-source.js migration:run",
"migration:revert": "npm run typeorm -- -d src/database/data-source.ts migration:revert",
"migration:revert": "node ./node_modules/typeorm/cli.js -d dist/database/data-source.js migration:revert",
"seed:run": "node ./node_modules/typeorm-extension/bin/cli.cjs seed:run -d dist/database/data-source.js",
"console:dev": "node --loader ts-node/esm src/console.ts",
"console": "node dist/console.js"
Expand Down
22 changes: 22 additions & 0 deletions src/database/migrations/1730343431370-add-token-circulation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm';

export class AddTokenCirculation1730343431370 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
return queryRunner.addColumns('common_configuration', [
new TableColumn({
name: 'total_weth_minted',
type: 'varchar',
default: '0',
}),
new TableColumn({
name: 'total_weth_burnt',
type: 'varchar',
default: '0',
}),
]);
}

public async down(queryRunner: QueryRunner): Promise<void> {
return queryRunner.dropColumns('common_configuration', ['total_weth_minted', 'total_weth_burnt']);
}
}
11 changes: 11 additions & 0 deletions src/database/repositories/event-log.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,4 +187,15 @@ export class EventLogRepository extends BaseRepository<EventLog> {

return qb.getOne();
}

async getTotalTokenSupply() {
const qb = this.createQb();

qb.select(['sum(CAST(amount_from as INT8))', 'sum(CAST(amount_received as INT8))', 'network_received']);

qb.where('status = :status', { status: EEventStatus.COMPLETED });
qb.groupBy('network_received');

return qb.execute();
}
}
11 changes: 11 additions & 0 deletions src/modules/crawler/crawler.console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { IGenerateSignature, IUnlockToken } from './interfaces/job.interface.js'
import { JobUnlockProvider } from './job-unlock.provider.js';
import { SenderEVMBridge } from './sender.evmbridge.js';
import { SenderMinaBridge } from './sender.minabridge.js';
import { POASync } from './services/token-poa-sync.service.js';

@Console()
export class CrawlerConsole {
Expand All @@ -24,6 +25,7 @@ export class CrawlerConsole {
private readonly loggerService: LoggerService,
private readonly queueService: QueueService,
private readonly unlockProviderService: JobUnlockProvider,
private readonly poaSyncer: POASync,
) {}
private readonly logger = this.loggerService.getLogger('CRAWLER_CONSOLE');

Expand Down Expand Up @@ -125,4 +127,13 @@ export class CrawlerConsole {
this.logger.info('JOB_UNLOCK_PROVIDER: started');
await this.unlockProviderService.handleJob();
}

@Command({
command: 'sync-token-proof-of-assets',
description: 'handle all network unlock.',
})
async handleSyncPOA() {
this.logger.info('SYNC_POA: started');
await this.poaSyncer.handleSyncPOA();
}
}
15 changes: 12 additions & 3 deletions src/modules/crawler/crawler.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 assert from 'assert';
import { BigNumber } from 'bignumber.js';
import { Logger } from 'log4js';
import { DataSource, EntityManager, Repository } from 'typeorm';
import { EventData } from 'web3-eth-contract';
Expand Down Expand Up @@ -51,7 +52,7 @@ export class BlockchainEVMCrawler {
await this.handlerLockEvent(event, eventLogRepo, configRepo);
break;
case 'Unlock':
await this.handlerUnLockEvent(event, eventLogRepo);
await this.handlerUnLockEvent(event, eventLogRepo, configRepo);
break;
default:
continue;
Expand Down Expand Up @@ -129,7 +130,11 @@ export class BlockchainEVMCrawler {
return { success: true };
}

public async handlerUnLockEvent(event: EventData, eventLogRepo: Repository<EventLog>): Promise<{ success: boolean }> {
public async handlerUnLockEvent(
event: EventData,
eventLogRepo: Repository<EventLog>,
configRepo: Repository<CommonConfig>,
): Promise<{ success: boolean }> {
const existLockTx = await eventLogRepo.findOneBy({
txHashLock: event.returnValues.hash,
});
Expand All @@ -145,7 +150,11 @@ export class BlockchainEVMCrawler {
tokenReceivedAddress: event.returnValues.token,
tokenReceivedName: EAsset.ETH,
});

// update total weth burned.
const currentConfig = await configRepo.findOneBy({});
assert(currentConfig, 'comomn config not exist');
const newTotalEthBurnt = new BigNumber(currentConfig.totalWethBurnt).plus(existLockTx.amountFrom).toString();
await configRepo.update(currentConfig.id, { totalWethBurnt: newTotalEthBurnt });
return {
success: true,
};
Expand Down
15 changes: 12 additions & 3 deletions src/modules/crawler/crawler.minabridge.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 assert from 'assert';
import { BigNumber } from 'bignumber.js';
import dayjs from 'dayjs';
import { Logger } from 'log4js';
import { fetchLastBlock, Field, Mina, PublicKey, UInt32 } from 'o1js';
Expand Down Expand Up @@ -69,11 +70,10 @@ export class SCBridgeMinaCrawler {
this.logger.info(`[handleCrawlMinaBridge] Crawling from ${startBlockNumber} to ${toBlock}`);
const configRepo = entityManager.getRepository(CommonConfig);
const eventLogRepo = entityManager.getRepository(EventLog);

for (const event of events) {
switch (event.type) {
case 'Unlock':
await this.handlerUnLockEvent(event, eventLogRepo);
await this.handlerUnLockEvent(event, eventLogRepo, configRepo);
break;
case 'Lock':
await this.handlerLockEvent(event, eventLogRepo, configRepo);
Expand All @@ -91,7 +91,11 @@ export class SCBridgeMinaCrawler {
}
}

public async handlerUnLockEvent(event: IMinaEvent, eventLogRepo: Repository<EventLog>) {
public async handlerUnLockEvent(
event: IMinaEvent,
eventLogRepo: Repository<EventLog>,
configRepo: Repository<CommonConfig>,
) {
const { id, tokenAddress } = event.event.data as IMinaLockTokenEventData;
const existLockTx = await eventLogRepo.findOneBy({
id: Number(id.toString()),
Expand All @@ -108,6 +112,11 @@ export class SCBridgeMinaCrawler {
tokenReceivedName: EAsset.WETH,
});

// update total weth minted
const currentConfig = await configRepo.findOneBy({});
assert(currentConfig, 'comomn config not exist');
const newTotalEthMinted = new BigNumber(currentConfig.totalWethMinted).plus(existLockTx.amountReceived).toString();
await configRepo.update(currentConfig.id, { totalWethMinted: newTotalEthMinted });
return {
success: true,
};
Expand Down
2 changes: 2 additions & 0 deletions src/modules/crawler/crawler.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { SCBridgeMinaCrawler } from './crawler.minabridge.js';
import { JobUnlockProvider } from './job-unlock.provider.js';
import { SenderEVMBridge } from './sender.evmbridge.js';
import { SenderMinaBridge } from './sender.minabridge.js';
import { POASync } from './services/token-poa-sync.service.js';

@Module({
imports: [
Expand All @@ -34,6 +35,7 @@ import { SenderMinaBridge } from './sender.minabridge.js';
SenderMinaBridge,
BatchJobGetPriceToken,
JobUnlockProvider,
POASync,
],
})
export class CrawlerModule {}
6 changes: 6 additions & 0 deletions src/modules/crawler/entities/common-config.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ export class CommonConfig extends BaseEntityIncludeTime {
@Column({ name: 'asset', type: 'varchar', nullable: true })
asset: string;

@Column({ name: 'total_weth_minted', type: 'varchar', default: '0' })
totalWethMinted: string;

@Column({ name: 'total_weth_burnt', type: 'varchar', default: '0' })
totalWethBurnt: string;

constructor(value: Partial<CommonConfig>) {
super();
Object.assign(this, value);
Expand Down
20 changes: 20 additions & 0 deletions src/modules/crawler/services/token-poa-sync.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Injectable } from '@nestjs/common';
import assert from 'assert';

import { CommonConfigRepository } from '../../../database/repositories/common-configuration.repository.js';
import { EventLogRepository } from '../../../database/repositories/event-log.repository.js';

@Injectable()
export class POASync {
constructor(
private readonly commonConfigRepo: CommonConfigRepository,
private readonly eventLogRepo: EventLogRepository,
) {}
public async handleSyncPOA() {
const currentConfig = await this.commonConfigRepo.findOneBy({});
assert(currentConfig, 'please seed common config');

const res = await this.eventLogRepo.getTotalTokenSupply();
console.log(res);
}
}
4 changes: 4 additions & 0 deletions src/modules/users/dto/user-response.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,7 @@ export class GetTokensPriceResponseDto {
@ApiProperty({ example: '1.23s' })
minaPriceInUsd: string;
}
export class GetProofOfAssetsResponseDto {
@ApiProperty({ example: '2345' })
totalWethInCirculation: string;
}
8 changes: 8 additions & 0 deletions src/modules/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { GetHistoryOfUserDto, GetHistoryOfUserResponseDto } from './dto/history-
import { GetProtocolFeeBodyDto } from './dto/user-request.dto.js';
import {
GetListTokenPairResponseDto,
GetProofOfAssetsResponseDto,
GetProtocolFeeResponseDto,
GetTokensPriceResponseDto,
} from './dto/user-response.dto.js';
Expand Down Expand Up @@ -50,4 +51,11 @@ export class UsersController {
getTokensPrices() {
return this.userService.getTokensPrices();
}

@Get('proof-of-assets')
@GuardPublic()
@ApiOkResponse({ type: GetProofOfAssetsResponseDto })
getProofOfAssets() {
return this.userService.getProofOfAssets();
}
}
10 changes: 9 additions & 1 deletion src/modules/users/users.service.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 assert from 'assert';
import { BigNumber } from 'bignumber.js';

import { EAsset } from '../../constants/api.constant.js';
import { ENetworkName } from '../../constants/blockchain.constant.js';
Expand All @@ -18,7 +19,7 @@ import { addDecimal } from '../../shared/utils/bignumber.js';
import { UpdateCommonConfigBodyDto } from './dto/common-config-request.dto.js';
import { GetHistoryDto, GetHistoryOfUserDto } from './dto/history-response.dto.js';
import { GetProtocolFeeBodyDto } from './dto/user-request.dto.js';
import { GetTokensPriceResponseDto } from './dto/user-response.dto.js';
import { GetProofOfAssetsResponseDto, GetTokensPriceResponseDto } from './dto/user-response.dto.js';

@Injectable()
export class UsersService {
Expand Down Expand Up @@ -119,4 +120,11 @@ export class UsersService {

return result;
}
async getProofOfAssets(): Promise<GetProofOfAssetsResponseDto> {
const config = await this.commonConfigRepository.findOneBy({});
assert(config, 'invalid config, please seed the value');
return {
totalWethInCirculation: new BigNumber(config.totalWethMinted).minus(config.totalWethBurnt).toString(),
};
}
}
2 changes: 1 addition & 1 deletion test.env
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ GAS_FEE_EVM=0.00001
DECIMAL_TOKEN_EVM=18

# coinmarketcap
COINMARKET_KEY=233ae614-1377-40e6-83c6-c042185a5a23
COINMARKET_KEY=494abf04-38b8-4451-8515-557ed1ab7a62
COINMARKET_URL='https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest?id=1027,8646'

MINA_BRIDGE_SC_PRIVATE_KEY=EKF19hihcXry9QMttf719fVp56DuRB2vZySdeQ1y9BkkvWWxnJAa
Expand Down

0 comments on commit 1b2bf0d

Please sign in to comment.