Upstream/server/trade.js
jvanvik 3c23c51902 Phase 4: close loot/refund leaks, landing-site garrisons, speed-scaled shipping, update/offsite tooling, broad e2e
Built:
- Economy: raid loot capped to the room the raiders have at home (rest stays with the victim, "lootLeft" in the report); trade escrow reserves its room so refunds always fit; trade accept refuses with no_room_for_goods when the goods would not fit. Loot destroyed per 30-day run 31-61k -> ~1k, refunds clipped ~27k -> 0 (docs/BALANCE.md, 3 seeds).
- End game: members of the holding alliance garrison landing sites (migration 005_site_garrison.sql), garrison counts in site defence, 72 h capture shield, withdraw route, POP view lists garrisoned units. Shipping capacity scales with world speed (3x world: winner 76-98 -> ~30-36 days after sites open). Bot runs show real contests (84-194 attacks on held sites at 1x).
- Ops: deploy/update.sh (backup, stop, ff-merge, npm ci --ignore-scripts, health check, rollback), deploy/upstream-offsite (rsync only), admin end-world snapshots results, EPIPE fix, docs/workflows/ filled in.
- e2e 62 -> 163 checks: units, raids/reports, alliance+messages, trade, end game, nb, PWA, reconnect, slow polling fallback (opt-in). Two app bugs found: message push ignored, "New" button stayed English.

Tested: npm test 274/274, openapi check, npm run e2e 163/163 (137 s), bot runs 50x30d seeds 1-3 and 140-day/60-day speed-3 end-game runs INVARIANTS OK, adversarial review pass (findings fixed or documented).
NOT tested: update.sh on a real box (systemd, real npm, runuser; stubs only, shellcheck not installed), garrison card/loot text on a phone, Node 22.13, humans. Known leaks left open and documented (BALANCE S6): loot/shipments can still overflow when stock arrives in flight, bounced backbone shipments lose overflow (reported to the sender). Garrison numbers (heldDefenceMult 2, shield 72 h) are first guesses from 2 seeds. Not claimed: balanced.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-12 00:58:12 +02:00

102 lines
6.2 KiB
JavaScript

