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
6 changes: 6 additions & 0 deletions prisma/migrations/20260721010244_refund_flow/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- AlterEnum
ALTER TYPE "BlockchainTxType" ADD VALUE 'REFUND';

-- AlterTable
ALTER TABLE "tickets" ADD COLUMN "refund_tx_hash" TEXT,
ADD COLUMN "refunded_at" TIMESTAMP(3);
3 changes: 3 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ enum BlockchainTxType {
WITHDRAW
SET_FEES
SET_ADMINS
REFUND
}

enum TicketAdminStatus {
Expand Down Expand Up @@ -339,6 +340,8 @@ model Ticket {
status TicketStatus @default(PENDING)
deliveryChannel DeliveryChannel @map("delivery_channel")
checkedInAt DateTime? @map("checked_in_at")
refundedAt DateTime? @map("refunded_at")
refundTxHash String? @map("refund_tx_hash")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")

Expand Down
13 changes: 13 additions & 0 deletions src/blockchain/blockchain.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ import { EventPublishProcessor } from './event-publish.processor';
import { MintFinalizerService } from './mint-finalizer.service';
import { MintQueueService, TICKET_MINT_QUEUE } from './mint-queue.service';
import { MintTicketProcessor } from './mint-ticket.processor';
import { RefundFinalizerService } from './refund-finalizer.service';
import { RefundProcessor } from './refund.processor';
import {
RefundQueueService,
TICKET_REFUND_QUEUE,
} from './refund-queue.service';
import { TicketCheckinProcessor } from './ticket-checkin.processor';

/**
Expand Down Expand Up @@ -49,6 +55,9 @@ import { TicketCheckinProcessor } from './ticket-checkin.processor';
BullModule.registerQueue({ name: 'event-publish' }),
BullModule.registerQueue({ name: TICKET_MINT_QUEUE }),
BullModule.registerQueue({ name: TICKET_CHECKIN_QUEUE }),
// Consumer side of the refund queue; EventsModule registers the
// producer side. registerQueue is idempotent across modules.
BullModule.registerQueue({ name: TICKET_REFUND_QUEUE }),
// Consumer side of the Circle webhook queue. The WebhooksModule
// registers the producer side; registerQueue is idempotent.
BullModule.registerQueue({ name: CIRCLE_WEBHOOK_QUEUE }),
Expand All @@ -61,6 +70,9 @@ import { TicketCheckinProcessor } from './ticket-checkin.processor';
MintFinalizerService,
MintQueueService,
MintTicketProcessor,
RefundFinalizerService,
RefundQueueService,
RefundProcessor,
CheckinQueueService,
TicketCheckinProcessor,
CircleWebhookProcessor,
Expand All @@ -71,6 +83,7 @@ import { TicketCheckinProcessor } from './ticket-checkin.processor';
CircleContractService,
MintFinalizerService,
MintQueueService,
RefundQueueService,
CheckinQueueService,
],
})
Expand Down
3 changes: 3 additions & 0 deletions src/blockchain/circle-webhook.processor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ function setup(opts: {
const findBt = jest.fn().mockResolvedValue(opts.bt ?? null);
const reconcile = jest.fn().mockResolvedValue(undefined);
const finalize = jest.fn().mockResolvedValue(true);
const refundFinalize = jest.fn().mockResolvedValue(true);
const enqueueMint = jest.fn().mockResolvedValue(undefined);

const findDeposit = jest.fn().mockResolvedValue(opts.deposit ?? null);
Expand All @@ -68,6 +69,7 @@ function setup(opts: {
prisma as never,
{ reconcile } as never,
{ finalize } as never,
{ finalize: refundFinalize } as never,
{ enqueueMint } as never,
);

Expand All @@ -78,6 +80,7 @@ function setup(opts: {
findBt,
reconcile,
finalize,
refundFinalize,
enqueueMint,
findDeposit,
updateDeposit,
Expand Down
9 changes: 9 additions & 0 deletions src/blockchain/circle-webhook.processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { CircleContractService } from './circle-contract.service';
import { MintFinalizerService } from './mint-finalizer.service';
import { MintQueueService } from './mint-queue.service';
import { RefundFinalizerService } from './refund-finalizer.service';
import {
CIRCLE_WEBHOOK_JOB,
CIRCLE_WEBHOOK_QUEUE,
Expand Down Expand Up @@ -59,6 +60,7 @@ export class CircleWebhookProcessor extends WorkerHost {
private readonly prisma: PrismaService,
private readonly circle: CircleContractService,
private readonly finalizer: MintFinalizerService,
private readonly refundFinalizer: RefundFinalizerService,
private readonly mintQueue: MintQueueService,
) {
super();
Expand Down Expand Up @@ -265,6 +267,13 @@ export class CircleWebhookProcessor extends WorkerHost {
);
}
await this.finalizer.finalize(bt.ticketId, tx.txHash);
} else if (bt.type === BlockchainTxType.REFUND && bt.ticketId) {
if (!tx.txHash) {
throw new Error(
`Confirmed refund webhook for ${circleTxId} has no txHash`,
);
}
await this.refundFinalizer.finalize(bt.ticketId, tx.txHash);
} else if (bt.type === BlockchainTxType.CHECKIN) {
// The door already flipped the ticket to USED (#24); the
// confirmed CHECKIN tx is the on-chain audit record, now
Expand Down
85 changes: 85 additions & 0 deletions src/blockchain/refund-finalizer.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { Injectable, Logger } from '@nestjs/common';
import { TicketStatus } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';

/**
* Shared post-refund finalization. Given a confirmed `claimRefund` tx
* hash, flips the Ticket to REFUNDED, stamps `refundedAt`/`refundTxHash`,
* and releases the seat by decrementing the TicketType's soldCount.
*
* Extracted so both completion paths drive it identically:
* - the polling fallback in RefundProcessor, and
* - the Circle webhook handler, authoritative once
* `circle.webhooksEnabled` is on.
*
* Idempotent: a ticket already REFUNDED is a no-op, so whichever path
* wins the race finalizes and the other simply returns — the soldCount
* decrement therefore runs at most once per ticket.
*/
@Injectable()
export class RefundFinalizerService {
private readonly logger = new Logger(RefundFinalizerService.name);

constructor(private readonly prisma: PrismaService) {}

/**
* Finalize a refunded ticket from its confirmed tx hash. Returns true
* if it performed finalization, false if it was a no-op (already
* finalized by the other completion path).
*/
async finalize(ticketId: string, txHash: string): Promise<boolean> {
const ticket = await this.prisma.ticket.findUnique({
where: { id: ticketId },
select: { id: true, status: true, ticketTypeId: true },
});

if (!ticket) {
throw new Error(`Ticket ${ticketId} not found`);
}

// Idempotency — already finalized (webhook + poll race, or webhook
// re-delivery). Guard the soldCount decrement behind the status flip
// so it can never double-count.
if (ticket.status === TicketStatus.REFUNDED) {
this.logger.log(
`Ticket ${ticketId} already refunded; skipping finalization`,
);
return false;
}

// Flip status + release the seat atomically. updateMany with a
// status guard makes the write a compare-and-set: a concurrent
// finalizer that already flipped the row updates zero rows, so we
// skip the decrement for it too.
const flipped = await this.prisma.$transaction(async (db) => {
const { count } = await db.ticket.updateMany({
where: { id: ticketId, status: { not: TicketStatus.REFUNDED } },
data: {
status: TicketStatus.REFUNDED,
refundedAt: new Date(),
refundTxHash: txHash,
},
});

if (count === 0) {
return false;
}

await db.ticketType.update({
where: { id: ticket.ticketTypeId },
data: { soldCount: { decrement: 1 } },
});
return true;
});

if (!flipped) {
this.logger.log(
`Ticket ${ticketId} refunded by a concurrent finalizer; skipping`,
);
return false;
}

this.logger.log(`Ticket refunded (ticket=${ticketId}, txHash=${txHash})`);
return true;
}
}
74 changes: 74 additions & 0 deletions src/blockchain/refund-queue.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { InjectQueue } from '@nestjs/bullmq';
import { Injectable, Logger } from '@nestjs/common';
import { BlockchainTxStatus, BlockchainTxType } from '@prisma/client';
import { Queue } from 'bullmq';
import { PrismaService } from '../prisma/prisma.service';

export const TICKET_REFUND_QUEUE = 'ticket-refund';
export const REFUND_TICKET_JOB = 'refund-ticket';

export interface RefundTicketJobData {
ticketId: string;
eventId: string;
blockchainTxId: string;
}

/**
* Producer for the `ticket-refund` queue. Called when a PUBLISHED event
* with sold tickets is cancelled — one enqueue per crypto-paid Ticket,
* so a cancelled event with N such tickets fans out into N independent
* refund jobs (mirrors MintQueueService).
*
* Only crypto (USDC) tickets are enqueued: the on-chain `claimRefund`
* reverts `FiatTicketNotRefundable` for fiat-minted tickets, so those
* are handled off-chain (out of scope here — cancelEvent logs them as
* pending). The producer stays rail-agnostic; the caller filters.
*
* The BlockchainTransaction row is written eagerly at enqueue time so we
* always have an audit row. The worker (RefundProcessor) attaches the
* Circle transaction id to this row when it submits to the chain.
*/
@Injectable()
export class RefundQueueService {
private readonly logger = new Logger(RefundQueueService.name);

constructor(
private readonly prisma: PrismaService,
@InjectQueue(TICKET_REFUND_QUEUE) private readonly queue: Queue,
) {}

async enqueueRefund(ticketId: string, eventId: string): Promise<void> {
const blockchainTx = await this.prisma.blockchainTransaction.create({
data: {
ticketId,
eventId,
type: BlockchainTxType.REFUND,
status: BlockchainTxStatus.PENDING,
},
});

await this.queue.add(
REFUND_TICKET_JOB,
{
ticketId,
eventId,
blockchainTxId: blockchainTx.id,
} satisfies RefundTicketJobData,
{
// Refund moves real on-chain value (escrowed USDC back to the
// buyer). Five attempts with exponential backoff rides out
// transient Circle outages; the processor short-circuits the
// contract's terminal reverts (window expired, not refundable)
// so those don't burn the full retry budget.
attempts: 5,
backoff: { type: 'exponential', delay: 10_000 },
removeOnComplete: { age: 60 * 60 * 24, count: 1000 },
removeOnFail: { age: 60 * 60 * 24 * 7 },
},
);

this.logger.log(
`Queued ticket-refund for ticket=${ticketId} event=${eventId} blockchainTxId=${blockchainTx.id}`,
);
}
}
Loading
Loading