Tax summary: real block timestamps for sale dates (the 2 s estimate drifted weeks), cached

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-04 07:24:17 -05:00
parent eb3cfebf1f
commit 4e35a83fdd
+13 -5
View File
@@ -404,6 +404,10 @@ async function imageCheck(url) {
// the P&L cannot derive it from chain events and has to read it across (Marty, 2026-09-23). Cached
// and fail-soft: the P&L page must never hang or break because the other site is down.
let huntCache = { at: 0, data: null };
// real block timestamps for the tax summary, read once and kept (a block's time never changes)
let blockTimesCache = null;
function blockTimes() { if (!blockTimesCache) { try { blockTimesCache = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'blocktimes.json'), 'utf8')); } catch (e) { blockTimesCache = {}; } } return blockTimesCache; }
function saveBlockTimes(bt) { try { const f = path.join(DATA_DIR, 'blocktimes.json'); fs.writeFileSync(f + '.tmp', JSON.stringify(bt)); fs.renameSync(f + '.tmp', f); } catch (e) {} }
async function huntLedger() {
if (Date.now() - huntCache.at < 120000) return huntCache.data;
const base = String(process.env.HUNT_URL || 'https://polhunter.com').replace(/\/+$/, '');
@@ -4131,15 +4135,19 @@ const server = http.createServer(async (req, res) => {
// of every package sale (AdminPaid), valued in dollars at that sale's own price (Purchase.priceCents / paidWei in the same
// transaction), minus sales to Marty's own positions (site config ownMemberIds, default "1": his own money moving around is
// not income), plus outside revenue lines. Costs = ledger 'cost' lines by category. Draws and transfers are listed apart:
// they are owner money, not expenses. Dates come from block numbers (Polygon ~2 s blocks), so a sale within a few hours
// of New Year can land in the neighbouring year; the CSV says so.
// they are owner money, not expenses. Dates are the blocks' REAL timestamps (2026-10-04: a 2-second-per-block
// estimate drifted weeks and put September sales in August), read once from the chain and kept in DATA_DIR/blocktimes.json.
if (p === '/api/admin/tax' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const year = String(Number(u.searchParams.get('year')) || new Date().getFullYear());
const own = new Set(String(siteConfig().ownMemberIds || '1').split(',').map(x => Number(x.trim())).filter(Boolean));
let latest = 0, latestTs = Date.now(); try { const b = await chain.rpc('eth_getBlockByNumber', ['latest', false]); latest = parseInt(b.number, 16); latestTs = parseInt(b.timestamp, 16) * 1000; } catch (e) {}
const dayOf = blk => new Date(latestTs - (latest - blk) * 2000).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const evs = chain.recentEvents(1e9);
const bt = blockTimes(); const need = Array.from(new Set(evs.filter(e => e.type === 'AdminPaid' && !bt[e.block]).map(e => e.block)));
for (let i = 0; i < need.length; i += 8) await Promise.all(need.slice(i, i + 8).map(async blk => { try { const b = await chain.rpc('eth_getBlockByNumber', ['0x' + blk.toString(16), false]); if (b && b.timestamp) bt[blk] = parseInt(b.timestamp, 16) * 1000; } catch (e) {} }));
if (need.length) saveBlockTimes(bt);
const missing = evs.filter(e => e.type === 'AdminPaid' && !bt[e.block]).length;
if (missing) return json(res, 503, { error: missing + ' sale dates could not be read from the chain right now. Try again in a minute.' });
const dayOf = blk => new Date(bt[blk]).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const buys = new Map(); for (const e of evs) if (e.type === 'Purchase') buys.set(e.tx, e);
const months = {}; let incomeUsd = 0, incomePol = 0, ownUsd = 0, sales = 0;
for (const e of evs) {
@@ -4164,7 +4172,7 @@ const server = http.createServer(async (req, res) => {
csv.push(['Income', day, 'Platform share of package sale', 'Member #' + e.buyerId + (b ? ' bought the $' + Math.round(b.priceCents / 100) + ' package' : ''), (Number(BigInt(e.amountWei) / 10n ** 12n) / 1e6).toFixed(6), usd.toFixed(2), e.tx].map(q).join(',')); }
for (const l of lines) { const sec = l.kind === 'revenue' ? 'Income' : l.kind === 'cost' ? 'Expense' : l.kind === 'draw' ? 'Owner draw (not an expense)' : 'Transfer (not income or expense)';
csv.push([sec, l.date, l.kind === 'cost' ? (ledger.CATS[l.category] || l.category) : l.kind, l.note, (l.dir === 'out' ? -1 : 1) * l.amount, (l.kind === 'cost' && l.dir === 'out' ? -1 : 1) * l.usd, l.tx].map(q).join(',')); }
csv.push(''); csv.push(q('Dates for on-chain sales come from block numbers; check any sale within a few hours of January 1. Sales to your own positions (' + Array.from(own).join(', ') + ') are left out.'));
csv.push(''); csv.push(q('Sale dates are the Polygon block timestamps, in US Central time. Sales to your own positions (' + Array.from(own).join(', ') + ') are left out. USD values are each sale\'s own package price.'));
return json(res, 200, { year, ownMemberIds: Array.from(own),
income: { platformUsd: r2(incomeUsd), platformPol: Math.round(incomePol * 1e4) / 1e4, sales, outsideUsd: r2(outsideUsd), totalUsd: r2(incomeUsd + outsideUsd), ownSalesExcludedUsd: r2(ownUsd) },
expenses: { byCategory: Object.fromEntries(Object.entries(costs).map(([k, v]) => [k, r2(v)])), labels: ledger.CATS, advertisingAndPromotionUsd: r2(adPromo), totalUsd: r2(allCosts) },