Skip to content
Closed
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
44 changes: 34 additions & 10 deletions src/bounties/bounties.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { Request } from 'express';
import { ArgumentMetadata, ParseUUIDPipe } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { BountiesController } from './bounties.controller';
Expand All @@ -9,6 +11,7 @@ import { ClaimBountyDto } from './dto/claim-bounty.dto';
import { AssetType, BountyDifficulty, BountyStatus } from '../common/enums';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { IdempotencyKey } from '../common/entities/idempotency-key.entity';

describe('BountiesController', () => {
let controller: BountiesController;
Expand Down Expand Up @@ -47,7 +50,13 @@ describe('BountiesController', () => {

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

await controller.create(dto);
await controller.create(dto, {
user: { userId: 'sponsor-1' },
} as unknown as Request);

expect(bountiesService.create).toHaveBeenCalledWith(dto);
expect(bountiesService.create).toHaveBeenCalledWith(dto, 'sponsor-1');
});
});

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

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

expect(bountiesService.fund).toHaveBeenCalledWith('b1', 'GFUNDER');
await controller.fund('b1', { funderAddress: 'GFUNDER' }, {
user: { userId: 'sponsor-1' },
} as unknown as Request);

expect(bountiesService.fund).toHaveBeenCalledWith(
'b1',
'GFUNDER',
'sponsor-1',
);
});
});

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

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

describe('refund', () => {
it('calls bountiesService.refund with the route param', async () => {
await controller.refund('b1');
await controller.refund('b1', {
user: { userId: 'sponsor-1' },
} as unknown as Request);

expect(bountiesService.refund).toHaveBeenCalledWith('b1');
expect(bountiesService.refund).toHaveBeenCalledWith(
'b1',
'sponsor-1',
);
});
});

