Skip to content

Commit

Permalink
Merge pull request #876 from aura-nw/baseline/main_20230720
Browse files Browse the repository at this point in the history
Baseline/main 20230720
  • Loading branch information
nhphuc2411 authored Jul 21, 2023
2 parents 278e019 + d8f1171 commit 8d6d441
Show file tree
Hide file tree
Showing 250 changed files with 13,309 additions and 12,750 deletions.
18 changes: 18 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,21 @@ MAX_REQUEST=250

# Config url
CONFIG_URL=https://explorer.dev.aura.network/assets/config/config.json

# Indexer v2
INDEXER_V2_URL=https://indexer-v2.dev.aurascan.io/
INDEXER_V2_DB=
INDEXER_V2_SECRET=

#GOOGLE OAUTH2
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_REDIRECT_URL=http://localhost:3000/api/v1/auth/google/redirect

#JWT
JWT_SECRET=example-secret-token
JWT_TOKEN_EXPIRES_IN='1h'
JWT_REFRESH_TOKEN_EXPIRES_IN='7d'

#ADMIN
ADMIN_INIT_EMAIL=[email protected]
15,935 changes: 8,569 additions & 7,366 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
"@nestjs/common": "^8.0.0",
"@nestjs/config": "^1.0.2",
"@nestjs/core": "^8.0.0",
"@nestjs/jwt": "^10.0.3",
"@nestjs/passport": "^9.0.3",
"@nestjs/platform-express": "^8.0.0",
"@nestjs/schedule": "^1.0.2",
"@nestjs/swagger": "^5.1.0",
Expand All @@ -45,11 +47,16 @@
"cache-manager-redis-store": "^2.0.0",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"cookie-parser": "^1.4.6",
"google-auth-library": "^8.8.0",
"joi": "^17.4.2",
"js-sha256": "^0.9.0",
"moment": "^2.29.4",
"mysql2": "^2.3.0",
"nest-schedule": "^0.6.4",
"passport": "^0.6.0",
"passport-google-oauth20": "^2.0.0",
"passport-jwt": "^4.0.1",
"redis": "^4.2.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
Expand Down
42 changes: 3 additions & 39 deletions src/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,15 @@
import {
ClassSerializerInterceptor,
Controller,
Get,
HttpStatus,
UseInterceptors,
} from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import {
AkcLogger,
BaseApiResponse,
ReqContext,
RequestContext,
SwaggerBaseApiResponse,
} from './shared';
import { Controller, Get } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';

import { AppService } from './app.service';
import { StatusOutput } from './components/dashboard/dtos/status-output.dto';

@ApiTags('dashboard')
@Controller()
export class AppController {
constructor(
private readonly appService: AppService,
private readonly logger: AkcLogger,
) {}
constructor(private readonly appService: AppService) {}

@Get()
getHello(): string {
return this.appService.getHello();
}

@Get('status')
@ApiOperation({
summary: 'Get status of the aura network',
})
@ApiResponse({
status: HttpStatus.OK,
type: SwaggerBaseApiResponse(StatusOutput),
})
@UseInterceptors(ClassSerializerInterceptor)
async getStatus(
@ReqContext() ctx: RequestContext,
): Promise<BaseApiResponse<StatusOutput>> {
this.logger.log(ctx, `${this.getStatus.name} was called!`);

const status = await this.appService.getStatus(ctx);

return { data: status, meta: {} };
}
}
15 changes: 4 additions & 11 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,34 +6,27 @@ import { SharedModule } from './shared/shared.module';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ComponentsModule } from './components/components.module';
import { BlockModule } from './components/block/block.module';
import { ValidatorModule } from './components/validator/validator.module';
import { AccountModule } from './components/account/account.module';
import { ServiceUtil } from './shared/utils/service.util';
import { ContractModule } from './components/contract/contract.module';
import { ContractCodeModule } from './components/contract-code/contract-code.module';
import { SyncStatusRepository } from './components/block/repositories/syns-status.repository';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Cw20TokenModule } from './components/cw20-token/cw20-token.module';
import { Cw721TokenModule } from './components/cw721-token/cw721-token.module';
import { MetricService } from './components/metric/services/metric.service';
import { SoulboundTokenModule } from './components/soulbound-token/soulbound-token.module';
import { NameTagModule } from './components/name-tag/name-tag.module';
import { AuthModule } from './auth/auth.module';

