Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { faker } from '@faker-js/faker';
import { createMock } from '@golevelup/ts-jest';
import { EscrowClient } from '@human-protocol/sdk';
import { Test } from '@nestjs/testing';
import { ethers } from 'ethers';
import _ from 'lodash';

import { CvatAnnotationMeta } from '@/common/types';
Expand Down Expand Up @@ -48,14 +47,24 @@ describe('CvatPayoutsCalculator', () => {
const mockedGetIntermediateResultsUrl = jest
.fn()
.mockImplementation(async () => faker.internet.url());
const mockedGetTokenAddress = jest.fn().mockImplementation(async () => {
return faker.finance.ethereumAddress();
});
const mockedGetReservedFunds = jest
.fn()
.mockImplementation(async () =>
BigInt(faker.number.int({ min: 1000, max: 100000 })),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's not mock default with some random number, because it can confuse in case of incorrect/failing test suite, it's better to mimic real behavior (i.e. funds not reserved) which returns 0n

Suggested change
BigInt(faker.number.int({ min: 1000, max: 100000 })),
0n,

);

beforeAll(() => {
mockedEscrowClient.build.mockResolvedValue({
getIntermediateResultsUrl: mockedGetIntermediateResultsUrl,
getTokenAddress: mockedGetTokenAddress,
getReservedFunds: mockedGetReservedFunds,
} as unknown as EscrowClient);
});

afterEach(() => {
jest.resetAllMocks();
mockedEscrowClient.build.mockResolvedValue({
getIntermediateResultsUrl: mockedGetIntermediateResultsUrl,
getReservedFunds: mockedGetReservedFunds,
} as unknown as EscrowClient);
});
Comment on lines +63 to 69

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need in this block

Suggested change
afterEach(() => {
jest.resetAllMocks();
mockedEscrowClient.build.mockResolvedValue({
getIntermediateResultsUrl: mockedGetIntermediateResultsUrl,
getReservedFunds: mockedGetReservedFunds,
} as unknown as EscrowClient);
});


Expand Down Expand Up @@ -84,23 +93,22 @@ describe('CvatPayoutsCalculator', () => {
);
});

it('should properly calculate workers bounties trimming the decimals', async () => {
it('should properly calculate workers bounties', async () => {
const annotators = [
faker.finance.ethereumAddress(),
faker.finance.ethereumAddress(),
];

const jobsPerAnnotator = faker.number.int({ min: 1, max: 3 });
const tokenDecimals = BigInt(6);
const jobCount = jobsPerAnnotator * annotators.length;
const payoutPerJob = BigInt(faker.number.int({ min: 1000, max: 100000 }));
const reservedFunds = payoutPerJob * BigInt(jobCount);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const reservedFunds = payoutPerJob * BigInt(jobCount);
mockedGetReservedFunds.mockResolvedValueOnce(payoutPerJob * BigInt(jobCount));


const annotationsMeta: CvatAnnotationMeta = {
jobs: Array.from(
{ length: jobsPerAnnotator * annotators.length },
(_v, index: number) => ({
job_id: index,
final_result_id: faker.number.int(),
}),
),
jobs: Array.from({ length: jobCount }, (_v, index: number) => ({
job_id: index,
final_result_id: faker.number.int(),
})),
results: [],
};
for (const job of annotationsMeta.jobs) {
Expand Down Expand Up @@ -130,26 +138,19 @@ describe('CvatPayoutsCalculator', () => {
mockedStorageService.downloadJsonLikeData.mockResolvedValueOnce(
annotationsMeta,
);
mockedWeb3Service.getTokenDecimals.mockResolvedValueOnce(tokenDecimals);

const mockedJobBounty = '0.123456789'; // more decimals than token has
const manifest = {
...generateCvatManifest(),
job_bounty: mockedJobBounty,
};

mockedGetReservedFunds.mockResolvedValueOnce(reservedFunds);
const manifest = generateCvatManifest();
const payouts = await calculator.calculate({
chainId,
escrowAddress,
manifest,
manifest: manifest,
finalResultsUrl: faker.internet.url(),
});
Comment on lines +142 to 149

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
mockedGetReservedFunds.mockResolvedValueOnce(reservedFunds);
const manifest = generateCvatManifest();
const payouts = await calculator.calculate({
chainId,
escrowAddress,
manifest,
manifest: manifest,
finalResultsUrl: faker.internet.url(),
});
const payouts = await calculator.calculate({
chainId,
escrowAddress,
manifest: generateCvatManifest(),
finalResultsUrl: faker.internet.url(),
});


const trimmedBounty = '0.123456';

const expectedJobBounty = payoutPerJob;
const expectedAmountPerAnnotator =
BigInt(jobsPerAnnotator) *
ethers.parseUnits(trimmedBounty, tokenDecimals);
BigInt(jobsPerAnnotator) * expectedJobBounty;

const expectedPayouts = annotators.map((address) => ({
address,
Expand All @@ -168,7 +169,9 @@ describe('CvatPayoutsCalculator', () => {
];

const jobsPerAnnotator = faker.number.int({ min: 1, max: 3 });
const tokenDecimals = BigInt(faker.number.int({ min: 6, max: 18 }));
const reservedFunds = BigInt(
faker.number.int({ min: 1000, max: 100000 }).toString(),
);

const annotationsMeta: CvatAnnotationMeta = {
jobs: Array.from(
Expand Down Expand Up @@ -207,7 +210,7 @@ describe('CvatPayoutsCalculator', () => {
mockedStorageService.downloadJsonLikeData.mockResolvedValueOnce(
annotationsMeta,
);
mockedWeb3Service.getTokenDecimals.mockResolvedValueOnce(tokenDecimals);
mockedGetReservedFunds.mockResolvedValueOnce(reservedFunds);

const manifest = generateCvatManifest();

Expand All @@ -218,9 +221,14 @@ describe('CvatPayoutsCalculator', () => {
finalResultsUrl: faker.internet.url(),
});

const matchedJobCount = annotationsMeta.jobs.filter((job) =>
annotationsMeta.results.some(
(result) => result.id === job.final_result_id,
),
).length;
const expectedJobBounty = reservedFunds / BigInt(matchedJobCount);
const expectedAmountPerAnnotator =
BigInt(jobsPerAnnotator) *
ethers.parseUnits(manifest.job_bounty, tokenDecimals);
BigInt(jobsPerAnnotator) * expectedJobBounty;

const expectedPayouts = annotators.map((address) => ({
address,
Expand All @@ -231,5 +239,33 @@ describe('CvatPayoutsCalculator', () => {
_.sortBy(expectedPayouts, 'address'),
);
});

it('throws when there are no jobs with matching final results', async () => {
mockedStorageService.downloadJsonLikeData.mockResolvedValueOnce({
jobs: [
{
job_id: faker.number.int(),
final_result_id: faker.number.int(),
},
],
results: [
{
id: faker.number.int(),
job_id: faker.number.int(),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even though we use faker there, there is a very little chance that faker.number.int() will generate final_result_id = result.id, so for the purpose of this test let's make sure somehow that those ids are 100% different

annotator_wallet_address: faker.finance.ethereumAddress(),
annotation_quality: faker.number.float(),
},
],
} as CvatAnnotationMeta);

await expect(
calculator.calculate({
chainId,
escrowAddress,
manifest: generateCvatManifest(),
finalResultsUrl: faker.internet.url(),
}),
).rejects.toThrow('Invalid annotation meta');
});
});
});
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { EscrowClient } from '@human-protocol/sdk';
import { Injectable } from '@nestjs/common';
import { ethers } from 'ethers';
import type { OverrideProperties } from 'type-fest';

import { CVAT_VALIDATION_META_FILENAME } from '@/common/constants';
Expand All @@ -27,7 +26,6 @@ export class CvatPayoutsCalculator implements EscrowPayoutsCalculator {
) {}

async calculate({
manifest,
chainId,
escrowAddress,
}: CalculateCvatPayoutsInput): Promise<CalculatedPayout[]> {
Expand All @@ -41,26 +39,28 @@ export class CvatPayoutsCalculator implements EscrowPayoutsCalculator {
await this.storageService.downloadJsonLikeData<CvatAnnotationMeta>(
`${intermediateResultsUrl}/${CVAT_VALIDATION_META_FILENAME}`,
);

if (!annotations.jobs.length || !annotations.results.length) {
throw new Error('Invalid annotation meta');
}

const tokenAddress = await escrowClient.getTokenAddress(escrowAddress);
const tokenDecimals = await this.web3Service.getTokenDecimals(
chainId,
tokenAddress,
);
const jobBountyValue = this.parseJobBounty(
manifest.job_bounty,
Number(tokenDecimals),
);
const workersBounties = new Map<string, bigint>();
const reservedFunds = await escrowClient.getReservedFunds(escrowAddress);

for (const job of annotations.jobs) {
const jobFinalResult = annotations.results.find(
(result) => result.id === job.final_result_id,
const matchedJobResults = annotations.jobs
.map((job) =>
annotations.results.find((result) => result.id === job.final_result_id),
)
.filter((result): result is CvatAnnotationMeta['results'][number] =>
Boolean(result),
);

if (!matchedJobResults.length) {
throw new Error('Invalid annotation meta');
}

const jobBountyValue = reservedFunds / BigInt(matchedJobResults.length);
const workersBounties = new Map<string, bigint>();

for (const jobFinalResult of matchedJobResults) {
// TODO: enable annotation quality validation when ready
if (

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already filtered above, so probably we can remove this check on jobFilanResult

jobFinalResult
Expand All @@ -84,21 +84,4 @@ export class CvatPayoutsCalculator implements EscrowPayoutsCalculator {
}),
);
}

private parseJobBounty(jobBounty: string, tokenDecimals: number): bigint {
const parts = jobBounty.split('.');
if (parts.length > 1) {
const decimalsInBounty = parts[1].length;
if (decimalsInBounty > tokenDecimals) {
if (tokenDecimals === 0) {
return ethers.parseUnits(parts[0], tokenDecimals);
}
return ethers.parseUnits(
`${parts[0]}.${parts[1].slice(0, tokenDecimals)}`,
tokenDecimals,
);
}
}
return ethers.parseUnits(jobBounty, tokenDecimals);
}
}
Loading