Expand Down
1 change: 1 addition & 0 deletions src/bounties/bounties.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ export class BountiesController {

@ApiOperation({ summary: 'Get a bounty by id' })
@ApiStandardErrorResponses()
@Throttle({ long: { limit: 1000, ttl: 3600000 } })
@Get(':id')
findOne(@Param('id', new ParseUUIDPipe()) id: string) {
return this.bountiesService.findOne(id);
Expand Down
79 changes: 67 additions & 12 deletions src/bounties/bounties.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { BadRequestException, NotImplementedException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
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 +19,7 @@ describe('BountiesService', () => {
};
let userRepo: { findOne: jest.Mock; find: jest.Mock };
let teamRepo: { findOne: jest.Mock };
let issueRepo: { findOne: jest.Mock };
let escrowService: {
fund: jest.Mock;
release: jest.Mock;
Expand All @@ -39,6 +41,7 @@ describe('BountiesService', () => {
};
userRepo = { findOne: jest.fn(), find: jest.fn() };
teamRepo = { findOne: jest.fn() };
issueRepo = { findOne: jest.fn().mockResolvedValue({ id: 'issue-1' }) };
escrowService = {
fund: jest.fn().mockResolvedValue({ id: 'escrow-1', status: 'locked' }),
release: jest.fn().mockResolvedValue(undefined),
Expand All @@ -52,6 +55,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 @@ -61,13 +65,17 @@ describe('BountiesService', () => {
});

it('creates a bounty in OPEN status', async () => {
const bounty = await service.create({
issueId: 'issue-1',
sponsorId: 'sponsor-1',
amount: '100',
asset: AssetType.USDC,
difficulty: BountyDifficulty.INTERMEDIATE,
});
userRepo.findOne.mockResolvedValue({ id: 'sponsor-1' });
const bounty = await service.create(
{
issueId: 'issue-1',
sponsorId: 'sponsor-1',
amount: '100',
asset: AssetType.USDC,
difficulty: BountyDifficulty.INTERMEDIATE,
},
'sponsor-1',
);
expect(bounty.status).toBe(BountyStatus.OPEN);
});

Expand All @@ -80,7 +88,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 +112,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 +126,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 All @@ -134,16 +143,47 @@ describe('BountiesService', () => {
);
});

it('claim moves FUNDED -> CLAIMED and records the contributor', async () => {
it('claim moves FUNDED -> CLAIMED and records the caller as claimant', async () => {
bountyRepo.findOne.mockResolvedValue({
id: 'b1',
status: BountyStatus.FUNDED,
});
userRepo.findOne.mockResolvedValue({
id: 'contributor-1',
stellarAddress: 'GCONTRIB',
});
const bounty = await service.claim('b1', 'contributor-1');
expect(userRepo.findOne).toHaveBeenCalledWith({
where: { id: 'contributor-1' },
});
expect(bounty.status).toBe(BountyStatus.CLAIMED);
expect(bounty.claimedById).toBe('contributor-1');
});

it('claim rejects a caller that is not a known user', async () => {
bountyRepo.findOne.mockResolvedValue({
id: 'b1',
status: BountyStatus.FUNDED,
});
userRepo.findOne.mockResolvedValue(null);
await expect(service.claim('b1', 'ghost')).rejects.toThrow(
BadRequestException,
);
});

it('claim rejects a caller without a linked Stellar address', async () => {
const stored = { id: 'b1', status: BountyStatus.FUNDED, claimedById: null };
bountyRepo.findOne.mockResolvedValue(stored);
userRepo.findOne.mockResolvedValue({
id: 'contributor-1',
stellarAddress: null,
});
await expect(service.claim('b1', 'contributor-1')).rejects.toThrow(
BadRequestException,
);
expect(stored.claimedById).toBeNull();
});

it('markMergedAndRelease releases escrow to the contributor and moves to PAID', async () => {
bountyRepo.findOne.mockResolvedValue({
id: 'b1',
Expand Down Expand Up @@ -315,3 +355,18 @@ describe('BountiesService', () => {
);
});
});

// Standalone: approve/reject touch no dependencies, so they're tested without
// the shared TestingModule above.
describe('BountiesService approve / reject (#533)', () => {
const service = Object.create(BountiesService.prototype) as BountiesService;

it('answer 501 instead of reporting a fake approval or rejection', async () => {
await expect(service.approve('b1')).rejects.toBeInstanceOf(
NotImplementedException,
);
await expect(service.reject('b1')).rejects.toBeInstanceOf(
NotImplementedException,
);
});
});
34 changes: 24 additions & 10 deletions src/bounties/bounties.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
NotFoundException,
Optional,
} from '@nestjs/common';
import { BadRequestException, Injectable, NotFoundException, Optional } from '@nestjs/common';
import { BadRequestException, Injectable, NotFoundException, NotImplementedException, Optional } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
Expand Down Expand Up @@ -106,22 +106,21 @@ export class BountiesService {
assertTransition(bounty.status, BountyStatus.CLAIMED);

// 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 @@ -295,11 +294,26 @@ export class BountiesService {
return qb.getMany();
}

approve(id: string) {
return Promise.resolve({ id, status: 'approved' });
/**
* Not implemented yet (#253, #533). This used to resolve
* `{ id, status: 'approved' }` without reading or writing anything, so the
* route reported success for an approval that never happened. It now
* answers 501 until the real approval flow exists.
*/
approve(id: string): Promise<never> {
return Promise.reject(
new NotImplementedException(
`Bounty approval is not implemented yet (bounty ${id})`,
),
);
}

reject(id: string) {
return Promise.resolve({ id, status: 'rejected' });
/** Not implemented yet (#253, #533) — see `approve`. */
reject(id: string): Promise<never> {
return Promise.reject(
new NotImplementedException(
`Bounty rejection is not implemented yet (bounty ${id})`,
),
);
}
}
10 changes: 2 additions & 8 deletions src/escrow/escrow.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -584,20 +584,14 @@ export class EscrowService {
recipients: Array<[string, number]>,
manager?: EntityManager,
): Promise<ContractInvocationResult> {
return this.invokeOnLockedEscrow(escrow, operation, () =>
this.soroban.invoke(
'release',
// `release(issue_id: u64, recipients)` — u64-typed on-chain (#301).
[u64(this.onChainKeyFor(escrow)), recipients],
this.contractOpts(escrow),
),
return this.invokeOnLockedEscrow(
escrow,
operation,
() =>
this.soroban.invoke(
'release',
[this.onChainKeyFor(escrow), recipients],
// `release(issue_id: u64, recipients)` — u64-typed on-chain (#301).
[u64(this.onChainKeyFor(escrow)), recipients],
this.contractOpts(escrow),
),
manager,
Expand Down
3 changes: 3 additions & 0 deletions src/github/github-webhooks.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -869,6 +869,9 @@ describe('GithubWebhooksService', () => {

expect(bountiesService.markInReview).not.toHaveBeenCalled();
expect(bountiesService.markMergedAndRelease).not.toHaveBeenCalled();
});
});

// #308: a redelivered X-GitHub-Delivery used to hit the unique constraint
// on webhook_events.deliveryId and escape handleEvent as a 500, so every
// redelivery of that event failed forever.
Expand Down
4 changes: 4 additions & 0 deletions src/maintenance-pool/maintenance-pool.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,17 @@ export class MaintenancePoolController {
}

@ApiOperation({ summary: 'List maintenance pools' })
// Public read returning the whole table — tighten past the global default
// so it can't be scraped at the lenient rate (#592).
@Throttle({ long: { limit: 300, ttl: 3600000 } })
@Get()
list() {
return this.poolService.list();
}

@ApiOperation({ summary: 'Get a maintenance pool by id' })
@ApiStandardErrorResponses()
@Throttle({ long: { limit: 1000, ttl: 3600000 } })
@Get(':id')
findOne(@Param('id', new ParseUUIDPipe()) id: string) {
return this.poolService.findOne(id);
Expand Down
Loading