@Module({
imports: [
AuthModule,
SharedModule,
ComponentsModule,
ConfigModule,
HttpModule,
BlockModule,
ValidatorModule,
AccountModule,
ContractModule,
ContractCodeModule,
Cw20TokenModule,
Cw721TokenModule,
SoulboundTokenModule,
TypeOrmModule.forFeature([SyncStatusRepository]),
NameTagModule,
],
controllers: [AppController],
providers: [AppService, ServiceUtil, MetricService],
Expand Down
80 changes: 2 additions & 78 deletions src/app.service.ts
Original file line number Diff line number Diff line change
@@ -1,97 +1,21 @@
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';

import * as util from 'util';
import { SyncStatusRepository } from './components/block/repositories/syns-status.repository';
import { StatusOutput } from './components/dashboard/dtos/status-output.dto';
import { MetricService } from './components/metric/services/metric.service';
import { ValidatorService } from './components/validator/services/validator.service';
import { AkcLogger, CONST_CHAR, INDEXER_API, RequestContext } from './shared';
import { AkcLogger, RequestContext } from './shared';
import * as appConfig from './shared/configs/configuration';
import { ServiceUtil } from './shared/utils/service.util';

@Injectable()
export class AppService {
cosmosScanAPI: string;
private indexerUrl;
private indexerChainId;
private appParams;
private minimalDenom;

constructor(
private readonly logger: AkcLogger,
private validatorService: ValidatorService,
private serviceUtil: ServiceUtil,
private syncStatusRepos: SyncStatusRepository,
private metricService: MetricService,
) {
constructor(private readonly logger: AkcLogger) {
this.logger.setContext(AppService.name);
this.appParams = appConfig.default();
this.cosmosScanAPI = this.appParams.cosmosScanAPI;
this.indexerUrl = this.appParams.indexer.url;
this.indexerChainId = this.appParams.indexer.chainId;
this.minimalDenom = this.appParams.chainInfo.coinMinimalDenom;
}
getHello(): string {
const ctx = new RequestContext();
this.logger.log(ctx, 'Hello World!');
return 'Hello World!';
}

async getStatus(ctx: RequestContext): Promise<StatusOutput> {
this.logger.log(ctx, `${this.getStatus.name} was called!`);
this.logger.log(ctx, `calling get latest txs from node`);

const [
statusData,
blocks,
totalValidatorNum,
totalValidatorActiveNum,
totalTxsNum
] = await Promise.all([
this.serviceUtil.getDataAPI(`${this.indexerUrl}${util.format(INDEXER_API.STATUS, this.indexerChainId)}`, '', ctx),
this.syncStatusRepos.findOne(),
this.validatorService.getTotalValidator(),
this.validatorService.getTotalValidatorActive(),
this.metricService.getNumberTransactions()
]);

let height;
let comPool;
let supply;
if (blocks) {
height = blocks.current_block;
}

const data = statusData.data;
const bonded_tokens = Number(data.pool.bonded_tokens);
const inflation = (data.inflation.inflation * 100).toFixed(2) + CONST_CHAR.PERCENT;
const communityPool = data?.communityPool;
const supplyData = data?.supply?.supply;

if (communityPool && communityPool?.pool && communityPool.pool.length > 0) {
const filterCommunityPool = communityPool.pool.filter( f => String(f.denom) === this.appParams.chainInfo.coinMinimalDenom);
if(filterCommunityPool){
comPool = Number(filterCommunityPool[0].amount);
}
}
if (data?.supply && data.supply?.supply && data.supply.supply.length > 0) {
const supplyDenom = data.supply.supply.find(f => f.denom === this.minimalDenom);
if (supplyDenom) {
supply = parseInt(supplyDenom.amount);
}
}

return {
block_height: height,
total_txs_num: (totalTxsNum)? Number(totalTxsNum[0].total): 0,
total_validator_num: totalValidatorNum,
total_validator_active_num: totalValidatorActiveNum,
block_time: '',
bonded_tokens: bonded_tokens,
inflation: inflation,
community_pool: comPool,
supply: supply
};
}
}
44 changes: 44 additions & 0 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {
BadRequestException,
Body,
Controller,
HttpStatus,
Post,
} from '@nestjs/common';
import {
ApiBadRequestResponse,
ApiOkResponse,
ApiOperation,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { RefreshTokenDto } from '../components/refresh-token/dtos/create-refresh-token.dto';
import { JwtAuthService } from './jwt/jwt-auth.service';
import { RefreshTokenResponseDto } from '../components/refresh-token/dtos/refresh-token.response.dto';
import { MESSAGES } from '../shared';

@ApiTags('auth')
@Controller('auth')
export class AuthController {
constructor(private jwtAuthService: JwtAuthService) {}
@Post('/refresh-token')
@ApiOperation({ summary: 'Refresh token' })
@ApiOkResponse({
description: 'Return user access tokens.',
type: RefreshTokenResponseDto,
})
@ApiBadRequestResponse({
description: MESSAGES.ERROR.BAD_REQUEST,
})
@ApiResponse({ status: HttpStatus.OK })
async refreshToken(@Body() request: RefreshTokenDto) {
try {
const newToken = await this.jwtAuthService.refreshToken(
request.refreshToken.toString(),
);
return newToken;
} catch (err) {
throw new BadRequestException(err.message);
}
}
}
14 changes: 14 additions & 0 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { GoogleOauthModule } from './google/google-oauth.module';
import { JwtAuthModule } from './jwt/jwt-auth.module';
import { UserModule } from '../components/user/user.module';
import { AuthController } from './auth.controller';
import { ConfigService } from '@nestjs/config';

@Module({
imports: [UserModule, PassportModule, GoogleOauthModule, JwtAuthModule],
providers: [ConfigService],
controllers: [AuthController],
})
export class AuthModule {}
34 changes: 34 additions & 0 deletions src/auth/google/google-oauth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Body, Controller, HttpStatus, Post, HttpCode } from '@nestjs/common';
import {
ApiBadRequestResponse,
ApiOkResponse,
ApiOperation,
ApiTags,
} from '@nestjs/swagger';
import { GoogleOAuthService } from './google-oauth.service';
import { GoogleOAuthLoginParamsDto } from '../../components/google/dtos/google-oauth-login.params.dto';
import { GoogleOAuthLoginResponseDto } from '../../components/google/dtos/google-oauth-login.response.dto';
import { MESSAGES } from '../../shared';

@ApiTags('auth')
@Controller('auth')
@ApiBadRequestResponse({
description: MESSAGES.ERROR.BAD_REQUEST,
})
export class GoogleOauthController {
constructor(private googleOAuthService: GoogleOAuthService) {}

@Post('google')
@ApiOperation({ summary: 'Verify google access token' })
@ApiOkResponse({
description: 'Return user access tokens.',
type: GoogleOAuthLoginResponseDto,
})
@HttpCode(HttpStatus.OK)
async login(
@Body() request: GoogleOAuthLoginParamsDto,
): Promise<GoogleOAuthLoginResponseDto> {
const tokens = await this.googleOAuthService.login(request.token);
return tokens;
}
}
5 changes: 5 additions & 0 deletions src/auth/google/google-oauth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class GoogleOauthGuard extends AuthGuard('google') {}
13 changes: 13 additions & 0 deletions src/auth/google/google-oauth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { JwtAuthModule } from '../jwt/jwt-auth.module';
import { GoogleOauthController } from './google-oauth.controller';
import { UserModule } from '../../components/user/user.module';
import { ConfigModule } from '@nestjs/config';
import { GoogleOAuthService } from './google-oauth.service';

@Module({
imports: [UserModule, JwtAuthModule, ConfigModule],
controllers: [GoogleOauthController],
providers: [GoogleOAuthService],
})
export class GoogleOauthModule {}
Loading

0 comments on commit 8d6d441

Please sign in to comment.