Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions __tests__/escrow-funding-breakdown.test.tsx
Original file line number Diff line number Diff line change
@@ -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(
<EscrowFundingBreakdown
totalValue="1500"
fundedAmount={500}
currency="USDC"
milestones={milestones}
network="TESTNET"
/>
)

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(
<EscrowFundingBreakdown
totalValue="1500"
currency="USDC"
milestones={[]}
network="PUBLIC"
/>
)

expect(screen.getByText(/No milestone allocations available/i)).toBeInTheDocument()
})

it('surfaces validation errors', () => {
render(
<EscrowFundingBreakdown
totalValue="1500"
currency="USDC"
milestones={milestones}
network="TESTNET"
validation={{ valid: false, errors: ['Milestone allocations do not match the contract value.'] }}
/>
)

expect(screen.getByRole('alert')).toHaveTextContent('Milestone allocations do not match')
})

it('shows a loading state', () => {
render(
<EscrowFundingBreakdown
totalValue="1500"
currency="USDC"
network="TESTNET"
isLoading
/>
)

expect(screen.getByRole('status')).toHaveTextContent('Loading funding breakdown')
})
})
171 changes: 171 additions & 0 deletions __tests__/escrow-funding-dialog.test.tsx
Original file line number Diff line number Diff line change
@@ -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<ComponentProps<typeof EscrowFundingDialog>> = {}) {
return render(
<EscrowFundingDialog
open
onOpenChange={() => {}}
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()
})
})
107 changes: 107 additions & 0 deletions __tests__/escrow-funding.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
Loading
Loading