Upstream/test/trade-api.test.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

81 lines
5.4 KiB
JavaScript

'use strict';
/* Trade over HTTP: routes, validation, error codes, pagination, and the declared response schemas (contract: true). */
const test = require('node:test');
const assert = require('node:assert');
const { createTestServer } = require('./helpers');
const D = require('../public/js/data.js');
test('trade API: post, list, take, mine, detail, cancel, errors', async () => {
const t = await createTestServer({ contract: true });
try {
const a = await t.signup('alice'), b = await t.signup('bob'), c = await t.signup('cara');
for (const u of [a, b]) t.setBuilding(u.townId, 'internet_exchange', 3);
// cara has no exchange at all
const body = (o) => Object.assign({ townId: a.townId, giveRes: 'fiber', giveAmount: 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 40 }, o || {});
const bad = await t.api('/trade/offers', { method: 'POST', body: body({ giveAmount: 500, wantAmount: 200 }) }, a.token);
assert.equal(bad.status, 409); assert.equal(bad.body.error.code, 'trade_ratio');
assert.equal((await t.api('/trade/offers', { method: 'POST', body: body({ wantRes: 'fiber' }) }, a.token)).status, 422);
assert.equal((await t.api('/trade/offers', { method: 'POST', body: body({ townId: b.townId }) }, a.token)).status, 404);
assert.equal((await t.api('/trade/offers', { method: 'POST', body: body() })).status, 401);
const made = await t.api('/trade/offers', { method: 'POST', body: body() }, a.token);
assert.equal(made.status, 201);
const id = made.body.offer.id;
assert.equal(made.body.offer.give.amount, 400);
assert.equal((await t.api('/trade/offers', { method: 'POST', body: body({ giveAmount: 100, wantAmount: 100, giveRes: 'capital' }) }, a.token)).status, 201);
const listB = await t.api('/trade/offers', {}, b.token);
assert.equal(listB.status, 200);
assert.equal(listB.body.items.length, 2);
assert.equal(listB.body.items[0].id > listB.body.items[1].id, true, 'newest first');
const p1 = await t.api('/trade/offers?limit=1', {}, b.token);
assert.equal(p1.body.items.length, 1);
const p2 = await t.api('/trade/offers?limit=1&after=' + p1.body.next, {}, b.token);
assert.equal(p2.body.items[0].id, id);
assert.equal(p2.body.next, null);
assert.equal((await t.api('/trade/offers?give=capital', {}, b.token)).body.items.length, 1, 'filter by offered resource');
assert.equal((await t.api('/trade/offers?want=capital', {}, b.token)).body.items.length, 0);
assert.equal((await t.api('/trade/offers', {}, a.token)).body.items.length, 0, 'not your own');
assert.equal((await t.api('/trade/offers', {}, c.token)).body.items.length, 0, 'no exchange: you see nothing');
assert.equal((await t.api('/trade/offers?give=gold', {}, b.token)).status, 422);
const one = await t.api('/trade/offers/' + id, {}, c.token);
assert.equal(one.body.offer.status, 'open', 'open offers are public inside the world');
// a full Rack hall cannot take the goods: refused up front instead of destroying them on arrival
t.srv.db.run('UPDATE towns SET fiber = 1000000 WHERE id = ?', b.townId);
const full = await t.api('/trade/offers/' + id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token);
assert.equal(full.status, 409); assert.equal(full.body.error.code, 'no_room_for_goods');
assert.equal(t.srv.db.get('SELECT status FROM trade_offers WHERE id = ?', id).status, 'open', 'nothing happened');
t.srv.db.run('UPDATE towns SET fiber = 0 WHERE id = ?', b.townId);
const acc = await t.api('/trade/offers/' + id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token);
assert.equal(acc.status, 201);
assert.equal(acc.body.status, 'accepted');
assert.equal((await t.api('/trade/offers/' + id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token)).body.error.code, 'offer_closed');
assert.equal((await t.api('/trade/offers/' + id, {}, c.token)).status, 404, 'closed offers are for the two parties');
t.clock.advance(acc.body.arriveAt - t.clock.now());
t.srv.scheduler.runDue();
const mineA = await t.api('/trade/offers/mine', {}, a.token), mineB = await t.api('/trade/offers/mine?status=completed', {}, b.token);
assert.equal(mineA.body.items.length, 2);
assert.equal(mineB.body.items[0].status, 'completed');
assert.equal(mineB.body.items[0].role, 'acceptor');
const notes = await t.api('/notifications', {}, a.token);
assert.ok(notes.body.items.some((n) => n.type === 'trade_completed'));
const other = await t.api('/trade/offers', { method: 'GET' }, b.token);
const open = other.body.items[0];
assert.equal((await t.api('/trade/offers/' + open.id, { method: 'DELETE' }, b.token)).status, 404);
const del = await t.api('/trade/offers/' + open.id, { method: 'DELETE' }, a.token);
assert.equal(del.status, 200);
assert.deepEqual(del.body.returned, { resource: 'capital', amount: 100 });
// the Idempotency-Key makes a retried POST safe: one offer, not two
const k = { 'idempotency-key': 'offer-retry-0001' };
const r1 = await t.api('/trade/offers', { method: 'POST', body: body({ giveAmount: 50, wantAmount: 50 }), headers: k }, a.token);
const r2 = await t.api('/trade/offers', { method: 'POST', body: body({ giveAmount: 50, wantAmount: 50 }), headers: k }, a.token);
assert.equal(r1.body.offer.id, r2.body.offer.id);
assert.equal(t.srv.db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE give_amount = 50").n, 1);
void D;
} finally { await t.close(); }
});