Skip to content

Commit

Permalink
Refactor competitions entity
Browse files Browse the repository at this point in the history
  • Loading branch information
ArtemKolodko committed Dec 6, 2024
1 parent 4b96500 commit 94b8447
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 101 deletions.
10 changes: 5 additions & 5 deletions src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,6 @@ export class AppController {
return this.appService.getTokenBalances(dto)
}

@Get('/winners')
getWinners(@Query() dto: GetTokenWinnersDto) {
return this.appService.getTokenWinners(dto)
}

@Get('/candles')
async getCandles(@Query() dto: GetCandlesDto) {
return await this.appService.getCandles(dto)
Expand Down Expand Up @@ -97,6 +92,11 @@ export class AppController {
return this.appService.getTrades(dto)
}

@Get('/competitions')
getCompetitions() {
return this.appService.getCompetitions()
}

@Get('/tokenBurns')
getTokenBurns(@Query() dto: GetTokenBurnsDto) {
return this.appService.getTokenBurns(dto)
Expand Down
31 changes: 20 additions & 11 deletions src/app.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import {Injectable, Logger} from '@nestjs/common';
import {DataSource, EntityManager, MoreThan} from "typeorm";
import {Comment, LiquidityProvision, Token, TokenBalance, TokenBurn, TokenWinner, Trade, UserAccount} from "./entities";
import {
Comment,
CompetitionEntity,
LiquidityProvision,
Token,
TokenBalance,
TokenBurn,
Trade,
UserAccount
} from "./entities";
import {AddCommentDto, GetCommentsDto} from "./dto/comment.dto";
import {GetTokenBalancesDto, GetTokenBurnsDto, GetTokensDto, GetTokenWinnersDto} from "./dto/token.dto";
import {GetCandlesDto, GetTradesDto} from "./dto/trade.dto";
Expand Down Expand Up @@ -77,16 +86,6 @@ export class AppService {
})
}

async getTokenWinners(dto: GetTokenWinnersDto) {
return await this.dataSource.manager.find(TokenWinner, {
order: {
timestamp: 'desc'
},
take: dto.limit,
skip: dto.offset,
})
}

