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
31 changes: 31 additions & 0 deletions __tests__/alerts/alertEngine.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { AlertEngine } from '@/lib/alerts/alertEngine';

describe('AlertEngine (#6)', () => {
it('evaluates thresholds, enforces cooldowns, and logs alert history', async () => {
const engine = new AlertEngine();
await engine.addAlert({
id: 'alert-1',
name: 'XLM Above $0.15',
type: 'price',
target: 'XLM/USDC',
comparison: 'above',
threshold: 0.15,
cooldownMs: 60_000,
enabled: true,
recurring: true,
});

const t0 = 1_700_000_000_000;
expect(engine.evaluate('XLM/USDC', 'price', 0.14, t0)).toHaveLength(0);

const fired1 = engine.evaluate('XLM/USDC', 'price', 0.16, t0);
expect(fired1).toHaveLength(1);

// Cooldown active 10s later -> does not re-fire
expect(engine.evaluate('XLM/USDC', 'price', 0.18, t0 + 10_000)).toHaveLength(0);

// After 61s cooldown -> fires again
expect(engine.evaluate('XLM/USDC', 'price', 0.18, t0 + 61_000)).toHaveLength(1);
expect(engine.getHistory()).toHaveLength(2);
});
});
30 changes: 30 additions & 0 deletions __tests__/analytics/pools.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import {
calculateCompoundedApy,
calculateImpermanentLoss,
calculatePoolAnalytics,
calculatePriceImpact,
} from '@/lib/analytics/pools';

describe('Pool Analytics (#1)', () => {
it('calculates impermanent loss accurately for 2x price change (~ -5.719%)', () => {
expect(calculateImpermanentLoss(1)).toBeCloseTo(0, 4);
expect(calculateImpermanentLoss(2)).toBeCloseTo(-5.7191, 3);
});

it('calculates compounded APY and price impact', () => {
const apy = calculateCompoundedApy(500, 500_000);
expect(apy).toBeGreaterThan(36.5);
expect(calculatePriceImpact(5_000, 500_000)).toBeCloseTo(1.9608, 3);
});

it('returns complete PoolAnalytics structure in < 200ms', async () => {
const start = Date.now();
const res = await calculatePoolAnalytics('XLM-USDC-001', '7d');
const elapsed = Date.now() - start;

expect(elapsed).toBeLessThan(200);
expect(res.apy.current).toBeGreaterThan(0);
expect(res.impermanentLoss.historical).toHaveLength(7);
expect(res.fees.breakdown).toHaveLength(3);
});
});
30 changes: 30 additions & 0 deletions __tests__/analytics/portfolio.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import {
calculatePortfolioPerformance,
calculateTimeWeightedReturn,
computePortfolioFromTrades,
} from '@/lib/analytics/portfolio';

describe('Portfolio Performance & Historical P&L (#3)', () => {
it('computes realized/unrealized P&L, ROI, and HODL benchmark outperformance', () => {
const perf = computePortfolioFromTrades(
[
{ asset: 'XLM', side: 'buy', quantity: 1000, price: 0.1, feeUSD: 0, timestamp: 1000 },
{ asset: 'XLM', side: 'sell', quantity: 500, price: 0.15, feeUSD: 0, timestamp: 2000 },
],
{ XLM: 0.2 },
0.1,
0.12,
);

expect(perf.realizedPnL).toBe(25);
expect(perf.unrealizedPnL).toBe(50);
expect(perf.totalPnL).toBe(75);
expect(perf.benchmark.hodlRoi).toBe(20);
});

it('calculates Time-Weighted Return and async wallet summary', async () => {
expect(calculateTimeWeightedReturn([0.1, 0.1])).toBe(21);
const res = await calculatePortfolioPerformance('GABC123', new Date('2026-01-01T00:00:00Z'));
expect(res.positions.length).toBeGreaterThanOrEqual(2);
});
});
38 changes: 38 additions & 0 deletions __tests__/export/dataExporter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { DataExporter } from '@/lib/export/dataExporter';

