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
26 changes: 26 additions & 0 deletions backend/src/common/pagination.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export const DEFAULT_PAGE_LIMIT = 20;
export const MAX_PAGE_LIMIT = 100;

export interface PaginatedResponse<T> {
items: T[];
total: number;
page: number;
limit: number;
}

export interface PaginationQuery {
page?: number;
limit?: number;
}

export function paginate<T>(items: T[], query: PaginationQuery): PaginatedResponse<T> {
const limit = Math.min(query.limit ?? DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT);
const page = query.page ?? 1;
const start = (page - 1) * limit;
return {
items: items.slice(start, start + limit),
total: items.length,
page,
limit,
};
}
60 changes: 60 additions & 0 deletions backend/src/escrow/escrow.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,66 @@ describe('EscrowController', () => {
expect(controller).toBeDefined();
});

describe('findByDepositor', () => {
it('returns paginated results with default offset=0, limit=20', async () => {
const escrows = Array.from({ length: 5 }, (_, i) => ({
id: `esc-${i}`,
depositor: VALID_ADDRESS,
beneficiary: 'GBEN',
amountXLM: '100',
status: 'pending',
createdAt: new Date().toISOString(),
}));
mockEscrowService.findByDepositor.mockResolvedValue({ data: escrows, total: 5 });

const result = await controller.findByDepositor(VALID_ADDRESS);

expect(mockEscrowService.findByDepositor).toHaveBeenCalledWith(VALID_ADDRESS, 0, 20);
expect(result).toEqual({ data: escrows, total: 5 });
});

it('applies custom offset and limit', async () => {
mockEscrowService.findByDepositor.mockResolvedValue({ data: [], total: 0 });

await controller.findByDepositor(VALID_ADDRESS, 10, 5);

expect(mockEscrowService.findByDepositor).toHaveBeenCalledWith(VALID_ADDRESS, 10, 5);
});

it('clamps limit to max 100', async () => {
mockEscrowService.findByDepositor.mockResolvedValue({ data: [], total: 0 });

await controller.findByDepositor(VALID_ADDRESS, 0, 200);

expect(mockEscrowService.findByDepositor).toHaveBeenCalledWith(VALID_ADDRESS, 0, 100);
});

it('clamps negative offset to 0', async () => {
mockEscrowService.findByDepositor.mockResolvedValue({ data: [], total: 0 });

await controller.findByDepositor(VALID_ADDRESS, -5, 10);

expect(mockEscrowService.findByDepositor).toHaveBeenCalledWith(VALID_ADDRESS, 0, 10);
});
});

