review modal, new smart contract pointer and network gas fees estimation
This commit is contained in:
@@ -10,6 +10,7 @@ import { useAccount } from 'wagmi';
|
|||||||
import { useTokenDetails, useGetPoolsByToken, type TokenDetails } from '@/hooks/usePartyPlanner';
|
import { useTokenDetails, useGetPoolsByToken, type TokenDetails } from '@/hooks/usePartyPlanner';
|
||||||
import { useSwapAmounts, useSwap, selectBestSwapRoute } from '@/hooks/usePartyPool';
|
import { useSwapAmounts, useSwap, selectBestSwapRoute } from '@/hooks/usePartyPool';
|
||||||
import { formatUnits, parseUnits } from 'viem';
|
import { formatUnits, parseUnits } from 'viem';
|
||||||
|
import { SwapReviewModal } from './swap-review-modal';
|
||||||
|
|
||||||
export function SwapForm() {
|
export function SwapForm() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -23,6 +24,7 @@ export function SwapForm() {
|
|||||||
const [slippage, setSlippage] = useState<number>(0.5); // Default 0.5%
|
const [slippage, setSlippage] = useState<number>(0.5); // Default 0.5%
|
||||||
const [customSlippage, setCustomSlippage] = useState<string>('');
|
const [customSlippage, setCustomSlippage] = useState<string>('');
|
||||||
const [isCustomSlippage, setIsCustomSlippage] = useState(false);
|
const [isCustomSlippage, setIsCustomSlippage] = useState(false);
|
||||||
|
const [isReviewModalOpen, setIsReviewModalOpen] = useState(false);
|
||||||
const fromDropdownRef = useRef<HTMLDivElement>(null);
|
const fromDropdownRef = useRef<HTMLDivElement>(null);
|
||||||
const toDropdownRef = useRef<HTMLDivElement>(null);
|
const toDropdownRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
@@ -55,7 +57,7 @@ export function SwapForm() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Initialize swap hook
|
// Initialize swap hook
|
||||||
const { executeSwap, isSwapping } = useSwap();
|
const { executeSwap, estimateGas, isSwapping, gasEstimate, isEstimatingGas } = useSwap();
|
||||||
|
|
||||||
// Update "You Receive" amount when swap calculation completes
|
// Update "You Receive" amount when swap calculation completes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -124,6 +126,20 @@ export function SwapForm() {
|
|||||||
setToAmount(fromAmount);
|
setToAmount(fromAmount);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Estimate gas when swap parameters change
|
||||||
|
useEffect(() => {
|
||||||
|
const estimateSwapGas = async () => {
|
||||||
|
if (!swapAmounts || swapAmounts.length === 0 || !selectedFromToken || !selectedToToken || !fromAmount || !isConnected) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await estimateGas();
|
||||||
|
};
|
||||||
|
|
||||||
|
estimateSwapGas();
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [swapAmounts, selectedFromToken, selectedToToken, fromAmount, currentSlippage, isConnected]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="w-full max-w-md mx-auto">
|
<Card className="w-full max-w-md mx-auto">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
@@ -310,19 +326,52 @@ export function SwapForm() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Swap Button */}
|
{/* Gas Estimate */}
|
||||||
|
{isConnected && fromAmount && toAmount && gasEstimate && !isEstimatingGas && (
|
||||||
|
<div className="px-4 py-2 bg-muted/30 rounded-lg">
|
||||||
|
<div className="flex justify-between text-sm">
|
||||||
|
<span className="text-muted-foreground">Estimated Gas Cost:</span>
|
||||||
|
<span className="font-medium">${gasEstimate.estimatedCostUsd}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{isConnected && fromAmount && toAmount && isEstimatingGas && (
|
||||||
|
<div className="px-4 py-2 bg-muted/30 rounded-lg">
|
||||||
|
<div className="flex justify-between text-sm">
|
||||||
|
<span className="text-muted-foreground">Estimated Gas Cost:</span>
|
||||||
|
<span className="text-muted-foreground">Calculating...</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Review Button */}
|
||||||
<Button
|
<Button
|
||||||
className="w-full h-14 text-lg"
|
className="w-full h-14 text-lg"
|
||||||
onClick={handleSwap}
|
onClick={() => setIsReviewModalOpen(true)}
|
||||||
disabled={!isConnected || !fromAmount || !toAmount || isSwapping}
|
disabled={!isConnected || !fromAmount || !toAmount}
|
||||||
>
|
>
|
||||||
{!isConnected
|
{!isConnected
|
||||||
? t('swap.connectWalletToSwap')
|
? t('swap.connectWalletToSwap')
|
||||||
: isSwapping
|
: 'Review'}
|
||||||
? 'Swapping...'
|
|
||||||
: t('swap.swapButton')}
|
|
||||||
</Button>
|
</Button>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|
||||||
|
{/* Review Modal */}
|
||||||
|
<SwapReviewModal
|
||||||
|
open={isReviewModalOpen}
|
||||||
|
onOpenChange={setIsReviewModalOpen}
|
||||||
|
fromToken={selectedFromToken}
|
||||||
|
toToken={selectedToToken}
|
||||||
|
fromAmount={fromAmount}
|
||||||
|
toAmount={toAmount}
|
||||||
|
slippage={currentSlippage}
|
||||||
|
gasEstimate={gasEstimate}
|
||||||
|
onConfirm={async () => {
|
||||||
|
await handleSwap();
|
||||||
|
setIsReviewModalOpen(false);
|
||||||
|
}}
|
||||||
|
isSwapping={isSwapping}
|
||||||
|
/>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
109
src/components/swap-review-modal.tsx
Normal file
109
src/components/swap-review-modal.tsx
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { ArrowDown, X } from 'lucide-react';
|
||||||
|
import type { TokenDetails } from '@/hooks/usePartyPlanner';
|
||||||
|
import type { GasEstimate } from '@/hooks/usePartyPool';
|
||||||
|
|
||||||
|
interface SwapReviewModalProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
fromToken: TokenDetails | null;
|
||||||
|
toToken: TokenDetails | null;
|
||||||
|
fromAmount: string;
|
||||||
|
toAmount: string;
|
||||||
|
slippage: number;
|
||||||
|
gasEstimate: GasEstimate | null;
|
||||||
|
onConfirm: () => void;
|
||||||
|
isSwapping: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SwapReviewModal({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
fromToken,
|
||||||
|
toToken,
|
||||||
|
fromAmount,
|
||||||
|
toAmount,
|
||||||
|
slippage,
|
||||||
|
gasEstimate,
|
||||||
|
onConfirm,
|
||||||
|
isSwapping,
|
||||||
|
}: SwapReviewModalProps) {
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Backdrop */}
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-50 bg-black/80 animate-in fade-in-0"
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Modal */}
|
||||||
|
<div className="fixed left-[50%] top-[50%] z-50 w-full max-w-md translate-x-[-50%] translate-y-[-50%] animate-in fade-in-0 zoom-in-95 slide-in-from-left-1/2 slide-in-from-top-[48%]">
|
||||||
|
<div className="bg-background border rounded-lg shadow-lg p-6">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex justify-between items-center mb-4">
|
||||||
|
<h2 className="text-lg font-semibold">Review Swap</h2>
|
||||||
|
<button
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
className="rounded-sm opacity-70 hover:opacity-100 transition-opacity"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* From Token */}
|
||||||
|
<div className="flex items-center justify-between p-4 bg-muted/30 rounded-lg">
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-muted-foreground">You pay</div>
|
||||||
|
<div className="text-2xl font-semibold">{fromAmount}</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-xl font-medium">{fromToken?.symbol}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Arrow */}
|
||||||
|
<div className="flex justify-center">
|
||||||
|
<ArrowDown className="h-5 w-5 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* To Token */}
|
||||||
|
<div className="flex items-center justify-between p-4 bg-muted/30 rounded-lg">
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-muted-foreground">You receive</div>
|
||||||
|
<div className="text-2xl font-semibold">{toAmount}</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-xl font-medium">{toToken?.symbol}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Details */}
|
||||||
|
<div className="space-y-2 pt-2">
|
||||||
|
<div className="flex justify-between text-sm">
|
||||||
|
<span className="text-muted-foreground">Slippage Tolerance</span>
|
||||||
|
<span className="font-medium">{slippage}%</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{gasEstimate && (
|
||||||
|
<div className="flex justify-between text-sm">
|
||||||
|
<span className="text-muted-foreground">Network Fee</span>
|
||||||
|
<span className="font-medium">${gasEstimate.estimatedCostUsd}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Confirm Button */}
|
||||||
|
<Button
|
||||||
|
className="w-full h-12 text-lg"
|
||||||
|
onClick={onConfirm}
|
||||||
|
disabled={isSwapping}
|
||||||
|
>
|
||||||
|
{isSwapping ? 'Swapping...' : 'Confirm Swap'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { usePublicClient } from 'wagmi';
|
import { usePublicClient } from 'wagmi';
|
||||||
import chainInfo from '@/app/liquidity-party.json';
|
import chainInfo from '../../../lmsr-amm/liqp-deployments.json';
|
||||||
import IPartyPlannerABI from '@/contracts/IPartyPlannerABI';
|
import IPartyPlannerABI from '@/contracts/IPartyPlannerABI';
|
||||||
import IPartyPoolABI from '@/contracts/IPartyPoolABI';
|
import IPartyPoolABI from '@/contracts/IPartyPoolABI';
|
||||||
import { ERC20ABI } from '@/contracts/ERC20ABI';
|
import { ERC20ABI } from '@/contracts/ERC20ABI';
|
||||||
@@ -34,7 +34,7 @@ export function useGetAllTokens(offset: number = 0, limit: number = 100) {
|
|||||||
|
|
||||||
// Get chain ID and contract address
|
// Get chain ID and contract address
|
||||||
const chainId = await publicClient.getChainId();
|
const chainId = await publicClient.getChainId();
|
||||||
const address = (chainInfo as Record<string, { IPartyPlanner: string; IPartyPoolViewer: string }>)[chainId.toString()]?.IPartyPlanner;
|
const address = (chainInfo as Record<string, { v1: { PartyPlanner: string; PartyPoolViewer: string } }>)[chainId.toString()]?.v1?.PartyPlanner;
|
||||||
|
|
||||||
if (!address) {
|
if (!address) {
|
||||||
setError('IPartyPlanner contract not found for current chain');
|
setError('IPartyPlanner contract not found for current chain');
|
||||||
@@ -52,6 +52,7 @@ export function useGetAllTokens(offset: number = 0, limit: number = 100) {
|
|||||||
|
|
||||||
setTokens(result);
|
setTokens(result);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
console.error('Error calling getAllTokens:', err);
|
||||||
setError(err instanceof Error ? err.message : 'Failed to fetch tokens');
|
setError(err instanceof Error ? err.message : 'Failed to fetch tokens');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
@@ -120,7 +121,7 @@ export function useGetPoolsByToken(tokenAddress: `0x${string}` | undefined, offs
|
|||||||
|
|
||||||
// Get chain ID and contract address
|
// Get chain ID and contract address
|
||||||
const chainId = await publicClient.getChainId();
|
const chainId = await publicClient.getChainId();
|
||||||
const address = (chainInfo as Record<string, { IPartyPlanner: string; IPartyPoolViewer: string }>)[chainId.toString()]?.IPartyPlanner;
|
const address = (chainInfo as Record<string, { v1: { PartyPlanner: string; PartyPoolViewer: string } }>)[chainId.toString()]?.v1?.PartyPlanner;
|
||||||
|
|
||||||
if (!address) {
|
if (!address) {
|
||||||
setError('IPartyPlanner contract not found for current chain');
|
setError('IPartyPlanner contract not found for current chain');
|
||||||
@@ -136,8 +137,6 @@ export function useGetPoolsByToken(tokenAddress: `0x${string}` | undefined, offs
|
|||||||
args: [tokenAddress, BigInt(offset), BigInt(limit)],
|
args: [tokenAddress, BigInt(offset), BigInt(limit)],
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('Pools for token', tokenAddress, ':', poolsResult);
|
|
||||||
|
|
||||||
// Get the symbol of the originally selected token
|
// Get the symbol of the originally selected token
|
||||||
const selectedTokenSymbol = await publicClient.readContract({
|
const selectedTokenSymbol = await publicClient.readContract({
|
||||||
address: tokenAddress,
|
address: tokenAddress,
|
||||||
@@ -216,7 +215,6 @@ export function useGetPoolsByToken(tokenAddress: `0x${string}` | undefined, offs
|
|||||||
}
|
}
|
||||||
|
|
||||||
const availableTokensList = Array.from(tokenRoutesMap.values());
|
const availableTokensList = Array.from(tokenRoutesMap.values());
|
||||||
console.log('Available tokens with swap routes:', availableTokensList);
|
|
||||||
setAvailableTokens(availableTokensList);
|
setAvailableTokens(availableTokensList);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : 'Failed to fetch pools and tokens');
|
setError(err instanceof Error ? err.message : 'Failed to fetch pools and tokens');
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
import { usePublicClient, useWalletClient } from 'wagmi';
|
import { usePublicClient, useWalletClient } from 'wagmi';
|
||||||
import IPartyPoolABI from '@/contracts/IPartyPoolABI';
|
import IPartyPoolABI from '@/contracts/IPartyPoolABI';
|
||||||
import type { AvailableToken } from './usePartyPlanner';
|
import type { AvailableToken } from './usePartyPlanner';
|
||||||
@@ -181,12 +181,71 @@ export function useSwapAmounts(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface GasEstimate {
|
||||||
|
totalGas: bigint;
|
||||||
|
gasPrice: bigint;
|
||||||
|
estimatedCostEth: string;
|
||||||
|
estimatedCostUsd: string;
|
||||||
|
}
|
||||||
|
|
||||||
export function useSwap() {
|
export function useSwap() {
|
||||||
const { data: walletClient } = useWalletClient();
|
const { data: walletClient } = useWalletClient();
|
||||||
const publicClient = usePublicClient();
|
const publicClient = usePublicClient();
|
||||||
const [isSwapping, setIsSwapping] = useState(false);
|
const [isSwapping, setIsSwapping] = useState(false);
|
||||||
const [swapHash, setSwapHash] = useState<`0x${string}` | null>(null);
|
const [swapHash, setSwapHash] = useState<`0x${string}` | null>(null);
|
||||||
const [swapError, setSwapError] = useState<string | null>(null);
|
const [swapError, setSwapError] = useState<string | null>(null);
|
||||||
|
const [gasEstimate, setGasEstimate] = useState<GasEstimate | null>(null);
|
||||||
|
const [isEstimatingGas, setIsEstimatingGas] = useState(false);
|
||||||
|
|
||||||
|
const estimateGas = useCallback(async () => {
|
||||||
|
if (!publicClient) {
|
||||||
|
console.error('Public client not available');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsEstimatingGas(true);
|
||||||
|
|
||||||
|
// Get current gas price from the network
|
||||||
|
const gasPrice = await publicClient.getGasPrice();
|
||||||
|
|
||||||
|
// Use fixed, typical gas amounts for AMM operations
|
||||||
|
const approvalGas = 50000n; // ERC20 approval typically uses ~50k gas
|
||||||
|
const swapGas = 150000n; // AMM swap typically uses ~150k gas
|
||||||
|
|
||||||
|
const totalGas = approvalGas + swapGas;
|
||||||
|
const estimatedCostWei = totalGas * gasPrice;
|
||||||
|
const estimatedCostEth = (Number(estimatedCostWei) / 1e18).toFixed(6);
|
||||||
|
|
||||||
|
// Fetch ETH price in USD
|
||||||
|
let estimatedCostUsd = '0.00';
|
||||||
|
try {
|
||||||
|
const response = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd');
|
||||||
|
const data = await response.json();
|
||||||
|
const ethPriceUsd = data.ethereum?.usd || 0;
|
||||||
|
const costInUsd = parseFloat(estimatedCostEth) * ethPriceUsd;
|
||||||
|
estimatedCostUsd = costInUsd.toFixed(2);
|
||||||
|
} catch (priceErr) {
|
||||||
|
console.error('Error fetching ETH price:', priceErr);
|
||||||
|
}
|
||||||
|
|
||||||
|
const estimate: GasEstimate = {
|
||||||
|
totalGas,
|
||||||
|
gasPrice,
|
||||||
|
estimatedCostEth,
|
||||||
|
estimatedCostUsd,
|
||||||
|
};
|
||||||
|
|
||||||
|
setGasEstimate(estimate);
|
||||||
|
console.log('⛽ Gas estimate:', estimate);
|
||||||
|
return estimate;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error estimating gas:', err);
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
setIsEstimatingGas(false);
|
||||||
|
}
|
||||||
|
}, [publicClient]);
|
||||||
|
|
||||||
const executeSwap = async (
|
const executeSwap = async (
|
||||||
poolAddress: `0x${string}`,
|
poolAddress: `0x${string}`,
|
||||||
@@ -290,8 +349,11 @@ export function useSwap() {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
executeSwap,
|
executeSwap,
|
||||||
|
estimateGas,
|
||||||
isSwapping,
|
isSwapping,
|
||||||
swapHash,
|
swapHash,
|
||||||
swapError,
|
swapError,
|
||||||
|
gasEstimate,
|
||||||
|
isEstimatingGas,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user