("0");
+
+ // Get balances and allowances (EVM chains use wagmi, Tron chains use custom logic)
const { data: fromTokenBalance } = useBalance({
- address,
+ address: isTronChain(swapState.fromChain) ? undefined : address,
token: swapState.fromToken.address as `0x${string}`,
chainId: swapState.fromChain,
});
const { data: toTokenBalance } = useBalance({
- address,
+ address: isTronChain(swapState.toChain) ? undefined : address,
token: swapState.toToken.address as `0x${string}`,
chainId: swapState.toChain,
});
@@ -73,90 +103,155 @@ export default function SwapComponent() {
chainId: swapState.fromChain,
});
+
+
+ // Update Tron balances when wallet or chain changes
+ useEffect(() => {
+ const updateTronBalances = async () => {
+ if (isTronChain(swapState.fromChain) && wallet && tronConnected && wallet.adapter.address) {
+ const balance = await getTronTokenBalance(
+ wallet,
+ swapState.fromToken.address,
+ wallet.adapter.address
+ );
+ setTronFromBalance(balance);
+ }
+
+ if (isTronChain(swapState.toChain) && wallet && tronConnected && wallet.adapter.address) {
+ const balance = await getTronTokenBalance(
+ wallet,
+ swapState.toToken.address,
+ wallet.adapter.address
+ );
+ setTronToBalance(balance);
+ }
+ };
+
+ updateTronBalances();
+ }, [swapState.fromChain, swapState.toChain, swapState.fromToken, swapState.toToken, wallet, tronConnected]);
+
+ // Update Tron allowance when wallet or chain changes
+ useEffect(() => {
+ const updateTronAllowance = async () => {
+ if (isTronChain(swapState.fromChain) && wallet && tronConnected && wallet.adapter.address) {
+ const allowance = await checkTronTokenAllowance(
+ wallet,
+ swapState.fromToken.address,
+ wallet.adapter.address,
+ LOP_ADDRESSES[swapState.fromChain]
+ );
+
+ setTronAllowance(allowance);
+ }
+ };
+
+ updateTronAllowance();
+ }, [swapState.fromChain, swapState.fromToken, wallet, tronConnected]);
+
const needsApproval = () => {
- // Check if we have all required data
- if (
- !address ||
- !swapState.fromAmount ||
- allowance === undefined ||
- allowance === null
- ) {
+ if (!swapState.fromAmount || parseFloat(swapState.fromAmount) <= 0) {
return false;
}
- try {
- const requiredAmount = parseUnits(
- swapState.fromAmount,
- swapState.fromToken.decimals
- );
-
- if (requiredAmount <= 0) {
+ if (isTronChain(swapState.fromChain)) {
+ // For Tron chains, check allowance using Tron wallet
+ if (!tronConnected || !wallet) {
return false;
}
- // Check if allowance is less than required amount
- const currentAllowance = allowance as bigint;
- const needsApproval = currentAllowance < requiredAmount;
+ const requiredAmount = parseFloat(swapState.fromAmount) * Math.pow(10, swapState.fromToken.decimals);
+ const currentAllowance = parseFloat(tronAllowance);
- console.log("🔍 Checking spending allowance...");
- console.log(
- `Current allowance: ${formatUnits(currentAllowance, swapState.fromToken.decimals)} ${swapState.fromToken.symbol}`
- );
- console.log(
- `Required amount: ${formatUnits(requiredAmount, swapState.fromToken.decimals)} ${swapState.fromToken.symbol}`
+ return currentAllowance < requiredAmount;
+ } else {
+ // For EVM chains, use wagmi allowance
+ if (!address || allowance === undefined || allowance === null) {
+ return false;
+ }
+ const requiredAmount = parseUnits(
+ swapState.fromAmount,
+ swapState.fromToken.decimals
);
- console.log(`Needs approval: ${needsApproval}`);
+ const needsApproval = (allowance as bigint) < requiredAmount;
return needsApproval;
- } catch (error) {
- console.error("Error checking approval:", error);
- return false;
}
};
const handleApprove = async () => {
- if (!address || !swapState.fromAmount) return;
-
setIsApproving(true);
try {
- console.log("🔐 Setting spending cap for token...");
- const requiredAmount = parseUnits(
- swapState.fromAmount,
- swapState.fromToken.decimals
- );
+ console.log("🔐 Approving token spend...");
- console.log(
- `Approving spending cap of ${formatUnits(requiredAmount, swapState.fromToken.decimals)} ${swapState.fromToken.symbol}`
- );
- console.log(`Spender: ${LOP_ADDRESSES[swapState.fromChain]}`);
- await writeContract({
- address: swapState.fromToken.address as `0x${string}`,
- abi: [
- {
- constant: false,
- inputs: [
- { name: "_spender", type: "address" },
- { name: "_value", type: "uint256" },
- ],
- name: "approve",
- outputs: [{ name: "", type: "bool" }],
- type: "function",
- },
- ],
- functionName: "approve",
- args: [
- LOP_ADDRESSES[swapState.fromChain] as `0x${string}`,
- requiredAmount,
- ],
- chainId: swapState.fromChain,
- });
+ if (isTronChain(swapState.fromChain)) {
+ // For Tron chains, use Tron wallet approval
+ if (!tronConnected || !wallet) {
+ throw new Error("Tron wallet not connected");
+ }
+
+ const requiredAmount = parseFloat(swapState.fromAmount) * Math.pow(10, swapState.fromToken.decimals);
+
+ const txHash = await approveTronToken(
+ wallet,
+ swapState.fromToken.address,
+ LOP_ADDRESSES[swapState.fromChain],
+ requiredAmount.toString()
+ );
+
+ console.log("✅ Tron token approval successful:", txHash);
+
+ // Update allowance after approval
+ const newAllowance = await checkTronTokenAllowance(
+ wallet,
+ swapState.fromToken.address,
+ wallet.adapter.address,
+ LOP_ADDRESSES[swapState.fromChain]
+ );
+ setTronAllowance(newAllowance);
+
+ } else {
+ // For EVM chains, use wagmi approval
+ if (!address) {
+ throw new Error("EVM wallet not connected");
+ }
- console.log("✅ Spending cap approved successfully");
- console.log("🔄 Allowance will be updated automatically...");
+ await switchChain({ chainId: swapState.fromChain });
+
+ // Add a delay to ensure the chain switch is complete
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ const requiredAmount = parseUnits(
+ swapState.fromAmount,
+ swapState.fromToken.decimals
+ );
+
+ await writeContract({
+ address: swapState.fromToken.address as `0x${string}`,
+ abi: [
+ {
+ constant: false,
+ inputs: [
+ { name: "_spender", type: "address" },
+ { name: "_value", type: "uint256" },
+ ],
+ name: "approve",
+ outputs: [{ name: "", type: "bool" }],
+ type: "function",
+ },
+ ],
+ functionName: "approve",
+ args: [
+ LOP_ADDRESSES[swapState.fromChain] as `0x${string}`,
+ requiredAmount,
+ ],
+ chainId: swapState.fromChain as number,
+ });
+ console.log("✅ EVM token approval successful");
+ }
} catch (error) {
- console.error("❌ Spending cap approval failed:", error);
- // You might want to show a user-friendly error message here
+ console.error("❌ Token approval failed:", error);
+ alert(`Approval failed: ${error instanceof Error ? error.message : "Unknown error"}`);
} finally {
setIsApproving(false);
}
@@ -186,13 +281,21 @@ export default function SwapComponent() {
};
const handleSwap = async () => {
- if (!isConnected) return;
+ if (!isWalletConnected()) {
+ alert("Please connect your wallet first");
+ return;
+ }
- // Safety check: Ensure we have sufficient allowance before proceeding
- if (needsApproval()) {
- console.error(
- "❌ Cannot proceed with swap: Insufficient allowance. Please approve spending cap first."
- );
+ // Check if we have the right wallet connected for the from chain
+ if (isTronChain(swapState.fromChain) && !tronConnected) {
+ alert("Please connect your Tron wallet to perform this swap");
+ setIsLoading(false);
+ return;
+ }
+
+ if (!isTronChain(swapState.fromChain) && !isConnected) {
+ alert("Please connect your EVM wallet to perform this swap");
+ setIsLoading(false);
return;
}
@@ -220,17 +323,32 @@ export default function SwapComponent() {
try {
console.log("🔄 Switching to source chain...");
- await switchChain({ chainId: swapState.fromChain });
- console.log("Switched to source chain");
- // Add a small delay to ensure the chain switch is complete
- await new Promise(resolve => setTimeout(resolve, 1000));
+
+ // Handle chain switching based on wallet type
+ if (isTronChain(swapState.fromChain)) {
+ // For Tron chains, we need to ensure Tron wallet is connected
+ if (!tronConnected) {
+ throw new Error("Please connect your Tron wallet first");
+ }
+ console.log("Using Tron wallet for source chain");
+ } else {
+ // For EVM chains, use wagmi switchChain
+ if (typeof swapState.fromChain === "number") {
+ await switchChain({ chainId: swapState.fromChain });
+ // Add a delay to ensure the chain switch is complete
+ await new Promise(resolve => setTimeout(resolve, 2000));
+ } else {
+ throw new Error("Invalid chain ID for EVM network");
+ }
+ }
+
const secret =
"0x0000000000000000000000000000000000000000000000000000000000000000";
console.log("✅ Switched to source chain successfully");
console.log("📝 Creating order data...");
const order = await createOrderLogic(
- address!,
+ getCurrentAddress()!,
swapState.fromAmount,
swapState.toAmount,
swapState.fromToken.address,
@@ -242,7 +360,6 @@ export default function SwapComponent() {
swapState.toToken.decimals
);
- console.log("🔐 Signing order data...");
const signature = await signTypedDataAsync(order.orderdata);
console.log("📦 Preparing order for submission...");
@@ -331,13 +448,13 @@ export default function SwapComponent() {
const updatedOrders = pendingSecretOrders.map((o: Order) =>
o.id === orderId
? {
- ...o,
- status: "PENDING_SECRET",
- transactions: resultBody.transactions || {},
- message:
- resultBody.message ||
- "Escrow contracts deployed on both chains. Waiting for secret revelation.",
- }
+ ...o,
+ status: "PENDING_SECRET",
+ transactions: resultBody.transactions || {},
+ message:
+ resultBody.message ||
+ "Escrow contracts deployed on both chains. Waiting for secret revelation.",
+ }
: o
);
localStorage.setItem("orders", JSON.stringify(updatedOrders));
@@ -365,10 +482,10 @@ export default function SwapComponent() {
const withdrawOrders = currentOrders.map((o: Order) =>
o.id === orderId
? {
- ...o,
- status: "PENDING_WITHDRAW",
- message: "Secret revealed. Starting withdrawal process...",
- }
+ ...o,
+ status: "PENDING_WITHDRAW",
+ message: "Secret revealed. Starting withdrawal process...",
+ }
: o
);
localStorage.setItem("orders", JSON.stringify(withdrawOrders));
@@ -465,12 +582,44 @@ export default function SwapComponent() {
};
const formatBalance = (
- balance: { value: bigint; decimals: number } | undefined
+ balance: { value: bigint; decimals: number } | undefined,
+ chainId?: number
) => {
if (!balance) return "0.00";
+ // For Tron chains, we don't have balance data from wagmi
+ if (chainId && isTronChain(chainId)) return "N/A";
return Number(formatUnits(balance.value, balance.decimals)).toFixed(4);
};
+ // Format Tron balance for display
+ const formatTronBalance = (balance: string | number, decimals: number = 6) => {
+ if (!balance || balance === "0" || balance === 0) {
+ return "0.00";
+ }
+
+ // Handle different balance formats
+ let balanceNum: number;
+
+ // If balance is already a number
+ if (typeof balance === 'number') {
+ balanceNum = balance;
+ } else if (typeof balance === 'string') {
+ // Remove any non-numeric characters except decimal point
+ const cleanBalance = balance.replace(/[^0-9.]/g, '');
+ balanceNum = parseFloat(cleanBalance);
+ } else {
+ // If it's an object (like BigNumber), try to convert to string first
+ const balanceStr = String(balance);
+ balanceNum = parseFloat(balanceStr);
+ }
+
+ // Apply decimal conversion
+ const adjustedBalance = balanceNum / Math.pow(10, decimals);
+ const result = adjustedBalance.toFixed(4);
+
+ return result;
+ };
+
return (
@@ -478,9 +627,9 @@ export default function SwapComponent() {
Exchange Assets
-
+
- Connected
+ {isWalletConnected() ? 'Connected' : 'Disconnected'}
@@ -492,7 +641,10 @@ export default function SwapComponent() {
From
- Balance: {formatBalance(fromTokenBalance)}
+ Balance: {isTronChain(swapState.fromChain)
+ ? formatTronBalance(tronFromBalance, swapState.fromToken.decimals)
+ : formatBalance(fromTokenBalance, swapState.fromChain)
+ }
@@ -510,14 +662,14 @@ export default function SwapComponent() {
className="w-6 h-6 rounded-full"
/>
- {CHAINS.find(c => c.id === swapState.fromChain)?.name}
+ {ALL_CHAINS.find(c => c.id === swapState.fromChain)?.name}
{showFromChainList && (
- {CHAINS.map(chain => (
+ {ALL_CHAINS.map(chain => (
@@ -633,14 +788,14 @@ export default function SwapComponent() {
className="w-6 h-6 rounded-full"
/>
- {CHAINS.find(c => c.id === swapState.toChain)?.name}
+ {ALL_CHAINS.find(c => c.id === swapState.toChain)?.name}
{showToChainList && (
- {CHAINS.map(chain => (
+ {ALL_CHAINS.map(chain => (
-
-
-
- Allowance
-
-
- {allowance != null
- ? formatUnits(allowance as bigint, swapState.fromToken.decimals)
- : "0.00"}
-
-