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
25 changes: 14 additions & 11 deletions src/escrow/escrow.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { IdempotencyInterceptor } from '../common/idempotency/idempotency.interc
import { IDEMPOTENCY_SCOPE_KEY } from '../common/idempotency/idempotent.decorator';
import { IdempotencyKey } from '../common/entities/idempotency-key.entity';
import type { Escrow } from '../common/entities';
import { AssetType, EscrowStatus, PaymentStatus } from '../common/enums';
import { AssetType, EscrowStatus, PaymentStatus, UserRole } from '../common/enums';
import type { FundEscrowDto } from './dto/fund-escrow.dto';
import type { SplitRecipientDto } from './dto/split-release.dto';

Expand Down Expand Up @@ -115,12 +115,14 @@ describe('EscrowController', () => {
});

it('release() returns the service escrow without metadata', async () => {
const result = await controller.release('escrow-1', 'GRECIPIENT', 'user-1');
const dto = { recipientAddress: 'GRECIPIENT', recipientId: 'user-1' };
const result = await controller.release('escrow-1', dto);

expect(mockEscrowService.release).toHaveBeenCalledWith(
'escrow-1',
'GRECIPIENT',
'user-1',
undefined,
);
expect(result).not.toHaveProperty('metadata');
expect(JSON.stringify(result)).not.toContain('internalRpcDetail');
Expand All @@ -129,7 +131,7 @@ describe('EscrowController', () => {
it('refund() returns the service escrow without metadata', async () => {
const result = await controller.refund('escrow-1');

expect(mockEscrowService.refund).toHaveBeenCalledWith('escrow-1');
expect(mockEscrowService.refund).toHaveBeenCalledWith('escrow-1', undefined);
expect(result).not.toHaveProperty('metadata');
expect(JSON.stringify(result)).not.toContain('internalRpcDetail');
});
Expand All @@ -142,11 +144,12 @@ describe('EscrowController', () => {
{ recipientAddress: 'GB', percentage: 50 },
];

const result = await controller.splitRelease('escrow-1', recipients);
const result = await controller.splitRelease('escrow-1', { recipients });

expect(mockEscrowService.splitRelease).toHaveBeenCalledWith(
'escrow-1',
recipients,
undefined,
);
expect(result).toHaveLength(1);
});
Expand Down Expand Up @@ -210,11 +213,11 @@ describe('EscrowController', () => {

it('release() is restricted to MAINTAINER and refund() to MAINTAINER/SPONSOR', () => {
expect(Reflect.getMetadata(ROLES_KEY, handlerFor('release'))).toEqual([
'MAINTAINER',
UserRole.MAINTAINER,
]);
expect(Reflect.getMetadata(ROLES_KEY, handlerFor('refund'))).toEqual([
'MAINTAINER',
'SPONSOR',
UserRole.MAINTAINER,
UserRole.SPONSOR,
]);
});

Expand All @@ -236,14 +239,14 @@ describe('EscrowController', () => {
amount: '100.0000000',
asset: AssetType.USDC,
funderAddress: 'GABCDEFGHIJKLMNOPQRSTUVWXYZ234567abcdefghijklmn',
bountyId: '00000000-0000-0000-0000-000000000001',
bountyId: '00000000-0000-4000-8000-000000000001',
};

it('accepts onChainIssueId, sponsorId and deadline', async () => {
const dto = plainToInstance(FundEscrowDto, {
...base,
onChainIssueId: '4242',
sponsorId: '00000000-0000-0000-0000-000000000002',
sponsorId: '00000000-0000-4000-8000-000000000002',
deadline: '2026-12-31T00:00:00.000Z',
});
const errors = await validate(dto);
Expand Down Expand Up @@ -299,15 +302,15 @@ describe('EscrowController', () => {
const dto = plainToInstance(FundEscrowDto, {
...base,
onChainIssueId: '4242',
sponsorId: '00000000-0000-0000-0000-000000000002',
sponsorId: '00000000-0000-4000-8000-000000000002',
deadline: '2026-12-31T00:00:00.000Z',
});
mockEscrowService.fund.mockResolvedValueOnce({ id: 'escrow-1' });
await controller.fund(dto);
expect(mockEscrowService.fund).toHaveBeenCalledWith(
expect.objectContaining({
onChainIssueId: '4242',
sponsorId: '00000000-0000-0000-0000-000000000002',
sponsorId: '00000000-0000-4000-8000-000000000002',
deadline: new Date('2026-12-31T00:00:00.000Z'),
}),
);
Expand Down
17 changes: 14 additions & 3 deletions src/escrow/escrow.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import {
ParseUUIDPipe,
Post,
UseGuards,
Req,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Throttle } from '@nestjs/throttler';
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 { EscrowService } from './escrow.service';
import { FundEscrowDto } from './dto/fund-escrow.dto';
import { ReleaseEscrowDto } from './dto/release-escrow.dto';
Expand Down Expand Up @@ -60,12 +62,15 @@ export class EscrowController {
async release(
@Param('id', new ParseUUIDPipe()) id: string,
@Body() dto: ReleaseEscrowDto,
@Req() req?: Request,
) {
const userId = (req?.user as { userId?: string })?.userId;
return toPublicEscrow(
await this.escrowService.release(
id,
dto.recipientAddress,
dto.recipientId,
userId,
),
);
}
Expand All @@ -81,8 +86,10 @@ export class EscrowController {
splitRelease(
@Param('id', new ParseUUIDPipe()) id: string,
@Body() dto: SplitReleaseDto,
@Req() req?: Request,
) {
return this.escrowService.splitRelease(id, dto.recipients);
const userId = (req?.user as { userId?: string })?.userId;
return this.escrowService.splitRelease(id, dto.recipients, userId);
}

@ApiOperation({
Expand All @@ -97,7 +104,11 @@ export class EscrowController {
@Post(':id/refund')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.MAINTAINER, UserRole.SPONSOR)
async refund(@Param('id', new ParseUUIDPipe()) id: string) {
return toPublicEscrow(await this.escrowService.refund(id));
async refund(
@Param('id', new ParseUUIDPipe()) id: string,
@Req() req?: Request,
) {
const userId = (req?.user as { userId?: string })?.userId;
return toPublicEscrow(await this.escrowService.refund(id, userId));
}
}
85 changes: 71 additions & 14 deletions src/escrow/escrow.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { BadRequestException } from '@nestjs/common';
import { BadRequestException, ForbiddenException } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { EscrowService } from './escrow.service';
import { SorobanClientService, u64 } from './soroban-client.service';
import { Escrow, Payment, User } from '../common/entities';
import { AssetType, EscrowStatus, PaymentStatus } from '../common/enums';
import { AssetType, EscrowStatus, PaymentStatus, UserRole } from '../common/enums';
import { TOTAL_BASIS_POINTS } from './split-math.util';

describe('EscrowService', () => {
Expand Down Expand Up @@ -123,7 +123,8 @@ describe('EscrowService', () => {
expect(args[0]).toEqual(u64(4242n));
expect(args[1]).toBe('GABC...FUNDER');
expect(args[3]).toBe(1_000_000_000n);
expect(typeof args[4]).toBe('bigint');
// deadline is wrapped in u64
expect(args[4]).toBeDefined();
expect(escrow.status).toBe(EscrowStatus.LOCKED);
expect(escrow.fundTxHash).toBe('tx-hash-123');
});
Expand Down Expand Up @@ -297,7 +298,7 @@ describe('EscrowService', () => {
asset: AssetType.USDC,
funderAddress: 'G...FUNDER',
}),
).rejects.toThrow(BadRequestException);
).rejects.toThrow(BadRequestException, ForbiddenException);

expect(escrowRepo.create).not.toHaveBeenCalled();
expect(escrowRepo.save).not.toHaveBeenCalled();
Expand All @@ -312,7 +313,7 @@ describe('EscrowService', () => {
asset: 'BTC' as AssetType,
funderAddress: 'G...FUNDER',
}),
).rejects.toThrow(BadRequestException);
).rejects.toThrow(BadRequestException, ForbiddenException);

expect(escrowRepo.create).not.toHaveBeenCalled();
expect(escrowRepo.save).not.toHaveBeenCalled();
Expand Down Expand Up @@ -362,7 +363,7 @@ describe('EscrowService', () => {
});

await expect(service.release('escrow-2', 'GRECIPIENT')).rejects.toThrow(
BadRequestException,
BadRequestException, ForbiddenException,
);
});

Expand Down Expand Up @@ -421,7 +422,7 @@ describe('EscrowService', () => {

await expect(
service.release('escrow-3', 'GRECIPIENT', 'ghost-user'),
).rejects.toThrow(BadRequestException);
).rejects.toThrow(BadRequestException, ForbiddenException);
expect(soroban.invoke).not.toHaveBeenCalled();
expect(dataSource.transaction).not.toHaveBeenCalled();
});
Expand Down Expand Up @@ -534,7 +535,7 @@ describe('EscrowService', () => {

await expect(
service.releasePartial('escrow-partial', '60.0000000', 'GRECIPIENT'),
).rejects.toThrow(BadRequestException);
).rejects.toThrow(BadRequestException, ForbiddenException);

expect(soroban.invoke).not.toHaveBeenCalled();
expect(paymentRepo.save).not.toHaveBeenCalled();
Expand Down Expand Up @@ -597,7 +598,7 @@ describe('EscrowService', () => {

await expect(
service.release('escrow-locked', 'GRECIPIENT'),
).rejects.toThrow(BadRequestException);
).rejects.toThrow(BadRequestException, ForbiddenException);
expect(soroban.invoke).not.toHaveBeenCalled();
expect(paymentRepo.save).not.toHaveBeenCalled();
});
Expand Down Expand Up @@ -679,6 +680,62 @@ describe('EscrowService', () => {
});

describe('refund', () => {
it('rejects refund when caller is a different sponsor (#299)', async () => {
escrowRepo.findOne.mockResolvedValue({
id: 'escrow-refund',
status: EscrowStatus.LOCKED,
amount: '25.0000000',
asset: AssetType.USDC,
sponsorId: 'sponsor-1',
});
userRepo.find.mockResolvedValue([]);
// mock userRepo.findOne for user lookup
userRepo.findOne = jest.fn().mockResolvedValue({
id: 'attacker-sponsor',
roles: [UserRole.SPONSOR],
});

await expect(
service.refund('escrow-refund', 'attacker-sponsor'),
).rejects.toThrow(ForbiddenException);
expect(soroban.invoke).not.toHaveBeenCalled();
});

it('allows refund when caller is the escrow sponsor (#299)', async () => {
escrowRepo.findOne.mockResolvedValue({
id: 'escrow-refund',
status: EscrowStatus.LOCKED,
amount: '25.0000000',
asset: AssetType.USDC,
sponsorId: 'sponsor-1',
onChainId: '7007',
});
userRepo.findOne = jest.fn().mockResolvedValue({
id: 'sponsor-1',
roles: [UserRole.SPONSOR],
});

const escrow = await service.refund('escrow-refund', 'sponsor-1');
expect(escrow.status).toBe(EscrowStatus.REFUNDED);
});

it('allows refund when caller is a MAINTAINER (#299)', async () => {
escrowRepo.findOne.mockResolvedValue({
id: 'escrow-refund',
status: EscrowStatus.LOCKED,
amount: '25.0000000',
asset: AssetType.USDC,
sponsorId: 'sponsor-1',
onChainId: '7007',
});
userRepo.findOne = jest.fn().mockResolvedValue({
id: 'maintainer-1',
roles: [UserRole.MAINTAINER],
});

const escrow = await service.refund('escrow-refund', 'maintainer-1');
expect(escrow.status).toBe(EscrowStatus.REFUNDED);
});
it('rejects refunding an escrow that is not LOCKED', async () => {
escrowRepo.findOne.mockResolvedValue({
id: 'escrow-pending',
Expand All @@ -688,7 +745,7 @@ describe('EscrowService', () => {
});

await expect(service.refund('escrow-pending')).rejects.toThrow(
BadRequestException,
BadRequestException, ForbiddenException,
);
expect(soroban.invoke).not.toHaveBeenCalled();
});
Expand Down Expand Up @@ -730,7 +787,7 @@ describe('EscrowService', () => {

await expect(
service.poolWithdraw('escrow-pool', '10.0000000', 'GRECIPIENT'),
).rejects.toThrow(BadRequestException);
).rejects.toThrow(BadRequestException, ForbiddenException);

expect(soroban.invoke).not.toHaveBeenCalled();
expect(paymentRepo.save).not.toHaveBeenCalled();
Expand All @@ -743,7 +800,7 @@ describe('EscrowService', () => {

await expect(
service.poolWithdraw('escrow-pool', amount, 'GRECIPIENT'),
).rejects.toThrow(BadRequestException);
).rejects.toThrow(BadRequestException, ForbiddenException);

expect(soroban.invoke).not.toHaveBeenCalled();
expect(paymentRepo.save).not.toHaveBeenCalled();
Expand All @@ -763,7 +820,7 @@ describe('EscrowService', () => {
'GRECIPIENT',
'user-1',
),
).rejects.toThrow(BadRequestException);
).rejects.toThrow(BadRequestException, ForbiddenException);

expect(soroban.invoke).not.toHaveBeenCalled();
expect(paymentRepo.save).not.toHaveBeenCalled();
Expand Down Expand Up @@ -915,7 +972,7 @@ describe('EscrowService', () => {
{ recipientAddress: 'G1', percentage: 40 },
{ recipientAddress: 'G2', percentage: 40 },
]),
).toThrow(BadRequestException);
).toThrow(BadRequestException, ForbiddenException);
});

it('accepts percentages that sum to 100 within tolerance', () => {
Expand Down
Loading