Skip to content

Commit

Permalink
[Recording Oracle] - Refactored (#732)
Browse files Browse the repository at this point in the history
* Added interfaces and enums

* Refactored job service and unit tests

* Refactored services

* Refactored configs

* Added config files

* Resolved comments

* Call StoreResults only once (#733)

* Fixed lint errors

* Updated lint (#783)
  • Loading branch information
eugenvoronov authored Aug 21, 2023
1 parent e8db754 commit 60ecff3
Show file tree
Hide file tree
Showing 44 changed files with 988 additions and 491 deletions.
13 changes: 0 additions & 13 deletions packages/apps/fortune/recording-oracle/.env.sample

This file was deleted.

9 changes: 3 additions & 6 deletions packages/apps/fortune/recording-oracle/.prettierrc
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
{
"arrowParens": "avoid",
"bracketSpacing": true,
"printWidth": 120,
"trailingComma": "all",
"singleQuote": false
}
"singleQuote": true,
"trailingComma": "all"
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { AppController } from "./app.controller";
import { AppController } from './app.controller';

describe("AppController", () => {
describe('AppController', () => {
let appController: AppController;

beforeEach(() => {
appController = new AppController();
});

describe("Health Check", () => {
it("should return OK", async () => {
expect(await appController.health()).toBe("OK");
describe('Health Check', () => {
it('should return OK', async () => {
expect(await appController.health()).toBe('OK');
});
});
});
14 changes: 7 additions & 7 deletions packages/apps/fortune/recording-oracle/src/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { Controller, Get } from "@nestjs/common";
import { ApiTags } from "@nestjs/swagger";
import { Controller, Get } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';

import { Public } from "@/common/decorators";
import { Public } from '@/common/decorators';

@Controller("/")
@Controller('/')
export class AppController {
@Public()
@Get("/")
@ApiTags("Health Check")
@Get('/')
@ApiTags('Health Check')
public health(): string {
return "OK";
return 'OK';
}
}
26 changes: 17 additions & 9 deletions packages/apps/fortune/recording-oracle/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { APP_PIPE } from "@nestjs/core";
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_PIPE } from '@nestjs/core';
import { HttpValidationPipe } from '@/common/pipes';
import { JobModule } from '@/modules/job/job.module';

import { serverConfig } from "@/common/config";
import { HttpValidationPipe } from "@/common/pipes";
import { JobModule } from "@/modules/job/job.module";

import { AppController } from "./app.controller";
import { AppController } from './app.controller';
import {
envValidator,
s3Config,
serverConfig,
web3Config,
} from './common/config';

@Module({
providers: [
Expand All @@ -17,7 +21,11 @@ import { AppController } from "./app.controller";
],
imports: [
ConfigModule.forRoot({
load: [serverConfig],
envFilePath: process.env.NODE_ENV
? `.env.${process.env.NODE_ENV as string}`
: '.env',
validationSchema: envValidator,
load: [serverConfig, s3Config, web3Config],
}),
JobModule,
],
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from "./ethereum.config";
export * from "./server.config";
export * from "./storage.config";
export * from './web3';
export * from './server';
export * from './s3';
export * from './validation';
13 changes: 13 additions & 0 deletions packages/apps/fortune/recording-oracle/src/common/config/s3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { ConfigType, registerAs } from '@nestjs/config';

export const s3Config = registerAs('s3', () => ({
endPoint: process.env.S3_ENDPOINT!,
port: +process.env.S3_PORT!,
accessKey: process.env.S3_ACCESS_KEY!,
secretKey: process.env.S3_SECRET_KEY!,
bucket: process.env.S3_BACKET!,
useSSL: process.env.S3_USE_SSL === 'true',
}));

export const s3ConfigKey = s3Config.KEY;
export type S3ConfigType = ConfigType<typeof s3Config>;

This file was deleted.

11 changes: 11 additions & 0 deletions packages/apps/fortune/recording-oracle/src/common/config/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { ConfigType, registerAs } from '@nestjs/config';

export const serverConfig = registerAs('server', () => ({
host: process.env.HOST!,
port: +process.env.PORT!,
sessionSecret: process.env.SESSION_SECRET!,
feUrl: process.env.FE_URL!,
reputationOracleWebhookUrl: process.env.REPUTATION_ORACLE_WEBHOOK_URL!,
}));
export const serverConfigKey = serverConfig.KEY;
export type ServerConfigType = ConfigType<typeof serverConfig>;

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import * as Joi from 'joi';

export const ConfigNames = {
NODE_ENV: 'NODE_ENV',
HOST: 'HOST',
PORT: 'PORT',
FE_URL: 'FE_URL',
SESSION_SECRET: 'SESSION_SECRET',
WEB3_PRIVATE_KEY: 'WEB3_PRIVATE_KEY',
REPUTATION_ORACLE_WEBHOOK_URL: 'REPUTATION_ORACLE_WEBHOOK_URL',
S3_ENDPOINT: 'S3_ENDPOINT',
S3_PORT: 'S3_PORT',
S3_ACCESS_KEY: 'S3_ACCESS_KEY',
S3_SECRET_KEY: 'S3_SECRET_KEY',
S3_BACKET: 'S3_BACKET',
S3_USE_SSL: 'S3_USE_SSL',
};

export const envValidator = Joi.object({
// General
NODE_ENV: Joi.string().default('development'),
HOST: Joi.string().default('localhost'),
PORT: Joi.string().default(5000),
FE_URL: Joi.string().default('http://localhost:3001'),
SESSION_SECRET: Joi.string().default('session_key'),
// Web3
WEB3_PRIVATE_KEY: Joi.string().required(),
REPUTATION_ORACLE_WEBHOOK_URL: Joi.string().default('http://localhost:4005'),
// S3
S3_ENDPOINT: Joi.string().default('127.0.0.1'),
S3_PORT: Joi.string().default(9000),
S3_ACCESS_KEY: Joi.string().required(),
S3_SECRET_KEY: Joi.string().required(),
S3_BACKET: Joi.string().default('solution'),
S3_USE_SSL: Joi.string().default(false),
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { ConfigType, registerAs } from '@nestjs/config';

export const web3Config = registerAs('web3', () => ({
web3PrivateKey: process.env.WEB3_PRIVATE_KEY!,
}));

export const web3ConfigKey = web3Config.KEY;
export type Web3ConfigType = ConfigType<typeof web3Config>;
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,21 @@
* Represents error messages associated with a job.
*/
export enum ErrorJob {
AddressMismatches = "Escrow Recording Oracle address mismatches the current one",
InvalidStatus = "Escrow is not in the Pending status",
InvalidManifest = "Manifest does not contain the required data",
InvalidJobType = "Manifest contains an invalid job type",
NotFoundIntermediateResultsUrl = "Error while getting intermediate results url from escrow contract",
SolutionAlreadyExists = "Solution already exists",
AllSolutionsHaveAlreadyBeenSent = "All solutions have already been sent",
AddressMismatches = 'Escrow Recording Oracle address mismatches the current one',
InvalidStatus = 'Escrow is not in the Pending status',
InvalidManifest = 'Manifest does not contain the required data',
InvalidJobType = 'Manifest contains an invalid job type',
NotFoundIntermediateResultsUrl = 'Error while getting intermediate results url from escrow contract',
SolutionAlreadyExists = 'Solution already exists',
AllSolutionsHaveAlreadyBeenSent = 'All solutions have already been sent',
WebhookWasNotSent = 'Webhook was not sent',
ManifestNotFound = 'Manifest not found',
}

/**
* Represents error messages related to bucket.
*/
export enum ErrorBucket {
NotPublic = 'Bucket is not public',
UnableSaveFile = 'Unable to save file',
}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { NetworkMapDto } from '../interfaces/network';

export const networkMap: NetworkMapDto = {
polygon: {
chainId: 137,
rpcUrl:
'https://polygon-mainnet.g.alchemy.com/v2/0Lorh5KRkGl5FsRwy2epTg8fEFFoqUfY',
},
bsc: {
chainId: 56,
rpcUrl: 'https://bsc-dataseed1.binance.org/',
},
mumbai: {
chainId: 80001,
rpcUrl:
'https://polygon-mumbai.g.alchemy.com/v2/vKNSJzJf6SW2sdW-05bgFwoyFxUrMzii',
},
goerli: {
chainId: 5,
rpcUrl: 'https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161',
},
moonbeam: {
chainId: 1284,
rpcUrl: 'https://rpc.api.moonbeam.network',
},
bsctest: {
chainId: 97,
rpcUrl: 'https://data-seed-prebsc-1-s1.binance.org:8545/',
},
};

export const networks = Object.values(networkMap).map((network) => network);
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from "./public";
export * from './public';
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { SetMetadata } from "@nestjs/common";
import { SetMetadata } from '@nestjs/common';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const Public = (): ((target: any, key?: any, descriptor?: any) => any) => SetMetadata("isPublic", true);
export const Public = (): ((target: any, key?: any, descriptor?: any) => any) =>
SetMetadata('isPublic', true);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export enum JobRequestType {
FORTUNE = 'FORTUNE',
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from "@nestjs/common";
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
} from '@nestjs/common';

@Catch()
export class GlobalExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();

const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;

response.status(status).json({
statusCode: status,
Expand All @@ -15,7 +24,7 @@ export class GlobalExceptionsFilter implements ExceptionFilter {
? exception.getResponse()
: exception instanceof Error
? exception.message
: "Internal Server Error",
: 'Internal Server Error',
});
}
}
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from "./global-exceptions.filter";
export * from './global-exceptions.filter';
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { ChainId } from '@human-protocol/sdk';
import { JobRequestType } from '../enums/job';

export interface IManifest {
submissionsRequired: number;
requesterTitle: string;
requesterDescription: string;
fundAmount: string;
requestType: JobRequestType;
}

export interface ISolution {
exchangeAddress: string;
workerAddress: string;
solution: string;
}
Loading

0 comments on commit 60ecff3

Please sign in to comment.