195 lines
6.1 KiB
TypeScript
195 lines
6.1 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getDb } from '@/lib/db';
|
|
import { polls, votes, distributions } from '@/lib/db/schema';
|
|
import { eq, and, sql } from 'drizzle-orm';
|
|
import { markPollDistributed } from '@/lib/db/polls';
|
|
import { distributePrizes } from '@/lib/distribution';
|
|
import { v4 as uuidv4 } from 'uuid';
|
|
|
|
interface DistributionRunLog {
|
|
timestamp: number;
|
|
runId: string;
|
|
processedPolls: number;
|
|
successfulDistributions: number;
|
|
failedDistributions: number;
|
|
totalDistributed: number;
|
|
errors: string[];
|
|
}
|
|
|
|
function generateRunId(): string {
|
|
return `distribute-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
}
|
|
|
|
function logDistributionRun(log: DistributionRunLog) {
|
|
console.log(`[${log.timestamp}] Cron Distribution Run ${log.runId}:`, {
|
|
processed: log.processedPolls,
|
|
successful: log.successfulDistributions,
|
|
failed: log.failedDistributions,
|
|
totalDistributed: `${log.totalDistributed} cUSD`,
|
|
errors: log.errors
|
|
});
|
|
|
|
// In production, you would send this to your logging service
|
|
if (process.env.NODE_ENV === 'production') {
|
|
// Send to monitoring service (e.g., DataDog, New Relic, etc.)
|
|
}
|
|
}
|
|
|
|
export async function GET(request: Request) {
|
|
const runId = generateRunId();
|
|
const startTime = Date.now();
|
|
const log: DistributionRunLog = {
|
|
timestamp: startTime,
|
|
runId,
|
|
processedPolls: 0,
|
|
successfulDistributions: 0,
|
|
failedDistributions: 0,
|
|
totalDistributed: 0,
|
|
errors: []
|
|
};
|
|
|
|
try {
|
|
// Security: Verify cron secret
|
|
const cronSecret = process.env.CRON_SECRET;
|
|
if (cronSecret) {
|
|
const authHeader = request.headers.get('Authorization');
|
|
const expectedAuth = `Bearer ${cronSecret}`;
|
|
|
|
if (authHeader !== expectedAuth) {
|
|
console.warn(`[${runId}] Unauthorized distribution cron attempt from ${request.headers.get('user-agent')}`);
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
}
|
|
|
|
console.log(`[${runId}] Starting distribution cron job...`);
|
|
|
|
// Check if protocol wallet is configured
|
|
const protocolKey = process.env.PROTOCOL_WALLET_PRIVATE_KEY;
|
|
if (!protocolKey) {
|
|
const errorMsg = 'PROTOCOL_WALLET_PRIVATE_KEY not configured';
|
|
log.errors.push(errorMsg);
|
|
console.error(`[${runId}] ${errorMsg}`);
|
|
return NextResponse.json({ error: errorMsg, runId }, { status: 500 });
|
|
}
|
|
|
|
const db = getDb(process.env.DATABASE_URL!);
|
|
|
|
// Get polls that need distribution (verified but not distributed)
|
|
const pollsToDistribute = await db.select()
|
|
.from(polls)
|
|
.where(and(
|
|
eq(polls.status, 'verified'),
|
|
sql`${polls.correctOptionId} IS NOT NULL` // Find polls WITH correctOptionId
|
|
))
|
|
.limit(25); // Process max 25 polls per run
|
|
|
|
log.processedPolls = pollsToDistribute.length;
|
|
console.log(`[${runId}] Found ${pollsToDistribute.length} polls for distribution`);
|
|
|
|
for (const poll of pollsToDistribute) {
|
|
try {
|
|
if (!poll.correctOptionId) {
|
|
console.warn(`[${runId}] Poll ${poll.id} has no correct option, skipping`);
|
|
continue;
|
|
}
|
|
|
|
console.log(`[${runId}] Distributing prizes for poll ${poll.id}: ${poll.question}`);
|
|
|
|
// Get winning votes
|
|
const winningVotes = await db.select()
|
|
.from(votes)
|
|
.where(and(
|
|
eq(votes.pollId, poll.id),
|
|
eq(votes.optionId, poll.correctOptionId)
|
|
));
|
|
|
|
if (winningVotes.length === 0) {
|
|
console.log(`[${runId}] No winners for poll ${poll.id}, marking as distributed`);
|
|
await markPollDistributed(poll.id, []);
|
|
continue;
|
|
}
|
|
|
|
// Perform distribution
|
|
const distributionResults = await distributePrizes(
|
|
poll,
|
|
winningVotes,
|
|
poll.totalPot,
|
|
protocolKey
|
|
);
|
|
|
|
let totalDistributedThisPoll = 0;
|
|
|
|
// Record distributions in database
|
|
for (const result of distributionResults) {
|
|
try {
|
|
await db.insert(distributions).values({
|
|
id: uuidv4(),
|
|
pollId: poll.id,
|
|
userFid: result.userFid,
|
|
userAddress: result.userAddress,
|
|
amount: result.amount,
|
|
txHash: result.txHash,
|
|
timestamp: Date.now(),
|
|
});
|
|
|
|
totalDistributedThisPoll += parseFloat(result.amount);
|
|
console.log(`[${runId}] ✅ Distributed ${result.amount} cUSD to ${result.userFid}: ${result.txHash}`);
|
|
|
|
} catch (dbError) {
|
|
const errorMsg = `Failed to record distribution for ${result.userFid}: ${dbError}`;
|
|
log.errors.push(errorMsg);
|
|
console.error(`[${runId}] ${errorMsg}`);
|
|
}
|
|
}
|
|
|
|
// Mark poll as distributed
|
|
const txHashes = distributionResults.map(r => r.txHash);
|
|
await markPollDistributed(poll.id, txHashes);
|
|
|
|
log.successfulDistributions++;
|
|
log.totalDistributed += totalDistributedThisPoll;
|
|
|
|
console.log(`[${runId}] ✅ Poll ${poll.id} distribution complete: ${totalDistributedThisPoll} cUSD to ${distributionResults.length} winners`);
|
|
|
|
} catch (error) {
|
|
const errorMsg = `Failed to distribute poll ${poll.id}: ${error}`;
|
|
log.errors.push(errorMsg);
|
|
log.failedDistributions++;
|
|
console.error(`[${runId}] ${errorMsg}`);
|
|
}
|
|
}
|
|
|
|
const duration = Date.now() - startTime;
|
|
console.log(`[${runId}] Distribution cron completed in ${duration}ms`);
|
|
|
|
logDistributionRun(log);
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
duration,
|
|
...log
|
|
});
|
|
|
|
} catch (error) {
|
|
const errorMsg = `Critical error in distribution cron: ${error}`;
|
|
log.errors.push(errorMsg);
|
|
logDistributionRun(log);
|
|
|
|
console.error(`[${runId}] ${errorMsg}`);
|
|
|
|
// In production, you would alert on critical failures
|
|
if (process.env.NODE_ENV === 'production') {
|
|
// Send critical alert (email, Slack, etc.)
|
|
}
|
|
|
|
return NextResponse.json(
|
|
{
|
|
error: 'Internal server error',
|
|
runId,
|
|
errors: log.errors
|
|
},
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|