Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,12 @@ export const dailyHmtSpentResponseSchema = z.object({

export const hcaptchaUserStatsResponseSchema = z.object({
balance: z.object({
available: z.number(),
estimated: z.number(),
recent: z.number(),
total: z.number(),
}),
served: z.number(),
solved: z.number(),
verified: z.number(),
currentDateStats: z.object({
billing_units: z.number(),
bypass: z.number(),
served: z.number(),
solved: z.number(),
}),
currentEarningsStats: z.number(),
});
38 changes: 28 additions & 10 deletions packages/apps/job-launcher/server/src/common/constants/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,46 +15,64 @@ export const TOKEN_ADDRESSES: {
address: NETWORKS[ChainId.MAINNET]!.hmtAddress,
decimals: 18,
},
// [EscrowFundToken.USDT]: { address: '0xdAC17F958D2ee523a2206206994597C13D831ec7', decimals: 6 },
// [EscrowFundToken.USDC]: { address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606EB48', decimals: 6 },
[EscrowFundToken.USDT]: {
address: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
decimals: 6,
},
[EscrowFundToken.USDC]: {
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
decimals: 6,
},
},
[ChainId.SEPOLIA]: {
[EscrowFundToken.HMT]: {
address: NETWORKS[ChainId.SEPOLIA]!.hmtAddress,
decimals: 18,
},
// [EscrowFundToken.USDT]: { address: '0xaA8E23Fb1079EA71e0a56F48a2aA51851D8433D0', decimals: 6 },
// [EscrowFundToken.USDC]: { address: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', decimals: 6 },
[EscrowFundToken.USDT]: {
address: '0xaA8E23Fb1079EA71e0a56F48a2aA51851D8433D0',
decimals: 6,
},
[EscrowFundToken.USDC]: {
address: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238',
decimals: 6,
},
},
[ChainId.BSC_MAINNET]: {
[EscrowFundToken.HMT]: {
address: NETWORKS[ChainId.BSC_MAINNET]!.hmtAddress,
decimals: 18,
},
// [EscrowFundToken.USDT]: { address: '0x55d398326f99059fF775485246999027B3197955', decimals: 18 },
// [EscrowFundToken.USDC]: { address: '0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d', decimals: 18 },
},
[ChainId.POLYGON]: {
[EscrowFundToken.HMT]: {
address: NETWORKS[ChainId.POLYGON]!.hmtAddress,
decimals: 18,
},
// [EscrowFundToken.USDT]: { address: '0x3813e82e6f7098b9583FC0F33a962D02018B6803', decimals: 6 },
// [EscrowFundToken.USDC]: { address: '0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174', decimals: 6 },
[EscrowFundToken.USDT]: {
address: '0xc2132D05D31c914a87C6611C10748AEb04B58e8F',
decimals: 6,
},
[EscrowFundToken.USDC]: {
address: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',
decimals: 6,
},
},
[ChainId.POLYGON_AMOY]: {
[EscrowFundToken.HMT]: {
address: NETWORKS[ChainId.POLYGON_AMOY]!.hmtAddress,
decimals: 18,
},
// [EscrowFundToken.USDC]: { address: '0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582', decimals: 6 },
[EscrowFundToken.USDC]: {
address: '0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582',
decimals: 6,
},
},
[ChainId.AURORA_TESTNET]: {
[EscrowFundToken.HMT]: {
address: NETWORKS[ChainId.AURORA_TESTNET]!.hmtAddress,
decimals: 18,
},
// [EscrowFundToken.USDC]: { address: '0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582', decimals: 6 },
},
[ChainId.LOCALHOST]: {
[EscrowFundToken.HMT]: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ export class PaymentService {
}

const signer = this.web3Service.getSigner(dto.chainId);
const tokenAddress = transaction.logs[0].address;
const tokenAddress = transaction.logs[0].address.toLowerCase();

const tokenContract: HMToken = HMToken__factory.connect(
tokenAddress,
Expand All @@ -262,7 +262,10 @@ export class PaymentService {
const tokenId = (await tokenContract.symbol()).toLowerCase();
const token = TOKEN_ADDRESSES[dto.chainId]?.[tokenId as EscrowFundToken];

if (token?.address !== tokenAddress || !CoingeckoTokenId[tokenId]) {
if (
token?.address?.toLowerCase() !== tokenAddress ||
!CoingeckoTokenId[tokenId]
) {
throw new ConflictError(ErrorPayment.UnsupportedToken);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,14 @@ describe('CvatPayoutsCalculator', () => {
const mockedGetIntermediateResultsUrl = jest
.fn()
.mockImplementation(async () => faker.internet.url());
const mockedGetTokenAddress = jest.fn().mockImplementation(async () => {
return faker.finance.ethereumAddress();
});

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

Expand Down Expand Up @@ -80,13 +84,91 @@ describe('CvatPayoutsCalculator', () => {
);
});

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

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

const annotationsMeta: CvatAnnotationMeta = {
jobs: Array.from(
{ length: jobsPerAnnotator * annotators.length },
(_v, index: number) => ({
job_id: index,
final_result_id: faker.number.int(),
}),
),
results: [],
};
for (const job of annotationsMeta.jobs) {
const annotatorIndex = job.job_id % annotators.length;

annotationsMeta.results.push({
id: job.final_result_id,
job_id: job.job_id,
annotator_wallet_address: annotators[annotatorIndex],
annotation_quality: faker.number.float(),
});
}

// imitate weird case: job w/o result
annotationsMeta.jobs.push({
job_id: faker.number.int(),
final_result_id: faker.number.int(),
});
// imitate weird case: result w/o job
annotationsMeta.results.push({
id: faker.number.int(),
job_id: faker.number.int(),
annotator_wallet_address: faker.helpers.arrayElement(annotators),
annotation_quality: faker.number.float(),
});

mockedStorageService.downloadJsonLikeData.mockResolvedValueOnce(
annotationsMeta,
);
mockedWeb3Service.getTokenDecimals.mockResolvedValueOnce(tokenDecimals);

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

const payouts = await calculator.calculate({
chainId,
escrowAddress,
manifest,
finalResultsUrl: faker.internet.url(),
});

const trimmedBounty = '0.123456';

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

const expectedPayouts = annotators.map((address) => ({
address,
amount: expectedAmountPerAnnotator,
}));

expect(_.sortBy(payouts, 'address')).toEqual(
_.sortBy(expectedPayouts, 'address'),
);
});

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(faker.number.int({ min: 6, max: 18 }));

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

const manifest = generateCvatManifest();

Expand All @@ -136,7 +219,8 @@ describe('CvatPayoutsCalculator', () => {
});

const expectedAmountPerAnnotator =
BigInt(jobsPerAnnotator) * ethers.parseUnits(manifest.job_bounty, 18);
BigInt(jobsPerAnnotator) *
ethers.parseUnits(manifest.job_bounty, tokenDecimals);

const expectedPayouts = annotators.map((address) => ({
address,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,15 @@ export class CvatPayoutsCalculator implements EscrowPayoutsCalculator {
throw new Error('Invalid annotation meta');
}

const jobBountyValue = ethers.parseUnits(manifest.job_bounty, 18);
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>();

for (const job of annotations.jobs) {
Expand Down Expand Up @@ -76,4 +84,21 @@ 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);
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
jest.mock('@human-protocol/sdk');

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 { StorageService } from '@/modules/storage';
import { Web3Service } from '@/modules/web3';

import { generateFortuneManifest, generateFortuneSolution } from '../fixtures';
import { FortunePayoutsCalculator } from './fortune-payouts-calculator';

const mockedStorageService = createMock<StorageService>();
const mockedWeb3Service = createMock<Web3Service>();
const mockedEscrowClient = jest.mocked(EscrowClient);

describe('FortunePayoutsCalculator', () => {
let calculator: FortunePayoutsCalculator;
Expand All @@ -22,12 +28,23 @@ describe('FortunePayoutsCalculator', () => {
provide: StorageService,
useValue: mockedStorageService,
},
{
provide: Web3Service,
useValue: mockedWeb3Service,
},
],
}).compile();

calculator = moduleRef.get<FortunePayoutsCalculator>(
FortunePayoutsCalculator,
);

const mockedGetTokenAddress = jest.fn().mockImplementation(async () => {
return faker.finance.ethereumAddress();
});
mockedEscrowClient.build.mockResolvedValue({
getTokenAddress: mockedGetTokenAddress,
} as unknown as EscrowClient);
});

describe('calculate', () => {
Expand All @@ -46,6 +63,9 @@ describe('FortunePayoutsCalculator', () => {
const resultsUrl = faker.internet.url();
const manifest = generateFortuneManifest();

const tokenDecimals = BigInt(faker.number.int({ min: 6, max: 18 }));
mockedWeb3Service.getTokenDecimals.mockResolvedValueOnce(tokenDecimals);

const payouts = await calculator.calculate({
chainId: faker.number.int(),
escrowAddress: faker.finance.ethereumAddress(),
Expand All @@ -56,8 +76,9 @@ describe('FortunePayoutsCalculator', () => {
const expectedPayouts = validSolutions.map((s) => ({
address: s.workerAddress,
amount:
BigInt(ethers.parseUnits(manifest.fundAmount.toString(), 'ether')) /
BigInt(validSolutions.length),
BigInt(
ethers.parseUnits(manifest.fundAmount.toString(), tokenDecimals),
) / BigInt(validSolutions.length),
}));

expect(_.sortBy(payouts, 'address')).toEqual(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { EscrowClient } from '@human-protocol/sdk';
import { Injectable } from '@nestjs/common';
import { ethers } from 'ethers';
import type { OverrideProperties } from 'type-fest';

import { FortuneFinalResult, FortuneManifest } from '@/common/types';
import { StorageService } from '@/modules/storage';
import { Web3Service } from '@/modules/web3';

import {
CalclulatePayoutsInput,
Expand All @@ -18,10 +20,15 @@ type CalculateFortunePayoutsInput = OverrideProperties<

@Injectable()
export class FortunePayoutsCalculator implements EscrowPayoutsCalculator {
constructor(private readonly storageService: StorageService) {}
constructor(
private readonly storageService: StorageService,
private readonly web3Service: Web3Service,
) {}

async calculate({
manifest,
chainId,
escrowAddress,
finalResultsUrl,
}: CalculateFortunePayoutsInput): Promise<CalculatedPayout[]> {
const finalResults =
Expand All @@ -33,8 +40,15 @@ export class FortunePayoutsCalculator implements EscrowPayoutsCalculator {
.filter((result) => !result.error)
.map((item) => item.workerAddress);

const signer = this.web3Service.getSigner(chainId);
const escrowClient = await EscrowClient.build(signer);
const tokenAddress = await escrowClient.getTokenAddress(escrowAddress);
const tokenDecimals = await this.web3Service.getTokenDecimals(
chainId,
tokenAddress,
);
const payoutAmount =
ethers.parseUnits(manifest.fundAmount.toString(), 18) /
ethers.parseUnits(manifest.fundAmount.toString(), tokenDecimals) /
BigInt(recipients.length);

return recipients.map((recipient) => ({
Expand Down
Loading