describe('DataExporter (#7)', () => {
const exporter = new DataExporter();
const baseRange = {
start: new Date('2026-11-01T00:00:00Z'),
end: new Date('2026-11-10T00:00:00Z'),
};

it('exports CSV, CoinTracker tax CSV, JSON, and PDF formats', async () => {
const data = await exporter.fetchData({
format: 'tax',
dataType: 'transactions',
dateRange: baseRange,
});
expect(data).toHaveLength(2);

const taxCsv = exporter.formatData(data, 'tax');
expect(taxCsv).toContain(
'Date,Received Quantity,Received Currency,Sent Quantity,Sent Currency,Fee Amount,Fee Currency,Tag',
);
expect(taxCsv).toContain('2026-11-03T12:00:00Z,1000,XLM,120,USDC,0.01,XLM,Trade');

const jsonStr = exporter.formatData(data, 'json');
expect(JSON.parse(jsonStr)).toHaveLength(2);

const pdfStr = exporter.formatData(data, 'pdf', 'tax');
expect(pdfStr).toContain('%PDF-1.4');

const blob = await exporter.export({
format: 'csv',
dataType: 'transactions',
dateRange: baseRange,
filters: { assets: ['XLM'] },
});
expect(blob.size).toBeGreaterThan(20);
});
});
33 changes: 33 additions & 0 deletions __tests__/indicators/technical.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import {
calculateBollingerBands,
calculateEMA,
calculateMACD,
calculateRSI,
calculateSMA,
} from '@/lib/indicators/technical';

describe('Technical Indicators (#5)', () => {
const samplePrices = Array.from({ length: 35 }, (_, i) => 10 + Math.sin(i / 2) * 2 + i * 0.2);

it('calculates SMA and EMA accurately', () => {
expect(calculateSMA([1, 2, 3, 4, 5], 3)).toEqual([2, 3, 4]);
const ema = calculateEMA([10, 11, 12, 13, 14], 3);
expect(ema).toHaveLength(3);
expect(ema[0]).toBe(11);
});

it('calculates RSI, MACD, and Bollinger Bands', () => {
const rsi = calculateRSI(samplePrices, 14);
expect(rsi.length).toBeGreaterThan(10);
expect(rsi.every((v) => v >= 0 && v <= 100)).toBe(true);

const macd = calculateMACD(samplePrices, 12, 26, 9);
expect(macd.macd.length).toBeGreaterThan(0);
expect(macd.signal.length).toBeGreaterThan(0);

const bb = calculateBollingerBands(samplePrices, 20, 2);
expect(bb.length).toBeGreaterThan(10);
expect(bb[0].upper).toBeGreaterThan(bb[0].middle);
expect(bb[0].middle).toBeGreaterThan(bb[0].lower);
});
});
17 changes: 17 additions & 0 deletions __tests__/protocols/aggregator.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import {
calculateRiskAdjustedScore,
YieldAggregator,
} from '@/services/protocols/aggregator';

describe('YieldAggregator (#4)', () => {
it('fetches opportunities across protocols and filters/sorts by risk-adjusted return', async () => {
const agg = new YieldAggregator();
const all = await agg.fetchAllOpportunities();
expect(all.length).toBeGreaterThanOrEqual(3);
expect(all[0].apy).toBeGreaterThanOrEqual(all[1].apy);

const lowIl = await agg.getTopOpportunities({ maxIlRisk: 'low', sortBy: 'riskAdjusted' });
expect(lowIl.every((o) => o.risk.impermanentLoss === 'low')).toBe(true);
expect(calculateRiskAdjustedScore(lowIl[0])).toBeGreaterThan(0);
});
});
28 changes: 28 additions & 0 deletions __tests__/realtime/priceStream.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { PriceStreamManager } from '@/lib/realtime/priceStream';

describe('PriceStreamManager (#2)', () => {
it('connects, multiplexes subscriptions, and cleans up on unsubscribe', async () => {
const mgr = new PriceStreamManager();
await mgr.connect('wss://horizon.stellar.org');
expect(mgr.isConnected()).toBe(true);

const received: number[] = [];
const unsub = mgr.subscribe('xlm/usdc', (u) => received.push(u.price));
expect(mgr.getActiveStreamCount()).toBe(1);

mgr.handleMessage({ pair: 'XLM/USDC', price: 0.125, change24h: 4.2, volume24h: 120000 });
expect(received).toEqual([0.125]);

unsub();
expect(mgr.getActiveStreamCount()).toBe(0);
mgr.disconnect();
expect(mgr.isConnected()).toBe(false);
});

it('computes exponential reconnect backoff', () => {
const mgr = new PriceStreamManager();
expect(mgr.getReconnectBackoffMs(1000)).toBe(1000);
expect(mgr.getReconnectBackoffMs(1000)).toBe(2000);
expect(mgr.getReconnectBackoffMs(1000)).toBe(4000);
});
});
39 changes: 39 additions & 0 deletions components/PoolAnalytics.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use client';

