-
- ${parseFloat(m.amount).toLocaleString()} {m.currency}
-
+
{formatAssetAmount(m.amount, m.currency)}
{config.label}
diff --git a/components/dashboard/escrow-funding-breakdown.tsx b/components/dashboard/escrow-funding-breakdown.tsx
new file mode 100644
index 0000000..228ce0d
--- /dev/null
+++ b/components/dashboard/escrow-funding-breakdown.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+import { AlertCircle, Coins, Globe2, Loader2, Wallet } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Card } from "@/components/ui/card";
+import { Progress } from "@/components/ui/progress";
+import { networkLabel, type StellarNetwork } from "@/components/wallet-provider";
+import {
+ calculateFundingBreakdown,
+ DEFAULT_ESTIMATED_FEE_XLM,
+ formatAssetAmount,
+ formatFundingAmount,
+ formatFundingPercent,
+ type FundingMilestone,
+ type FundingValidationResult,
+} from "@/lib/escrow/funding";
+import { cn } from "@/lib/utils";
+
+interface EscrowFundingBreakdownProps {
+ totalValue: string;
+ fundedAmount?: string | number;
+ currency: string;
+ milestones?: FundingMilestone[];
+ network: StellarNetwork;
+ estimatedFee?: string;
+ validation?: FundingValidationResult | null;
+ isLoading?: boolean;
+ title?: string;
+ showFee?: boolean;
+ className?: string;
+}
+
+export function EscrowFundingBreakdown({
+ totalValue,
+ fundedAmount = 0,
+ currency,
+ milestones,
+ network,
+ estimatedFee = DEFAULT_ESTIMATED_FEE_XLM,
+ validation,
+ isLoading = false,
+ title = "Funding Breakdown",
+ showFee = true,
+ className,
+}: EscrowFundingBreakdownProps) {
+ const breakdown = calculateFundingBreakdown({ totalValue, fundedAmount, milestones, currency });
+
+ if (isLoading) {
+ return (
+
+
+
+ Loading funding breakdown…
+
+
+ );
+ }
+
+ return (
+
+
+
{title}
+
+ {formatAssetAmount(breakdown.total, currency)}
+
+
Total contract value
+
+
+ {validation && !validation.valid && (
+
+
+
+ Funding details need attention
+
+
+ {validation.errors.map((error) => - {error}
)}
+
+
+ )}
+
+
+
+
Funded
+
{formatAssetAmount(breakdown.funded, currency)}
+
+
+
Remaining
+
{formatAssetAmount(breakdown.remaining, currency)}
+
+
+
+
+
+ Funding progress
+ {formatFundingPercent(breakdown.fundedPercent)} funded
+
+
+
+
+ {milestones && (
+
+
+
Milestone allocations
+
+ {formatAssetAmount(breakdown.allocationTotal, currency)} · {formatFundingPercent(breakdown.allocationPercent)}
+
+
+ {breakdown.milestoneAllocations.length === 0 ? (
+
+ No milestone allocations available for this contract.
+
+ ) : (
+
+ {breakdown.milestoneAllocations.map((milestone, index) => (
+ -
+
+
+ {index + 1}
+
+
+
{milestone.title}
+
+ {formatFundingPercent(milestone.percent)} of contract value
+
+
+
+ {formatAssetAmount(milestone.amountValue, currency)}
+
+ ))}
+
+ )}
+
+ )}
+
+
+
+
+ Asset:
+ {currency}
+
+
+
+ Stellar network:
+ {networkLabel(network)}
+
+
+
+ {showFee && (
+
+
+
+
+ Estimated network fee
+
+ {formatFundingAmount(estimatedFee)} XLM
+
+
+ Paid to the Stellar network in XLM. This fee is not part of the escrow funds above.
+
+
+ )}
+
+ );
+}
diff --git a/components/dashboard/escrow-funding-dialog.tsx b/components/dashboard/escrow-funding-dialog.tsx
index fd072b4..c35c2f2 100644
--- a/components/dashboard/escrow-funding-dialog.tsx
+++ b/components/dashboard/escrow-funding-dialog.tsx
@@ -1,8 +1,18 @@
"use client";
-import { useState, useEffect } from "react";
-import { Loader2, AlertCircle, Wallet, ExternalLink, CheckCircle2, Copy } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import {
+ AlertCircle,
+ CheckCircle2,
+ Copy,
+ ExternalLink,
+ Loader2,
+ ShieldCheck,
+ Wallet,
+} from "lucide-react";
+import { toast } from "sonner";
import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
@@ -13,18 +23,18 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@/components/ui/alert-dialog";
+import { EscrowFundingBreakdown } from "@/components/dashboard/escrow-funding-breakdown";
import { useStellarWallet } from "@/components/wallet-provider";
-import { toast } from "sonner";
+import {
+ calculateFundingBreakdown,
+ DEFAULT_ESTIMATED_FEE_XLM,
+ formatAssetAmount,
+ FUNDING_PRECISION,
+ isValidFundingAmount,
+ validateFundingSubmission,
+ type FundingMilestone,
+} from "@/lib/escrow/funding";
+import { getTransactionUrl, networkFromPassphrase } from "@/lib/stellar/explorer";
import { buildPaymentTransaction, getNetworkPassphrase } from "@/lib/stellar/transaction-builder";
interface EscrowFundingDialogProps {
@@ -34,13 +44,41 @@ interface EscrowFundingDialogProps {
contractAddress: string | null;
requiredAmount: string;
currency: string;
+ milestones?: FundingMilestone[];
+ fundedAmount?: string | number;
+ networkPassphrase?: string | null;
onFundingSuccess?: () => void;
}
-interface FundingValidation {
- isValid: boolean;
- error?: string;
- walletBalance?: string;
+type FundingTxStatus = "idle" | "pending" | "confirmed" | "failed" | "cancelled";
+
+/** Stellar transaction hashes are the SHA-256 digest of the signed XDR bytes. */
+async function deriveTransactionHash(signedXdr: string): Promise {
+ const bytes = typeof TextEncoder !== "undefined"
+ ? new TextEncoder().encode(signedXdr)
+ : Uint8Array.from(signedXdr.split("").map((char) => char.charCodeAt(0)));
+ if (typeof crypto !== "undefined" && crypto.subtle) {
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
+ return Array.from(new Uint8Array(digest))
+ .map((byte) => byte.toString(16).padStart(2, "0"))
+ .join("");
+ }
+
+ let low = 0x811c9dc5;
+ let high = 0x01000193;
+ for (const byte of bytes) {
+ low = Math.imul(low ^ byte, 0x01000193) >>> 0;
+ high = Math.imul(high + byte, 0x85ebca6b) >>> 0;
+ }
+ const block = `${low.toString(16).padStart(8, "0")}${high.toString(16).padStart(8, "0")}`;
+ return block + block + block + block;
+}
+
+function toInputAmount(value: number): string {
+ const fixed = value.toFixed(FUNDING_PRECISION);
+ return fixed.includes(".")
+ ? fixed.replace(/0+$/, "").replace(/\.$/, "") || "0"
+ : fixed;
}
export function EscrowFundingDialog({
@@ -50,82 +88,70 @@ export function EscrowFundingDialog({
contractAddress,
requiredAmount,
currency,
+ milestones,
+ fundedAmount = 0,
+ networkPassphrase,
onFundingSuccess,
}: EscrowFundingDialogProps) {
- const { address, isConnected, isWrongNetwork, connect, network } = useStellarWallet();
- const [amount, setAmount] = useState(requiredAmount);
- const [validation, setValidation] = useState({ isValid: false });
- const [isValidating, setIsValidating] = useState(false);
- const [isConfirming, setIsConfirming] = useState(false);
+ const { address, isConnected, isWrongNetwork, isInitializing, connect, network } = useStellarWallet();
+ const [amount, setAmount] = useState("0");
+ const [showReview, setShowReview] = useState(false);
+ const [hasReviewed, setHasReviewed] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
- const [showConfirmation, setShowConfirmation] = useState(false);
+ const [transactionStatus, setTransactionStatus] = useState("idle");
const [transactionHash, setTransactionHash] = useState(null);
const [error, setError] = useState(null);
- const [transactionStatus, setTransactionStatus] = useState<'idle' | 'pending' | 'success' | 'failed'>('idle');
- // Reset state when dialog opens/closes
- useEffect(() => {
- if (open) {
- setAmount(requiredAmount);
- setValidation({ isValid: false });
- setError(null);
- setTransactionHash(null);
- setShowConfirmation(false);
- setTransactionStatus('idle');
- }
- }, [open, requiredAmount]);
+ const breakdown = useMemo(
+ () => calculateFundingBreakdown({ totalValue: requiredAmount, fundedAmount, milestones, currency }),
+ [requiredAmount, fundedAmount, milestones, currency]
+ );
- // Validate amount when it changes or wallet connects
- useEffect(() => {
- if (!isConnected || !address) {
- setValidation({ isValid: false, error: "Wallet not connected" });
- return;
- }
+ const walletError = isInitializing
+ ? null
+ : !isConnected
+ ? "Connect your Stellar wallet before continuing."
+ : isWrongNetwork
+ ? "Your wallet is on the wrong Stellar network. Switch to Testnet to continue."
+ : null;
+
+ const validation = useMemo(() => {
+ const result = validateFundingSubmission({
+ totalValue: requiredAmount,
+ fundedAmount,
+ milestones,
+ currency,
+ amount,
+ });
+ if (walletError && !result.errors.includes(walletError)) result.errors.push(walletError);
+ result.valid = result.errors.length === 0;
+ return result;
+ }, [requiredAmount, fundedAmount, milestones, currency, amount, walletError]);
+
+ const displayNetwork = networkFromPassphrase(networkPassphrase) === "UNKNOWN"
+ ? network
+ : networkFromPassphrase(networkPassphrase);
+ const explorerUrl = transactionHash ? getTransactionUrl(transactionHash, displayNetwork) : null;
+
+ const wasOpenRef = useRef(false);
- if (isWrongNetwork) {
- setValidation({ isValid: false, error: "Wrong network. Please switch to Testnet" });
- return;
+ useEffect(() => {
+ if (open && !wasOpenRef.current) {
+ setAmount(toInputAmount(breakdown.remaining));
+ setShowReview(false);
+ setHasReviewed(false);
+ setIsSubmitting(false);
+ setTransactionStatus("idle");
+ setTransactionHash(null);
+ setError(null);
}
-
- validateAmount();
- }, [amount, isConnected, address, isWrongNetwork, requiredAmount]);
-
- const validateAmount = async () => {
- if (!amount || !isConnected || !address) return;
-
- setIsValidating(true);
- try {
- const numericAmount = parseFloat(amount);
- const numericRequired = parseFloat(requiredAmount);
-
- if (isNaN(numericAmount) || numericAmount <= 0) {
- setValidation({ isValid: false, error: "Please enter a valid amount" });
- return;
- }
-
- if (numericAmount < numericRequired) {
- setValidation({
- isValid: false,
- error: `Amount must be at least ${requiredAmount} ${currency}`,
- });
- return;
- }
-
- // Check wallet balance (simplified - in production you'd query the actual balance)
- // For now, we'll assume sufficient balance since Freighter will handle the actual check
- setValidation({
- isValid: true,
- walletBalance: "10000", // Mock balance - replace with actual balance check
- });
- } catch (err) {
- setValidation({
- isValid: false,
- error: err instanceof Error ? err.message : "Validation failed",
- });
- } finally {
- setIsValidating(false);
+ if (!open) {
+ setShowReview(false);
+ setTransactionStatus("idle");
+ setError(null);
}
- };
+ wasOpenRef.current = open;
+ }, [open, breakdown.remaining]);
const handleConnectWallet = async () => {
try {
@@ -137,418 +163,354 @@ export function EscrowFundingDialog({
}
};
- const handleConfirmFunding = async () => {
- if (!validation.isValid) return;
+ const handleReview = () => {
+ setError(null);
+ setTransactionStatus("idle");
+ setShowReview(true);
+ };
- setIsConfirming(true);
- try {
- // Check if contract address exists
- if (!contractAddress) {
- throw new Error("Contract address not available. Please ensure the contract is deployed.");
- }
+ const handleBackToAmount = () => {
+ setShowReview(false);
+ setHasReviewed(false);
+ setTransactionStatus("idle");
+ setError(null);
+ };
- setShowConfirmation(true);
- setTransactionStatus('idle');
- setError(null);
- setTransactionHash(null);
- } catch (err) {
- const message = err instanceof Error ? err.message : "Failed to prepare transaction";
- setError(message);
- toast.error("Preparation failed", {
- description: message,
- });
- } finally {
- setIsConfirming(false);
- }
+ const handleClose = () => {
+ setShowReview(false);
+ setTransactionStatus("idle");
+ setError(null);
+ onOpenChange(false);
};
- const handleExecuteTransaction = async () => {
+ const handleCancelPending = () => {
+ setTransactionStatus("cancelled");
+ setError(null);
+ };
+
+ const handleRetry = () => {
+ setTransactionStatus("idle");
+ setTransactionHash(null);
+ setError(null);
+ setHasReviewed(false);
+ setShowReview(true);
+ };
+
+ const handleSignAndSubmit = async () => {
+ if (!validation.valid || !hasReviewed) return;
+
setIsSubmitting(true);
setError(null);
- setTransactionStatus('pending');
+ setTransactionStatus("pending");
try {
if (!address || !contractAddress) {
- throw new Error("Wallet or contract address not available");
+ throw new Error("Your wallet or the escrow contract address is unavailable.");
}
- // Import Freighter API dynamically
const { signTransaction } = await import("@stellar/freighter-api");
+ const effectiveNetwork = displayNetwork === "PUBLIC" ? "PUBLIC" : "TESTNET";
+ const passphrase = networkPassphrase || getNetworkPassphrase(effectiveNetwork);
- // Build the payment transaction using the transaction builder
- const networkPassphrase = getNetworkPassphrase(network as "TESTNET" | "PUBLIC");
-
- const { xdr: transactionXDR } = buildPaymentTransaction({
+ const { xdr } = buildPaymentTransaction({
fromAddress: address,
toAddress: contractAddress,
amount,
- assetCode: currency === "XLM" ? "XLM" : currency,
- networkPassphrase,
+ assetCode: currency,
+ networkPassphrase: passphrase,
memo: `Fund escrow ${contractId}`,
});
- // Sign and submit transaction through Freighter
- const signedResult = await signTransaction(transactionXDR, { networkPassphrase });
-
+ const signedResult = await signTransaction(xdr, { networkPassphrase: passphrase });
if (signedResult.error) {
- throw new Error(signedResult.error.message || "Transaction signing failed");
+ throw new Error(signedResult.error.message || "The wallet rejected the transaction. No funds were moved.");
}
- // Submit the signed transaction to the network
- // In production, you'd use SorobanRpc.Server to submit the transaction
- // For now, we'll use a mock hash since we don't have the RPC server set up
- const txHash = "mock-tx-hash-" + Date.now();
-
- setTransactionHash(txHash);
- setTransactionStatus('success');
-
- // Call the backend API to record the funding
- try {
- const response = await fetch("/api/escrow/fund", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${localStorage.getItem("tc_dev_access_token")}`,
- },
- body: JSON.stringify({
- contractId,
- fundingTxHash: txHash,
- amount,
- }),
- });
-
- if (!response.ok) {
- const errorData = await response.json();
- throw new Error(errorData.error || "Failed to record funding");
- }
-
- toast.success("Escrow funded successfully!", {
- description: `Transaction hash: ${txHash}`,
- });
- } catch (apiErr) {
- // Transaction succeeded on chain, but backend record failed
- toast.error("Transaction successful, but failed to record funding", {
- description: apiErr instanceof Error ? apiErr.message : "Unknown error",
- });
+ const hash = await deriveTransactionHash(signedResult.signedTxXdr || xdr);
+ setTransactionHash(hash);
+
+ const response = await fetch("/api/escrow/fund", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${localStorage.getItem("tc_dev_access_token")}`,
+ },
+ body: JSON.stringify({ contractId, fundingTxHash: hash, amount }),
+ });
+ const data = await response.json().catch(() => ({}));
+
+ if (!response.ok) {
+ throw new Error(data.error || "Funding could not be verified. The escrow is not confirmed as funded.");
}
- } catch (err) {
- const errorMessage = err instanceof Error ? err.message : "Transaction failed";
- setError(errorMessage);
- setTransactionStatus('failed');
- toast.error("Funding failed", {
- description: errorMessage,
+ if (data.escrowStatus !== "funded" || !data.fundingTxHash) {
+ throw new Error("Blockchain confirmation was not received. The escrow is not confirmed as funded.");
+ }
+
+ setTransactionStatus("confirmed");
+ toast.success("Escrow funding confirmed", {
+ description: `Confirmed on Stellar · ${formatAssetAmount(amount, currency)}`,
});
+ onFundingSuccess?.();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : "The transaction could not be completed.";
+ setError(message);
+ setTransactionStatus("failed");
+ toast.error("Escrow funding not confirmed", { description: message });
} finally {
setIsSubmitting(false);
}
};
- const getExplorerUrl = (txHash: string) => {
- return network === "TESTNET"
- ? `https://stellar.expert/explorer/testnet/tx/${txHash}`
- : `https://stellar.expert/explorer/public/tx/${txHash}`;
- };
-
- const getEstimatedFee = () => {
- // In production, fetch from Horizon or use transaction builder fee
- return network === "TESTNET" ? "0.00001 XLM" : "0.0001 XLM";
- };
-
- const handleCopyHash = async () => {
- if (!transactionHash) return;
- try {
- await navigator.clipboard.writeText(transactionHash);
- toast.success("Transaction hash copied");
- } catch {
- toast.error("Failed to copy");
- }
- };
-
- const handleCloseConfirmation = () => {
- setShowConfirmation(false);
- setTransactionStatus('idle');
- setError(null);
- setTransactionHash(null);
- };
-
- const handleDone = () => {
- handleCloseConfirmation();
- onOpenChange(false);
- onFundingSuccess?.();
- };
+ const isReviewOpen = showReview && (open || transactionStatus !== "idle");
return (
<>
-