async getTrades(dto: GetTradesDto){
return await this.dataSource.manager.find(Trade, {
where: {
Expand All @@ -102,6 +101,16 @@ export class AppService {
})
}

async getCompetitions() {
return await this.dataSource.manager.find(CompetitionEntity, {
relations: ['winnerToken'],
where: {},
order: {
competitionId: 'desc'
}
})
}

async getTokenBurns(dto: GetTokenBurnsDto){
return await this.dataSource.manager.find(TokenBurn, {
where: {
Expand Down
21 changes: 19 additions & 2 deletions src/entities/competition.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ import {
Column,
CreateDateColumn,
Entity,
OneToOne,
PrimaryGeneratedColumn,
JoinColumn
} from 'typeorm';
import { ApiProperty } from '@nestjs/swagger';
import {Token} from "./token.entity";

@Entity({ name: 'competitions' })
export class CompetitionEntity {
@ApiProperty()
Expand All @@ -24,8 +28,21 @@ export class CompetitionEntity {
competitionId: number;

@ApiProperty()
@Column({ type: 'bigint' })
timestamp: number;
@Column({ type: 'bigint', nullable: false })
timestampStart: number;

@ApiProperty()
@Column({ type: 'bigint', nullable: true })
timestampEnd: number;

@ApiProperty()
@Column('bool', { default: false })
isCompleted: boolean;

@ApiProperty()
@OneToOne((type) => Token, token => token.competition)
@JoinColumn()
winnerToken: Token | null

@ApiProperty()
@CreateDateColumn({ name: 'createdAt' })
Expand Down
3 changes: 0 additions & 3 deletions src/entities/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { IndexerState } from './indexer.state.entity';
import { Trade } from './trade.entity';
import { Comment } from './comment.entity';
import { TokenBalance } from './token.balances.entity';
import { TokenWinner } from './token.winner.entity';
import { SignInRequestEntity } from './signin.entity';
import { TokenBurn } from './token.burn.entity';
import { LiquidityProvision } from './liquidity.provision.entity';
Expand All @@ -17,7 +16,6 @@ const entities = [
Trade,
Comment,
TokenBalance,
TokenWinner,
SignInRequestEntity,
TokenBurn,
LiquidityProvision,
Expand All @@ -31,7 +29,6 @@ export {
Trade,
Comment,
TokenBalance,
TokenWinner,
SignInRequestEntity,
TokenBurn,
LiquidityProvision,
Expand Down
15 changes: 11 additions & 4 deletions src/entities/token.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@ import {UserAccount} from "./user-account.entity";
import {TokenMetadata} from "../types";
import {Trade} from "./trade.entity";
import Decimal from "decimal.js";
import {CompetitionEntity} from "./competition.entity";

class ColumnNumericTransformer {
to(data: string): string {
return data;
}
from(data: number): string {
return new Decimal(data).toFixed()
return data ? new Decimal(data).toFixed() : '0'
}
}

Expand Down Expand Up @@ -57,9 +58,15 @@ export class Token {
@Column({ type: 'json', nullable: true })
uriData: TokenMetadata | null;

@ApiProperty()
@Column({ type: 'integer' })
competitionId: number;
// @ApiProperty()
// @Column({ type: 'integer' })
// competitionId: number;

@ManyToOne(() => CompetitionEntity, {
eager: true
})
@JoinTable()
competition: CompetitionEntity

@ApiProperty()
@Column({ type: 'bigint' })
Expand Down
41 changes: 0 additions & 41 deletions src/entities/token.winner.entity.ts

This file was deleted.

89 changes: 54 additions & 35 deletions src/indexer/indexer.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ import {Injectable, Logger} from '@nestjs/common';
import {Contract, ContractAbi, EventLog, Web3} from "web3";
import {TokenMetadata, TradeType} from "../types";
import axios from "axios";
import process from "process";
import * as process from "process";
import {
CompetitionEntity,
IndexerState,
LiquidityProvision,
Token,
TokenBalance,
TokenBurn,
TokenWinner,
Trade
} from "../entities";
import {ConfigService} from "@nestjs/config";
Expand Down Expand Up @@ -107,37 +106,27 @@ export class IndexerService {
return
}

const existedWinner = await transactionalEntityManager.findOne(TokenWinner, {
where: {
token: {
address: winnerAddress,
},
competitionId,
timestamp
}
const token = await this.appService.getTokenByAddress(winnerAddress, transactionalEntityManager)
if(!token) {
this.logger.error(`Failed to add winner: winner token not found in database, winnerAddress=${winnerAddress}, exit`)
process.exit(1)
}

const competition = await transactionalEntityManager.findOne(CompetitionEntity, {
where: { competitionId }
})
if(!competition) {
this.logger.error(`Failed to add winner: competition=${competitionId} not found in database, exit`)
process.exit(1)
}

if(!existedWinner) {
const token = await this.appService.getTokenByAddress(winnerAddress, transactionalEntityManager)
if(!token) {
this.logger.error(`Failed to add winner: winner token not found in database, winnerAddress=${winnerAddress}, exit`)
process.exit(1)
}
token.isWinner = true
await transactionalEntityManager.save(token)

token.isWinner = true
competition.winnerToken = token
await transactionalEntityManager.save(competition)

await transactionalEntityManager.save(token)
await transactionalEntityManager.insert(TokenWinner, {
token,
timestamp,
competitionId,
txnHash,
blockNumber
})
this.logger.log(`Added new token winner=${winnerAddress}, competitionId=${competitionId}, timestamp=${timestamp}`)
} else {
this.logger.warn(`Token winner=${winnerAddress}, competitionId=${competitionId}, timestamp=${timestamp} already exists, skip`)
}
this.logger.log(`Added new token winner=${winnerAddress}, competitionId=${competitionId}, timestamp=${timestamp}`)
}

private async processCreateTokenEvent(event: EventLog, transactionalEntityManager: EntityManager) {
Expand Down Expand Up @@ -170,17 +159,32 @@ export class IndexerService {
}
}

const competition = await transactionalEntityManager.findOne(CompetitionEntity, {
where: {},
order: {
competitionId: 'DESC'
}
})
if(!competition) {
this.logger.error(`Create token: current competition is missing in DB; exit`)
process.exit(1)
}
if(competition.isCompleted) {
this.logger.error(`Create token: current competition is completed, new competitions has not started yet; exit`)
process.exit(1)
}

await transactionalEntityManager.insert(Token, {
txnHash,
address: tokenAddress,
blockNumber: Number(event.blockNumber),
name,
symbol,
competitionId,
timestamp,
user,
uri,
uriData,
competition
});
this.logger.log(`Create token: address=${tokenAddress}, name=${name}, symbol=${symbol}, uri=${uri}, creator=${creatorAddress}, competitionId=${competitionId}, txnHash=${txnHash}`);
}
Expand Down Expand Up @@ -370,11 +374,26 @@ export class IndexerService {
const values = event.returnValues
const competitionId = Number(values['competitionId'] as bigint)
const timestamp = Number(values['timestamp'] as bigint)

const competitions = await this.appService.getCompetitions()
if(competitions.length > 0) {
const currentCompetition = competitions[0]
if(currentCompetition) {
currentCompetition.isCompleted = true
currentCompetition.timestampEnd = timestamp
await transactionalEntityManager.save(currentCompetition)
}

}

await transactionalEntityManager.insert(CompetitionEntity, {
txnHash,
blockNumber: Number(event.blockNumber),
competitionId,
timestamp,
timestampStart: timestamp,
timestampEnd: null,
isCompleted: false,
winnerToken: null,
});
this.logger.log(`NewCompetitionStarted: competitionId=${competitionId}, timestamp=${timestamp}, txnHash=${txnHash}`);
}
Expand Down Expand Up @@ -413,6 +432,10 @@ export class IndexerService {
}

if(toBlock - fromBlock >= 1) {
const newCompetitionEvents = await this.tokenFactoryContract.getPastEvents('allEvents', {
fromBlock, toBlock, topics: [ this.web3.utils.sha3('NewCompetitionStarted(uint256,uint256)')],
}) as EventLog[];

const setWinnerEvents = await this.tokenFactoryContract.getPastEvents('allEvents', {
fromBlock, toBlock, topics: [ this.web3.utils.sha3('SetWinner(address,uint256,uint256)')],
}) as EventLog[];
Expand All @@ -421,10 +444,6 @@ export class IndexerService {
fromBlock, toBlock, topics: [ this.web3.utils.sha3('WinnerLiquidityAdded(address,address,address,address,uint256,uint128,uint256,uint256,uint256)')],
}) as EventLog[];

const newCompetitionEvents = await this.tokenFactoryContract.getPastEvents('allEvents', {
fromBlock, toBlock, topics: [ this.web3.utils.sha3('NewCompetitionStarted(uint256,uint256)')],
}) as EventLog[];

const tokenCreatedEvents = await this.tokenFactoryContract.getPastEvents('allEvents', {
fromBlock,
toBlock,
Expand Down

0 comments on commit 94b8447

Please sign in to comment.