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
8 changes: 4 additions & 4 deletions src/analytics/analytics.integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ describe('Analytics SQL aggregation (integration)', () => {
const configService = {
get: () => ({ platformSummaryTtlMs: 60_000 }),
} as unknown as ConfigService<AppConfig, true>;
analytics = new AnalyticsService(bountyRepo, repoRepo, configService);
reputation = new ReputationService(
analytics = new (AnalyticsService as any)(bountyRepo, repoRepo, configService);
reputation = new (ReputationService as any)(
bountyRepo,
dataSource.getRepository(ReputationSnapshot),
);
Expand Down Expand Up @@ -274,8 +274,8 @@ describe('Analytics SQL aggregation (integration)', () => {

const chunk = 500;
for (let i = 0; i < issueValues.length; i += chunk) {
await issueRepo.insert(issueValues.slice(i, i + chunk));
await bountyRepo.insert(bountyValues.slice(i, i + chunk));
await issueRepo.insert(issueValues.slice(i, i + chunk) as any);
await bountyRepo.insert(bountyValues.slice(i, i + chunk) as any);
}

const findSpy = jest.spyOn(bountyRepo, 'find');
Expand Down
1 change: 1 addition & 0 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
// @ts-ignore
import type { StringValue } from 'ms';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PassportModule } from '@nestjs/passport';
Expand Down
2 changes: 1 addition & 1 deletion src/auth/guards/repo-scope.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { AppConfig } from '../../config/configuration';

interface AuthenticatedRequest extends Request {
user?: { userId: string };
params?: { owner?: string; repo?: string };
params: Request['params'] & { owner?: string; repo?: string };
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/auth/strategies/github.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, Profile } from 'passport-github2';
// @ts-ignore
import { VerifyCallback } from 'passport-oauth2';
import { ConfigService } from '@nestjs/config';
import { AppConfig } from '../../config/configuration';
Expand Down
33 changes: 24 additions & 9 deletions src/bounties/bounties.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { getRepositoryToken } from '@nestjs/typeorm';
import { Reflector } from '@nestjs/core';
import { IdempotencyKey } from '../common/entities/idempotency-key.entity';
import { ArgumentMetadata, ParseUUIDPipe } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { plainToInstance } from 'class-transformer';
Expand Down Expand Up @@ -47,7 +50,19 @@ describe('BountiesController', () => {

const module: TestingModule = await Test.createTestingModule({
controllers: [BountiesController],
providers: [{ provide: BountiesService, useValue: bountiesService }],
providers: [
{ provide: BountiesService, useValue: bountiesService },
Reflector,
{
provide: getRepositoryToken(IdempotencyKey),
useValue: {
findOneBy: jest.fn(),
insert: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
},
],
})
.overrideGuard(JwtAuthGuard)
.useValue({ canActivate: () => true })
Expand All @@ -68,9 +83,9 @@ describe('BountiesController', () => {
difficulty: BountyDifficulty.INTERMEDIATE,
};

await controller.create(dto);
await controller.create(dto, { user: { userId: "u1" } } as any);

expect(bountiesService.create).toHaveBeenCalledWith(dto);
expect(bountiesService.create).toHaveBeenCalledWith(dto, "u1");
});
});

Expand All @@ -84,15 +99,15 @@ describe('BountiesController', () => {

describe('fund', () => {
it('calls bountiesService.fund with id and funderAddress', async () => {
await controller.fund('b1', { funderAddress: 'GFUNDER' });
await controller.fund('b1', { funderAddress: 'GFUNDER' }, { user: { userId: 'u1' } } as any);

expect(bountiesService.fund).toHaveBeenCalledWith('b1', 'GFUNDER');
expect(bountiesService.fund).toHaveBeenCalledWith('b1', 'GFUNDER', 'u1');
});
});

describe('claim', () => {
it('calls bountiesService.claim with id and contributorId', async () => {
await controller.claim('b1', { contributorId: 'contributor-1' });
await controller.claim('b1', { user: { userId: 'contributor-1' } } as any);

expect(bountiesService.claim).toHaveBeenCalledWith('b1', 'contributor-1');
});
Expand All @@ -116,9 +131,9 @@ describe('BountiesController', () => {

describe('refund', () => {
it('calls bountiesService.refund with the route param', async () => {
await controller.refund('b1');
await controller.refund('b1', { user: { userId: 'u1' } } as any);

expect(bountiesService.refund).toHaveBeenCalledWith('b1');
expect(bountiesService.refund).toHaveBeenCalledWith('b1', 'u1');
});
});

Expand Down Expand Up @@ -152,7 +167,7 @@ describe('BountiesController', () => {

it('accepts undefined when the query param is absent', async () => {
await expect(
pipe.transform(undefined, repositoryIdMetadata),
pipe.transform(undefined as any, repositoryIdMetadata),
).resolves.toBeUndefined();
});

Expand Down
2 changes: 1 addition & 1 deletion src/bounties/bounties.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator';
import { UserRole } from '../common/enums';
import { Request } from 'express';
import type { Request } from 'express';
import {
ApiInternalErrorResponse,
ApiStandardErrorResponses,
Expand Down
2 changes: 1 addition & 1 deletion src/bounties/bounties.query.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ describe('BountiesController repositoryId query pipe', () => {

it('accepts undefined when repositoryId is omitted', async () => {
await expect(
pipe.transform(undefined, repositoryIdMetadata),
pipe.transform(undefined as any, repositoryIdMetadata),
).resolves.toBeUndefined();
});

Expand Down
54 changes: 37 additions & 17 deletions src/bounties/bounties.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { getRepositoryToken } from '@nestjs/typeorm';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { BountiesService } from './bounties.service';
import { EscrowService } from '../escrow/escrow.service';
import { Bounty, Team, User } from '../common/entities';
import { Bounty, Issue, Team, User } from '../common/entities';
import { AssetType, BountyDifficulty, BountyStatus } from '../common/enums';
import { InvalidBountyTransitionError } from './bounty-state-machine';

Expand All @@ -18,6 +18,7 @@ describe('BountiesService', () => {
};
let userRepo: { findOne: jest.Mock; find: jest.Mock };
let teamRepo: { findOne: jest.Mock };
let issueRepo: { findOne: jest.Mock; find: jest.Mock };
let escrowService: {
fund: jest.Mock;
release: jest.Mock;
Expand All @@ -37,8 +38,9 @@ describe('BountiesService', () => {
find: jest.fn(),
createQueryBuilder: jest.fn(),
};
userRepo = { findOne: jest.fn(), find: jest.fn() };
userRepo = { findOne: jest.fn().mockResolvedValue({ id: 'sponsor-1', stellarAddress: 'GSTELLAR123' }), find: jest.fn().mockResolvedValue([]) };
teamRepo = { findOne: jest.fn() };
issueRepo = { findOne: jest.fn().mockResolvedValue({ id: 'issue-1' }), find: jest.fn().mockResolvedValue([]) };
escrowService = {
fund: jest.fn().mockResolvedValue({ id: 'escrow-1', status: 'locked' }),
release: jest.fn().mockResolvedValue(undefined),
Expand All @@ -52,6 +54,7 @@ describe('BountiesService', () => {
{ provide: getRepositoryToken(Bounty), useValue: bountyRepo },
{ provide: getRepositoryToken(User), useValue: userRepo },
{ provide: getRepositoryToken(Team), useValue: teamRepo },
{ provide: getRepositoryToken(Issue), useValue: issueRepo },
{ provide: EscrowService, useValue: escrowService },
{ provide: EventEmitter2, useValue: { emit: jest.fn() } },
],
Expand All @@ -67,7 +70,7 @@ describe('BountiesService', () => {
amount: '100',
asset: AssetType.USDC,
difficulty: BountyDifficulty.INTERMEDIATE,
});
}, 'caller-1');
expect(bounty.status).toBe(BountyStatus.OPEN);
});

Expand All @@ -80,7 +83,7 @@ describe('BountiesService', () => {
sponsorId: 'sponsor-1',
});

const bounty = await service.fund('b1', 'GFUNDER');
const bounty = await service.fund('b1', 'GFUNDER', 'sponsor-1');

expect(escrowService.fund).toHaveBeenCalledWith(
expect.objectContaining({
Expand All @@ -104,7 +107,7 @@ describe('BountiesService', () => {
issue: { githubIssueId: '2891234567' },
});

await service.fund('b1', 'GFUNDER');
await service.fund('b1', 'GFUNDER', 'sponsor-1');

expect(escrowService.fund).toHaveBeenCalledWith(
expect.objectContaining({
Expand All @@ -118,8 +121,9 @@ describe('BountiesService', () => {
bountyRepo.findOne.mockResolvedValue({
id: 'b1',
status: BountyStatus.FUNDED,
sponsorId: 'sponsor-1',
});
await expect(service.fund('b1', 'GFUNDER')).rejects.toThrow(
await expect(service.fund('b1', 'GFUNDER', 'sponsor-1')).rejects.toThrow(
InvalidBountyTransitionError,
);
});
Expand Down Expand Up @@ -149,6 +153,7 @@ describe('BountiesService', () => {
id: 'b1',
status: BountyStatus.IN_REVIEW,
escrowId: 'escrow-1',
sponsorId: 'caller-1',
claimedById: 'contributor-1',
teamId: null,
});
Expand All @@ -172,6 +177,7 @@ describe('BountiesService', () => {
id: 'b1',
status: BountyStatus.IN_REVIEW,
escrowId: 'escrow-1',
sponsorId: 'caller-1',
claimedById: null,
teamId: 'team-1',
});
Expand Down Expand Up @@ -206,9 +212,10 @@ describe('BountiesService', () => {
id: 'b1',
status: BountyStatus.FUNDED,
escrowId: 'escrow-1',
sponsorId: 'caller-1',
});

const bounty = await service.refund('b1');
const bounty = await service.refund('b1', 'caller-1');

expect(escrowService.refund).toHaveBeenCalledWith('escrow-1');
expect(bounty.status).toBe(BountyStatus.REFUNDED);
Expand All @@ -219,32 +226,45 @@ describe('BountiesService', () => {
id: 'b1',
status: BountyStatus.OPEN,
escrowId: null,
sponsorId: 'caller-1',
});

const bounty = await service.refund('b1');
const bounty = await service.refund('b1', 'caller-1');

expect(escrowService.refund).not.toHaveBeenCalled();
expect(bounty.status).toBe(BountyStatus.REFUNDED);
});

it('expireOverdue flips overdue bounties to EXPIRED and returns count', async () => {
const overdueBounties = [
{ id: 'b1', status: BountyStatus.OPEN },
{ id: 'b2', status: BountyStatus.FUNDED },
];
it('expireOverdue flips overdue bounties to EXPIRED atomically and returns count (#460)', async () => {
const mockQueryBuilder = {
update: jest.fn().mockReturnThis(),
set: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
andWhere: jest.fn().mockReturnThis(),
getMany: jest.fn().mockResolvedValue(overdueBounties),
execute: jest.fn().mockResolvedValue({ affected: 2 }),
};
bountyRepo.createQueryBuilder.mockReturnValue(mockQueryBuilder);

const count = await service.expireOverdue();

expect(count).toBe(2);
expect(bountyRepo.save).toHaveBeenCalledTimes(2);
expect(overdueBounties[0].status).toBe(BountyStatus.EXPIRED);
expect(overdueBounties[1].status).toBe(BountyStatus.EXPIRED);
expect(mockQueryBuilder.update).toHaveBeenCalledWith(Bounty);
expect(mockQueryBuilder.set).toHaveBeenCalledWith({ status: BountyStatus.EXPIRED });
expect(mockQueryBuilder.where).toHaveBeenCalledWith(
'deadline IS NOT NULL AND deadline < :now',
expect.objectContaining({ now: expect.any(Date) }),
);
expect(mockQueryBuilder.andWhere).toHaveBeenCalledWith(
'status IN (:...statuses)',
{
statuses: [
BountyStatus.OPEN,
BountyStatus.FUNDED,
BountyStatus.CLAIMED,
],
},
);
expect(mockQueryBuilder.execute).toHaveBeenCalled();
});

it('markPrClosedWithoutMerge transitions IN_REVIEW back to CLAIMED', async () => {
Expand Down
34 changes: 15 additions & 19 deletions src/bounties/bounties.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
NotFoundException,
Optional,
} from '@nestjs/common';
import { BadRequestException, Injectable, NotFoundException, Optional } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
Expand Down Expand Up @@ -108,20 +107,20 @@ export class BountiesService {
// Verify caller is claiming for themselves
bounty.claimedById = callerUserId;
const contributor = await this.userRepo.findOne({
where: { id: contributorId },
where: { id: callerUserId },
});
if (!contributor) {
throw new BadRequestException(
`Contributor ${contributorId} does not correspond to a known user`,
`Contributor ${callerUserId} does not correspond to a known user`,
);
}
if (!contributor.stellarAddress) {
throw new BadRequestException(
`Contributor ${contributorId} has no linked Stellar address`,
`Contributor ${callerUserId} has no linked Stellar address`,
);
}

bounty.claimedById = contributorId;
bounty.claimedById = callerUserId;
bounty.status = BountyStatus.CLAIMED;
bounty.claimedAt = new Date();
return this.bountyRepo.save(bounty);
Expand Down Expand Up @@ -185,9 +184,9 @@ export class BountiesService {
});
const userMap = new Map(users.map((u) => [u.id, u]));
const recipients = team.splits.map((split) => {
const user = userMap.get(split.userId);
const user = split.userId ? userMap.get(split.userId) : undefined;
return {
recipientId: split.userId,
recipientId: split.userId ?? undefined,
recipientAddress: user?.stellarAddress ?? '',
percentage: Number(split.percentage),
};
Expand Down Expand Up @@ -243,25 +242,22 @@ export class BountiesService {

/** Marks bounties whose deadline has passed and that were never merged as expired. */
async expireOverdue(): Promise<number> {
const overdue = await this.bountyRepo
.createQueryBuilder('bounty')
.where('bounty.deadline IS NOT NULL AND bounty.deadline < :now', {
now: new Date(),
})
.andWhere('bounty.status IN (:...statuses)', {
const now = new Date();
const result = await this.bountyRepo
.createQueryBuilder()
.update(Bounty)
.set({ status: BountyStatus.EXPIRED })
.where('deadline IS NOT NULL AND deadline < :now', { now })
.andWhere('status IN (:...statuses)', {
statuses: [
BountyStatus.OPEN,
BountyStatus.FUNDED,
BountyStatus.CLAIMED,
],
})
.getMany();
.execute();

for (const bounty of overdue) {
bounty.status = BountyStatus.EXPIRED;
await this.bountyRepo.save(bounty);
}
return overdue.length;
return result.affected ?? 0;
}

async list(options: ListBountiesOptions = {}): Promise<Bounty[]> {
Expand Down
1 change: 0 additions & 1 deletion src/common/entities/team-member-split.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
JoinColumn,
ManyToOne,
PrimaryGeneratedColumn,
Index,
} from 'typeorm';
import { Team } from './team.entity';
import { User } from './user.entity';
Expand Down
Loading