#!/usr/bin/env node // Run with Node.js 24+. --fixture is entirely offline and uses synthetic data. import { readFile } from 'node:fs/promises'; const API_ORIGIN = 'https://api.pareto.credit'; const args = process.argv.slice(2); const fixtureMode = args[0] === '--fixture'; const requestedId = args[0] === '--vault-id' ? args[1] : undefined; if (!((fixtureMode && args.length === 1) || args.length === 0 || (args[0] === '--vault-id' && args.length === 2 && /^[a-f0-9]{24}$/.test(requestedId)))) { console.error('Usage: node vault-read.mjs [--fixture | --vault-id <24-character-vault-id>]'); process.exitCode = 1; } else { try { const fixture = fixtureMode ? JSON.parse(await readFile(new URL('./vault-read.fixture.json', import.meta.url), 'utf8')) : undefined; const key = fixtureMode ? undefined : process.env.PARETO_API_KEY; if (!fixtureMode && !key) throw new Error('Set PARETO_API_KEY to an issued server-side key, or use --fixture.'); async function get(path) { if (fixtureMode) { if (!Object.hasOwn(fixture.responses, path)) throw new Error(`No synthetic fixture for ${path}`); return fixture.responses[path]; } const response = await fetch(new URL(path, API_ORIGIN), { headers: { Authorization: `Bearer ${key}`, Accept: 'application/json' }, redirect: 'error', signal: AbortSignal.timeout(15000), }); if (!response.ok) throw new Error(`API returned HTTP ${response.status} for ${path.split('?')[0]}`); if (!response.headers.get('content-type')?.toLowerCase().includes('application/json')) { throw new Error('Expected an application/json response'); } return response.json(); } function page(value, label) { if (!Array.isArray(value?.data) || !Number.isSafeInteger(value.totalCount) || value.totalCount < 0) { throw new Error(`Invalid ${label} page: expected { data: [], totalCount: nonnegative integer }`); } return value; } function id(value, label) { if (typeof value !== 'string' || !/^[a-f0-9]{24}$/.test(value)) throw new Error(`Missing or invalid ${label}`); return value; } function formatUnits(raw, decimals) { if (typeof raw !== 'string' || !/^\d+$/.test(raw) || !Number.isInteger(decimals) || decimals < 0 || decimals > 255) { throw new Error('Invalid underlying amount or token decimals'); } const amount = BigInt(raw); if (decimals === 0) return amount.toString(); const scale = 10n ** BigInt(decimals); return `${amount / scale}.${(amount % scale).toString().padStart(decimals, '0')}`; } const catalog = requestedId ? undefined : page(await get('/v1/vaults?limit=10&sort=name&order=asc'), 'vault catalog'); const vaultId = requestedId ?? catalog.data.find(item => item.tokenId && item.chainId)?._id; id(vaultId, 'vault ID; choose an accessible vault with tokenId and chainId'); const vault = await get(`/v1/vaults/${vaultId}`); if (vault?._id !== vaultId) throw new Error('Vault detail identity does not match the requested ID'); const tokenId = id(vault.tokenId, 'underlying token ID'); const chainId = id(vault.chainId, 'chain database ID'); const token = await get(`/v1/tokens/${tokenId}`); const chain = await get(`/v1/chains/${chainId}`); if (token?._id !== tokenId || chain?._id !== chainId || token.chainId !== chainId) { throw new Error('Vault, token, and chain metadata do not agree'); } if (!Number.isSafeInteger(chain.chainID) || !Number.isInteger(token.decimals) || token.decimals < 0 || token.decimals > 255) { throw new Error('Missing numeric chainID or valid token decimals'); } const latestPage = page(await get(`/v1/vault-latest-blocks?vaultId=${vaultId}&limit=1`), 'latest snapshot'); const latest = latestPage.data[0]; const history = page(await get(`/v1/vault-blocks?vaultId=${vaultId}&sort=timestamp&order=asc&limit=2&offset=0`), 'history'); for (const snapshot of [...latestPage.data, ...history.data]) { if (snapshot.vaultId !== vaultId || !Number.isSafeInteger(snapshot.block?.number) || !Number.isSafeInteger(snapshot.block?.timestamp)) throw new Error('Invalid snapshot identity or block'); } const nextOffset = history.data.length > 0 && history.data.length < history.totalCount ? history.data.length : null; const output = { mode: fixtureMode ? 'fixture (synthetic, offline)' : 'live API read', vault: { id: vaultId, name: vault.name, address: vault.address }, network: { name: chain.name, chainID: chain.chainID }, asset: { symbol: token.symbol, decimals: token.decimals }, latest: latest ? { block: latest.block.number, timestamp: new Date(latest.block.timestamp * 1000).toISOString(), underlyingTVL: latest.TVL?.token === undefined ? null : formatUnits(latest.TVL.token, token.decimals), } : null, history: { returned: history.data.length, totalCount: history.totalCount, nextOffset }, }; console.log(JSON.stringify(output, null, 2)); } catch (error) { console.error(`Read failed: ${error.message}`); process.exitCode = 1; } }