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
38 changes: 32 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions src/lib/__tests__/batchTransaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,25 @@ describe("BatchTransactionService", () => {
expect(result.error).toBe("Insufficient balance");
});

it("returns the provider message when no revert data is available", async () => {
const { BatchTransactionService } = await import("../batchTransaction");
const executor: BatchPurchaseExecutor = {
execute: jest.fn(async () => {
throw new Error("RPC connection failed");
}),
};

const result = await BatchTransactionService.executeBatchPurchase(
[validItem],
walletAddress,
0.005,
executor,
);

expect(result.success).toBe(false);
expect(result.error).toBe("RPC connection failed");
});

it("returns a user rejection without fabricating a hash", async () => {
const { BatchTransactionService } = await import("../batchTransaction");
const executor: BatchPurchaseExecutor = {
Expand Down
31 changes: 31 additions & 0 deletions src/lib/__tests__/csrf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { readFileSync } from 'fs';
import { join } from 'path';
import { NextResponse } from 'next/server';
import {
getAuthStatePart,
getCsrfSessionId,
generateTokenForSession,
validateCsrf,
withCsrf,
Expand Down Expand Up @@ -84,6 +86,33 @@ const signWithSecret = (secret: string, sessionId: string, authState: string) =>
.update(`${sessionId}:${authState}`)
.digest('hex');

describe('session and authentication binding', () => {
it('returns an existing CSRF session without replacing it', () => {
const request = createRequest({ sessionId: 'existing-session' });

expect(getCsrfSessionId(asNextRequest(request))).toEqual({
sessionId: 'existing-session',
isNew: false,
});
});

it('creates a new session when the CSRF cookie is missing', () => {
const randomUUID = jest.spyOn(crypto, 'randomUUID').mockReturnValue('generated-session');

expect(getCsrfSessionId(asNextRequest(createRequest()))).toEqual({
sessionId: 'generated-session',
isNew: true,
});

randomUUID.mockRestore();
});

it('reads the auth cookie and defaults to an anonymous state', () => {
expect(getAuthStatePart(asNextRequest(createRequest({ authToken: 'auth-1' })))).toBe('auth-1');
expect(getAuthStatePart(asNextRequest(createRequest()))).toBe('');
});
});

describe('generateTokenForSession', () => {
it('fails closed (throws) when CSRF_SECRET is unset', () => {
delete process.env.CSRF_SECRET;
Expand All @@ -108,7 +137,9 @@ describe('generateTokenForSession', () => {
it('produces different tokens for different sessions/auth states', () => {
const tokenA = generateTokenForSession('session-1', 'auth-1');
const tokenB = generateTokenForSession('session-2', 'auth-1');
const tokenC = generateTokenForSession('session-1', 'auth-2');
expect(tokenA).not.toBe(tokenB);
expect(tokenA).not.toBe(tokenC);
});
});

Expand Down
56 changes: 56 additions & 0 deletions src/lib/__tests__/portfolioService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ jest.mock('@/utils/logger', () => ({
},
}));

jest.mock('@/config/chains', () => ({
CHAIN_CONFIG: {
1: { name: 'Ethereum', symbol: 'ETH', color: '#627EEA' },
137: { name: 'Polygon', symbol: 'MATIC', color: '#8247E5' },
56: { name: 'Binance Smart Chain', symbol: 'BNB', color: '#F3BA2F' },
},
}));

import { PortfolioService } from '@/lib/portfolioService';

const ADDRESS = '0xdeadbeef';
Expand Down Expand Up @@ -109,3 +117,51 @@ describe('PortfolioService.fetchPortfolioOverview (#504)', () => {
expect(perfSpy).toHaveBeenCalledWith(ADDRESS, 7);
});
});

describe('PortfolioService.fetchMultiChainPortfolio', () => {
beforeEach(() => {
jest.restoreAllMocks();
});

it('maps holdings and gas balances into per-chain and aggregate totals', async () => {
const portfolio = await PortfolioService.fetchMultiChainPortfolio('0xdeadbeef');

expect(portfolio.error).toBeNull();
expect(portfolio.isLoading).toBe(false);
expect(portfolio.totalValueUSD).toBe(608570);
expect(portfolio.totalValueNative.get(1)).toBeCloseTo(130.65);
expect(portfolio.totalValueNative.get(137)).toBe(106500);
expect(portfolio.totalValueNative.get(56)).toBeCloseTo(138.2);

expect(portfolio.chains).toEqual(expect.arrayContaining([
expect.objectContaining({
chainId: 1,
totalValueUSD: 344000,
totalValueNative: expect.any(Number),
gasBalance: '2.45',
gasBalanceUSD: 6500,
holdings: expect.arrayContaining([
expect.objectContaining({ propertyId: 'prop-1', quantity: 150 }),
expect.objectContaining({ propertyId: 'prop-2', quantity: 75 }),
]),
}),
expect.objectContaining({
chainId: 137,
totalValueUSD: 187650,
totalValueNative: 106500,
gasBalance: '8500',
gasBalanceUSD: 7650,
holdings: [expect.objectContaining({ propertyId: 'prop-3' })],
}),
expect.objectContaining({
chainId: 56,
totalValueUSD: 76920,
totalValueNative: 138.2,
gasBalance: '3.2',
gasBalanceUSD: 1920,
holdings: [expect.objectContaining({ propertyId: 'prop-4' })],
}),
]));
expect(portfolio.chains.find((chain) => chain.chainId === 1)?.totalValueNative).toBeCloseTo(130.65);
});
});
24 changes: 12 additions & 12 deletions src/lib/__tests__/secondaryMarketService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,7 @@ describe('secondaryMarketService', () => {

it('filters by blockchain', async () => {
const ethereumListings = await secondaryMarketService.getListings({ blockchain: 'ethereum' });
for (const listing of ethereumListings) {
expect(listing.blockchain).toBe('ethereum');
}
expect(ethereumListings.map((listing) => listing.id)).toEqual(['sec-1']);
});

it('filters by property name (propertyId)', async () => {
Expand All @@ -74,17 +72,19 @@ describe('secondaryMarketService', () => {
expect(filtered[0].propertyId).toBe('prop-1');
});

it('filters by price range via propertyId and blockchain combined', async () => {
const allListings = await secondaryMarketService.getListings();
const allIds = allListings.map((l) => l.id);
it('applies propertyId and blockchain filters together', async () => {
const filtered = await secondaryMarketService.getListings({
propertyId: 'prop-1',
blockchain: 'ethereum',
});

const ethereumOnly = await secondaryMarketService.getListings({ blockchain: 'ethereum' });
const ethereumIds = ethereumOnly.map((l) => l.id);
expect(filtered.map((listing) => listing.id)).toEqual(['sec-1']);
});

expect(ethereumIds.length).toBeLessThanOrEqual(allIds.length);
for (const id of ethereumIds) {
expect(allIds).toContain(id);
}
it('returns no listings when a filter matches nothing', async () => {
await expect(
secondaryMarketService.getListings({ propertyId: 'missing-property' })
).resolves.toEqual([]);
});
});
});
2 changes: 1 addition & 1 deletion src/lib/portfolioService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export class PortfolioService {
const totalValueNative = new Map<ChainId, number>();

// Fetch data for each supported chain
for (const chainId of Object.keys(CHAIN_CONFIG) as unknown as ChainId[]) {
for (const chainId of Object.keys(CHAIN_CONFIG).map(Number) as ChainId[]) {
const holdings = MOCK_TOKEN_HOLDINGS[chainId] || [];
const gasBalance = MOCK_GAS_BALANCES[chainId] || { balance: '0', balanceUSD: 0 };

Expand Down
Loading