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
10 changes: 5 additions & 5 deletions src/bounties/bounties.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ describe('BountiesController', () => {
difficulty: BountyDifficulty.INTERMEDIATE,
};

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

expect(bountiesService.create).toHaveBeenCalledWith(dto);
});
Expand All @@ -84,15 +84,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');
});
});

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,7 +116,7 @@ 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');
});
Expand Down Expand Up @@ -152,7 +152,7 @@ describe('BountiesController', () => {

it('accepts undefined when the query param is absent', async () => {
await expect(
pipe.transform(undefined, repositoryIdMetadata),
pipe.transform("" 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("" as any, repositoryIdMetadata),
).resolves.toBeUndefined();
});

Expand Down
12 changes: 6 additions & 6 deletions src/bounties/bounties.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ describe('BountiesService', () => {
amount: '100',
asset: AssetType.USDC,
difficulty: BountyDifficulty.INTERMEDIATE,
});
}, 'caller-1');
expect(bounty.status).toBe(BountyStatus.OPEN);
});

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

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

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

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

expect(escrowService.fund).toHaveBeenCalledWith(
expect.objectContaining({
Expand All @@ -119,7 +119,7 @@ describe('BountiesService', () => {
id: 'b1',
status: BountyStatus.FUNDED,
});
await expect(service.fund('b1', 'GFUNDER')).rejects.toThrow(
await expect(service.fund('b1', 'GFUNDER', 'caller-1')).rejects.toThrow(
InvalidBountyTransitionError,
);
});
Expand Down Expand Up @@ -208,7 +208,7 @@ describe('BountiesService', () => {
escrowId: 'escrow-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 @@ -221,7 +221,7 @@ describe('BountiesService', () => {
escrowId: null,
});

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);
Expand Down
13 changes: 6 additions & 7 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
9 changes: 9 additions & 0 deletions src/common/entities/payment.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
} from 'typeorm';
import { Escrow } from './escrow.entity';
import { User } from './user.entity';
import { Issue } from './issue.entity';
import { AssetType, PaymentStatus } from '../enums';

