From 5d52dbdfbd07470a09faa08cf44c60d628b21901 Mon Sep 17 00:00:00 2001 From: Stanley Owoh Date: Thu, 19 Nov 2026 13:34:49 +0100 Subject: [PATCH] feat(escrow): add funding breakdown and confirmation UI (#254) --- __tests__/escrow-funding-breakdown.test.tsx | 75 ++ __tests__/escrow-funding-dialog.test.tsx | 171 ++++ __tests__/escrow-funding.test.ts | 107 +++ app/dashboard/contracts/[id]/page.tsx | 34 +- .../dashboard/contract-escrow-summary.tsx | 53 +- .../dashboard/contract-milestone-list.tsx | 5 +- .../dashboard/escrow-funding-breakdown.tsx | 170 ++++ .../dashboard/escrow-funding-dialog.tsx | 740 +++++++++--------- .../dashboard/escrow-status-tracker.tsx | 2 + lib/escrow/funding.ts | 146 ++++ 10 files changed, 1086 insertions(+), 417 deletions(-) create mode 100644 __tests__/escrow-funding-breakdown.test.tsx create mode 100644 __tests__/escrow-funding-dialog.test.tsx create mode 100644 __tests__/escrow-funding.test.ts create mode 100644 components/dashboard/escrow-funding-breakdown.tsx create mode 100644 lib/escrow/funding.ts diff --git a/__tests__/escrow-funding-breakdown.test.tsx b/__tests__/escrow-funding-breakdown.test.tsx new file mode 100644 index 0000000..f32f6e2 --- /dev/null +++ b/__tests__/escrow-funding-breakdown.test.tsx @@ -0,0 +1,75 @@ +import { render, screen } from '@testing-library/react' +import { describe, expect, it, vi } from 'vitest' +import { EscrowFundingBreakdown } from '@/components/dashboard/escrow-funding-breakdown' + +vi.mock('@/components/wallet-provider', () => ({ + networkLabel: (network: string) => (network === 'PUBLIC' ? 'Mainnet' : 'Testnet'), +})) + +const milestones = [ + { id: '1', title: 'Design', amount: '500' }, + { id: '2', title: 'Development', amount: '1000' }, +] + +describe('EscrowFundingBreakdown', () => { + it('summarises the total, funded/remaining amounts, allocations, asset, network and fee', () => { + render( + + ) + + expect(screen.getByLabelText('Total contract value')).toHaveTextContent('1,500.00 USDC') + expect(screen.getAllByText('1,000.00 USDC').length).toBeGreaterThan(0) + expect(screen.getByText('Design')).toBeInTheDocument() + expect(screen.getByText('Development')).toBeInTheDocument() + expect(screen.getByText('33.3% of contract value')).toBeInTheDocument() + expect(screen.getByText('USDC')).toBeInTheDocument() + expect(screen.getByText('Testnet')).toBeInTheDocument() + expect(screen.getByText(/not part of the escrow funds/i)).toBeInTheDocument() + }) + + it('shows an empty state when no milestone allocations exist', () => { + render( + + ) + + expect(screen.getByText(/No milestone allocations available/i)).toBeInTheDocument() + }) + + it('surfaces validation errors', () => { + render( + + ) + + expect(screen.getByRole('alert')).toHaveTextContent('Milestone allocations do not match') + }) + + it('shows a loading state', () => { + render( + + ) + + expect(screen.getByRole('status')).toHaveTextContent('Loading funding breakdown') + }) +}) diff --git a/__tests__/escrow-funding-dialog.test.tsx b/__tests__/escrow-funding-dialog.test.tsx new file mode 100644 index 0000000..62b87ff --- /dev/null +++ b/__tests__/escrow-funding-dialog.test.tsx @@ -0,0 +1,171 @@ +import type { ComponentProps } from 'react' +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ + toastSuccess: vi.fn(), + toastError: vi.fn(), + signTransaction: vi.fn(), + connect: vi.fn(), + onFundingSuccess: vi.fn(), + wallet: { + address: 'GABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRSTUVWX', + isConnected: true, + isWrongNetwork: false, + isInitializing: false, + network: 'TESTNET', + }, +})) + +vi.mock('sonner', () => ({ + toast: { success: mocks.toastSuccess, error: mocks.toastError }, +})) + +vi.mock('@/components/wallet-provider', () => ({ + useStellarWallet: () => ({ ...mocks.wallet, connect: mocks.connect }), + networkLabel: (network: string) => (network === 'PUBLIC' ? 'Mainnet' : 'Testnet'), + REQUIRED_NETWORK: 'TESTNET', +})) + +vi.mock('@stellar/freighter-api', () => ({ + signTransaction: mocks.signTransaction, +})) + +vi.mock('@/lib/stellar/transaction-builder', () => ({ + buildPaymentTransaction: () => ({ xdr: 'unsigned-xdr' }), + getNetworkPassphrase: () => 'Test SDF Network ; September 2015', +})) + +import { EscrowFundingDialog } from '@/components/dashboard/escrow-funding-dialog' + +const milestones = [ + { id: '1', title: 'Design', amount: '500' }, + { id: '2', title: 'Development', amount: '1000' }, +] + +function renderDialog(overrides: Partial> = {}) { + return render( + {}} + contractId="contract-1" + contractAddress="CABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRSTUVWX" + requiredAmount="1500" + currency="USDC" + milestones={milestones} + networkPassphrase="Test SDF Network ; September 2015" + onFundingSuccess={mocks.onFundingSuccess} + {...overrides} + /> + ) +} + +async function openReview() { + fireEvent.click(screen.getByRole('button', { name: /Review Funding Details/i })) + expect(await screen.findByRole('checkbox')).toBeInTheDocument() +} + +describe('EscrowFundingDialog', () => { + beforeEach(() => { + vi.clearAllMocks() + Object.assign(mocks.wallet, { + address: 'GABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRSTUVWX', + isConnected: true, + isWrongNetwork: false, + isInitializing: false, + network: 'TESTNET', + }) + mocks.signTransaction.mockResolvedValue({ signedTxXdr: 'signed-xdr', error: null }) + vi.stubGlobal('fetch', vi.fn()) + }) + + afterEach(() => { + cleanup() + vi.unstubAllGlobals() + }) + + it('requires an explicit confirmation step before wallet signing', async () => { + renderDialog() + expect(screen.getByLabelText('Total contract value')).toHaveTextContent('1,500.00 USDC') + + await openReview() + const continueButton = screen.getByRole('button', { name: /Continue to Wallet/i }) + expect(continueButton).toBeDisabled() + + fireEvent.click(screen.getByRole('checkbox')) + expect(continueButton).toBeEnabled() + expect(mocks.signTransaction).not.toHaveBeenCalled() + }) + + it('blocks review when milestone allocations do not match the contract total', () => { + renderDialog({ milestones: [{ id: '1', title: 'Design', amount: '900' }] }) + + expect(screen.getByRole('alert')).toHaveTextContent(/Milestone allocations total 900\.00 USDC/) + expect(screen.getByRole('button', { name: /Review Funding Details/i })).toBeDisabled() + }) + + it('never shows success until the blockchain confirmation response resolves', async () => { + let resolveFetch: (value: unknown) => void = () => {} + const pendingFetch = new Promise((resolve) => { resolveFetch = resolve }) + vi.stubGlobal('fetch', vi.fn(() => pendingFetch)) + + renderDialog() + await openReview() + fireEvent.click(screen.getByRole('checkbox')) + fireEvent.click(screen.getByRole('button', { name: /Continue to Wallet/i })) + + expect(await screen.findByText(/Awaiting blockchain confirmation/i)).toBeInTheDocument() + expect(screen.queryByText(/Confirmed on Stellar/i)).not.toBeInTheDocument() + + resolveFetch({ + ok: true, + json: async () => ({ escrowStatus: 'funded', fundingTxHash: 'confirmed-hash' }), + }) + + expect(await screen.findByText(/Confirmed on Stellar/i)).toBeInTheDocument() + expect(mocks.onFundingSuccess).toHaveBeenCalled() + expect(mocks.toastSuccess).toHaveBeenCalled() + }) + + it('keeps escrow unfunded and shows an actionable error when verification fails', async () => { + vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({ + ok: false, + json: async () => ({ error: 'Funding verification failed' }), + }))) + + renderDialog() + await openReview() + fireEvent.click(screen.getByRole('checkbox')) + fireEvent.click(screen.getByRole('button', { name: /Continue to Wallet/i })) + + expect(await screen.findByText(/Funding was not confirmed/i)).toBeInTheDocument() + expect(screen.getByText(/The escrow remains unfunded/i)).toBeInTheDocument() + expect(screen.queryByText(/Confirmed on Stellar/i)).not.toBeInTheDocument() + expect(mocks.onFundingSuccess).not.toHaveBeenCalled() + }) + + it('distinguishes a cancelled pending transaction from a failure', async () => { + vi.stubGlobal('fetch', vi.fn(() => new Promise(() => {}))) + + renderDialog() + await openReview() + fireEvent.click(screen.getByRole('checkbox')) + fireEvent.click(screen.getByRole('button', { name: /Continue to Wallet/i })) + + expect(await screen.findByText(/Awaiting blockchain confirmation/i)).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: /^Cancel$/i })) + + await waitFor(() => { + expect(screen.getByText('Funding cancelled')).toBeInTheDocument() + }) + expect(screen.queryByText(/Funding was not confirmed/i)).not.toBeInTheDocument() + }) + + it('requires a connected wallet on the correct network', () => { + mocks.wallet.isConnected = false + + renderDialog() + expect(screen.getByText(/Wallet not connected/i)).toBeInTheDocument() + expect(screen.getByRole('button', { name: /Review Funding Details/i })).toBeDisabled() + }) +}) diff --git a/__tests__/escrow-funding.test.ts b/__tests__/escrow-funding.test.ts new file mode 100644 index 0000000..bfd795d --- /dev/null +++ b/__tests__/escrow-funding.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, it } from 'vitest' +import { + calculateFundingBreakdown, + formatAssetAmount, + formatFundingAmount, + formatFundingPercent, + isValidFundingAmount, + validateFundingSubmission, +} from '@/lib/escrow/funding' + +const milestones = [ + { id: '1', title: 'Discovery', amount: '500.0000000' }, + { id: '2', title: 'Build', amount: '1000.0000000' }, +] + +describe('escrow funding calculations', () => { + it('calculates funded, remaining and allocation percentages', () => { + const result = calculateFundingBreakdown({ + totalValue: '1500.00', + fundedAmount: 500, + milestones, + currency: 'USDC', + }) + + expect(result.total).toBe(1500) + expect(result.funded).toBe(500) + expect(result.remaining).toBe(1000) + expect(result.fundedPercent).toBeCloseTo(33.333, 2) + expect(result.allocationTotal).toBe(1500) + expect(result.milestoneAllocations[1].percent).toBeCloseTo(66.667, 2) + }) + + it('formats amounts with consistent precision', () => { + expect(formatFundingAmount('1500')).toBe('1,500.00') + expect(formatFundingAmount('0.0000001')).toBe('0.0000001') + expect(formatAssetAmount('1500', 'USDC')).toBe('1,500.00 USDC') + expect(formatFundingPercent(25)).toBe('25.0%') + }) + + it('only accepts positive Stellar amounts with at most seven decimals', () => { + expect(isValidFundingAmount('1000')).toBe(true) + expect(isValidFundingAmount('1000.1234567')).toBe(true) + expect(isValidFundingAmount('1000.12345678')).toBe(false) + expect(isValidFundingAmount('0')).toBe(false) + expect(isValidFundingAmount('abc')).toBe(false) + }) +}) + +describe('validateFundingSubmission', () => { + const validInput = { + totalValue: '1500.00', + fundedAmount: 0, + milestones, + currency: 'USDC', + amount: '1500.00', + } + + it('accepts a fully funded, internally consistent allocation', () => { + expect(validateFundingSubmission(validInput)).toEqual({ valid: true, errors: [] }) + }) + + it('rejects submissions when milestone allocations do not match the contract total', () => { + const result = validateFundingSubmission({ + ...validInput, + milestones: [{ id: '1', title: 'Discovery', amount: '1400' }], + }) + + expect(result.valid).toBe(false) + expect(result.errors[0]).toMatch(/Milestone allocations total 1,400\.00 USDC/) + }) + + it('rejects an empty allocation list when milestones are supplied', () => { + const result = validateFundingSubmission({ ...validInput, milestones: [] }) + + expect(result.valid).toBe(false) + expect(result.errors[0]).toMatch(/No milestone allocations found/) + }) + + it('rejects amounts that do not cover the remaining balance', () => { + const result = validateFundingSubmission({ ...validInput, amount: '900' }) + + expect(result.valid).toBe(false) + expect(result.errors).toContain('Funding amount must be at least 1,500.00 USDC.') + }) + + it('rejects amounts exceeding the remaining balance', () => { + const result = validateFundingSubmission({ + ...validInput, + fundedAmount: 200, + amount: '1500', + }) + + expect(result.valid).toBe(false) + expect(result.errors).toContain('Funding amount exceeds the remaining 1,300.00 USDC.') + }) + + it('skips allocation validation for legacy contracts without milestones', () => { + const result = validateFundingSubmission({ + totalValue: '1500.00', + fundedAmount: 500, + currency: 'XLM', + amount: '1000', + }) + + expect(result.valid).toBe(true) + }) +}) diff --git a/app/dashboard/contracts/[id]/page.tsx b/app/dashboard/contracts/[id]/page.tsx index 947c0da..5e3f278 100644 --- a/app/dashboard/contracts/[id]/page.tsx +++ b/app/dashboard/contracts/[id]/page.tsx @@ -3,16 +3,16 @@ import { useEffect, useState } from "react"; import { useParams } from "next/navigation"; import Link from "next/link"; -import { ArrowLeft, Loader2, AlertCircle, Star, ShieldCheck, Wallet, User } from "lucide-react"; +import { ArrowLeft, Loader2, AlertCircle, Wallet } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Card } from "@/components/ui/card"; import { ProfileCard } from "@/components/dashboard/profile-card"; import { ContractMilestoneList, type ContractMilestone } from "@/components/dashboard/contract-milestone-list"; import { ContractEscrowSummary } from "@/components/dashboard/contract-escrow-summary"; -import { EscrowStatusTracker, type EscrowStage } from "@/components/dashboard/escrow-status-tracker"; import { EscrowFundingDialog } from "@/components/dashboard/escrow-funding-dialog"; import { ActivityTimeline } from "@/components/ActivityTimeline"; +import { calculateFundingBreakdown, formatAssetAmount } from "@/lib/escrow/funding"; interface ProfileInfo { display_name: string | null; @@ -56,11 +56,6 @@ const contractStatusConfig: Record = { - draft: "Funded", open: "Funded", in_progress: "In Progress", - completed: "Released", disputed: "In Progress", -}; - function getAuthHeaders(): Record { const token = typeof window !== "undefined" @@ -146,7 +141,6 @@ export default function ContractDetailPage() { } const statusCfg = contractStatusConfig[contract.status] ?? contractStatusConfig.pending; - const escrowStage = escrowStageMap[contract.status] ?? "Funded"; const clientBadge = ( Owner ); @@ -212,7 +206,7 @@ export default function ContractDetailPage() {
- + {canFund && (
+ {/* Milestone Allocations */} +
+
+

Milestone Allocations

+ + {formatAssetAmount( + calculateFundingBreakdown({ + totalValue: contract.total_amount, + milestones: contract.milestones, + currency: contract.currency, + }).allocationTotal, + contract.currency + )}{" "} + allocated + +
+ +
+ {/* Contract Activity Timeline */}
@@ -239,6 +252,9 @@ export default function ContractDetailPage() { contractAddress={contract.escrow?.escrow_address ?? null} requiredAmount={contract.total_amount} currency={contract.currency} + milestones={contract.milestones} + fundedAmount={contract.escrow?.funded_amount ?? 0} + networkPassphrase={contract.escrow?.network_passphrase ?? null} onFundingSuccess={handleFundingSuccess} /> diff --git a/components/dashboard/contract-escrow-summary.tsx b/components/dashboard/contract-escrow-summary.tsx index f3ec6ce..34b9cbb 100644 --- a/components/dashboard/contract-escrow-summary.tsx +++ b/components/dashboard/contract-escrow-summary.tsx @@ -1,14 +1,13 @@ -import Link from "next/link"; import { ArrowLeft, ShieldCheck, Wallet } from "lucide-react"; import { Button } from "@/components/ui/button"; -import { Badge } from "@/components/ui/badge"; import { Card } from "@/components/ui/card"; import { EscrowStatusTracker, type EscrowStage, } from "@/components/dashboard/escrow-status-tracker"; import { ContractAddress, TransactionHash } from "@/components/stellar"; -import { networkFromPassphrase } from "@/lib/stellar/explorer"; +import { getNetworkLabel, networkFromPassphrase } from "@/lib/stellar/explorer"; +import { formatFundingAmount } from "@/lib/escrow/funding"; interface EscrowInfo { escrow_address: string | null; @@ -22,6 +21,21 @@ interface EscrowInfo { network_passphrase: string | null; } +function toEscrowStage(status: string | null | undefined): EscrowStage { + switch (status) { + case "funded": + return "Funded"; + case "partially_released": + return "In Progress"; + case "fully_released": + return "Released"; + case "refunded": + return "Refunded"; + default: + return "Unfunded"; + } +} + export function ContractEscrowSummary({ escrow, currency, @@ -31,10 +45,11 @@ export function ContractEscrowSummary({ currency: string; onBack?: () => void; }) { - const escrowStage: EscrowStage = - (escrow?.escrow_status as EscrowStage | undefined) ?? "Funded"; - + const escrowStage = toEscrowStage(escrow?.escrow_status); + const isFunded = escrowStage !== "Unfunded"; const network = networkFromPassphrase(escrow?.network_passphrase); + const fundedAmount = escrow?.funded_amount ?? 0; + const remainingAmount = Math.max(Number(escrow?.total_amount ?? 0) - fundedAmount, 0); return (
@@ -76,37 +91,43 @@ export function ContractEscrowSummary({

)} {escrow.network_passphrase && ( -

- Network: {escrow.network_passphrase} +

+ Stellar network: {getNetworkLabel(network)}

)}
- Total Locked + {isFunded ? "Total Locked" : "Total To Lock"} - {escrow.total_amount} {currency} + {formatFundingAmount(escrow.total_amount)} {currency}
-
+

Funded

- {escrow.funded_amount.toLocaleString()} {currency} + {formatFundingAmount(fundedAmount)} {currency} +

+
+
+

Remaining

+

+ {formatFundingAmount(remainingAmount)} {currency}

Released

- {escrow.released_amount.toLocaleString()} {currency} + {formatFundingAmount(escrow.released_amount)} {currency}

- {escrow.funding_tx_hash && ( + {isFunded && escrow.funding_tx_hash && (

Funding Tx: )} - {escrow.funded_at && ( + {isFunded && escrow.funded_at && (

Funded at: {new Date(escrow.funded_at).toLocaleString()}

@@ -135,4 +156,4 @@ export function ContractEscrowSummary({ )}
); -} \ No newline at end of file +} diff --git a/components/dashboard/contract-milestone-list.tsx b/components/dashboard/contract-milestone-list.tsx index 1f1b451..fcf1182 100644 --- a/components/dashboard/contract-milestone-list.tsx +++ b/components/dashboard/contract-milestone-list.tsx @@ -4,6 +4,7 @@ import { CheckCircle2, Clock, AlertCircle, ChevronRight } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import Link from "next/link"; +import { formatAssetAmount } from "@/lib/escrow/funding"; export interface ContractMilestone { id: string; @@ -78,9 +79,7 @@ export function ContractMilestoneList({ milestones, isLoading }: { milestones: C
-

- ${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 ( <> - - + + - - Fund Escrow Contract + + Review Escrow Funding - Fund the escrow contract securely from your Stellar wallet + Verify the contract allocation before preparing a funding transaction. -
- {/* Contract Info */} -
-
- Required Amount: - {requiredAmount} {currency} +
+ + + {isInitializing ? ( +
+ + Checking wallet…
- {contractAddress && ( -
- Contract: - {contractAddress} -
- )} -
- - {/* Wallet Connection Status */} - {!isConnected ? ( -
-
+ ) : !isConnected ? ( +
+

- Wallet Not Connected -

-

- Connect your Stellar wallet to fund the escrow + Wallet not connected

-
) : isWrongNetwork ? ( -
-
+
+

- Wrong Network -

-

- Please switch your wallet to Testnet to continue + Wrong network +

+

+ Switch your wallet to Testnet before funding escrow.

) : ( <> - {/* Amount Input */}
- + setAmount(e.target.value)} - disabled={isSubmitting} - placeholder={`Enter amount (min: ${requiredAmount})`} + onChange={(event) => setAmount(event.target.value)} + aria-invalid={!isValidFundingAmount(amount)} /> +

+ Remaining to fully fund: {formatAssetAmount(breakdown.remaining, currency)} +

- {/* Validation Status */} - {isValidating && ( -
- - Validating... -
- )} - - {validation.error && !isValidating && ( -
- - {validation.error} -
- )} - - {validation.isValid && validation.walletBalance && ( -
- - Wallet balance sufficient -
- )} - - {/* Connected Wallet Info */} -
-
- - Connected: - {address} +
+
+ + + Funding wallet + + {address}
)} - - {/* Error Display */} - {error && ( -
-
- - {error} -
-
- )}
- - - +
- {/* Confirmation Modal */} - - + !next && handleClose()}> + - {transactionStatus === 'success' ? ( + {transactionStatus === "confirmed" ? ( - ) : transactionStatus === 'failed' ? ( + ) : transactionStatus === "failed" || transactionStatus === "cancelled" ? ( ) : ( - + )} - Transaction Confirmation + Confirm Escrow Funding - Review your transaction details + {transactionStatus === "pending" + ? "Transaction submitted. Waiting for blockchain confirmation." + : transactionStatus === "confirmed" + ? "Your escrow funding is confirmed on the Stellar network." + : "Review the final details before your wallet opens for signing."} -
- {/* Transaction Details */} -
-
- Type: - Fund Escrow -
-
- Amount: - {amount} {currency} +
+ + +
+
+ Amount to fund + {formatAssetAmount(amount, currency)}
-
- From: - {address} +
+ From wallet + {address}
-
- Network: - {network === "TESTNET" ? "Testnet" : "Mainnet"} +
+ Escrow contract + {contractAddress}
-
- Estimated Fee: - {getEstimatedFee()} +
+ Estimated network fee (not escrowed) + {DEFAULT_ESTIMATED_FEE_XLM} XLM
- {/* Transaction Status */} - {transactionStatus === 'pending' && ( -
- - Processing transaction... + {transactionStatus === "idle" && ( + + )} + + {transactionStatus === "pending" && ( +
+

+ + Awaiting blockchain confirmation +

+

+ Your transaction has been signed. Escrow status will remain unfunded until the Stellar network confirms it. Keep this window open. +

+ {transactionHash && ( +

Hash: {transactionHash}

+ )}
)} - {transactionStatus === 'success' && transactionHash && ( -
-
+ {transactionStatus === "confirmed" && transactionHash && ( +
+

- Transaction Successful -

+ Confirmed on Stellar — escrow is funded +

Hash: - {transactionHash} -
- - - View on Explorer - + {explorerUrl && ( + + + View on Explorer + + )}
)} - {transactionStatus === 'failed' && ( -
-
+ {transactionStatus === "failed" && ( +
+

- Transaction Failed -

- {error && ( -

{error}

- )} -
- - -
+ Funding was not confirmed +

+

{error}

+

+ The escrow remains unfunded. Review the details and try again, or check your wallet for a rejected signature. +

+
+ )} + + {transactionStatus === "cancelled" && ( +
+

Funding cancelled

+

+ No funds were confirmed. You can review the details again before signing. +

)}
- - {transactionStatus === 'pending' ? ( - - ) : transactionStatus === 'success' ? ( - - ) : transactionStatus === 'failed' ? ( - - ) : ( -
- + - + -
+ + )} + {transactionStatus === "confirmed" && ( + + )} + {(transactionStatus === "failed" || transactionStatus === "cancelled") && ( + <> + + + )}
diff --git a/components/dashboard/escrow-status-tracker.tsx b/components/dashboard/escrow-status-tracker.tsx index 1a328a3..99bdaa9 100644 --- a/components/dashboard/escrow-status-tracker.tsx +++ b/components/dashboard/escrow-status-tracker.tsx @@ -3,11 +3,13 @@ import { Check } from "lucide-react"; import { cn } from "@/lib/utils"; const escrowStages = [ + "Unfunded", "Funded", "In Progress", "Submitted", "Approved", "Released", + "Refunded", ] as const; export type EscrowStage = (typeof escrowStages)[number]; diff --git a/lib/escrow/funding.ts b/lib/escrow/funding.ts new file mode 100644 index 0000000..1253582 --- /dev/null +++ b/lib/escrow/funding.ts @@ -0,0 +1,146 @@ +/** + * Escrow funding math, validation and display formatting. + * + * Stellar assets support seven decimal places. All helpers in this module use + * the same precision rules so totals, allocations, fees and remaining balances + * are presented consistently throughout the funding flow. + */ + +export const FUNDING_PRECISION = 7 +export const FUNDING_TOLERANCE = 10 ** -FUNDING_PRECISION +export const DEFAULT_ESTIMATED_FEE_XLM = '0.00001' + +const amountFormatter = new Intl.NumberFormat('en-US', { + minimumFractionDigits: 2, + maximumFractionDigits: FUNDING_PRECISION, +}) + +const percentFormatter = new Intl.NumberFormat('en-US', { + minimumFractionDigits: 1, + maximumFractionDigits: 1, +}) + +export interface FundingMilestone { + id: string + title: string + amount: string +} + +export interface FundingBreakdownInput { + totalValue: string | number + fundedAmount?: string | number + milestones?: FundingMilestone[] + currency: string +} + +export interface FundingBreakdown extends FundingBreakdownInput { + total: number + funded: number + remaining: number + fundedPercent: number + allocationTotal: number + allocationPercent: number + milestoneAllocations: Array +} + +/** Parse a value coming from the API or an input without producing NaN totals. */ +export function toFundingAmount(value: string | number | null | undefined): number { + if (typeof value === 'number') return Number.isFinite(value) && value >= 0 ? value : 0 + if (!value) return 0 + const parsed = Number(value) + return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0 +} + +/** Format any monetary value using the shared Stellar precision rules. */ +export function formatFundingAmount(value: string | number | null | undefined): string { + return amountFormatter.format(toFundingAmount(value)) +} + +/** Format an amount together with its asset code. */ +export function formatAssetAmount( + value: string | number | null | undefined, + currency: string +): string { + return `${formatFundingAmount(value)} ${currency}` +} + +/** Format a percentage of a total, e.g. `25.0%`. */ +export function formatFundingPercent(value: number): string { + return `${percentFormatter.format(Number.isFinite(value) ? value : 0)}%` +} + +/** Check that a string is a non-zero Stellar amount (max seven decimals). */ +export function isValidFundingAmount(value: string): boolean { + return /^\d+(\.\d{1,7})?$/.test(value.trim()) && Number(value) > 0 +} + +export function calculateFundingBreakdown(input: FundingBreakdownInput): FundingBreakdown { + const total = toFundingAmount(input.totalValue) + const funded = Math.min(toFundingAmount(input.fundedAmount), total) + const remaining = Math.max(total - funded, 0) + const milestones = input.milestones ?? [] + const milestoneAllocations = milestones.map((milestone) => { + const amountValue = toFundingAmount(milestone.amount) + return { + ...milestone, + amountValue, + percent: total > 0 ? (amountValue / total) * 100 : 0, + } + }) + const allocationTotal = milestoneAllocations.reduce((sum, milestone) => sum + milestone.amountValue, 0) + + return { + ...input, + total, + funded, + remaining, + fundedPercent: total > 0 ? (funded / total) * 100 : 0, + allocationTotal, + allocationPercent: total > 0 ? (allocationTotal / total) * 100 : 0, + milestoneAllocations, + } +} + +export interface FundingValidationResult { + valid: boolean + errors: string[] +} + +export interface FundingValidationInput extends FundingBreakdownInput { + amount: string +} + +/** + * Validate everything that must be true before a funding transaction may be + * submitted. Milestone totals are only checked when a milestone list was + * supplied, so older contracts without milestones remain fundable. + */ +export function validateFundingSubmission(input: FundingValidationInput): FundingValidationResult { + const errors: string[] = [] + const breakdown = calculateFundingBreakdown(input) + const { total, remaining, allocationTotal } = breakdown + + if (input.milestones) { + if (input.milestones.length === 0) { + errors.push('No milestone allocations found. Add milestones before funding escrow.') + } else if (Math.abs(allocationTotal - total) > FUNDING_TOLERANCE) { + errors.push( + `Milestone allocations total ${formatAssetAmount(allocationTotal, input.currency)} but the contract value is ${formatAssetAmount(total, input.currency)}.` + ) + } + } + + if (!isValidFundingAmount(input.amount)) { + errors.push(`Enter a valid amount with no more than ${FUNDING_PRECISION} decimal places.`) + } else { + const amount = toFundingAmount(input.amount) + if (amount < remaining - FUNDING_TOLERANCE) { + errors.push(`Funding amount must be at least ${formatAssetAmount(remaining, input.currency)}.`) + } + if (amount > remaining + FUNDING_TOLERANCE) { + errors.push(`Funding amount exceeds the remaining ${formatAssetAmount(remaining, input.currency)}.`) + } + } + + return { valid: errors.length === 0, errors } +}