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

[Job Launcher] Refactor nested services dependencies #747

Merged
merged 1 commit into from
Aug 3, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
30 changes: 30 additions & 0 deletions packages/apps/job-launcher/server/src/common/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { firstValueFrom } from "rxjs";
import { CoingeckoTokenId } from "../constants/payment";
import { TokenId } from "../enums/payment";
import { COINGECKO_API_URL } from "../constants";
import { NotFoundException } from "@nestjs/common";
import { ErrorCurrency } from "../constants/errors";

export async function getRate(from: string, to: string): Promise<number> {
let reversed = false;

if (Object.values(TokenId).includes(to as TokenId)) {
[from, to] = [CoingeckoTokenId[to], from];
} else {
reversed = true;
}

const { data } = await firstValueFrom(
this.httpService.get(
`${COINGECKO_API_URL}?ids=${from}&vs_currencies=${to}`,
),
) as any;

if (!data[from] || !data[from][to]) {
throw new NotFoundException(ErrorCurrency.PairNotFound);
}

const rate = data[from][to];

return reversed ? 1 / rate : rate;
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import { JobRepository } from './job.repository';
import { JobService } from './job.service';

import { HMToken__factory } from '@human-protocol/core/typechain-types';
import { CurrencyService } from '../payment/currency.service';
import { PaymentRepository } from '../payment/payment.repository';

jest.mock('@human-protocol/sdk', () => ({
...jest.requireActual('@human-protocol/sdk'),
Expand All @@ -61,11 +61,16 @@ jest.mock('@human-protocol/sdk', () => ({
})),
}));

jest.mock('../../common/utils', () => ({
getRate: jest.fn().mockImplementation(() => 0.5)
}));

describe('JobService', () => {
let jobService: JobService;
let jobRepository: JobRepository;
let paymentService: PaymentService;
let currencyService: CurrencyService;
let jobService: JobService,
jobRepository: JobRepository,
paymentRepository: PaymentRepository,
paymentService: PaymentService,
createPaymentMock: any;

const signerMock = {
address: MOCK_ADDRESS,
Expand Down Expand Up @@ -109,18 +114,19 @@ describe('JobService', () => {
getSigner: jest.fn().mockReturnValue(signerMock),
},
},
{ provide: CurrencyService, useValue: createMock<CurrencyService>() },
{ provide: JobRepository, useValue: createMock<JobRepository>() },
{ provide: PaymentRepository, useValue: createMock<PaymentRepository>() },
{ provide: PaymentService, useValue: createMock<PaymentService>() },
{ provide: ConfigService, useValue: mockConfigService },
{ provide: HttpService, useValue: createMock<HttpService>() },
],
}).compile();

currencyService = moduleRef.get(CurrencyService);
jobService = moduleRef.get<JobService>(JobService);
jobRepository = moduleRef.get(JobRepository);
paymentRepository = moduleRef.get(PaymentRepository);
paymentService = moduleRef.get(PaymentService);
createPaymentMock = jest.spyOn(paymentRepository, 'create');
});