/**
Expand All @@ -25,6 +26,7 @@ import { AssetType, PaymentStatus } from '../enums';
*/
@Entity('payments')
@Index('IDX_payment_escrow', ['escrowId'])
@Index('UQ_payment_escrow_maintenance_issue', ['escrowId', 'maintenanceIssueId'], { unique: true })
export class Payment {
@PrimaryGeneratedColumn('uuid')
id: string;
Expand Down Expand Up @@ -67,6 +69,13 @@ export class Payment {
@Column({ type: 'varchar', nullable: true })
txHash: string | null;

@ManyToOne(() => Issue, { onDelete: 'SET NULL', nullable: true })
@JoinColumn({ name: 'maintenanceIssueId' })
maintenanceIssue?: Issue | null;

@Column({ type: 'varchar', nullable: true })
maintenanceIssueId?: string | null;

@CreateDateColumn()
createdAt: Date;

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
6 changes: 3 additions & 3 deletions src/common/stats/contributor-stats.sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export async function queryPayoutHeatmap(
.select(PAYMENT_UTC_DATE_SQL, 'date')
.addSelect('COUNT(*)', 'count')
.where('payment.recipientId = :userId', { userId })
.andWhere('payment.status = :paid', { paid: PaymentStatus.PAID });
.andWhere('payment.status = :paid', { paid: PaymentStatus.CONFIRMED });

if (range.from) {
pQb.andWhere('payment.createdAt >= :from', { from: range.from });
Expand Down Expand Up @@ -178,7 +178,7 @@ export async function queryTopClients(
"COALESCE(SUM(payment.amount) FILTER (WHERE payment.status = :paid AND payment.recipientId = :userId AND escrow.sponsorId IS NOT NULL), 0)",
'totalPaid',
)
.setParameter('paid', PaymentStatus.PAID)
.setParameter('paid', PaymentStatus.CONFIRMED)
.setParameter('userId', userId)
.groupBy('escrow.sponsorId')
.orderBy('totalPaid', 'DESC')
Expand Down Expand Up @@ -260,7 +260,7 @@ export async function queryContributorCoreStats(
"COALESCE(SUM(payment.amount) FILTER (WHERE payment.status = :paid AND payment.recipientId = :userId), 0)",
'totalPaid',
)
.setParameter('paid', PaymentStatus.PAID)
.setParameter('paid', PaymentStatus.CONFIRMED)
.setParameter('userId', userId)
.getRawOne<{ totalPaid: string }>()
: Promise.resolve({ totalPaid: '0' }),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

/**
* Adds `payments.maintenanceIssueId` and unique index `UQ_payment_escrow_maintenance_issue` (#458).
*
* Prevents race conditions and duplicate reward payouts for the same maintenance issue
* from a pool escrow.
*/
export class AddPaymentMaintenanceIssueIdAndUniqueIndex1785400000000
implements MigrationInterface
{
name = 'AddPaymentMaintenanceIssueIdAndUniqueIndex1785400000000';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "payments" ADD COLUMN IF NOT EXISTS "maintenanceIssueId" character varying`,
);
await queryRunner.query(
`ALTER TABLE "payments" ADD CONSTRAINT "FK_payment_maintenance_issue" FOREIGN KEY ("maintenanceIssueId") REFERENCES "issues"("id") ON DELETE SET NULL`,
);
await queryRunner.query(
`CREATE UNIQUE INDEX IF NOT EXISTS "UQ_payment_escrow_maintenance_issue" ON "payments" ("escrowId", "maintenanceIssueId") WHERE "maintenanceIssueId" IS NOT NULL`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`DROP INDEX IF EXISTS "UQ_payment_escrow_maintenance_issue"`,
);
await queryRunner.query(
`ALTER TABLE "payments" DROP CONSTRAINT IF EXISTS "FK_payment_maintenance_issue"`,
);
await queryRunner.query(
`ALTER TABLE "payments" DROP COLUMN IF EXISTS "maintenanceIssueId"`,
);
}
}
10 changes: 4 additions & 6 deletions src/escrow/escrow.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { EscrowController } from './escrow.controller';
import { EscrowService } from './escrow.service';
import { FundEscrowDto } from './dto/fund-escrow.dto';
import { AssetType } from '../common/enums';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { ROLES_KEY } from '../auth/decorators/roles.decorator';
Expand All @@ -15,7 +13,7 @@ import { IDEMPOTENCY_SCOPE_KEY } from '../common/idempotency/idempotent.decorato
import { IdempotencyKey } from '../common/entities/idempotency-key.entity';
import type { Escrow } from '../common/entities';
import { AssetType, EscrowStatus, PaymentStatus } from '../common/enums';
import type { FundEscrowDto } from './dto/fund-escrow.dto';
import { FundEscrowDto } from './dto/fund-escrow.dto';
import type { SplitRecipientDto } from './dto/split-release.dto';

// These tests call the REAL EscrowController methods off a compiled Nest
Expand All @@ -27,7 +25,7 @@ import type { SplitRecipientDto } from './dto/split-release.dto';
describe('EscrowController', () => {
let controller: EscrowController;

const escrowRow = (overrides: Partial<EscrowEntity> = {}) =>
const escrowRow = (overrides: Partial<Escrow> = {}) =>
({
id: 'escrow-1',
amount: '10.0000000',
Expand Down Expand Up @@ -115,7 +113,7 @@ describe('EscrowController', () => {
});

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

expect(mockEscrowService.release).toHaveBeenCalledWith(
'escrow-1',
Expand All @@ -142,7 +140,7 @@ describe('EscrowController', () => {
{ recipientAddress: 'GB', percentage: 50 },
];

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

expect(mockEscrowService.splitRelease).toHaveBeenCalledWith(
'escrow-1',
Expand Down
4 changes: 2 additions & 2 deletions src/escrow/escrow.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ 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');
expect(args[4]).toEqual(expect.objectContaining({ __sorobanU64: expect.any(BigInt) }));
expect(escrow.status).toBe(EscrowStatus.LOCKED);
expect(escrow.fundTxHash).toBe('tx-hash-123');
});
Expand Down Expand Up @@ -645,7 +645,7 @@ describe('EscrowService', () => {
'10.0000000',
'GRECIPIENT',
undefined,
dataSource.manager,
dataSource.manager as any,
);

// #254: the lock and the caller's writes share the caller's transaction.
Expand Down
Loading