398 lines
9.9 KiB
TypeScript
398 lines
9.9 KiB
TypeScript
/**
|
|
* Poll Database Operations
|
|
* All database queries for polls using Neon PostgreSQL with Drizzle ORM
|
|
*/
|
|
|
|
import { getDb } from './index'
|
|
import { polls, pollOptions, votes, distributions } from './schema'
|
|
import { Poll, PollOption, Vote } from '@/types'
|
|
import { eq, and, desc, asc, count, sql, lt, gte } from 'drizzle-orm'
|
|
|
|
/**
|
|
* Create a new poll
|
|
*/
|
|
export async function createPoll(
|
|
poll: Omit<Poll, 'totalPot' | 'winnersCount' | 'protocolFee'>
|
|
): Promise<Poll> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
|
|
// Insert poll using Drizzle ORM
|
|
const [pollRow] = await db.insert(polls).values({
|
|
id: poll.id,
|
|
creatorFid: poll.creatorFid,
|
|
creatorAddress: poll.creatorAddress,
|
|
question: poll.question,
|
|
description: poll.description,
|
|
emoji: poll.emoji,
|
|
startTime: poll.startTime,
|
|
endTime: poll.endTime,
|
|
status: poll.status,
|
|
verificationType: poll.verificationType,
|
|
verificationConfig: poll.verificationConfig,
|
|
creationFee: poll.creationFee ? poll.creationFee.toString() : '5',
|
|
createdAt: Math.floor(Date.now() / 1000),
|
|
}).returning()
|
|
|
|
// Insert options
|
|
const optionInserts = poll.options.map((option, index) => ({
|
|
id: option.id,
|
|
pollId: pollRow.id,
|
|
text: option.text,
|
|
emoji: option.emoji,
|
|
position: index,
|
|
}))
|
|
|
|
await db.insert(pollOptions).values(optionInserts)
|
|
|
|
const result = await getPollById(pollRow.id)
|
|
if (!result) throw new Error('Failed to retrieve created poll')
|
|
return result
|
|
} catch (error) {
|
|
throw error
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get poll by ID with options
|
|
*/
|
|
export async function getPollById(pollId: string): Promise<Poll | null> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
|
|
const [poll] = await db.select().from(polls).where(eq(polls.id, pollId))
|
|
|
|
if (!poll) return null
|
|
|
|
const options = await db.select().from(pollOptions)
|
|
.where(eq(pollOptions.pollId, pollId))
|
|
.orderBy(asc(pollOptions.position))
|
|
|
|
return {
|
|
...poll,
|
|
options: options.map(opt => ({
|
|
id: opt.id,
|
|
text: opt.text,
|
|
emoji: opt.emoji,
|
|
votes: opt.votes,
|
|
totalAmount: Number(opt.totalAmount),
|
|
})),
|
|
totalPot: Number(poll.totalPot),
|
|
protocolFee: Number(poll.protocolFee),
|
|
creationFee: Number(poll.creationFee),
|
|
verificationConfig: poll.verificationConfig as any,
|
|
} as Poll
|
|
} catch (error) {
|
|
throw error
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get today's active poll (for homepage)
|
|
*/
|
|
export async function getTodaysPoll(): Promise<Poll | null> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
const now = Math.floor(Date.now() / 1000)
|
|
|
|
const [poll] = await db.select().from(polls)
|
|
.where(and(eq(polls.status, 'active'), gte(polls.endTime, now)))
|
|
.orderBy(desc(polls.createdAt))
|
|
.limit(1)
|
|
|
|
if (!poll) return null
|
|
|
|
return await getPollById(poll.id)
|
|
} catch (error) {
|
|
return null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get all active polls
|
|
*/
|
|
export async function getActivePolls(): Promise<Poll[]> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
|
|
const pollRows = await db.select().from(polls)
|
|
.where(eq(polls.status, 'active'))
|
|
.orderBy(desc(polls.createdAt))
|
|
|
|
const pollsList = await Promise.all(pollRows.map(p => getPollById(p.id)))
|
|
return pollsList.filter((poll): poll is Poll => poll !== null)
|
|
} catch (error) {
|
|
return []
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get all polls (for history)
|
|
*/
|
|
export async function getAllPolls(limit: number = 100): Promise<Poll[]> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
|
|
const pollRows = await db.select().from(polls)
|
|
.orderBy(desc(polls.createdAt))
|
|
.limit(limit)
|
|
|
|
const pollsList = await Promise.all(pollRows.map(p => getPollById(p.id)))
|
|
return pollsList.filter((poll): poll is Poll => poll !== null)
|
|
} catch (error) {
|
|
return []
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get user's vote for a poll
|
|
*/
|
|
export async function getUserVote(pollId: string, userFid: string): Promise<Vote | null> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
|
|
const [vote] = await db.select().from(votes)
|
|
.where(and(eq(votes.pollId, pollId), eq(votes.userFid, userFid)))
|
|
.limit(1)
|
|
|
|
if (!vote) return null
|
|
|
|
return {
|
|
id: vote.id,
|
|
pollId: vote.pollId,
|
|
userId: vote.userFid,
|
|
optionId: vote.optionId,
|
|
amount: Number(vote.amount),
|
|
txHash: vote.txHash,
|
|
timestamp: Number(vote.timestamp),
|
|
} as Vote
|
|
} catch (error) {
|
|
return null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get all votes for a poll
|
|
*/
|
|
export async function getPollVotes(pollId: string): Promise<Vote[]> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
|
|
const voteRows = await db.select().from(votes)
|
|
.where(eq(votes.pollId, pollId))
|
|
|
|
return voteRows.map(vote => ({
|
|
id: vote.id,
|
|
pollId: vote.pollId,
|
|
userId: vote.userFid,
|
|
optionId: vote.optionId,
|
|
amount: Number(vote.amount),
|
|
txHash: vote.txHash,
|
|
timestamp: Number(vote.timestamp),
|
|
})) as Vote[]
|
|
} catch (error) {
|
|
return []
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Mark poll as verified with result
|
|
*/
|
|
export async function markPollVerified(
|
|
pollId: string,
|
|
correctOptionId: string,
|
|
verificationProof: any
|
|
): Promise<void> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
|
|
await db.update(polls)
|
|
.set({
|
|
status: 'verified',
|
|
correctOptionId,
|
|
verifiedAt: Date.now(),
|
|
verificationProof: JSON.stringify(verificationProof),
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(eq(polls.id, pollId))
|
|
|
|
// Count winners
|
|
const [winnerCount] = await db.select({ count: count() })
|
|
.from(votes)
|
|
.where(and(eq(votes.pollId, pollId), eq(votes.optionId, correctOptionId)))
|
|
|
|
await db.update(polls)
|
|
.set({ winnersCount: winnerCount.count })
|
|
.where(eq(polls.id, pollId))
|
|
} catch (error) {
|
|
throw error
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Mark poll as distributed
|
|
*/
|
|
export async function markPollDistributed(
|
|
pollId: string,
|
|
distributionTxHashes: string[]
|
|
): Promise<void> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
|
|
await db.update(polls)
|
|
.set({
|
|
status: 'distributed',
|
|
distributedAt: Date.now(),
|
|
distributionTxHashes: distributionTxHashes as any,
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(eq(polls.id, pollId))
|
|
} catch (error) {
|
|
throw error
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get polls pending verification (closed but not verified)
|
|
*/
|
|
export async function getPollsPendingVerification(): Promise<Poll[]> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
const now = Date.now()
|
|
|
|
const pollRows = await db.select().from(polls)
|
|
.where(and(eq(polls.status, 'active'), lt(polls.endTime, now)))
|
|
.orderBy(asc(polls.endTime))
|
|
.limit(50)
|
|
|
|
const pollsList = await Promise.all(pollRows.map(p => getPollById(p.id)))
|
|
return pollsList.filter((poll): poll is Poll => poll !== null)
|
|
} catch (error) {
|
|
return []
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Log verification attempt
|
|
*/
|
|
export async function logVerificationAttempt(
|
|
pollId: string,
|
|
success: boolean,
|
|
resultData?: any,
|
|
errorMessage?: string
|
|
): Promise<void> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
|
|
await db.execute(sql`
|
|
INSERT INTO verification_attempts (poll_id, success, result_data, error_message)
|
|
VALUES (
|
|
${pollId},
|
|
${success},
|
|
${resultData ? JSON.stringify(resultData) : null},
|
|
${errorMessage || null}
|
|
)
|
|
`)
|
|
} catch (error) {
|
|
// Silent fail - verification logging should not break the main flow
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update poll pot and option totals when vote is added
|
|
*/
|
|
export async function updatePollTotals(
|
|
pollId: string,
|
|
optionId: string,
|
|
amount: number
|
|
): Promise<void> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
|
|
// Update option totals using SQL functions
|
|
await db.update(pollOptions)
|
|
.set({
|
|
votes: sql`${pollOptions.votes} + 1`,
|
|
totalAmount: sql`CAST(${pollOptions.totalAmount} AS DECIMAL) + ${amount.toString()}`,
|
|
})
|
|
.where(eq(pollOptions.id, optionId))
|
|
|
|
// Update poll totals using SQL functions
|
|
await db.update(polls)
|
|
.set({
|
|
totalPot: sql`CAST(${polls.totalPot} AS DECIMAL) + ${amount.toString()}`,
|
|
protocolFee: sql`(CAST(${polls.totalPot} AS DECIMAL) + ${amount.toString()}) * 0.05`,
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(eq(polls.id, pollId))
|
|
} catch (error) {
|
|
throw error
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Submit a vote for a poll
|
|
*/
|
|
export async function submitVote(
|
|
pollId: string,
|
|
userFid: string,
|
|
userAddress: string,
|
|
optionId: string,
|
|
amount: number,
|
|
txHash: string
|
|
): Promise<Vote> {
|
|
try {
|
|
const db = getDb(process.env.DATABASE_URL!)
|
|
|
|
if (!userAddress) {
|
|
throw new Error('User address is required')
|
|
}
|
|
|
|
// Insert the vote
|
|
const [vote] = await db.insert(votes).values({
|
|
pollId,
|
|
userFid,
|
|
userAddress,
|
|
optionId,
|
|
amount: amount.toString(),
|
|
txHash,
|
|
timestamp: sql`${Date.now()}`,
|
|
}).returning()
|
|
|
|
// Update poll totals
|
|
await updatePollTotals(pollId, optionId, amount)
|
|
|
|
return {
|
|
id: vote.id,
|
|
pollId: vote.pollId,
|
|
userId: vote.userFid,
|
|
optionId: vote.optionId,
|
|
amount: Number(vote.amount),
|
|
txHash: vote.txHash,
|
|
timestamp: Number(vote.timestamp),
|
|
} as Vote
|
|
} catch (error) {
|
|
throw error
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Calculate user's winnings based on poll result
|
|
*/
|
|
export function calculateWinnings(poll: Poll, userVote: Vote): number {
|
|
if (poll.status !== 'closed' || !poll.correctOptionId || userVote.optionId !== poll.correctOptionId) {
|
|
return 0
|
|
}
|
|
|
|
// Find the correct option
|
|
const correctOption = poll.options.find(opt => opt.id === poll.correctOptionId)
|
|
if (!correctOption) return 0
|
|
|
|
// Calculate proportional winnings
|
|
const totalCorrectAmount = correctOption.totalAmount
|
|
const userShare = userVote.amount / totalCorrectAmount
|
|
const netPot = poll.totalPot * 0.95 // 5% protocol fee
|
|
|
|
return userShare * netPot
|
|
}
|