P&L: Game marketing category for game wallet top-ups (old top-ups moved once from Player rewards); counted in Advertising and promotion

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-05 08:22:06 -05:00
parent 18813a4127
commit 503a252fc8
4 changed files with 129 additions and 124 deletions
+124 -119
View File
@@ -1,119 +1,124 @@
// Money moving in and out of the receiver wallets, which the chain index cannot tell us about
// (Marty, 2026-09-23). The P&L derives revenue from AdminPaid events and holdings from
// eth_getBalance, so two real things were invisible:
//
// OUT a draw. Marty funded RM Circle #139's Culmen->Apex upgrade from Receiver A. That is a
// legitimate use of house profit, but nothing recorded it, so "earned" and "on hand" drift
// apart for ever. ("Why would I ever keep a receiver wallet that I never take anything out
// of? That's stupid, so I need to be able to account for it.")
// IN outside income paid into the same wallet, e.g. a ClickBaitPays withdrawal. Real profit,
// but it is not an AdminPaid event, so the revenue lines never see it.
//
// Both are hand-entered because only Marty knows what a transfer was for. Storage:
// DATA_DIR/ledger.json { entries: [{id, date, dir, asset, amount, usd, wallet, note, tx, ts}] }
const fs = require('fs');
const path = require('path');
let FILE = null;
const DIRS = ['in', 'out'];
// 'outside': a wallet that is not one of ours above, e.g. Marty funding a game wallet from his own Tangem
const WALLETS = ['feeA', 'feeB', 'engine', 'hunt', 'outside'];
// assets we can actually value; anything else is recorded but valued only by the usd field
const ASSETS = ['POL', 'USDC', 'USDT', 'DAI', 'other'];
// WHY a kind and not just a direction (Marty, 2026-09-23): three different things move through
// Receiver A and only one of them is profit.
// revenue outside income earned by the business, e.g. a ClickBaitPays withdrawal in POL.
// Counts toward profit AND toward the balance.
// draw house profit spent on something, e.g. funding RM Circle #139's upgrade. Leaves the
// wallet, but it is not a cost of running InstantAdPay.
// transfer Marty's own capital moved in or out for safekeeping, e.g. consolidating balances
// from other owned positions into the Tangem receiver. Touches the balance ONLY and
// must never show up as revenue, or the P&L reports his savings as earnings.
// cost a real cost of running the network (2026-10-04, Marty: top up game wallets as needed and record each top-up so
// the P&L balances; "show what I spent in advertising versus income" at tax time). Every cost has a category.
const KINDS = ['revenue', 'draw', 'transfer', 'cost'];
// tax-friendly cost categories: advertising + rewards are both "advertising and promotion" on the tax summary
const CATS = { advertising: 'Advertising (paid traffic, ad networks)', rewards: 'Player rewards (game and earning-site payouts)', software: 'Software and hosting', other: 'Other costs' };
function init(opts) { FILE = path.join(opts.dataDir, 'ledger.json'); }
function load() { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { return { entries: [] }; } }
function save(d) {
const tmp = FILE + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(d, null, 1));
fs.renameSync(tmp, FILE); // never leave a half-written ledger behind
}
const newId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
const num = v => { const n = Number(v); return Number.isFinite(n) && n >= 0 ? Math.round(n * 1e6) / 1e6 : 0; };
function entries() {
return load().entries.slice().sort((a, b) =>
(b.date || '').localeCompare(a.date || '') || (b.ts || 0) - (a.ts || 0));
}
function put(input) {
const d = load();
const dir = DIRS.includes(input.dir) ? input.dir : null;
if (!dir) return { error: 'Say whether the money came in or went out.' };
const amount = num(input.amount);
const usd = num(input.usd);
if (!amount && !usd) return { error: 'Give an amount, in POL or in dollars.' };
const note = String(input.note || '').trim().slice(0, 200);
if (!note) return { error: 'Say what this was for. An unexplained line is the thing we are fixing.' };
const date = /^\d{4}-\d{2}-\d{2}$/.test(String(input.date || '')) ? input.date
: new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); // Central, like every other day key here
const e = {
id: input.id && d.entries.find(x => x.id === input.id) ? input.id : newId(),
date, dir, amount, usd, note,
asset: ASSETS.includes(input.asset) ? input.asset : 'POL',
kind: KINDS.includes(input.kind) ? input.kind : (dir === 'in' ? 'revenue' : 'draw'),
wallet: WALLETS.includes(input.wallet) ? input.wallet : 'feeA',
tx: /^0x[0-9a-fA-F]{64}$/.test(String(input.tx || '')) ? String(input.tx).toLowerCase() : '',
ts: Date.now(),
};
if (e.kind === 'cost') e.category = CATS[input.category] ? input.category : 'other';
if (e.tx && d.entries.some(x => x.tx === e.tx && x.id !== e.id)) return { error: 'That transaction is already recorded.', duplicate: true };
const i = d.entries.findIndex(x => x.id === e.id);
if (i >= 0) d.entries[i] = e; else d.entries.push(e);
save(d);
return { ok: true, entry: e };
}
function remove(id) {
const d = load();
const i = d.entries.findIndex(x => x.id === id);
if (i < 0) return { error: 'No such entry.' };
const [gone] = d.entries.splice(i, 1);
save(d);
return { ok: true, entry: gone };
}
// Totals per wallet, split by direction. POL is summed separately from dollar-denominated assets
// because only POL can be reconciled against an on-chain balance.
function totals(wallet) {
const rows = load().entries.filter(e => !wallet || e.wallet === wallet);
const t = { inPol: 0, outPol: 0, inUsd: 0, outUsd: 0, count: rows.length,
// revenue and draws are the P&L numbers; transfers move the balance and nothing else
revenuePol: 0, revenueUsd: 0, drawPol: 0, drawUsd: 0, transferPol: 0, costPol: 0, costUsd: 0 };
for (const e of rows) {
const pol = e.asset === 'POL' ? e.amount : 0;
if (e.dir === 'in') { t.inPol += pol; t.inUsd += e.usd; } else { t.outPol += pol; t.outUsd += e.usd; }
if (e.kind === 'revenue') { t.revenuePol += pol; t.revenueUsd += e.usd; }
else if (e.kind === 'draw') { t.drawPol += pol; t.drawUsd += e.usd; }
else if (e.kind === 'cost') { t.costPol += (e.dir === 'out' ? pol : -pol); t.costUsd += (e.dir === 'out' ? e.usd : -e.usd); }
else t.transferPol += (e.dir === 'in' ? pol : -pol);
}
for (const k of Object.keys(t)) if (k !== 'count') t[k] = Math.round(t[k] * 1e6) / 1e6;
return t;
}
// earned (AdminPaid) + POL in - POL out = what should be sitting there. Any drift is a transfer
// nobody has written down yet, and naming the number is the whole point of this file.
function reconcile(earnedPol, actualPol, wallet) {
const t = totals(wallet || 'feeA');
const expected = Math.round((Number(earnedPol || 0) + t.inPol - t.outPol) * 1e6) / 1e6;
const actual = Math.round(Number(actualPol || 0) * 1e6) / 1e6;
return { earnedPol: Number(earnedPol || 0), expected, actual,
drift: Math.round((actual - expected) * 1e6) / 1e6, totals: t };
}
module.exports = { init, entries, put, remove, totals, reconcile, DIRS, ASSETS, KINDS, WALLETS, CATS, entriesFor: year => load().entries.filter(e => String(e.date || '').startsWith(String(year))) };
// Money moving in and out of the receiver wallets, which the chain index cannot tell us about
// (Marty, 2026-09-23). The P&L derives revenue from AdminPaid events and holdings from
// eth_getBalance, so two real things were invisible:
//
// OUT a draw. Marty funded RM Circle #139's Culmen->Apex upgrade from Receiver A. That is a
// legitimate use of house profit, but nothing recorded it, so "earned" and "on hand" drift
// apart for ever. ("Why would I ever keep a receiver wallet that I never take anything out
// of? That's stupid, so I need to be able to account for it.")
// IN outside income paid into the same wallet, e.g. a ClickBaitPays withdrawal. Real profit,
// but it is not an AdminPaid event, so the revenue lines never see it.
//
// Both are hand-entered because only Marty knows what a transfer was for. Storage:
// DATA_DIR/ledger.json { entries: [{id, date, dir, asset, amount, usd, wallet, note, tx, ts}] }
const fs = require('fs');
const path = require('path');
let FILE = null;
const DIRS = ['in', 'out'];
// 'outside': a wallet that is not one of ours above, e.g. Marty funding a game wallet from his own Tangem
const WALLETS = ['feeA', 'feeB', 'engine', 'hunt', 'outside'];
// assets we can actually value; anything else is recorded but valued only by the usd field
const ASSETS = ['POL', 'USDC', 'USDT', 'DAI', 'other'];
// WHY a kind and not just a direction (Marty, 2026-09-23): three different things move through
// Receiver A and only one of them is profit.
// revenue outside income earned by the business, e.g. a ClickBaitPays withdrawal in POL.
// Counts toward profit AND toward the balance.
// draw house profit spent on something, e.g. funding RM Circle #139's upgrade. Leaves the
// wallet, but it is not a cost of running InstantAdPay.
// transfer Marty's own capital moved in or out for safekeeping, e.g. consolidating balances
// from other owned positions into the Tangem receiver. Touches the balance ONLY and
// must never show up as revenue, or the P&L reports his savings as earnings.
// cost a real cost of running the network (2026-10-04, Marty: top up game wallets as needed and record each top-up so
// the P&L balances; "show what I spent in advertising versus income" at tax time). Every cost has a category.
const KINDS = ['revenue', 'draw', 'transfer', 'cost'];
// tax-friendly cost categories: advertising + rewards are both "advertising and promotion" on the tax summary
// games (2026-10-05, Marty): game wallet top-ups are a marketing cost for InstantAdPay, booked apart from paid traffic
const CATS = { advertising: 'Advertising (paid traffic, ad networks)', games: 'Game marketing (game wallet top-ups)', rewards: 'Player rewards (game and earning-site payouts)', software: 'Software and hosting', other: 'Other costs' };
function init(opts) {
FILE = path.join(opts.dataDir, 'ledger.json');
// one-time move (2026-10-05): earlier game wallet top-ups, booked by the wallet watcher as Player rewards, become Game marketing
try { const d = load(); let n = 0; for (const e of d.entries) if (e.kind === 'cost' && e.category === 'rewards' && /^Player rewards funding: /.test(e.note || '')) { e.category = 'games'; e.note = e.note.replace(/^Player rewards funding: /, 'Game marketing: '); n++; } if (n) { save(d); console.log('ledger: moved', n, 'game wallet top-ups to Game marketing'); } } catch (e) { console.error('ledger migrate', e.message); }
}
function load() { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { return { entries: [] }; } }
function save(d) {
const tmp = FILE + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(d, null, 1));
fs.renameSync(tmp, FILE); // never leave a half-written ledger behind
}
const newId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
const num = v => { const n = Number(v); return Number.isFinite(n) && n >= 0 ? Math.round(n * 1e6) / 1e6 : 0; };
function entries() {
return load().entries.slice().sort((a, b) =>
(b.date || '').localeCompare(a.date || '') || (b.ts || 0) - (a.ts || 0));
}
function put(input) {
const d = load();
const dir = DIRS.includes(input.dir) ? input.dir : null;
if (!dir) return { error: 'Say whether the money came in or went out.' };
const amount = num(input.amount);
const usd = num(input.usd);
if (!amount && !usd) return { error: 'Give an amount, in POL or in dollars.' };
const note = String(input.note || '').trim().slice(0, 200);
if (!note) return { error: 'Say what this was for. An unexplained line is the thing we are fixing.' };
const date = /^\d{4}-\d{2}-\d{2}$/.test(String(input.date || '')) ? input.date
: new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); // Central, like every other day key here
const e = {
id: input.id && d.entries.find(x => x.id === input.id) ? input.id : newId(),
date, dir, amount, usd, note,
asset: ASSETS.includes(input.asset) ? input.asset : 'POL',
kind: KINDS.includes(input.kind) ? input.kind : (dir === 'in' ? 'revenue' : 'draw'),
wallet: WALLETS.includes(input.wallet) ? input.wallet : 'feeA',
tx: /^0x[0-9a-fA-F]{64}$/.test(String(input.tx || '')) ? String(input.tx).toLowerCase() : '',
ts: Date.now(),
};
if (e.kind === 'cost') e.category = CATS[input.category] ? input.category : 'other';
if (e.tx && d.entries.some(x => x.tx === e.tx && x.id !== e.id)) return { error: 'That transaction is already recorded.', duplicate: true };
const i = d.entries.findIndex(x => x.id === e.id);
if (i >= 0) d.entries[i] = e; else d.entries.push(e);
save(d);
return { ok: true, entry: e };
}
function remove(id) {
const d = load();
const i = d.entries.findIndex(x => x.id === id);
if (i < 0) return { error: 'No such entry.' };
const [gone] = d.entries.splice(i, 1);
save(d);
return { ok: true, entry: gone };
}
// Totals per wallet, split by direction. POL is summed separately from dollar-denominated assets
// because only POL can be reconciled against an on-chain balance.
function totals(wallet) {
const rows = load().entries.filter(e => !wallet || e.wallet === wallet);
const t = { inPol: 0, outPol: 0, inUsd: 0, outUsd: 0, count: rows.length,
// revenue and draws are the P&L numbers; transfers move the balance and nothing else
revenuePol: 0, revenueUsd: 0, drawPol: 0, drawUsd: 0, transferPol: 0, costPol: 0, costUsd: 0 };
for (const e of rows) {
const pol = e.asset === 'POL' ? e.amount : 0;
if (e.dir === 'in') { t.inPol += pol; t.inUsd += e.usd; } else { t.outPol += pol; t.outUsd += e.usd; }
if (e.kind === 'revenue') { t.revenuePol += pol; t.revenueUsd += e.usd; }
else if (e.kind === 'draw') { t.drawPol += pol; t.drawUsd += e.usd; }
else if (e.kind === 'cost') { t.costPol += (e.dir === 'out' ? pol : -pol); t.costUsd += (e.dir === 'out' ? e.usd : -e.usd); }
else t.transferPol += (e.dir === 'in' ? pol : -pol);
}
for (const k of Object.keys(t)) if (k !== 'count') t[k] = Math.round(t[k] * 1e6) / 1e6;
return t;
}
// earned (AdminPaid) + POL in - POL out = what should be sitting there. Any drift is a transfer
// nobody has written down yet, and naming the number is the whole point of this file.
function reconcile(earnedPol, actualPol, wallet) {
const t = totals(wallet || 'feeA');
const expected = Math.round((Number(earnedPol || 0) + t.inPol - t.outPol) * 1e6) / 1e6;
const actual = Math.round(Number(actualPol || 0) * 1e6) / 1e6;
return { earnedPol: Number(earnedPol || 0), expected, actual,
drift: Math.round((actual - expected) * 1e6) / 1e6, totals: t };
}
module.exports = { init, entries, put, remove, totals, reconcile, DIRS, ASSETS, KINDS, WALLETS, CATS, entriesFor: year => load().entries.filter(e => String(e.date || '').startsWith(String(year))) };
+2 -2
View File
@@ -455,7 +455,7 @@
<div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:8px;margin-top:12px">
<select id="ldDir"><option value="in">Money in</option><option value="out">Money out</option></select>
<select id="ldKind"><option value="revenue">Revenue</option><option value="cost">Cost</option><option value="draw">Draw</option><option value="transfer">Transfer</option></select>
<select id="ldCat" hidden><option value="advertising">Advertising</option><option value="rewards">Player rewards</option><option value="software">Software and hosting</option><option value="other">Other cost</option></select>
<select id="ldCat" hidden><option value="advertising">Advertising</option><option value="games">Game marketing</option><option value="rewards">Player rewards</option><option value="software">Software and hosting</option><option value="other">Other cost</option></select>
<select id="ldWallet"><option value="feeA">Receiver A</option><option value="feeB">Receiver B</option><option value="engine">Engine</option><option value="hunt">PolHunter</option><option value="outside">Outside wallet</option></select>
<input type="number" id="ldAmount" min="0" step="0.0001" placeholder="Amount in POL">
<input type="number" id="ldUsd" min="0" step="0.01" placeholder="USD (optional)">
@@ -521,6 +521,6 @@
</div>
<script src="/assets/common.js?v=20261003fr2"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/admin.js?v=20261005st"></script>
<script src="/assets/admin.js?v=20261005gm"></script>
</body>
</html>
+2 -2
View File
@@ -758,7 +758,7 @@
// makes "earned" and "on hand" agree. A drift that will not go to zero is a transfer nobody
// wrote down (Marty, 2026-09-23).
const LD_KIND = { revenue: 'Revenue', draw: 'Draw', transfer: 'Transfer', cost: 'Cost' };
const LD_CAT = { advertising: 'Advertising', rewards: 'Player rewards', software: 'Software and hosting', other: 'Other cost' };
const LD_CAT = { advertising: 'Advertising', games: 'Game marketing', rewards: 'Player rewards', software: 'Software and hosting', other: 'Other cost' };
const LD_WALLET = { feeA: 'Receiver A', feeB: 'Receiver B', engine: 'Engine', hunt: 'PolHunter', outside: 'Outside wallet' };
const pol4 = n => Number(n || 0).toLocaleString(undefined, { maximumFractionDigits: 4 });
function renderLedger(r) {
@@ -1036,7 +1036,7 @@
+ (r.income.outsideUsd ? '<tr><td>Outside revenue</td><td class="num">' + money(r.income.outsideUsd) + '</td></tr>' : '')
+ '<tr><td><b>Total income</b></td><td class="num"><b>' + money(r.income.totalUsd) + '</b></td></tr>'
+ (cats || '<tr><td>No costs recorded yet</td><td></td></tr>')
+ '<tr><td><b>Advertising and promotion</b> (advertising + player rewards)</td><td class="num"><b>' + money(r.expenses.advertisingAndPromotionUsd) + '</b></td></tr>'
+ '<tr><td><b>Advertising and promotion</b> (advertising + game marketing + player rewards)</td><td class="num"><b>' + money(r.expenses.advertisingAndPromotionUsd) + '</b></td></tr>'
+ '<tr><td><b>Total costs</b></td><td class="num"><b>' + money(r.expenses.totalUsd) + '</b></td></tr>'
+ '<tr><td><b>Net</b></td><td class="num"><b>' + money(r.netUsd) + '</b></td></tr></table>'
+ '<p class="muted">Left out: ' + money(r.income.ownSalesExcludedUsd) + ' of sales to your own positions (' + r.ownMemberIds.join(', ') + '); ' + r.draws + ' draws and ' + r.transfers + ' transfers (your money, not expenses).</p>';
+1 -1
View File
@@ -4310,7 +4310,7 @@ const server = http.createServer(async (req, res) => {
else if (l.kind === 'cost') { const c = l.category || 'other', v = l.dir === 'out' ? l.usd : -l.usd; costs[c] = (costs[c] || 0) + v; months[m].costUsd[c] = (months[m].costUsd[c] || 0) + v; }
else if (l.kind === 'draw') draws.push(l); else transfers.push(l);
}
const r2 = n => Math.round(n * 100) / 100, adPromo = (costs.advertising || 0) + (costs.rewards || 0), allCosts = Object.values(costs).reduce((n, v) => n + v, 0);
const r2 = n => Math.round(n * 100) / 100, adPromo = (costs.advertising || 0) + (costs.games || 0) + (costs.rewards || 0), allCosts = Object.values(costs).reduce((n, v) => n + v, 0);
const csv = [['Section', 'Date', 'Category', 'Description', 'POL', 'USD', 'Transaction'].join(',')];
const q = v => '"' + String(v == null ? '' : v).replace(/"/g, '""') + '"';
for (const e of evs) { if (e.type !== 'AdminPaid' || own.has(Number(e.buyerId))) continue; const day = dayOf(e.block); if (!day.startsWith(year)) continue; const b = buys.get(e.tx);