Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Oracles-discovery #14

Merged
merged 15 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/apps/human-app/server/.env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
HOST=
PORT=
REPUTATION_ORACLE_URL=
REDIS_PORT=
REDIS_HOST=
CACHE_TTL_ORACLE_DISCOVERY=
E2E_TESTING_EMAIL_ADDRESS=
E2E_TESTING_PASSWORD=
E2E_TESTING_EXCHANGE_ORACLE_URL=
Expand Down
9 changes: 9 additions & 0 deletions packages/apps/human-app/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,24 @@
"@automapper/classes": "^8.8.1",
"@automapper/core": "^8.8.1",
"@automapper/nestjs": "^8.8.1",
"@human-protocol/sdk": "*",
"@nestjs/axios": "^2.0.0",
"@nestjs/cache-manager": "^2.2.1",
"@nestjs/common": "^10.2.7",
"@nestjs/config": "^3.1.1",
"@nestjs/core": "^10.2.8",
"@nestjs/platform-express": "^10.2.6",
"@nestjs/swagger": "^7.1.13",
"cache-manager": "^5.4.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"ethers": "^6.11.0",
"joi": "^17.12.2",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.2.0"
},
"devDependencies": {
"@nestjs/cache-manager": "^2.2.1",
"@nestjs/cli": "^9.4.3",
"@nestjs/schematics": "^9.2.0",
"@nestjs/testing": "^9.4.3",
Expand All @@ -43,9 +50,11 @@
"@types/supertest": "^2.0.15",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"cache-manager-redis-store": "^3.0.1",
"eslint": "^8.55.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.0.0",
"ioredis": "^5.3.2",
"jest": "29.5.0",
"nock": "^13.5.1",
"prettier": "^3.1.1",
Expand Down
7 changes: 7 additions & 0 deletions packages/apps/human-app/server/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import { OperatorModule } from './modules/user-operator/operator.module';
import { OperatorController } from './modules/user-operator/operator.controller';
import { WorkerController } from './modules/user-worker/worker.controller';
import { CommonConfigModule } from './common/config/common-config.module';
import { CacheFactoryConfig } from './common/config/cache-factory.config';
import { CacheModule } from '@nestjs/cache-manager';
import { OracleDiscoveryController } from './modules/oracle-discovery/oracle-discovery.controller';
import { OracleDiscoveryModule } from './modules/oracle-discovery/oracle-discovery.module';
import { JobsDiscoveryModule } from './modules/jobs-discovery/jobs-discovery.module';
import { JobsDiscoveryController } from './modules/jobs-discovery/jobs-discovery.controller';
import { JobAssignmentController } from './modules/job-assignment/job-assignment.controller';
Expand All @@ -26,19 +30,22 @@ import { JobAssignmentModule } from './modules/job-assignment/job-assignment.mod
AutomapperModule.forRoot({
strategyInitializer: classes(),
}),
CacheModule.registerAsync(CacheFactoryConfig),
HttpModule,
WorkerModule,
OperatorModule,
JobsDiscoveryModule,
JobAssignmentModule,
ReputationOracleModule,
CommonConfigModule,
OracleDiscoveryModule,
],
controllers: [
AppController,
OperatorController,
WorkerController,
JobsDiscoveryController,
OracleDiscoveryController,
JobAssignmentController,
],
providers: [],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { CacheModuleAsyncOptions } from '@nestjs/common/cache';
import { ConfigModule } from '@nestjs/config';
import { EnvironmentConfigService } from './environment-config.service';
import { redisStore } from 'cache-manager-redis-store';
export const CacheFactoryConfig: CacheModuleAsyncOptions = {
isGlobal: true,
imports: [ConfigModule],
useFactory: async (configService: EnvironmentConfigService) => {
const store = await redisStore({
socket: {
host: configService.cacheHost,
port: configService.cachePort,
},
});
return {
store: () => store,
};
},
inject: [EnvironmentConfigService],
};
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ export class EnvironmentConfigService {
get reputationOracleUrl(): string {
return this.configService.get<string>('REPUTATION_ORACLE_URL', '');
}
get cachePort(): number {
return this.configService.get<number>('REDIS_PORT', 6379);
}
get cacheHost(): string {
return this.configService.get<string>('REDIS_HOST', 'localhost');
}

get cacheTtlOracleDiscovery(): number {
return this.configService.get<number>(
'CACHE_TTL_ORACLE_DISCOVERY',
24 * 60 * 60,
);
}
}

