Adding logic to get token info and remove swap counter that's not needed anymore
This commit is contained in:
@@ -3,7 +3,6 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { SwapForm } from '@/components/swap-form';
|
||||
import { TokenCountDisplay } from '@/components/token-count-display';
|
||||
|
||||
export default function HomePage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -17,10 +16,7 @@ export default function HomePage() {
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="swap">
|
||||
<div className="space-y-6">
|
||||
<TokenCountDisplay />
|
||||
<SwapForm />
|
||||
</div>
|
||||
<SwapForm />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="stake">
|
||||
|
||||
@@ -1,18 +1,51 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect, useRef } 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 { ArrowDownUp } from 'lucide-react';
|
||||
import { ArrowDownUp, ChevronDown } from 'lucide-react';
|
||||
import { useAccount } from 'wagmi';
|
||||
import { useTokenDetails, type TokenDetails } from '@/hooks/usePartyPlanner';
|
||||
import { formatUnits } from 'viem';
|
||||
|
||||
export function SwapForm() {
|
||||
const { t } = useTranslation();
|
||||
const { isConnected } = useAccount();
|
||||
const { isConnected, address } = useAccount();
|
||||
const [fromAmount, setFromAmount] = useState('');
|
||||
const [toAmount, setToAmount] = useState('');
|
||||
const [selectedFromToken, setSelectedFromToken] = useState<TokenDetails | null>(null);
|
||||
const [selectedToToken, setSelectedToToken] = useState<TokenDetails | null>(null);
|
||||
const [isFromDropdownOpen, setIsFromDropdownOpen] = useState(false);
|
||||
const [isToDropdownOpen, setIsToDropdownOpen] = useState(false);
|
||||
const fromDropdownRef = useRef<HTMLDivElement>(null);
|
||||
const toDropdownRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Use the custom hook to get all token details with a single batched RPC call
|
||||
const { tokenDetails, loading, error } = useTokenDetails(address);
|
||||
|
||||
// Trigger the hook to fetch data when address is available
|
||||
useEffect(() => {
|
||||
if (tokenDetails) {
|
||||
console.log('Token details loaded in swap-form');
|
||||
}
|
||||
}, [tokenDetails]);
|
||||
|
||||
// Close dropdowns when clicking outside
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (fromDropdownRef.current && !fromDropdownRef.current.contains(event.target as Node)) {
|
||||
setIsFromDropdownOpen(false);
|
||||
}
|
||||
if (toDropdownRef.current && !toDropdownRef.current.contains(event.target as Node)) {
|
||||
setIsToDropdownOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
const handleSwap = () => {
|
||||
// Swap logic will be implemented later
|
||||
@@ -35,7 +68,9 @@ export function SwapForm() {
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<label className="text-muted-foreground">{t('swap.youPay')}</label>
|
||||
<span className="text-muted-foreground">{t('swap.balance')}: 0.00</span>
|
||||
<span className="text-muted-foreground">
|
||||
{t('swap.balance')}: {selectedFromToken ? formatUnits(selectedFromToken.balance, selectedFromToken.decimals) : '0.00'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
@@ -45,9 +80,45 @@ export function SwapForm() {
|
||||
onChange={(e) => setFromAmount(e.target.value)}
|
||||
className="text-2xl h-16"
|
||||
/>
|
||||
<Button variant="secondary" className="min-w-[120px]">
|
||||
{t('swap.selectToken')}
|
||||
</Button>
|
||||
<div className="relative min-w-[160px]" ref={fromDropdownRef}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="w-full h-16 justify-between"
|
||||
onClick={() => setIsFromDropdownOpen(!isFromDropdownOpen)}
|
||||
>
|
||||
{selectedFromToken ? (
|
||||
<span className="font-medium">{selectedFromToken.symbol}</span>
|
||||
) : (
|
||||
t('swap.selectToken')
|
||||
)}
|
||||
<ChevronDown className="h-4 w-4 ml-2" />
|
||||
</Button>
|
||||
{isFromDropdownOpen && (
|
||||
<div className="absolute z-50 w-full mt-2 bg-popover border rounded-md shadow-lg max-h-[300px] overflow-y-auto">
|
||||
{tokenDetails && tokenDetails.length > 0 ? (
|
||||
tokenDetails.map((token) => (
|
||||
<button
|
||||
key={token.address}
|
||||
className="w-full px-4 py-3 text-left hover:bg-accent focus:bg-accent focus:outline-none flex items-center justify-between"
|
||||
onClick={() => {
|
||||
setSelectedFromToken(token);
|
||||
setIsFromDropdownOpen(false);
|
||||
}}
|
||||
>
|
||||
<span className="font-medium">{token.symbol}</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{formatUnits(token.balance, token.decimals)}
|
||||
</span>
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<div className="px-4 py-3 text-sm text-muted-foreground">
|
||||
{loading ? 'Loading tokens...' : 'No tokens available'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -67,7 +138,9 @@ export function SwapForm() {
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<label className="text-muted-foreground">{t('swap.youReceive')}</label>
|
||||
<span className="text-muted-foreground">{t('swap.balance')}: 0.00</span>
|
||||
<span className="text-muted-foreground">
|
||||
{t('swap.balance')}: {selectedToToken ? formatUnits(selectedToToken.balance, selectedToToken.decimals) : '0.00'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
@@ -77,9 +150,45 @@ export function SwapForm() {
|
||||
onChange={(e) => setToAmount(e.target.value)}
|
||||
className="text-2xl h-16"
|
||||
/>
|
||||
<Button variant="secondary" className="min-w-[120px]">
|
||||
{t('swap.selectToken')}
|
||||
</Button>
|
||||
<div className="relative min-w-[160px]" ref={toDropdownRef}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="w-full h-16 justify-between"
|
||||
onClick={() => setIsToDropdownOpen(!isToDropdownOpen)}
|
||||
>
|
||||
{selectedToToken ? (
|
||||
<span className="font-medium">{selectedToToken.symbol}</span>
|
||||
) : (
|
||||
t('swap.selectToken')
|
||||
)}
|
||||
<ChevronDown className="h-4 w-4 ml-2" />
|
||||
</Button>
|
||||
{isToDropdownOpen && (
|
||||
<div className="absolute z-50 w-full mt-2 bg-popover border rounded-md shadow-lg max-h-[300px] overflow-y-auto">
|
||||
{tokenDetails && tokenDetails.length > 0 ? (
|
||||
tokenDetails.map((token) => (
|
||||
<button
|
||||
key={token.address}
|
||||
className="w-full px-4 py-3 text-left hover:bg-accent focus:bg-accent focus:outline-none flex items-center justify-between"
|
||||
onClick={() => {
|
||||
setSelectedToToken(token);
|
||||
setIsToDropdownOpen(false);
|
||||
}}
|
||||
>
|
||||
<span className="font-medium">{token.symbol}</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{formatUnits(token.balance, token.decimals)}
|
||||
</span>
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<div className="px-4 py-3 text-sm text-muted-foreground">
|
||||
{loading ? 'Loading tokens...' : 'No tokens available'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import {useEffect, useState} from 'react';
|
||||
import {usePublicClient} from 'wagmi';
|
||||
import {Card, CardContent, CardHeader, CardTitle} from '@/components/ui/card';
|
||||
import chainInfo from '@/app/liquidity-party.json';
|
||||
import IPartyPlannerABI from '@/contracts/IPartyPlannerABI';
|
||||
|
||||
|
||||
export function TokenCountDisplay() {
|
||||
const publicClient = usePublicClient();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [tokenCount, setTokenCount] = useState<bigint | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Handle hydration for Next.js static export
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
|
||||
const fetchTokenCount = async () => {
|
||||
if (!publicClient) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
// In viem 2.x, readContract is a method on the client
|
||||
const chainId = await publicClient.getChainId()
|
||||
const address = chainInfo[chainId.toString()]?.IPartyPlanner;
|
||||
const count = !address ? BigInt(0) : await publicClient.readContract({
|
||||
address,
|
||||
abi: IPartyPlannerABI,
|
||||
functionName: 'tokenCount', // Fully typed from ABI
|
||||
});
|
||||
|
||||
setTokenCount(count);
|
||||
} catch (err) {
|
||||
console.error('Error reading token count:', err);
|
||||
setError(err instanceof Error ? err.message : 'Failed to read token count');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchTokenCount();
|
||||
}, [publicClient, mounted]);
|
||||
|
||||
// Don't render until client-side hydration is complete
|
||||
if (!mounted) {
|
||||
return (
|
||||
<Card className="w-full max-w-md mx-auto">
|
||||
<CardHeader>
|
||||
<CardTitle>Party Planner Token Count</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="w-full max-w-md mx-auto">
|
||||
<CardHeader>
|
||||
<CardTitle>Party Planner Token Count</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{loading && (
|
||||
<p className="text-muted-foreground">Loading token count...</p>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="text-destructive">Error: {error}</p>
|
||||
)}
|
||||
|
||||
{tokenCount !== null && !loading && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-3xl font-bold">{tokenCount.toString()}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Total tokens in Party Planner
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
166
src/hooks/usePartyPlanner.ts
Normal file
166
src/hooks/usePartyPlanner.ts
Normal file
@@ -0,0 +1,166 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { usePublicClient } from 'wagmi';
|
||||
import chainInfo from '@/app/liquidity-party.json';
|
||||
import IPartyPlannerABI from '@/contracts/IPartyPlannerABI';
|
||||
import { ERC20ABI } from '@/contracts/ERC20ABI';
|
||||
|
||||
export function useGetAllTokens(offset: number = 0, limit: number = 100) {
|
||||
const publicClient = usePublicClient();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [tokens, setTokens] = useState<readonly `0x${string}`[] | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Handle hydration for Next.js static export
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mounted) return;
|
||||
|
||||
const fetchTokens = async () => {
|
||||
if (!publicClient) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
// Get chain ID and contract address
|
||||
const chainId = await publicClient.getChainId();
|
||||
const address = chainInfo[chainId.toString()]?.IPartyPlanner;
|
||||
|
||||
if (!address) {
|
||||
setError('IPartyPlanner contract not found for current chain');
|
||||
setTokens([]);
|
||||
return;
|
||||
}
|
||||
|
||||
// Call getAllTokens function
|
||||
const result = await publicClient.readContract({
|
||||
address,
|
||||
abi: IPartyPlannerABI,
|
||||
functionName: 'getAllTokens',
|
||||
args: [BigInt(offset), BigInt(limit)],
|
||||
});
|
||||
|
||||
setTokens(result);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to fetch tokens');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchTokens();
|
||||
}, [publicClient, mounted, offset, limit]);
|
||||
|
||||
return {
|
||||
tokens,
|
||||
loading,
|
||||
error,
|
||||
isReady: mounted,
|
||||
};
|
||||
}
|
||||
|
||||
export interface TokenDetails {
|
||||
address: `0x${string}`;
|
||||
name: string;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
balance: bigint;P
|
||||
}
|
||||
|
||||
export function useTokenDetails(userAddress: `0x${string}` | undefined) {
|
||||
const publicClient = usePublicClient();
|
||||
const { tokens, loading: tokensLoading, isReady } = useGetAllTokens();
|
||||
const [tokenDetails, setTokenDetails] = useState<TokenDetails[] | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isReady || tokensLoading || !tokens || !publicClient || !userAddress) {
|
||||
setLoading(tokensLoading || !isReady);
|
||||
return;
|
||||
}
|
||||
|
||||
const fetchTokenDetails = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
if (tokens.length === 0) {
|
||||
setTokenDetails([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const details: TokenDetails[] = [];
|
||||
|
||||
// Make individual calls for each token
|
||||
for (const tokenAddress of tokens) {
|
||||
try {
|
||||
const [name, symbol, decimals, balance] = await Promise.all([
|
||||
publicClient.readContract({
|
||||
address: tokenAddress,
|
||||
abi: ERC20ABI,
|
||||
functionName: 'name',
|
||||
}).catch(() => 'Unknown'),
|
||||
publicClient.readContract({
|
||||
address: tokenAddress,
|
||||
abi: ERC20ABI,
|
||||
functionName: 'symbol',
|
||||
}).catch(() => '???'),
|
||||
publicClient.readContract({
|
||||
address: tokenAddress,
|
||||
abi: ERC20ABI,
|
||||
functionName: 'decimals',
|
||||
}).catch(() => 18),
|
||||
publicClient.readContract({
|
||||
address: tokenAddress,
|
||||
abi: ERC20ABI,
|
||||
functionName: 'balanceOf',
|
||||
args: [userAddress],
|
||||
}).catch(() => BigInt(0)),
|
||||
]);
|
||||
|
||||
details.push({
|
||||
address: tokenAddress,
|
||||
name: name as string,
|
||||
symbol: symbol as string,
|
||||
decimals: Number(decimals),
|
||||
balance: balance as bigint,
|
||||
});
|
||||
} catch (err) {
|
||||
// Add token with fallback values if individual call fails
|
||||
details.push({
|
||||
address: tokenAddress,
|
||||
name: 'Unknown',
|
||||
symbol: '???',
|
||||
decimals: 18,
|
||||
balance: BigInt(0),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
setTokenDetails(details);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to fetch token details');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchTokenDetails();
|
||||
}, [tokens, tokensLoading, publicClient, isReady, userAddress]);
|
||||
|
||||
return {
|
||||
tokenDetails,
|
||||
loading,
|
||||
error,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user