celo-poll/lib/db/distributions.ts
2025-12-08 16:31:30 +03:00

233 lines
5.5 KiB
TypeScript

/**
* Distribution Database Operations
* Tracks all prize distributions to winners
*/
import { getDb } from './index'
import { sql } from 'drizzle-orm'
export interface Distribution {
id: number
pollId: string
userFid: string
userAddress: string
amount: number
txHash: string
timestamp: number
}
export async function recordDistribution(
pollId: string,
userFid: string,
userAddress: string,
amount: number,
txHash: string
): Promise<Distribution> {
try {
const db = getDb(process.env.DATABASE_URL!)
// Use raw SQL to insert since we don't have a distributions schema defined
const result = await db.execute(sql`
INSERT INTO distributions (
poll_id,
user_fid,
user_address,
amount,
tx_hash,
timestamp
) VALUES (
${pollId},
${userFid},
${userAddress},
${amount},
${txHash},
${Date.now()}
) RETURNING *
`)
// Convert result to our interface
const dist = result.rows[0] as any
return {
id: dist.id,
pollId: dist.poll_id,
userFid: dist.user_fid,
userAddress: dist.user_address,
amount: Number(dist.amount),
txHash: dist.tx_hash,
timestamp: Number(dist.timestamp),
}
} catch (error) {
console.error('Failed to record distribution:', error)
throw error
}
}
/**
* Get all distributions for a poll
*/
export async function getAllDistributions(
pollId: string
): Promise<Distribution[]> {
try {
const db = getDb(process.env.DATABASE_URL!)
const result = await db.execute(sql`
SELECT * FROM distributions
WHERE poll_id = ${pollId}
ORDER BY timestamp ASC
`)
return result.rows.map((dist: any) => ({
id: dist.id,
pollId: dist.poll_id,
userFid: dist.user_fid,
userAddress: dist.user_address,
amount: Number(dist.amount),
txHash: dist.tx_hash,
timestamp: Number(dist.timestamp),
createdAt: dist.created_at,
}))
} catch (error) {
console.error(`Failed to get distributions for poll ${pollId}:`, error)
return []
}
}
/**
* Get user's distributions (winnings)
*/
export async function getUserDistributions(
userFid: string
): Promise<Distribution[]> {
try {
const db = getDb(process.env.DATABASE_URL!)
const result = await db.execute(sql`
SELECT * FROM distributions
WHERE user_fid = ${userFid}
ORDER BY timestamp DESC
`)
return result.rows.map((dist: any) => ({
id: dist.id,
pollId: dist.poll_id,
userFid: dist.user_fid,
userAddress: dist.user_address,
amount: Number(dist.amount),
txHash: dist.tx_hash,
timestamp: Number(dist.timestamp),
createdAt: dist.created_at,
}))
} catch (error) {
console.error(`Failed to get distributions for user ${userFid}:`, error)
return []
}
}
/**
* Get total winnings for a user
*/
export async function getUserTotalWinnings(userFid: string): Promise<number> {
try {
const db = getDb(process.env.DATABASE_URL!)
const result = await db.execute(sql`
SELECT COALESCE(SUM(amount), 0) as total
FROM distributions
WHERE user_fid = ${userFid}
`)
return Number(result.rows[0]?.total || 0)
} catch (error) {
console.error(`Failed to get total winnings for user ${userFid}:`, error)
return 0
}
}
/**
* Get distribution statistics for a poll
*/
export async function getDistributionStats(pollId: string): Promise<{
totalDistributed: number
recipientCount: number
txHashes: string[]
}> {
try {
const db = getDb(process.env.DATABASE_URL!)
const result = await db.execute(sql`
SELECT
COALESCE(SUM(amount), 0) as total_distributed,
COUNT(*) as recipient_count,
array_agg(tx_hash) as tx_hashes
FROM distributions
WHERE poll_id = ${pollId}
`)
const stats = result.rows[0]
return {
totalDistributed: Number(stats?.total_distributed || 0),
recipientCount: Number(stats?.recipient_count || 0),
txHashes: Array.isArray(stats?.tx_hashes) ? stats.tx_hashes : [],
}
} catch (error) {
console.error(`Failed to get distribution stats for poll ${pollId}:`, error)
return {
totalDistributed: 0,
recipientCount: 0,
txHashes: [],
}
}
}
/**
* Check if poll has been fully distributed
*/
export async function isPollDistributed(pollId: string): Promise<boolean> {
try {
const db = getDb(process.env.DATABASE_URL!)
const result = await db.execute(sql`
SELECT distributed_at FROM polls WHERE id = ${pollId}
`)
const poll = result.rows[0]
return poll && poll.distributed_at !== null
} catch (error) {
console.error(`Failed to check if poll ${pollId} is distributed:`, error)
return false
}
}
/**
* Get recent distributions (all polls)
*/
export async function getRecentDistributions(
limit: number = 50
): Promise<Distribution[]> {
try {
const db = getDb(process.env.DATABASE_URL!)
const result = await db.execute(sql`
SELECT * FROM distributions
ORDER BY timestamp DESC
LIMIT ${limit}
`)
return result.rows.map((dist: any) => ({
id: dist.id,
pollId: dist.poll_id,
userFid: dist.user_fid,
userAddress: dist.user_address,
amount: Number(dist.amount),
txHash: dist.tx_hash,
timestamp: Number(dist.timestamp),
createdAt: dist.created_at,
}))
} catch (error) {
console.error('Failed to get recent distributions:', error)
return []
}
}