describe('release', () => {
it('releases the escrow and records the completion with the reputation engine', async () => {
const escrow = {
id: 'esc-1',
depositor: 'GDEP',
beneficiary: 'GBEN',
amountXLM: '100',
status: 'released',
createdAt: new Date().toISOString(),
};
mockEscrowService.release.mockResolvedValue(escrow);

const result = await controller.release('esc-1');

expect(mockEscrowService.release).toHaveBeenCalledWith('esc-1');
expect(mockReputationService.recordEscrowCompleted).toHaveBeenCalledWith(escrow);
expect(result).toEqual(escrow);
// ─── POST /escrows (create) ───────────────────────────────────────────────

describe('create()', () => {
Expand Down
52 changes: 38 additions & 14 deletions backend/src/escrow/escrow.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,33 +131,57 @@ export class EscrowController {
@Get('depositor/:address')
@ApiOperation({
summary: 'Get escrows by depositor',
description: 'Retrieves all escrows created by a specific depositor address.',
description: 'Retrieves escrows created by a specific depositor address with pagination.',
})
@ApiParam({
name: 'address',
description: 'Stellar address of the depositor',
example: 'GXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
})
@ApiQuery({
name: 'offset',
required: false,
type: Number,
description: 'Number of items to skip. Defaults to 0.',
})
@ApiQuery({
name: 'limit',
required: false,
type: Number,
description: 'Maximum number of items to return (max 100). Defaults to 20.',
})
@ApiResponse({
status: 200,
description: 'List of escrows',
description: 'Paginated list of escrows',
schema: {
type: 'array',
items: {
type: 'object',
properties: {
id: { type: 'string' },
depositor: { type: 'string' },
beneficiary: { type: 'string' },
amountXLM: { type: 'string' },
status: { type: 'string' },
createdAt: { type: 'string', format: 'date-time' },
type: 'object',
properties: {
data: {
type: 'array',
items: {
type: 'object',
properties: {
id: { type: 'string' },
depositor: { type: 'string' },
beneficiary: { type: 'string' },
amountXLM: { type: 'string' },
status: { type: 'string' },
createdAt: { type: 'string', format: 'date-time' },
},
},
},
total: { type: 'number' },
},
},
})
findByDepositor(@Param('address') address: string) {
return this.escrowService.findByDepositor(address);
findByDepositor(
@Param('address') address: string,
@Query('offset') offset?: number,
@Query('limit') limit?: number,
) {
const safeOffset = Math.max(0, Number(offset) || 0);
const safeLimit = Math.min(Math.max(1, Number(limit) || 20), 100);
return this.escrowService.findByDepositor(address, safeOffset, safeLimit);
}

@Post(':id/release')
Expand Down
53 changes: 53 additions & 0 deletions backend/src/escrow/escrow.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,22 @@ describe('EscrowService', () => {
service = module.get<EscrowService>(EscrowService);
});

describe('create', () => {
it('generates unique IDs even when called concurrently in a tight loop', async () => {
const numEscrows = 1000;
const promises: Promise<import('./escrow.service').Escrow>[] = [];
for (let i = 0; i < numEscrows; i++) {
promises.push(service.create(`GDEP${i}`, `GBEN${i}`, '100'));
}

const escrows = await Promise.all(promises);
const ids = new Set(escrows.map(e => e.id));

expect(ids.size).toBe(numEscrows);

// Verify UUID format (basic check)
const sampleId = escrows[0].id;
expect(sampleId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
it('should be defined', () => {
expect(service).toBeDefined();
});
Expand Down Expand Up @@ -95,6 +111,43 @@ describe('EscrowService', () => {
});
});

describe('findByDepositor', () => {
it('returns paginated results for a depositor', async () => {
for (let i = 0; i < 5; i++) {
await service.create('GDEP', 'GBEN', '100');
}
await service.create('GOTHER', 'GBEN', '200');

const result = await service.findByDepositor('GDEP', 0, 3);

expect(result.total).toBe(5);
expect(result.data).toHaveLength(3);
});

it('returns empty data when offset exceeds total', async () => {
await service.create('GDEP', 'GBEN', '100');

const result = await service.findByDepositor('GDEP', 10, 20);

expect(result.total).toBe(1);
expect(result.data).toHaveLength(0);
});

it('returns empty data for unknown depositor', async () => {
await service.create('GDEP', 'GBEN', '100');

const result = await service.findByDepositor('GUNKNOWN', 0, 20);

expect(result.total).toBe(0);
expect(result.data).toHaveLength(0);
});
});

describe('fund', () => {
it('updates status to active for a pending escrow', async () => {
const escrow = await service.create('GDEP', 'GBEN', '100');
const updated = await service.fund(escrow.id);
expect(updated.status).toBe('active');
// ─── release() ────────────────────────────────────────────────────────────

describe('release()', () => {
Expand Down
11 changes: 9 additions & 2 deletions backend/src/escrow/escrow.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,15 @@ export class EscrowService {
return this.escrows.get(id);
}

async findByDepositor(address: string): Promise<Escrow[]> {
return [...this.escrows.values()].filter(e => e.depositor === address);
async findByDepositor(
address: string,
offset = 0,
limit = 20,
): Promise<{ data: Escrow[]; total: number }> {
const all = [...this.escrows.values()].filter(e => e.depositor === address);
const total = all.length;
const data = all.slice(offset, offset + limit);
return { data, total };
}

async findAll(): Promise<Escrow[]> {
Expand Down
46 changes: 42 additions & 4 deletions backend/src/gig/gig.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,50 @@ describe('GigController', () => {
});

describe('findByCreator', () => {
it('delegates to the service', async () => {
mockGigService.findByCreator.mockResolvedValue([{ id: 'gig-1' }]);
it('delegates to the service with default pagination', async () => {
mockGigService.findByCreator.mockResolvedValue({ data: [{ id: 'gig-1' }], total: 1 });
const address = 'GXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

await expect(controller.findByCreator(address)).resolves.toEqual([{ id: 'gig-1' }]);
expect(mockGigService.findByCreator).toHaveBeenCalledWith(address);
const result = await controller.findByCreator(address);

expect(result).toEqual({ data: [{ id: 'gig-1' }], total: 1 });
expect(mockGigService.findByCreator).toHaveBeenCalledWith(address, {
status: undefined,
minBudgetXLM: undefined,
maxBudgetXLM: undefined,
offset: 0,
limit: 20,
});
});

it('applies custom pagination and filters', async () => {
mockGigService.findByCreator.mockResolvedValue({ data: [], total: 0 });
const address = 'GXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

await controller.findByCreator(address, GigStatus.OPEN, '10', '100', 5, 10);

expect(mockGigService.findByCreator).toHaveBeenCalledWith(address, {
status: GigStatus.OPEN,
minBudgetXLM: '10',
maxBudgetXLM: '100',
offset: 5,
limit: 10,
});
});

it('clamps limit to max 100', async () => {
mockGigService.findByCreator.mockResolvedValue({ data: [], total: 0 });
const address = 'GXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

await controller.findByCreator(address, undefined, undefined, undefined, 0, 500);

expect(mockGigService.findByCreator).toHaveBeenCalledWith(address, {
status: undefined,
minBudgetXLM: undefined,
maxBudgetXLM: undefined,
offset: 0,
limit: 100,
});
});
});

Expand Down
Loading