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
113 changes: 113 additions & 0 deletions indexer/src/__tests__/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import request from 'supertest';
const mockPrisma = vi.hoisted(() => ({
listing: {
findMany: vi.fn(),
findFirst: vi.fn(),
count: vi.fn(),
aggregate: vi.fn(),
},
Expand All @@ -15,6 +16,9 @@ const mockPrisma = vi.hoisted(() => ({
findFirst: vi.fn(),
count: vi.fn(),
},
stakedNFT: {
findMany: vi.fn(),
},
collection: {
findMany: vi.fn(),
},
Expand Down Expand Up @@ -551,6 +555,115 @@ describe('GET /wallets/:address/royalty-stats — extended', () => {
});
});

// ── GET /wallets/:address/portfolio ──────────────────────────────────────────

describe('GET /wallets/:address/portfolio', () => {
beforeEach(() => vi.clearAllMocks());

it('returns total portfolio value based on collection floor prices', async () => {
// Wallet owns NFTs in two collections
mockPrisma.listing.findMany.mockResolvedValue([
{ collection: 'COLLECTION_A' },
{ collection: 'COLLECTION_A' },
{ collection: 'COLLECTION_B' },
]);
mockPrisma.stakedNFT.findMany.mockResolvedValue([
{ collection: 'COLLECTION_B' },
]);

// Floor prices: A=100, B=50 (lowest Active listing in each collection)
mockPrisma.listing.findFirst
.mockResolvedValueOnce({ price: '100.0000000' }) // COLLECTION_A floor
.mockResolvedValueOnce({ price: '50.0000000' }); // COLLECTION_B floor

const res = await request(app).get('/wallets/GWALLET/portfolio');

expect(res.status).toBe(200);
expect(res.body.totalValue).toBe('150.0000000');
expect(res.body.collectionFloorPrices).toEqual({
COLLECTION_A: '100.0000000',
COLLECTION_B: '50.0000000',
});
expect(res.body.ownedCount).toBe(4); // 3 listings + 1 staked
});

it('returns zero when wallet owns no NFTs', async () => {
mockPrisma.listing.findMany.mockResolvedValue([]);
mockPrisma.stakedNFT.findMany.mockResolvedValue([]);

const res = await request(app).get('/wallets/GEMPTY/portfolio');

expect(res.status).toBe(200);
expect(res.body.totalValue).toBe('0.0000000');
expect(res.body.collectionFloorPrices).toEqual({});
expect(res.body.ownedCount).toBe(0);
});

it('excludes collections with no active floor price', async () => {
mockPrisma.listing.findMany.mockResolvedValue([
{ collection: 'COLLECTION_X' },
]);
mockPrisma.stakedNFT.findMany.mockResolvedValue([]);

// No Active listing exists for this collection
mockPrisma.listing.findFirst.mockResolvedValue(null);

const res = await request(app).get('/wallets/GWALLET/portfolio');

expect(res.status).toBe(200);
expect(res.body.totalValue).toBe('0.0000000');
expect(res.body.collectionFloorPrices).toEqual({});
});

it('returns 500 when Prisma throws', async () => {
mockPrisma.listing.findMany.mockRejectedValue(new Error('DB down'));

const res = await request(app).get('/wallets/GWALLET/portfolio');
expect(res.status).toBe(500);
expect(res.body.error).toBeDefined();
});

it('sums floor prices from multiple collections correctly', async () => {
// 3 collections: floor prices 10, 200, 3000
mockPrisma.listing.findMany.mockResolvedValue([
{ collection: 'C1' },
{ collection: 'C2' },
{ collection: 'C3' },
]);
mockPrisma.stakedNFT.findMany.mockResolvedValue([]);

mockPrisma.listing.findFirst
.mockResolvedValueOnce({ price: '10.0000000' })
.mockResolvedValueOnce({ price: '200.0000000' })
.mockResolvedValueOnce({ price: '3000.0000000' });

const res = await request(app).get('/wallets/GWALLET/portfolio');

expect(res.status).toBe(200);
expect(res.body.totalValue).toBe('3210.0000000');
expect(res.body.ownedCount).toBe(3);
});

it('deduplicates collections when wallet has both owned and staked NFTs in same collection', async () => {
mockPrisma.listing.findMany.mockResolvedValue([
{ collection: 'COLLECTION_C' },
]);
mockPrisma.stakedNFT.findMany.mockResolvedValue([
{ collection: 'COLLECTION_C' },
]);

mockPrisma.listing.findFirst.mockResolvedValue({ price: '75.5000000' });

const res = await request(app).get('/wallets/GWALLET/portfolio');

expect(res.status).toBe(200);
// Floor price counted only once despite two entries in same collection
expect(res.body.totalValue).toBe('75.5000000');
expect(res.body.ownedCount).toBe(2);
expect(mockPrisma.listing.findFirst).toHaveBeenCalledTimes(1);
});
});

// ── PUT /wallets/:address/preferences (POST /settings) ───────────────────────

describe('PUT /wallets/:address/preferences', () => {
Expand Down
55 changes: 55 additions & 0 deletions indexer/src/api/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,61 @@ router.get('/wallets/:address/tokens', async (req: Request, res: Response) => {
}
});

// GET /wallets/:address/portfolio — total portfolio value based on floor prices
router.get('/wallets/:address/portfolio', strictRateLimiter, async (req: Request, res: Response) => {
const { address } = req.params;
try {
// Owned NFTs from marketplace listings
const ownedListings = await prisma.listing.findMany({
where: { owner: address as string },
select: { collection: true },
});

// Active staked NFTs
const stakedNFTs = await prisma.stakedNFT.findMany({
where: { owner: address as string, status: 'Active' },
select: { collection: true },
});

// Unique collections across both owned and staked
const collectionSet = new Set<string>();
ownedListings.forEach(l => collectionSet.add(l.collection));
stakedNFTs.forEach(s => collectionSet.add(s.collection));

let totalValue = 0;
const collectionFloorPrices: Record<string, string> = {};

// Query floor prices for all unique collections in parallel
const collections = [...collectionSet];
const floorResults = await Promise.all(
collections.map(collection =>
prisma.listing.findFirst({
where: { collection, status: 'Active' },
orderBy: { price: 'asc' },
select: { price: true },
})
)
);

for (const [i, floorListing] of floorResults.entries()) {
if (floorListing) {
const fp = Number(floorListing.price);
collectionFloorPrices[collections[i]] = fp.toFixed(7);
totalValue += fp;
}
}

res.json({
totalValue: totalValue.toFixed(7),
collectionFloorPrices,
ownedCount: ownedListings.length + stakedNFTs.length,
});
} catch (err) {
console.error('Error details:', err);
res.status(500).json({ error: 'Failed to fetch portfolio' });
}
});

// GET /wallets/:address/preferences — user settings
router.get('/wallets/:address/preferences', async (req: Request, res: Response) => {
const address = req.params.address as string;
Expand Down
Loading
Loading