2025-12-08 16:31:30 +03:00

270 lines
11 KiB
TypeScript

'use client';
import { useState } from 'react';
import { useAccount, useSendTransaction } from 'wagmi';
import { parseEther } from 'viem';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Plus, Trash2 } from 'lucide-react';
// Protocol wallet address (replace with your own for production)
const PROTOCOL_WALLET = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e'; // Example address
export default function CreatePollPage() {
const router = useRouter();
const { address } = useAccount();
const { sendTransactionAsync, isPending: isSending } = useSendTransaction();
const [question, setQuestion] = useState('');
const [description, setDescription] = useState('');
const [emoji, setEmoji] = useState('📊');
const [options, setOptions] = useState(['Yes', 'No']);
const [verificationType, setVerificationType] = useState('manual');
const [chainlinkConfig, setChainlinkConfig] = useState({ feed: '', target: '', type: 'above' });
const [error, setError] = useState('');
const [isCreating, setIsCreating] = useState(false);
const handleAddOption = () => {
if (options.length < 4) {
setOptions([...options, '']);
}
};
const handleRemoveOption = (index: number) => {
if (options.length > 2) {
const newOptions = [...options];
newOptions.splice(index, 1);
setOptions(newOptions);
}
};
const handleOptionChange = (index: number, value: string) => {
const newOptions = [...options];
newOptions[index] = value;
setOptions(newOptions);
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
if (!question.trim()) {
setError('Question is required');
return;
}
if (options.some(opt => !opt.trim())) {
setError('All options must be filled');
return;
}
try {
setIsCreating(true);
// 1. Send 5 cUSD (using CELO for testnet MVP)
const hash = await sendTransactionAsync({
to: PROTOCOL_WALLET,
value: parseEther('0.01'), // Charging 0.01 CELO for test
});
// 2. Create Poll in Backend
const res = await fetch('/api/create-poll', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
question,
options,
creatorFid: 0, // Mock FID for now, or get from SDK context if available
creatorAddress: address,
txHash: hash,
verificationType,
description,
emoji,
verificationConfig: verificationType === 'chainlink' ? {
priceFeedAddress: chainlinkConfig.feed,
targetPrice: chainlinkConfig.target,
comparisonType: chainlinkConfig.type
} : {}
}),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || 'Failed to create poll');
}
router.push('/');
} catch (err: any) {
console.error(err);
setError(err.message || 'Something went wrong');
} finally {
setIsCreating(false);
}
};
return (
<div className="p-4 max-w-md mx-auto font-sans pb-20">
<button
onClick={() => router.push('/')}
className="flex items-center text-gray-600 mb-6 hover:text-gray-900"
>
<ArrowLeft className="w-4 h-4 mr-1" />
Back to Polls
</button>
<h1 className="text-2xl font-bold mb-6">Create Daily Poll</h1>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Question
</label>
<input
type="text"
value={question}
onChange={(e) => setQuestion(e.target.value)}
className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-purple-500 outline-none"
placeholder="Will BTC break $100k?"
maxLength={200}
/>
</div>
<div className="mt-4">
<label className="block text-sm font-medium text-gray-700 mb-1">
Description (Optional)
</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-purple-500 outline-none"
placeholder="Add more context..."
rows={2}
/>
</div>
<div className="mt-4">
<label className="block text-sm font-medium text-gray-700 mb-1">
Emoji
</label>
<input
type="text"
value={emoji}
onChange={(e) => setEmoji(e.target.value)}
className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-purple-500 outline-none"
placeholder="📊"
maxLength={2}
/>
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Options
</label>
<div className="space-y-2">
{options.map((opt, idx) => (
<div key={idx} className="flex gap-2">
<input
type="text"
value={opt}
onChange={(e) => handleOptionChange(idx, e.target.value)}
className="flex-1 p-3 border rounded-lg focus:ring-2 focus:ring-purple-500 outline-none"
placeholder={`Option ${idx + 1}`}
/>
{options.length > 2 && (
<button
type="button"
onClick={() => handleRemoveOption(idx)}
className="p-3 text-red-500 hover:bg-red-50 rounded-lg"
>
<Trash2 className="w-5 h-5" />
</button>
)}
</div>
))}
</div>
{options.length < 4 && (
<button
type="button"
onClick={handleAddOption}
className="mt-2 text-sm text-purple-600 font-medium flex items-center hover:text-purple-700"
>
<Plus className="w-4 h-4 mr-1" />
Add Option
</button>
)}
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Verification Method
</label>
<select
value={verificationType}
onChange={(e) => setVerificationType(e.target.value)}
className="w-full p-3 border rounded-lg focus:ring-2 focus:ring-purple-500 outline-none bg-white"
>
<option value="manual">Manual Verification</option>
<option value="chainlink">Chainlink Price Feed</option>
<option value="api">External API</option>
</select>
</div>
{verificationType === 'chainlink' && (
<div className="space-y-3 p-4 bg-gray-50 rounded-lg">
<h3 className="font-medium text-sm">Chainlink Configuration</h3>
<input
type="text"
placeholder="Feed Address (e.g., 0x...)"
value={chainlinkConfig.feed}
onChange={(e) => setChainlinkConfig({ ...chainlinkConfig, feed: e.target.value })}
className="w-full p-2 border rounded"
/>
<div className="flex gap-2">
<select
value={chainlinkConfig.type}
onChange={(e) => setChainlinkConfig({ ...chainlinkConfig, type: e.target.value })}
className="p-2 border rounded"
>
<option value="above">Above</option>
<option value="below">Below</option>
</select>
<input
type="number"
placeholder="Target Price"
value={chainlinkConfig.target}
onChange={(e) => setChainlinkConfig({ ...chainlinkConfig, target: e.target.value })}
className="flex-1 p-2 border rounded"
/>
</div>
</div>
)}
<div className="bg-purple-50 p-4 rounded-lg text-sm text-purple-800">
<p className="font-bold mb-1">Fee Breakdown (5 cUSD)</p>
<ul className="list-disc list-inside space-y-1">
<li>3.00 cUSD → Prize Pot 🏆</li>
<li>1.50 cUSD → Protocol Fee 🏦</li>
<li>0.50 cUSD → Verification Cost 🔮</li>
</ul>
</div>
{error && (
<div className="text-red-500 text-sm bg-red-50 p-3 rounded-lg">
{error}
</div>
)}
<button
type="submit"
disabled={isCreating || isSending}
className="w-full bg-purple-600 text-white py-4 rounded-xl font-bold text-lg hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{isCreating || isSending ? 'Creating...' : 'Pay 5 cUSD & Create'}
</button>
</form>
</div>
);
}