export const envValidator = Joi.object({
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { ChainId, IOperator } from '@human-protocol/sdk';
import { AutoMap } from '@automapper/classes';
import { ApiProperty } from '@nestjs/swagger';

export class OracleDiscoveryDto {
@AutoMap()
@ApiProperty({ example: 80001 })
chainId: ChainId;
@AutoMap()
@ApiProperty({ example: '0x1a23b23432cf23f09f3f' })
address: string;
@AutoMap()
@ApiProperty({ example: 'Exchange Oracle' })
role: string;
constructor(chainId: ChainId, address: string, role: string) {
this.chainId = chainId;
this.address = address;
this.role = role;
}
}
export class OracleDiscoveryCommand {
@AutoMap()
chainId: ChainId;
@AutoMap()
address: string;
@AutoMap()
role: string;
}

export class OracleDiscoveryResponse implements IOperator {
address: string;
role?: string;
constructor(address: string, role: string) {
this.address = address;
this.role = role;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import {
Body,
Controller,
Get,
Logger,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { Mapper } from '@automapper/core';
import { InjectMapper } from '@automapper/nestjs';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { OracleDiscoveryService } from './oracle-discovery.serivce';
import {
OracleDiscoveryCommand,
OracleDiscoveryResponse,
OracleDiscoveryDto,
} from './interface/oracle-discovery.interface';

@Controller()
export class OracleDiscoveryController {
logger = new Logger(OracleDiscoveryController.name);
constructor(
private readonly service: OracleDiscoveryService,
@InjectMapper() private readonly mapper: Mapper,
) {}
@ApiTags('Oracle-Discovery')
@Get('/oracles')
macnablocky marked this conversation as resolved.
Show resolved Hide resolved
@ApiOperation({ summary: 'Operator signup' })
macnablocky marked this conversation as resolved.
Show resolved Hide resolved
@UsePipes(new ValidationPipe())
public oracleDiscovery(
@Body() oracleDiscoveryDto: OracleDiscoveryDto,
): Promise<OracleDiscoveryResponse[]> {
this.logger.log(
macnablocky marked this conversation as resolved.
Show resolved Hide resolved
`Oracle Discovery request: {
chainId: ${oracleDiscoveryDto.chainId},
address: ${oracleDiscoveryDto.address},
role: ${oracleDiscoveryDto.role}
}`,
);
const oracleDiscoveryCommand = this.mapper.map(
oracleDiscoveryDto,
OracleDiscoveryDto,
OracleDiscoveryCommand,
);
return this.service.processOracleDiscovery(oracleDiscoveryCommand);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Injectable } from '@nestjs/common';
import { AutomapperProfile, InjectMapper } from '@automapper/nestjs';
import { createMap, Mapper } from '@automapper/core';
import {
OracleDiscoveryCommand,
OracleDiscoveryDto,
} from './interface/oracle-discovery.interface';

@Injectable()
export class OracleDiscoveryProfile extends AutomapperProfile {
constructor(@InjectMapper() mapper: Mapper) {
super(mapper);
}

override get profile() {
return (mapper: Mapper) => {
createMap(mapper, OracleDiscoveryDto, OracleDiscoveryCommand);
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { OracleDiscoveryController } from './oracle-discovery.controller';
import { OracleDiscoveryService } from './oracle-discovery.serivce';
import { OracleDiscoveryProfile } from './oracle-discovery.mapper';

@Module({
controllers: [OracleDiscoveryController],
providers: [OracleDiscoveryService, OracleDiscoveryProfile],
exports: [OracleDiscoveryService],
})
export class OracleDiscoveryModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Inject, Injectable, Logger } from '@nestjs/common';
import {
OracleDiscoveryCommand,
OracleDiscoveryResponse,
} from './interface/oracle-discovery.interface';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { OperatorUtils } from '@human-protocol/sdk';
import { EnvironmentConfigService } from '../../common/config/environment-config.service';
@Injectable()
export class OracleDiscoveryService {
logger = new Logger(OracleDiscoveryService.name);
constructor(
@Inject(CACHE_MANAGER) private cacheManager: Cache,
private configService: EnvironmentConfigService,
) {}

async processOracleDiscovery(
command: OracleDiscoveryCommand,
): Promise<OracleDiscoveryResponse[]> {
let data: OracleDiscoveryResponse[] | undefined =
await this.cacheManager.get(command.address);
if (!data) {
data = await this.getOperatorsForOracleDiscovery(command);
await this.setOperatorsForAddress(command.address, data);
}
this.logger.log(`Returning data: ${JSON.stringify(data)}`);
return data;
}

async getOperatorsForOracleDiscovery(
cmd: OracleDiscoveryCommand,
): Promise<OracleDiscoveryResponse[]> {
return OperatorUtils.getReputationNetworkOperators(
cmd.chainId,
cmd.address,
cmd.role,
);
}
async setOperatorsForAddress(
address: string,
operators: OracleDiscoveryResponse[],
): Promise<void> {
return this.cacheManager.set(
address,
operators,
this.configService.cacheTtlOracleDiscovery,
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AutomapperModule } from '@automapper/nestjs';
import { classes } from '@automapper/classes';
import { OracleDiscoveryController } from '../oracle-discovery.controller';
import { OracleDiscoveryService } from '../oracle-discovery.serivce';
import { oracleDiscoveryServiceMock } from './oracle-discovery.service.mock';
import { OracleDiscoveryProfile } from '../oracle-discovery.mapper';
import {
OracleDiscoveryCommand,
OracleDiscoveryResponse,
OracleDiscoveryDto,
} from '../interface/oracle-discovery.interface';
import { ChainId } from '@human-protocol/sdk';
import { generateOracleDiscoveryResponseBody } from '../../../../test/fixtures/oracle-discovery.fixture';

describe('OracleDiscoveryController', () => {
let controller: OracleDiscoveryController;
let service: OracleDiscoveryService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [OracleDiscoveryController],
imports: [
AutomapperModule.forRoot({
strategyInitializer: classes(),
}),
],
providers: [OracleDiscoveryService, OracleDiscoveryProfile],
})
.overrideProvider(OracleDiscoveryService)
.useValue(oracleDiscoveryServiceMock)
.compile();

controller = module.get<OracleDiscoveryController>(
OracleDiscoveryController,
);
service = module.get<OracleDiscoveryService>(OracleDiscoveryService);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});

describe('oracle discovery', () => {
it('oracle discovery should be called with input in OracleDiscoveryDto format and return OracleDiscoveryData', async () => {
const dto: OracleDiscoveryDto = {
chainId: 80001,
address: '0x4708354213453af0cdC33eb75d94fBC00045841E',
role: 'Exchange Oracle',
};
const result: OracleDiscoveryResponse[] =
await controller.oracleDiscovery(dto);
const expectedCommand = {
chainId: ChainId.POLYGON_MUMBAI,
address: dto.address,
role: 'Exchange Oracle',
} as OracleDiscoveryCommand;
expect(service.processOracleDiscovery).toHaveBeenCalledWith(
expectedCommand,
);
const expectedResponse = generateOracleDiscoveryResponseBody();
expect(result).toEqual(expectedResponse);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { generateOracleDiscoveryResponseBody } from '../../../../test/fixtures/oracle-discovery.fixture';
macnablocky marked this conversation as resolved.
Show resolved Hide resolved

export const oracleDiscoveryServiceMock = {
processOracleDiscovery: jest
.fn()
.mockResolvedValue(generateOracleDiscoveryResponseBody()),
};
Loading
Loading