Compare commits

..

2 Commits

Author SHA1 Message Date
e2198c9b31 adding token from pool logic and updating ABIs to support new smart contracts 2025-10-15 13:36:04 -04:00
64b998d119 slippage stuff 2025-10-14 18:26:36 -04:00
5 changed files with 308 additions and 30 deletions

View File

@@ -1,6 +1,6 @@
{ {
"31337": { "31337": {
"IPartyPlanner": "0xB35D3C9b9f2Fd72FAAb282E8Dd56da31FAA30E3d", "IPartyPlanner": "0x536F14E49e1Bb927003E83aDEBF295F3682ff121",
"IPartyPoolViewer": "0x238213078DbD09f2D15F4c14c02300FA1b2A81BB" "IPartyPoolViewer": "0xd85BdcdaE4db1FAEB8eF93331525FE68D7C8B3f0"
} }
} }

View File

@@ -7,7 +7,7 @@ import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { ArrowDownUp, ChevronDown } from 'lucide-react'; import { ArrowDownUp, ChevronDown } from 'lucide-react';
import { useAccount } from 'wagmi'; import { useAccount } from 'wagmi';
import { useTokenDetails, type TokenDetails } from '@/hooks/usePartyPlanner'; import { useTokenDetails, useGetPoolsByToken, type TokenDetails } from '@/hooks/usePartyPlanner';
import { formatUnits } from 'viem'; import { formatUnits } from 'viem';
export function SwapForm() { export function SwapForm() {
@@ -19,12 +19,18 @@ export function SwapForm() {
const [selectedToToken, setSelectedToToken] = useState<TokenDetails | null>(null); const [selectedToToken, setSelectedToToken] = useState<TokenDetails | null>(null);
const [isFromDropdownOpen, setIsFromDropdownOpen] = useState(false); const [isFromDropdownOpen, setIsFromDropdownOpen] = useState(false);
const [isToDropdownOpen, setIsToDropdownOpen] = useState(false); const [isToDropdownOpen, setIsToDropdownOpen] = useState(false);
const [slippage, setSlippage] = useState<number>(0.5); // Default 0.5%
const [customSlippage, setCustomSlippage] = useState<string>('');
const [isCustomSlippage, setIsCustomSlippage] = useState(false);
const fromDropdownRef = useRef<HTMLDivElement>(null); const fromDropdownRef = useRef<HTMLDivElement>(null);
const toDropdownRef = useRef<HTMLDivElement>(null); const toDropdownRef = useRef<HTMLDivElement>(null);
// Use the custom hook to get all token details with a single batched RPC call // Use the custom hook to get all token details with a single batched RPC call
const { tokenDetails, loading, error } = useTokenDetails(address); const { tokenDetails, loading, error } = useTokenDetails(address);
// Get available tokens for the selected "from" token
const { availableTokens } = useGetPoolsByToken(selectedFromToken?.address);
// Trigger the hook to fetch data when address is available // Trigger the hook to fetch data when address is available
useEffect(() => { useEffect(() => {
if (tokenDetails) { if (tokenDetails) {
@@ -47,6 +53,19 @@ export function SwapForm() {
return () => document.removeEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside);
}, []); }, []);
// Calculate and log limit price when amount or slippage changes
useEffect(() => {
if (fromAmount && parseFloat(fromAmount) > 0) {
const amount = parseFloat(fromAmount);
const slippagePercent = isCustomSlippage ? parseFloat(customSlippage) || 0 : slippage;
const limitPrice = amount * (1 + slippagePercent / 100);
console.log('Limit Price:', limitPrice);
console.log('From Amount:', amount);
console.log('Slippage %:', slippagePercent);
console.log('Additional Amount from Slippage:', limitPrice - amount);
}
}, [fromAmount, slippage, customSlippage, isCustomSlippage]);
const handleSwap = () => { const handleSwap = () => {
// Swap logic will be implemented later // Swap logic will be implemented later
console.log('Swap clicked'); console.log('Swap clicked');
@@ -149,12 +168,14 @@ export function SwapForm() {
value={toAmount} value={toAmount}
onChange={(e) => setToAmount(e.target.value)} onChange={(e) => setToAmount(e.target.value)}
className="text-2xl h-16" className="text-2xl h-16"
disabled={!selectedFromToken}
/> />
<div className="relative min-w-[160px]" ref={toDropdownRef}> <div className="relative min-w-[160px]" ref={toDropdownRef}>
<Button <Button
variant="secondary" variant="secondary"
className="w-full h-16 justify-between" className="w-full h-16 justify-between"
onClick={() => setIsToDropdownOpen(!isToDropdownOpen)} onClick={() => setIsToDropdownOpen(!isToDropdownOpen)}
disabled={!selectedFromToken}
> >
{selectedToToken ? ( {selectedToToken ? (
<span className="font-medium">{selectedToToken.symbol}</span> <span className="font-medium">{selectedToToken.symbol}</span>
@@ -165,25 +186,36 @@ export function SwapForm() {
</Button> </Button>
{isToDropdownOpen && ( {isToDropdownOpen && (
<div className="absolute z-50 w-full mt-2 bg-popover border rounded-md shadow-lg max-h-[300px] overflow-y-auto"> <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 ? ( {availableTokens && availableTokens.length > 0 && tokenDetails ? (
tokenDetails.map((token) => ( // Filter tokenDetails to only show tokens in availableTokens
<button tokenDetails
key={token.address} .filter((token) =>
className="w-full px-4 py-3 text-left hover:bg-accent focus:bg-accent focus:outline-none flex items-center justify-between" availableTokens.some((availToken) =>
onClick={() => { availToken.toLowerCase() === token.address.toLowerCase()
setSelectedToToken(token); )
setIsToDropdownOpen(false); )
}} .map((token) => (
> <button
<span className="font-medium">{token.symbol}</span> key={token.address}
<span className="text-sm text-muted-foreground"> className="w-full px-4 py-3 text-left hover:bg-accent focus:bg-accent focus:outline-none flex items-center justify-between"
{formatUnits(token.balance, token.decimals)} onClick={() => {
</span> setSelectedToToken(token);
</button> setIsToDropdownOpen(false);
)) }}
>
<span className="font-medium">{token.symbol}</span>
<span className="text-sm text-muted-foreground">
{formatUnits(token.balance, token.decimals)}
</span>
</button>
))
) : selectedFromToken ? (
<div className="px-4 py-3 text-sm text-muted-foreground">
{loading ? 'Loading available tokens...' : 'No tokens available for swap'}
</div>
) : ( ) : (
<div className="px-4 py-3 text-sm text-muted-foreground"> <div className="px-4 py-3 text-sm text-muted-foreground">
{loading ? 'Loading tokens...' : 'No tokens available'} Select a token in "You Pay" first
</div> </div>
)} )}
</div> </div>
@@ -192,6 +224,51 @@ export function SwapForm() {
</div> </div>
</div> </div>
{/* Slippage Tolerance */}
<div className="space-y-3 pt-2">
<div className="flex justify-between items-center">
<label className="text-sm font-medium">Slippage Tolerance</label>
<span className="text-sm text-muted-foreground">
{isCustomSlippage ? customSlippage || '0' : slippage}%
</span>
</div>
<div className="flex gap-2 flex-wrap">
{[0.1, 0.2, 0.3, 1, 2, 3].map((percent) => (
<Button
key={percent}
variant={!isCustomSlippage && slippage === percent ? 'default' : 'outline'}
size="sm"
onClick={() => {
setSlippage(percent);
setIsCustomSlippage(false);
}}
className="flex-1 min-w-[60px]"
>
{percent}%
</Button>
))}
<div className="flex-1 min-w-[80px] relative">
<Input
type="number"
placeholder="Custom"
value={customSlippage}
onChange={(e) => {
setCustomSlippage(e.target.value);
setIsCustomSlippage(true);
}}
onFocus={() => setIsCustomSlippage(true)}
className={`h-9 pr-6 ${isCustomSlippage ? 'border-primary' : ''}`}
step="0.01"
/>
{isCustomSlippage && (
<span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">
%
</span>
)}
</div>
</div>
</div>
{/* Swap Button */} {/* Swap Button */}
<Button <Button
className="w-full h-14 text-lg" className="w-full h-14 text-lg"

View File

@@ -317,7 +317,7 @@ const IPartyPlannerABI = [
}, },
{ {
"type": "function", "type": "function",
"name": "swapMintImpl", "name": "swapImpl",
"inputs": [], "inputs": [],
"outputs": [ "outputs": [
{ {

View File

@@ -147,6 +147,11 @@ const IPartyPoolABI = [
"name": "deadline", "name": "deadline",
"type": "uint256", "type": "uint256",
"internalType": "uint256" "internalType": "uint256"
},
{
"name": "unwrap",
"type": "bool",
"internalType": "bool"
} }
], ],
"outputs": [ "outputs": [
@@ -186,6 +191,11 @@ const IPartyPoolABI = [
"name": "deadline", "name": "deadline",
"type": "uint256", "type": "uint256",
"internalType": "uint256" "internalType": "uint256"
},
{
"name": "unwrap",
"type": "bool",
"internalType": "bool"
} }
], ],
"outputs": [ "outputs": [
@@ -318,7 +328,7 @@ const IPartyPoolABI = [
"internalType": "uint256" "internalType": "uint256"
} }
], ],
"stateMutability": "nonpayable" "stateMutability": "payable"
}, },
{ {
"type": "function", "type": "function",
@@ -365,7 +375,7 @@ const IPartyPoolABI = [
"internalType": "uint256" "internalType": "uint256"
} }
], ],
"stateMutability": "nonpayable" "stateMutability": "payable"
}, },
{ {
"type": "function", "type": "function",
@@ -457,6 +467,11 @@ const IPartyPoolABI = [
"name": "deadline", "name": "deadline",
"type": "uint256", "type": "uint256",
"internalType": "uint256" "internalType": "uint256"
},
{
"name": "unwrap",
"type": "bool",
"internalType": "bool"
} }
], ],
"outputs": [ "outputs": [
@@ -476,7 +491,51 @@ const IPartyPoolABI = [
"internalType": "uint256" "internalType": "uint256"
} }
], ],
"stateMutability": "nonpayable" "stateMutability": "payable"
},
{
"type": "function",
"name": "swapAmounts",
"inputs": [
{
"name": "inputTokenIndex",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "outputTokenIndex",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "maxAmountIn",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "limitPrice",
"type": "int128",
"internalType": "int128"
}
],
"outputs": [
{
"name": "amountIn",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "amountOut",
"type": "uint256",
"internalType": "uint256"
},
{
"name": "fee",
"type": "uint256",
"internalType": "uint256"
}
],
"stateMutability": "view"
}, },
{ {
"type": "function", "type": "function",
@@ -528,7 +587,7 @@ const IPartyPoolABI = [
"internalType": "uint256" "internalType": "uint256"
} }
], ],
"stateMutability": "nonpayable" "stateMutability": "payable"
}, },
{ {
"type": "function", "type": "function",
@@ -563,6 +622,11 @@ const IPartyPoolABI = [
"name": "deadline", "name": "deadline",
"type": "uint256", "type": "uint256",
"internalType": "uint256" "internalType": "uint256"
},
{
"name": "unwrap",
"type": "bool",
"internalType": "bool"
} }
], ],
"outputs": [ "outputs": [
@@ -582,7 +646,7 @@ const IPartyPoolABI = [
"internalType": "uint256" "internalType": "uint256"
} }
], ],
"stateMutability": "nonpayable" "stateMutability": "payable"
}, },
{ {
"type": "function", "type": "function",
@@ -663,6 +727,19 @@ const IPartyPoolABI = [
], ],
"stateMutability": "nonpayable" "stateMutability": "nonpayable"
}, },
{
"type": "function",
"name": "wrapperToken",
"inputs": [],
"outputs": [
{
"name": "",
"type": "address",
"internalType": "contract IWETH9"
}
],
"stateMutability": "view"
},
{ {
"type": "event", "type": "event",
"name": "Approval", "name": "Approval",

View File

@@ -4,6 +4,7 @@ import { useState, useEffect } from 'react';
import { usePublicClient } from 'wagmi'; import { usePublicClient } from 'wagmi';
import chainInfo from '@/app/liquidity-party.json'; import chainInfo from '@/app/liquidity-party.json';
import IPartyPlannerABI from '@/contracts/IPartyPlannerABI'; import IPartyPlannerABI from '@/contracts/IPartyPlannerABI';
import IPartyPoolABI from '@/contracts/IPartyPoolABI';
import { ERC20ABI } from '@/contracts/ERC20ABI'; import { ERC20ABI } from '@/contracts/ERC20ABI';
export function useGetAllTokens(offset: number = 0, limit: number = 100) { export function useGetAllTokens(offset: number = 0, limit: number = 100) {
@@ -33,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[chainId.toString()]?.IPartyPlanner; const address = (chainInfo as Record<string, { IPartyPlanner: string; IPartyPoolViewer: string }>)[chainId.toString()]?.IPartyPlanner;
if (!address) { if (!address) {
setError('IPartyPlanner contract not found for current chain'); setError('IPartyPlanner contract not found for current chain');
@@ -43,7 +44,7 @@ export function useGetAllTokens(offset: number = 0, limit: number = 100) {
// Call getAllTokens function // Call getAllTokens function
const result = await publicClient.readContract({ const result = await publicClient.readContract({
address, address: address as `0x${string}`,
abi: IPartyPlannerABI, abi: IPartyPlannerABI,
functionName: 'getAllTokens', functionName: 'getAllTokens',
args: [BigInt(offset), BigInt(limit)], args: [BigInt(offset), BigInt(limit)],
@@ -73,7 +74,127 @@ export interface TokenDetails {
name: string; name: string;
symbol: string; symbol: string;
decimals: number; decimals: number;
balance: bigint;P balance: bigint;
index: number;
}
export function useGetPoolsByToken(tokenAddress: `0x${string}` | undefined, offset: number = 0, limit: number = 100) {
const publicClient = usePublicClient();
const [mounted, setMounted] = useState(false);
const [availableTokens, setAvailableTokens] = useState<`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 || !tokenAddress) {
setLoading(false);
return;
}
const fetchPoolsFromTokens = 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 as Record<string, { IPartyPlanner: string; IPartyPoolViewer: string }>)[chainId.toString()]?.IPartyPlanner;
if (!address) {
setError('IPartyPlanner contract not found for current chain');
setAvailableTokens([]);
return;
}
// Call getPoolsByToken function
const poolsResult = await publicClient.readContract({
address: address as `0x${string}`,
abi: IPartyPlannerABI,
functionName: 'getPoolsByToken',
args: [tokenAddress, BigInt(offset), BigInt(limit)],
});
console.log('Pools for token', tokenAddress, ':', poolsResult);
// Get the symbol of the originally selected token
const selectedTokenSymbol = await publicClient.readContract({
address: tokenAddress,
abi: ERC20ABI,
functionName: 'symbol',
}).catch(() => null);
if (!selectedTokenSymbol) {
setAvailableTokens([]);
return;
}
// For each pool, fetch all tokens in that pool
const allTokensInPools: `0x${string}`[] = [];
for (const poolAddress of poolsResult) {
try {
const tokensInPool = await publicClient.readContract({
address: poolAddress,
abi: IPartyPoolABI,
functionName: 'allTokens',
}) as readonly `0x${string}`[];
// Add all tokens from this pool
allTokensInPools.push(...tokensInPool);
} catch (err) {
console.error('Error fetching tokens from pool', poolAddress, err);
}
}
// Remove duplicates by address
const uniqueTokenAddresses = Array.from(new Set(allTokensInPools));
// Fetch symbols for all tokens and filter out those matching the selected token's symbol
const filteredTokens: `0x${string}`[] = [];
for (const token of uniqueTokenAddresses) {
try {
const tokenSymbol = await publicClient.readContract({
address: token,
abi: ERC20ABI,
functionName: 'symbol',
}).catch(() => null);
// Only include tokens with different symbols
if (tokenSymbol && tokenSymbol !== selectedTokenSymbol) {
filteredTokens.push(token);
}
} catch (err) {
console.error('Error fetching symbol for token', token, err);
}
}
console.log('Available tokens to swap to (excluding', selectedTokenSymbol, '):', filteredTokens);
setAvailableTokens(filteredTokens);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch pools and tokens');
} finally {
setLoading(false);
}
};
fetchPoolsFromTokens();
}, [publicClient, mounted, tokenAddress, offset, limit]);
return {
availableTokens,
loading,
error,
isReady: mounted,
};
} }
export function useTokenDetails(userAddress: `0x${string}` | undefined) { export function useTokenDetails(userAddress: `0x${string}` | undefined) {
@@ -102,7 +223,8 @@ export function useTokenDetails(userAddress: `0x${string}` | undefined) {
const details: TokenDetails[] = []; const details: TokenDetails[] = [];
// Make individual calls for each token // Make individual calls for each token
for (const tokenAddress of tokens) { for (let i = 0; i < tokens.length; i++) {
const tokenAddress = tokens[i];
try { try {
const [name, symbol, decimals, balance] = await Promise.all([ const [name, symbol, decimals, balance] = await Promise.all([
publicClient.readContract({ publicClient.readContract({
@@ -134,6 +256,7 @@ export function useTokenDetails(userAddress: `0x${string}` | undefined) {
symbol: symbol as string, symbol: symbol as string,
decimals: Number(decimals), decimals: Number(decimals),
balance: balance as bigint, balance: balance as bigint,
index: i,
}); });
} catch (err) { } catch (err) {
// Add token with fallback values if individual call fails // Add token with fallback values if individual call fails
@@ -143,6 +266,7 @@ export function useTokenDetails(userAddress: `0x${string}` | undefined) {
symbol: '???', symbol: '???',
decimals: 18, decimals: 18,
balance: BigInt(0), balance: BigInt(0),
index: i,
}); });
} }
} }