import React from 'react';
import { usePoolAnalytics } from '@/hooks/usePoolAnalytics';

export function PoolAnalytics({ poolId = 'XLM-USDC-POOL' }: { poolId?: string }) {
const { analytics, isLoading, error } = usePoolAnalytics(poolId, '30d');

if (error) {
return <div className="p-4 text-red-600">Failed to load pool analytics: {error.message}</div>;
}
if (isLoading || !analytics) {
return <div className="p-4 text-gray-500">Loading pool analytics...</div>;
}

return (
<div className="p-6 border border-gray-200 rounded-lg bg-white shadow space-y-4">
<h3 className="text-xl font-bold text-gray-800">Pool Analytics ({poolId})</h3>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="p-3 bg-blue-50 rounded">
<div className="text-xs text-gray-500">Current APY</div>
<div className="text-lg font-bold text-blue-700">{analytics.apy.current}%</div>
</div>
<div className="p-3 bg-amber-50 rounded">
<div className="text-xs text-gray-500">Impermanent Loss</div>
<div className="text-lg font-bold text-amber-700">{analytics.impermanentLoss.current}%</div>
</div>
<div className="p-3 bg-green-50 rounded">
<div className="text-xs text-gray-500">30d Fees Earned</div>
<div className="text-lg font-bold text-green-700">${analytics.fees.total.toLocaleString()}</div>
</div>
<div className="p-3 bg-purple-50 rounded">
<div className="text-xs text-gray-500">Avg Price Impact ($5k)</div>
<div className="text-lg font-bold text-purple-700">{analytics.health.averagePriceImpact}%</div>
</div>
</div>
</div>
);
}
33 changes: 33 additions & 0 deletions hooks/usePoolAnalytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { useState, useEffect } from 'react';
import { PoolAnalytics } from '@/types/pool';
import { calculatePoolAnalytics } from '@/lib/analytics/pools';

export function usePoolAnalytics(poolId: string, timeframe = '30d') {
const [analytics, setAnalytics] = useState<PoolAnalytics | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [error, setError] = useState<Error | null>(null);

useEffect(() => {
let active = true;
setIsLoading(true);
calculatePoolAnalytics(poolId, timeframe)
.then((res) => {
if (active) {
setAnalytics(res);
setError(null);
}
})
.catch((err) => {
if (active) setError(err as Error);
})
.finally(() => {
if (active) setIsLoading(false);
});

return () => {
active = false;
};
}, [poolId, timeframe]);

return { analytics, isLoading, error };
}
40 changes: 40 additions & 0 deletions hooks/useRealtimePrice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useState, useEffect } from 'react';
import { PriceStreamManager, PriceUpdate } from '@/lib/realtime/priceStream';

const defaultManager = new PriceStreamManager();

export function useRealtimePrice(baseAsset: string, counterAsset: string) {
const pair = `${baseAsset}/${counterAsset}`.toUpperCase();
const [price, setPrice] = useState<number | null>(null);
const [change24h, setChange24h] = useState<number>(0);
const [volume24h, setVolume24h] = useState<number>(0);
const [isConnected, setIsConnected] = useState<boolean>(false);
const [error, setError] = useState<Error | null>(null);

useEffect(() => {
let mounted = true;
defaultManager
.connect()
.then(() => {
if (mounted) setIsConnected(true);
})
.catch((err) => {
if (mounted) setError(err as Error);
});

const unsubscribe = defaultManager.subscribe(pair, (update: PriceUpdate) => {
if (mounted) {
setPrice(update.price);
setChange24h(update.change24h);
setVolume24h(update.volume24h);
}
});

return () => {
mounted = false;
unsubscribe();
};
}, [pair]);

return { price, change24h, volume24h, isConnected, error };
}
14 changes: 14 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const nextJest = require('next/jest');

const createJestConfig = nextJest({
dir: './',
});

const customJestConfig = {
testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1',
},
};

module.exports = createJestConfig(customJestConfig);
Loading
Loading