adding a stake form and approvals in both stake and swap form

This commit is contained in:
2025-10-28 11:27:26 -04:00
parent dbfdfbd4ab
commit 66e28ed08d
6 changed files with 752 additions and 33 deletions

View File

@@ -0,0 +1,364 @@
'use client';
import { useState, useEffect, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { ChevronDown, CheckCircle, XCircle, Loader2 } from 'lucide-react';
import { useAccount } from 'wagmi';
import { useGetAllPools, useTokenDetails, useSwapMintAmounts, type PoolDetails, type TokenDetails } from '@/hooks/usePartyPlanner';
import { useSwapMint } from '@/hooks/usePartyPool';
import { formatUnits, parseUnits } from 'viem';
import IPartyPoolABI from '@/contracts/IPartyPoolABI';
type TransactionStatus = 'idle' | 'pending' | 'success' | 'error';
export function StakeForm() {
const { t } = useTranslation();
const { isConnected, address } = useAccount();
const [stakeAmount, setStakeAmount] = useState('');
const [selectedPool, setSelectedPool] = useState<PoolDetails | null>(null);
const [selectedToken, setSelectedToken] = useState<TokenDetails | null>(null);
const [isPoolDropdownOpen, setIsPoolDropdownOpen] = useState(false);
const [isTokenDropdownOpen, setIsTokenDropdownOpen] = useState(false);
const [transactionStatus, setTransactionStatus] = useState<TransactionStatus>('idle');
const [transactionError, setTransactionError] = useState<string | null>(null);
const poolDropdownRef = useRef<HTMLDivElement>(null);
const tokenDropdownRef = useRef<HTMLDivElement>(null);
// Fetch all pools using the new hook
const { poolDetails, loading: poolsLoading } = useGetAllPools();
// Get token details for the user
const { tokenDetails, loading: tokensLoading } = useTokenDetails(address);
// Initialize swap mint hook
const { executeSwapMint, isSwapMinting } = useSwapMint();
// Get available tokens for staking based on selected pool
const availableTokensForPool = selectedPool && tokenDetails
? tokenDetails.filter(token =>
selectedPool.tokens.some(poolToken =>
poolToken.toLowerCase() === token.address.toLowerCase()
)
)
: [];
// Check if amount exceeds balance
const isAmountExceedingBalance = useMemo(() => {
if (!stakeAmount || !selectedToken) return false;
try {
const amountInWei = parseUnits(stakeAmount, selectedToken.decimals);
return amountInWei > selectedToken.balance;
} catch {
// If parseUnits fails (invalid input), don't show error
return false;
}
}, [stakeAmount, selectedToken]);
// Get the input token index in the selected pool
const inputTokenIndex = useMemo(() => {
if (!selectedPool || !selectedToken) return undefined;
const index = selectedPool.tokens.findIndex(
token => token.toLowerCase() === selectedToken.address.toLowerCase()
);
return index !== -1 ? index : undefined;
}, [selectedPool, selectedToken]);
// Parse the stake amount to Wei
const maxAmountIn = useMemo(() => {
if (!stakeAmount || !selectedToken) return undefined;
try {
return parseUnits(stakeAmount, selectedToken.decimals);
} catch {
return undefined;
}
}, [stakeAmount, selectedToken]);
// Fetch swap mint amounts
const { swapMintAmounts, loading: swapMintLoading } = useSwapMintAmounts(
selectedPool?.address,
inputTokenIndex,
maxAmountIn
);
// Close dropdowns when clicking outside
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (poolDropdownRef.current && !poolDropdownRef.current.contains(event.target as Node)) {
setIsPoolDropdownOpen(false);
}
if (tokenDropdownRef.current && !tokenDropdownRef.current.contains(event.target as Node)) {
setIsTokenDropdownOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const handleStake = async () => {
if (!selectedPool || !selectedToken || !stakeAmount || inputTokenIndex === undefined || !maxAmountIn) {
console.error('Missing required stake parameters');
return;
}
setTransactionStatus('pending');
setTransactionError(null);
try {
// Execute the swap mint transaction
await executeSwapMint(
selectedPool.address,
selectedToken.address,
inputTokenIndex,
maxAmountIn
);
setTransactionStatus('success');
} catch (err) {
console.error('Stake failed:', err);
setTransactionError(err instanceof Error ? err.message : 'Transaction failed');
setTransactionStatus('error');
}
};
const handleCloseModal = () => {
if (transactionStatus === 'success') {
// Clear the form after successful stake
setStakeAmount('');
setSelectedPool(null);
setSelectedToken(null);
}
setTransactionStatus('idle');
setTransactionError(null);
};
return (
<Card className="w-full max-w-md mx-auto relative">
<CardHeader>
<div className="flex justify-between items-center">
<CardTitle>Stake</CardTitle>
</div>
</CardHeader>
<CardContent className="space-y-4">
{/* Pool Selection */}
<div className="space-y-2">
<div className="text-sm">
<label className="text-muted-foreground">{t('stake.selectPool')}</label>
</div>
<div className="relative" ref={poolDropdownRef}>
<Button
variant="secondary"
className="w-full h-16 justify-between"
onClick={() => setIsPoolDropdownOpen(!isPoolDropdownOpen)}
>
{selectedPool ? (
<div className="flex flex-col items-start">
<span className="font-medium">{selectedPool.symbol}</span>
<span className="text-xs text-muted-foreground">{selectedPool.name}</span>
</div>
) : (
t('stake.selectPool')
)}
<ChevronDown className="h-4 w-4 ml-2" />
</Button>
{isPoolDropdownOpen && (
<div className="absolute z-50 w-full mt-2 bg-popover border rounded-md shadow-lg max-h-[300px] overflow-y-auto">
{poolDetails && poolDetails.length > 0 ? (
poolDetails.map((pool) => (
<button
key={pool.address}
className="w-full px-4 py-3 text-left hover:bg-accent focus:bg-accent focus:outline-none"
onClick={() => {
setSelectedPool(pool);
setIsPoolDropdownOpen(false);
// Reset token selection when pool changes
setSelectedToken(null);
}}
>
<div className="flex flex-col">
<span className="font-medium">{pool.symbol}</span>
<span className="text-xs text-muted-foreground">{pool.name}</span>
</div>
</button>
))
) : (
<div className="px-4 py-3 text-sm text-muted-foreground">
{poolsLoading ? 'Loading pools...' : 'No pools available'}
</div>
)}
</div>
)}
</div>
</div>
{/* Token Selection */}
<div className="space-y-2">
<div className="text-sm">
<label className="text-muted-foreground">{t('stake.selectToken')}</label>
</div>
<div className="relative" ref={tokenDropdownRef}>
<Button
variant="secondary"
className="w-full h-16 justify-between"
onClick={() => setIsTokenDropdownOpen(!isTokenDropdownOpen)}
disabled={!selectedPool}
>
{selectedToken ? (
<span className="font-medium">{selectedToken.symbol}</span>
) : (
t('stake.selectToken')
)}
<ChevronDown className="h-4 w-4 ml-2" />
</Button>
<div className="text-xs text-muted-foreground text-right mt-1">
{t('swap.balance')}: {selectedToken ? formatUnits(selectedToken.balance, selectedToken.decimals) : '0.00'}
</div>
{isTokenDropdownOpen && (
<div className="absolute z-50 w-full mt-2 bg-popover border rounded-md shadow-lg max-h-[300px] overflow-y-auto">
{availableTokensForPool.length > 0 ? (
availableTokensForPool.map((token) => (
<button
key={token.address}
className="w-full px-4 py-3 text-left hover:bg-accent focus:bg-accent focus:outline-none"
onClick={() => {
setSelectedToken(token);
setIsTokenDropdownOpen(false);
}}
>
<span className="font-medium">{token.symbol}</span>
</button>
))
) : selectedPool ? (
<div className="px-4 py-3 text-sm text-muted-foreground">
{tokensLoading ? 'Loading tokens...' : 'No tokens available for this pool'}
</div>
) : (
<div className="px-4 py-3 text-sm text-muted-foreground">
Select a pool first
</div>
)}
</div>
)}
</div>
</div>
{/* Amount Input */}
<div className="space-y-2">
<div className="text-sm">
<label className="text-muted-foreground">{t('stake.amount')}</label>
</div>
<Input
type="number"
placeholder="0.0"
value={stakeAmount}
onChange={(e) => setStakeAmount(e.target.value)}
className="text-2xl h-16"
disabled={!selectedToken || !selectedPool}
/>
{isAmountExceedingBalance && (
<p className="text-sm text-destructive">
{t('stake.insufficientBalance')}
</p>
)}
</div>
{/* Swap Mint Amounts Display */}
{swapMintAmounts && selectedToken && !isAmountExceedingBalance && (
<div className="px-4 py-3 bg-muted/30 rounded-lg space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">{t('stake.amountUsed')}:</span>
<span className="font-medium">
{swapMintLoading ? 'Calculating...' : `${formatUnits(swapMintAmounts.amountInUsed, selectedToken.decimals)} ${selectedToken.symbol}`}
</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">{t('stake.fee')}:</span>
<span className="font-medium">
{swapMintLoading ? 'Calculating...' : `${formatUnits(swapMintAmounts.fee, selectedToken.decimals)} ${selectedToken.symbol}`}
</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">{t('stake.lpMinted')}:</span>
<span className="font-medium">
{swapMintLoading ? 'Calculating...' : `${formatUnits(swapMintAmounts.lpMinted, 18)} ${selectedPool?.symbol || 'LP'}`}
</span>
</div>
</div>
)}
{/* Stake Button */}
<Button
className="w-full h-14 text-lg"
onClick={handleStake}
disabled={!isConnected || !stakeAmount || !selectedPool || !selectedToken || isAmountExceedingBalance || isSwapMinting}
>
{!isConnected
? t('swap.connectWalletToSwap')
: isSwapMinting
? 'Staking...'
: t('stake.stakeButton')}
</Button>
</CardContent>
{/* Transaction Modal Overlay */}
{transactionStatus !== 'idle' && (
<div className="absolute inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center z-50 rounded-lg">
<div className="bg-card border rounded-lg p-8 max-w-sm w-full mx-4 shadow-lg">
{transactionStatus === 'pending' && (
<div className="flex flex-col items-center space-y-4">
<Loader2 className="h-16 w-16 animate-spin text-primary" />
<h3 className="text-xl font-semibold text-center">Approving Stake</h3>
<p className="text-sm text-muted-foreground text-center">
Staking {stakeAmount} {selectedToken?.symbol} to {selectedPool?.symbol}
</p>
<p className="text-xs text-muted-foreground text-center">
Please confirm the transactions in your wallet
</p>
</div>
)}
{transactionStatus === 'success' && (
<div className="flex flex-col items-center space-y-4">
<CheckCircle className="h-16 w-16 text-green-500" />
<h3 className="text-xl font-semibold text-center">Stake Confirmed!</h3>
<p className="text-sm text-muted-foreground text-center">
Successfully staked {stakeAmount} {selectedToken?.symbol} to {selectedPool?.symbol}
</p>
<Button
onClick={handleCloseModal}
className="w-full mt-4"
>
Close
</Button>
</div>
)}
{transactionStatus === 'error' && (
<div className="flex flex-col items-center space-y-4">
<XCircle className="h-16 w-16 text-destructive" />
<h3 className="text-xl font-semibold text-center">Stake Failed</h3>
<p className="text-sm text-muted-foreground text-center break-words">
{transactionError || 'Transaction failed'}
</p>
<Button
onClick={handleCloseModal}
variant="outline"
className="w-full mt-4"
>
Close
</Button>
</div>
)}
</div>
</div>
)}
</Card>
);
}