287 lines
8.0 KiB
TypeScript
287 lines
8.0 KiB
TypeScript
import { createWalletClient, http, parseEther, publicActions } from 'viem';
|
|
import { privateKeyToAccount } from 'viem/accounts';
|
|
import { celo } from 'viem/chains';
|
|
import { CUSD_ADDRESS, CUSD_ABI, PROTOCOL_CONFIG } from './celo';
|
|
import { formatCUSD } from './format';
|
|
|
|
export interface DistributionResult {
|
|
userFid: string;
|
|
userAddress: string;
|
|
amount: string; // in cUSD
|
|
txHash: string;
|
|
success: boolean;
|
|
error?: string;
|
|
}
|
|
|
|
export interface DistributionConfig {
|
|
pollId: string;
|
|
totalPot: number; // in cUSD
|
|
protocolFeePercentage?: number; // default 5%
|
|
winnersPotPercentage?: number; // default 95%
|
|
minimumDistribution?: number; // default 0.001 cUSD
|
|
}
|
|
|
|
/**
|
|
* Distribute prizes to poll winners
|
|
*
|
|
* This function calculates proportional payouts and sends cUSD to winners
|
|
*/
|
|
export async function distributePrizes(
|
|
poll: any,
|
|
winningVotes: any[],
|
|
totalPot: number | string,
|
|
protocolPrivateKey: string
|
|
): Promise<DistributionResult[]> {
|
|
|
|
if (!winningVotes || winningVotes.length === 0) {
|
|
console.log('No winning votes to distribute');
|
|
return [];
|
|
}
|
|
|
|
const totalPotNumber = typeof totalPot === 'string' ? parseFloat(totalPot) : totalPot;
|
|
|
|
// Calculate distribution amounts
|
|
const winnersPot = totalPotNumber * PROTOCOL_CONFIG.FEES.WINNERS_PERCENTAGE;
|
|
const protocolFee = totalPotNumber * PROTOCOL_CONFIG.FEES.PROTOCOL_FEE_PERCENTAGE;
|
|
|
|
console.log(`Distributing prizes:`, {
|
|
totalPot: totalPotNumber,
|
|
winnersPot,
|
|
protocolFee,
|
|
winnersCount: winningVotes.length
|
|
});
|
|
|
|
// Calculate proportional shares
|
|
const totalWinningAmount = winningVotes.reduce((sum, vote) => sum + parseFloat(vote.amount), 0);
|
|
|
|
const distributionResults: DistributionResult[] = [];
|
|
|
|
// Set up wallet client
|
|
const account = privateKeyToAccount(protocolPrivateKey as `0x${string}`);
|
|
const client = createWalletClient({
|
|
account,
|
|
chain: celo,
|
|
transport: http(process.env.NEXT_PUBLIC_CELO_RPC_URL || 'https://forno.celo.org'),
|
|
}).extend(publicActions);
|
|
|
|
for (const vote of winningVotes) {
|
|
try {
|
|
// Calculate winner's share
|
|
const voteAmount = parseFloat(vote.amount);
|
|
const sharePercentage = voteAmount / totalWinningAmount;
|
|
const winnerShare = winnersPot * sharePercentage;
|
|
|
|
// Skip if below minimum distribution
|
|
if (winnerShare < PROTOCOL_CONFIG.MINIMUMS.DISTRIBUTION) {
|
|
console.log(`Skipping distribution to ${vote.userFid}: amount ${winnerShare} below minimum`);
|
|
continue;
|
|
}
|
|
|
|
console.log(`Sending ${winnerShare} cUSD to ${vote.userFid} (${vote.userAddress})`);
|
|
|
|
// Send cUSD to winner
|
|
const hash = await client.writeContract({
|
|
address: CUSD_ADDRESS,
|
|
abi: CUSD_ABI,
|
|
functionName: 'transfer',
|
|
args: [vote.userAddress as `0x${string}`, parseEther(winnerShare.toString())],
|
|
});
|
|
|
|
console.log(`✅ Distribution successful: ${formatCUSD(winnerShare)} to ${vote.userFid}`);
|
|
|
|
distributionResults.push({
|
|
userFid: vote.userFid,
|
|
userAddress: vote.userAddress,
|
|
amount: winnerShare.toString(),
|
|
txHash: hash,
|
|
success: true,
|
|
});
|
|
|
|
// Wait between transactions to avoid nonce issues
|
|
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
|
|
} catch (error) {
|
|
console.error(`❌ Failed to distribute to ${vote.userFid}:`, error);
|
|
|
|
distributionResults.push({
|
|
userFid: vote.userFid,
|
|
userAddress: vote.userAddress,
|
|
amount: '0',
|
|
txHash: '',
|
|
success: false,
|
|
error: error instanceof Error ? error.message : String(error),
|
|
});
|
|
}
|
|
}
|
|
|
|
const successfulDistributions = distributionResults.filter(r => r.success).length;
|
|
const totalDistributed = distributionResults
|
|
.filter(r => r.success)
|
|
.reduce((sum, r) => sum + parseFloat(r.amount), 0);
|
|
|
|
console.log(`Distribution complete:`, {
|
|
totalRecipients: winningVotes.length,
|
|
successfulDistributions,
|
|
totalDistributed: totalDistributed.toFixed(4),
|
|
protocolFee: protocolFee.toFixed(4)
|
|
});
|
|
|
|
return distributionResults;
|
|
}
|
|
|
|
/**
|
|
* Calculate distribution amounts without executing transactions
|
|
*/
|
|
export function calculateDistributionAmounts(
|
|
poll: any,
|
|
winningVotes: any[],
|
|
config: DistributionConfig
|
|
): {
|
|
totalPot: number;
|
|
winnersPot: number;
|
|
protocolFee: number;
|
|
distributions: Array<{
|
|
userFid: string;
|
|
userAddress: string;
|
|
voteAmount: number;
|
|
sharePercentage: number;
|
|
distributionAmount: number;
|
|
}>;
|
|
} {
|
|
const totalPot = typeof config.totalPot === 'string' ? parseFloat(config.totalPot) : config.totalPot;
|
|
const protocolFeePercentage = config.protocolFeePercentage ?? PROTOCOL_CONFIG.FEES.PROTOCOL_FEE_PERCENTAGE;
|
|
const winnersPotPercentage = config.winnersPotPercentage ?? PROTOCOL_CONFIG.FEES.WINNERS_PERCENTAGE;
|
|
const minimumDistribution = config.minimumDistribution ?? PROTOCOL_CONFIG.MINIMUMS.DISTRIBUTION;
|
|
|
|
const winnersPot = totalPot * winnersPotPercentage;
|
|
const protocolFee = totalPot * protocolFeePercentage;
|
|
const totalWinningAmount = winningVotes.reduce((sum, vote) => sum + parseFloat(vote.amount), 0);
|
|
|
|
const distributions = winningVotes
|
|
.map(vote => {
|
|
const voteAmount = parseFloat(vote.amount);
|
|
const sharePercentage = voteAmount / totalWinningAmount;
|
|
const distributionAmount = winnersPot * sharePercentage;
|
|
|
|
return {
|
|
userFid: vote.userFid,
|
|
userAddress: vote.userAddress,
|
|
voteAmount,
|
|
sharePercentage,
|
|
distributionAmount: distributionAmount >= minimumDistribution ? distributionAmount : 0,
|
|
};
|
|
})
|
|
.filter(d => d.distributionAmount > 0);
|
|
|
|
return {
|
|
totalPot,
|
|
winnersPot,
|
|
protocolFee,
|
|
distributions,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Validate distribution before execution
|
|
*/
|
|
export function validateDistribution(
|
|
poll: any,
|
|
winningVotes: any[],
|
|
config: DistributionConfig
|
|
): { valid: boolean; errors: string[] } {
|
|
const errors: string[] = [];
|
|
|
|
if (!poll) {
|
|
errors.push('Poll data is required');
|
|
}
|
|
|
|
if (!winningVotes || winningVotes.length === 0) {
|
|
errors.push('No winning votes provided');
|
|
}
|
|
|
|
if (!config.totalPot || config.totalPot <= 0) {
|
|
errors.push('Invalid total pot amount');
|
|
}
|
|
|
|
if (!process.env.PROTOCOL_WALLET_PRIVATE_KEY) {
|
|
errors.push('Protocol wallet private key not configured');
|
|
}
|
|
|
|
// Check if protocol wallet has sufficient balance
|
|
// This would require a balance check function
|
|
|
|
return {
|
|
valid: errors.length === 0,
|
|
errors,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Batch distribute to multiple polls (for cron jobs)
|
|
*/
|
|
export async function batchDistributePrizes(
|
|
polls: any[],
|
|
protocolPrivateKey: string
|
|
): Promise<{
|
|
pollId: string;
|
|
results: DistributionResult[];
|
|
totalDistributed: number;
|
|
}[]> {
|
|
|
|
const batchResults = [];
|
|
|
|
for (const poll of polls) {
|
|
try {
|
|
console.log(`Processing distribution for poll ${poll.id}`);
|
|
|
|
// Get winning votes for this poll
|
|
const { getDb } = await import('@/lib/db');
|
|
const db = getDb(process.env.DATABASE_URL!);
|
|
const { votes } = await import('@/lib/db/schema');
|
|
const { eq, and } = await import('drizzle-orm');
|
|
|
|
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(`No winners for poll ${poll.id}, skipping`);
|
|
continue;
|
|
}
|
|
|
|
const results = await distributePrizes(
|
|
poll,
|
|
winningVotes,
|
|
poll.totalPot,
|
|
protocolPrivateKey
|
|
);
|
|
|
|
const totalDistributed = results
|
|
.filter(r => r.success)
|
|
.reduce((sum, r) => sum + parseFloat(r.amount), 0);
|
|
|
|
batchResults.push({
|
|
pollId: poll.id,
|
|
results,
|
|
totalDistributed,
|
|
});
|
|
|
|
console.log(`Poll ${poll.id} distribution complete: ${totalDistributed} cUSD`);
|
|
|
|
} catch (error) {
|
|
console.error(`Failed to process distribution for poll ${poll.id}:`, error);
|
|
|
|
batchResults.push({
|
|
pollId: poll.id,
|
|
results: [],
|
|
totalDistributed: 0,
|
|
});
|
|
}
|
|
}
|
|
|
|
return batchResults;
|
|
}
|