'use strict';
/*
* Internet exchange trade: shared helpers of the trade commands, the expiry event and the read model.
*
* Offer life cycle (table trade_offers, status):
* open the offered amount is ESCROWED in the row (it left the POP at creation) and one transport link of the poster's POP is
* held in reserve (military/movements.activeLinks counts open offers)
* accepted two transports are on the road: poster -> acceptor carries the escrow, acceptor -> poster carries the payment
* completed both legs were delivered (the `transportArrived` hook below)
* cancelled the poster took it back: the escrow is credited to the POP again
* expired ttl ran out (event `tradeExpire`): same
* void the poster's POP changed hands while the offer was open: the escrow stays in that POP (it goes with the POP)
* Escrowed goods keep occupying the POP's Rack hall (S2 in docs/BALANCE.md, rules.storageCapOf): while an offer is open the stock
* of that resource stops growing at hall size minus escrow, so the refund always fits. Nothing is lost and the escrow is no extra
* storage (decision R1). The one case that can still clip a refund is a Rack hall that was shot down below stock + escrow in the
* meantime; that loss is reported (`trade_refund_clipped`). Every way out of `open` must settle the POP first (the cap changes
* there): closeOffer does, and so does tradeAccept for the poster's POP. The only other loss anywhere in trade is what a delivery
* cannot store (the existing cargoLost rule of transports).
*/
const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
const { loadTown, settle } = require('./state');
const M = require('./military/movements');
const COL = { fiber: 'fiber', hardware: 'hardware', capital: 'capital' };
// Credit `amount` of `res` back to a POP that is still carrying the escrow in its Rack hall (the offer is still `open` when this
// runs, so the town's escrow includes it). Settled first. -> the part that did not fit (only after a lowered Rack hall), else 0
function refund(db, townId, res, amount, at) {
const town = loadTown(db, townId);
if (!town) return 0;
settle(db, town, at);
// The hall's room once this offer is gone is storageCapOf + amount. Stock already above it stays (like cancelBuild), a refund never lifts it further.
const room = Math.max(R.storageCapOf(town, res) + amount, town.res[res]);
const next = Math.min(room, town.res[res] + amount);
db.run('UPDATE towns SET ' + COL[res] + ' = ? WHERE id = ?', next, townId);
return Math.max(0, town.res[res] + amount - next);
}
const getOffer = (db, id) => db.get('SELECT * FROM trade_offers WHERE id = ?', id) || null;
function expiryMs(speed) { return Math.round(D.TRADE.ttlHours * D.HOUR_MS / (speed || 1)); }
function userOfOperator(db, operatorId) { const o = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return o ? o.user_id : null; }
// Close an open offer and give the escrow back to its POP. `status`: cancelled | expired | void. -> { credited, lost }
function closeOffer(ctx, offer, status, at) {
const { db } = ctx;
const lost = refund(db, offer.town_id, offer.give_res, offer.give_amount, at); // BEFORE the status changes: the open escrow shaped the settle
db.run('UPDATE trade_offers SET status = ?, closed_at = ? WHERE id = ?', status, at, offer.id);
if (offer.expire_event_id) db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", at, offer.expire_event_id);
const lostWhole = Math.round(lost);
if (lostWhole > 0) {
const uid = userOfOperator(db, offer.operator_id);
if (uid) ctx.notify(uid, offer.world_id, 'trade_refund_clipped', { offerId: offer.id, townId: offer.town_id, resource: offer.give_res, lost: lostWhole, credited: offer.give_amount - lostWhole });
}
return { credited: offer.give_amount - lost, lost };
}
// A POP changed hands (takeover): its open offers end and the escrow stays with the POP. Called from combat.transferTown.
function onTownTransferred(ctx, townId, at) {
const { db } = ctx;
for (const o of db.all("SELECT * FROM trade_offers WHERE town_id = ? AND status = 'open'", townId)) {
closeOffer(ctx, o, 'void', at);
const uid = userOfOperator(db, o.operator_id);
if (uid) ctx.notify(uid, o.world_id, 'trade_void', { offerId: o.id, townId });
}
}
// `transportArrived` consumer: both legs of an accepted offer delivered -> completed.
function onTransportArrived(ctx, mv, res) {
const tradeId = mv.extra && mv.extra.tradeId;
if (!tradeId) return;
const { db } = ctx;
const o = getOffer(db, tradeId);
if (!o || o.status !== 'accepted') return;
const legs = o.legs_done + 1;
if (legs < 2) { db.run('UPDATE trade_offers SET legs_done = ? WHERE id = ?', legs, o.id); return; }
db.run("UPDATE trade_offers SET legs_done = ?, status = 'completed', closed_at = ? WHERE id = ?", legs, ctx.now, o.id);
const body = { offerId: o.id, give: { resource: o.give_res, amount: o.give_amount }, want: { resource: o.want_res, amount: o.want_amount } };
for (const opId of [o.operator_id, o.accepted_by_operator]) {
const uid = userOfOperator(db, opId);
if (uid) ctx.notify(uid, o.world_id, 'trade_completed', body);
}
}
// Registered once, whoever requires this module first (commands and events both do): tests and the server see the same wiring.
if (!M.hooks.transportArrived.some((f) => f.name === 'tradeTransportArrived')) {
M.hooks.transportArrived.push(function tradeTransportArrived(ctx, mv, res) { return onTransportArrived(ctx, mv, res); });
}
function offerView(db, o, towns) {
const t = towns && towns.get(o.town_id);
return {
id: o.id, status: o.status, worldId: o.world_id, townId: o.town_id, townName: t ? t.name : null, x: t ? t.x : null, y: t ? t.y : null,
operator: { id: o.operator_id, name: (db.get('SELECT name FROM operators WHERE id = ?', o.operator_id) || {}).name || null },
give: { resource: o.give_res, amount: o.give_amount }, want: { resource: o.want_res, amount: o.want_amount },
maxDistance: o.max_distance, createdAt: o.created_at, expiresAt: o.expires_at, acceptedAt: o.accepted_at, closedAt: o.closed_at,
};
}
module.exports = { refund, getOffer, expiryMs, closeOffer, onTownTransferred, onTransportArrived, offerView, userOfOperator };