describe('createFortuneJob', () => {
Expand All @@ -138,9 +144,7 @@ describe('JobService', () => {

beforeEach(() => {
getUserBalanceMock = jest.spyOn(paymentService, 'getUserBalance');

jest.spyOn(currencyService, 'getRate').mockResolvedValue(rate);
jest.spyOn(paymentService, 'savePayment').mockResolvedValue(true);
createPaymentMock.mockResolvedValue(true);
});

afterEach(() => {
Expand Down Expand Up @@ -171,14 +175,14 @@ describe('JobService', () => {
await jobService.createFortuneJob(userId, dto);

expect(paymentService.getUserBalance).toHaveBeenCalledWith(userId);
expect(paymentService.savePayment).toHaveBeenCalledWith(
expect(paymentRepository.create).toHaveBeenCalledWith({
userId,
PaymentSource.BALANCE,
Currency.USD,
TokenId.HMT,
PaymentType.WITHDRAWAL,
usdTotalAmount,
);
source: PaymentSource.BALANCE,
type: PaymentType.WITHDRAWAL,
currency: TokenId.HMT,
amount: usdTotalAmount.toString(),
rate: 0.5
});
expect(jobRepository.create).toHaveBeenCalledWith({
chainId: dto.chainId,
userId,
Expand Down Expand Up @@ -250,6 +254,8 @@ describe('JobService', () => {
.spyOn(HMToken__factory, 'connect')
.mockReturnValue(mockTokenContract);
getManifestMock = jest.spyOn(jobService, 'getManifest');

createPaymentMock.mockResolvedValue(true);
});

afterEach(() => {
Expand Down
40 changes: 20 additions & 20 deletions packages/apps/job-launcher/server/src/modules/job/job.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import {
ChainId,
EscrowClient,
NETWORKS,
StakingClient,
StorageClient,
StorageCredentials,
StorageParams,
Expand Down Expand Up @@ -53,7 +52,8 @@ import {
HMToken,
HMToken__factory,
} from '@human-protocol/core/typechain-types';
import { CurrencyService } from '../payment/currency.service';
import { PaymentRepository } from '../payment/payment.repository';
import { getRate } from '../../common/utils';

@Injectable()
export class JobService {
Expand All @@ -66,8 +66,8 @@ export class JobService {
@Inject(Web3Service)
private readonly web3Service: Web3Service,
public readonly jobRepository: JobRepository,
public readonly paymentService: PaymentService,
private readonly currencyService: CurrencyService,
private readonly paymentRepository: PaymentRepository,
private readonly paymentService: PaymentService,
public readonly httpService: HttpService,
public readonly configService: ConfigService,
) {
Expand Down Expand Up @@ -111,7 +111,7 @@ export class JobService {
'ether',
);

const rate = await this.currencyService.getRate(Currency.USD, TokenId.HMT);
const rate = await getRate(Currency.USD, TokenId.HMT);

const jobLauncherFee = BigNumber.from(
this.configService.get<number>(ConfigNames.JOB_LAUNCHER_FEE)!,
Expand Down Expand Up @@ -159,14 +159,14 @@ export class JobService {
throw new NotFoundException(ErrorJob.NotCreated);
}

await this.paymentService.savePayment(
await this.paymentRepository.create({
userId,
PaymentSource.BALANCE,
Currency.USD,
TokenId.HMT,
PaymentType.WITHDRAWAL,
usdTotalAmount,
);
source: PaymentSource.BALANCE,
type: PaymentType.WITHDRAWAL,
amount: usdTotalAmount.toString(),
currency: TokenId.HMT,
rate
})

jobEntity.status = JobStatus.PAID;
await jobEntity.save();
Expand All @@ -192,7 +192,7 @@ export class JobService {
'ether',
);

const rate = await this.currencyService.getRate(Currency.USD, TokenId.HMT);
const rate = await getRate(Currency.USD, TokenId.HMT);

const jobLauncherFee = BigNumber.from(
this.configService.get<number>(ConfigNames.JOB_LAUNCHER_FEE)!,
Expand Down Expand Up @@ -242,14 +242,14 @@ export class JobService {
throw new NotFoundException(ErrorJob.NotCreated);
}

await this.paymentService.savePayment(
await this.paymentRepository.create({
userId,
PaymentSource.BALANCE,
Currency.USD,
TokenId.HMT,
PaymentType.WITHDRAWAL,
usdTotalAmount,
);
source: PaymentSource.BALANCE,
type: PaymentType.WITHDRAWAL,
amount: usdTotalAmount.toString(),
currency: TokenId.HMT,
rate
})

jobEntity.status = JobStatus.PAID;
await jobEntity.save();
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ import {
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from 'src/common/guards';

import { CurrencyService } from './currency.service';
import {
GetRateDto,
PaymentCryptoCreateDto,
PaymentFiatConfirmDto,
PaymentFiatCreateDto,
} from './payment.dto';
import { PaymentService } from './payment.service';
import { getRate } from '../../common/utils';

@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
Expand All @@ -26,7 +26,6 @@ import { PaymentService } from './payment.service';
export class PaymentController {
constructor(
private readonly paymentService: PaymentService,
private readonly currencyService: CurrencyService,
) {}

@Post('/fiat')
Expand Down Expand Up @@ -59,7 +58,7 @@ export class PaymentController {
@Get('/rates')
public async getRate(@Query() data: GetRateDto): Promise<number> {
try {
return this.currencyService.getRate(data.currency, data.token);
return getRate(data.currency, data.token);
} catch (e) {
throw new Error(e);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Module } from '@nestjs/common';

import { PaymentService } from './payment.service';
import { CurrencyService } from './currency.service';
import { MinioModule } from 'nestjs-minio-client';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { PaymentEntity } from './payment.entity';
Expand Down Expand Up @@ -32,7 +31,7 @@ import { Web3Module } from '../web3/web3.module';
}),
],
controllers: [PaymentController],
providers: [PaymentService, PaymentRepository, CurrencyService],
exports: [PaymentService, CurrencyService],
providers: [PaymentService, PaymentRepository],
exports: [PaymentService, PaymentRepository],
})
export class PaymentModule {}
Loading