'use strict'; /* Internet exchange trade: offers, escrow, accept (two transports), cancel, expire, rules, conservation. Fake clock, in-memory db. */ const test = require('node:test'); const assert = require('node:assert'); const T = require('./military-helpers'); const { R, D, H } = T; // Two traders next to each other with no production at all, so every resource that moves can be counted exactly. function traders(o) { o = o || {}; const h = T.setup(); const a = T.addOperator(h, 'alice', { x: 5, y: 0, infra: o.aInfra }); const b = T.addOperator(h, 'bob', { x: 9, y: 0, infra: o.bInfra }); for (const t of [a, b]) h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", t.townId); return { h, a, b }; } const stock = (h, townId) => { const t = T.town(h, townId); return { fiber: t.fiber, hardware: t.hardware, capital: t.capital }; }; // every unit of every resource in the world: in POPs, in open offers (escrow), on the road function total(h) { let sum = 0; for (const t of h.db.all('SELECT fiber, hardware, capital FROM towns')) sum += t.fiber + t.hardware + t.capital; for (const o of h.db.all("SELECT give_amount FROM trade_offers WHERE status = 'open'")) sum += o.give_amount; for (const m of h.db.all("SELECT cargo FROM movements WHERE status = 'out'")) for (const v of Object.values(JSON.parse(m.cargo))) sum += v; return sum; } const post = (h, who, townId, o) => h.run('tradeOffer', Object.assign({ userId: who.userId, townId, giveRes: 'fiber', giveAmount: 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 30 }, o || {})).offer; const { createTradeQueries } = require('../server/tradeQueries'); const err = (fn) => { try { fn(); } catch (e) { return e; } assert.fail('expected an error'); }; test('trade: post, escrow, accept spawns two transports, both arrive, offer completes; nothing is created or lost', () => { const { h, a, b } = traders(); const before = total(h); const aStart = stock(h, a.townId), bStart = stock(h, b.townId); const offer = post(h, a, a.townId); assert.equal(offer.status, 'open'); assert.equal(stock(h, a.townId).fiber, aStart.fiber - 400, 'the offered amount left the POP (escrow)'); assert.equal(total(h), before, 'escrow is counted: conserved'); assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'tradeExpire' AND status = 'pending'").n, 1); // bob sees it and can take it const tq = createTradeQueries(h); const list = tq.offers(b.userId, {}); assert.equal(list.items.length, 1); assert.equal(list.items[0].id, offer.id); assert.equal(list.items[0].acceptableFrom[0].townId, b.townId); assert.equal(tq.offers(a.userId, {}).items.length, 0, 'your own offers are not in the market list'); const t0 = h.clock.now(); const acc = h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId }); assert.equal(acc.status, 'accepted'); const dist = R.distance(a.x, a.y, b.x, b.y); assert.equal(acc.arriveAt, t0 + R.transportMs(dist, 1), 'both legs use the transport speed'); assert.equal(stock(h, b.townId).hardware, bStart.hardware - 300, "the acceptor's payment left at once"); assert.equal(total(h), before, 'in flight: still conserved'); const mvs = h.db.all("SELECT * FROM movements WHERE type = 'transport' ORDER BY id"); assert.equal(mvs.length, 2); const goods = mvs.find((m) => m.id === acc.goodsMovementId), pay = mvs.find((m) => m.id === acc.paymentMovementId); assert.equal(goods.from_town_id, a.townId); assert.equal(goods.to_town_id, b.townId); assert.deepEqual(JSON.parse(goods.cargo), { fiber: 400 }); assert.equal(pay.from_town_id, b.townId); assert.equal(pay.to_town_id, a.townId); assert.deepEqual(JSON.parse(pay.cargo), { hardware: 300 }); assert.equal(T.notes(h, a.userId, 'trade_accepted').length, 1); assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'accepted'); assert.equal(h.db.get("SELECT status FROM events WHERE type = 'tradeExpire'").status, 'cancelled', 'an accepted offer cannot expire'); h.advanceTo(acc.arriveAt); assert.equal(h.db.get('SELECT status, legs_done FROM trade_offers WHERE id = ?', offer.id).status, 'completed'); assert.equal(stock(h, a.townId).hardware, aStart.hardware + 300); assert.equal(stock(h, b.townId).fiber, bStart.fiber + 400); assert.equal(stock(h, a.townId).fiber, aStart.fiber - 400); assert.equal(T.notes(h, a.userId, 'trade_completed').length, 1); assert.equal(T.notes(h, b.userId, 'trade_completed').length, 1); assert.equal(total(h), before, 'delivered: conserved'); // the carriers drive back; the links are free again afterwards const back = h.db.all("SELECT * FROM movements WHERE type = 'return' AND status = 'out'"); assert.equal(back.length, 2); h.advance(10 * H); assert.equal(require('../server/military/movements').activeLinks(h.db, a.townId), 0); assert.equal(total(h), before); assert.equal(h.db.all("SELECT 1 FROM events WHERE status = 'failed'").length, 0); }); test('trade: terms - 1:2 ratio band, capacity, distinct resources, links, resources, ownership', () => { const { h, a, b } = traders({ aInfra: { internet_exchange: 1 } }); assert.equal(err(() => post(h, a, a.townId, { giveAmount: 500, wantAmount: 249 })).code, 'trade_ratio'); assert.equal(err(() => post(h, a, a.townId, { giveAmount: 100, wantAmount: 201 })).code, 'trade_ratio'); assert.equal(err(() => post(h, a, a.townId, { giveAmount: 500, wantAmount: 501 })).code, 'capacity_exceeded'); assert.equal(err(() => post(h, a, a.townId, { wantRes: 'fiber' })).code, 'validation_failed'); assert.equal(err(() => post(h, a, a.townId, { giveRes: 'power' })).code, 'validation_failed'); assert.equal(err(() => post(h, a, a.townId, { giveAmount: 0 })).code, 'validation_failed'); assert.equal(err(() => post(h, a, a.townId, { giveAmount: 1.5 })).code, 'validation_failed'); assert.equal(err(() => post(h, a, a.townId, { maxDistance: 0 })).code, 'validation_failed'); assert.equal(err(() => post(h, a, a.townId, { maxDistance: D.TRADE.maxDistance + 1 })).code, 'validation_failed'); assert.equal(err(() => post(h, b, a.townId)).code, 'not_found', 'not your POP'); assert.equal(post(h, a, a.townId, { giveAmount: 500, wantAmount: 250 }).status, 'open', 'exactly 2:1 is allowed'); // level 1 exchange = one link, held by the open offer: no second offer and no direct transport meanwhile assert.equal(err(() => post(h, a, a.townId)).code, 'no_transport_link'); assert.equal(err(() => h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { fiber: 10 } })).code, 'no_transport_link'); // a POP without an exchange cannot post h.db.run("DELETE FROM buildings WHERE town_id = ? AND key = 'internet_exchange'", b.townId); assert.equal(err(() => post(h, b, b.townId)).code, 'no_transport_link'); // not enough of the offered resource const c = T.addOperator(h, 'cat', { x: 14, y: 0, res: 100 }); assert.equal(err(() => post(h, c, c.townId)).code, 'not_enough_resources'); }); test('trade: accept rules - own offer, closed, range, exchange, cannot afford (atomic), links', () => { const { h, a, b } = traders(); const c = T.addOperator(h, 'cat', { x: 40, y: 0 }); // 35 tiles from alice const d = T.addOperator(h, 'dan', { x: 12, y: 0, infra: { internet_exchange: 0 } }); h.db.run("DELETE FROM buildings WHERE town_id = ? AND key = 'internet_exchange'", d.townId); const offer = post(h, a, a.townId, { maxDistance: 12 }); assert.equal(err(() => h.run('tradeAccept', { userId: a.userId, offerId: offer.id, townId: a.townId })).code, 'own_offer'); assert.equal(err(() => h.run('tradeAccept', { userId: c.userId, offerId: offer.id, townId: c.townId })).code, 'trade_out_of_range', 'beyond the offer\'s max distance'); assert.equal(err(() => h.run('tradeAccept', { userId: d.userId, offerId: offer.id, townId: d.townId })).code, 'no_transport_link', 'no Internet exchange'); assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: 999, townId: b.townId })).code, 'not_found'); assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: a.townId })).code, 'not_found', 'not your POP'); // reach: a level-1 exchange sees 10 tiles const far = T.addOperator(h, 'far', { x: 20, y: 0, infra: { internet_exchange: 1 } }); // 15 tiles from alice, within the offer's 30 below const wide = post(h, a, a.townId, { maxDistance: 30, giveAmount: 100, wantAmount: 100 }); assert.equal(err(() => h.run('tradeAccept', { userId: far.userId, offerId: wide.id, townId: far.townId })).code, 'trade_out_of_range'); const seen = createTradeQueries(h).offers(far.userId, {}); assert.equal(seen.items.length, 0, 'out of reach: not even listed'); assert.equal(seen.exchangeLevels[0].reach, 10); // bob cannot pay: nothing changes (all or nothing) h.db.run('UPDATE towns SET hardware = 100 WHERE id = ?', b.townId); const snap = JSON.stringify([stock(h, a.townId), stock(h, b.townId), h.db.all('SELECT * FROM movements'), h.db.all('SELECT status FROM trade_offers ORDER BY id')]); assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'not_enough_resources'); assert.equal(JSON.stringify([stock(h, a.townId), stock(h, b.townId), h.db.all('SELECT * FROM movements'), h.db.all('SELECT status FROM trade_offers ORDER BY id')]), snap, 'a failed accept leaves no trace'); // no free link for bob (level 3, three running transports) h.db.run('UPDATE towns SET hardware = 1000 WHERE id = ?', b.townId); for (let i = 0; i < 3; i++) h.run('sendTransport', { userId: b.userId, fromTownId: b.townId, toTownId: c.townId, cargo: { capital: 10 } }); assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'no_transport_link'); assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'open'); }); test('trade: cancel returns the escrow, closed offers cannot be taken, strangers cannot cancel', () => { const { h, a, b } = traders(); const start = stock(h, a.townId), before = total(h); const offer = post(h, a, a.townId); assert.equal(err(() => h.run('tradeCancel', { userId: b.userId, offerId: offer.id })).code, 'not_found'); const r = h.run('tradeCancel', { userId: a.userId, offerId: offer.id }); assert.deepEqual(r.returned, { resource: 'fiber', amount: 400 }); assert.deepEqual(stock(h, a.townId), start); assert.equal(total(h), before); assert.equal(h.db.get("SELECT status FROM events WHERE type = 'tradeExpire'").status, 'cancelled'); assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'offer_closed'); assert.equal(err(() => h.run('tradeCancel', { userId: a.userId, offerId: offer.id })).code, 'offer_closed'); assert.equal(require('../server/military/movements').activeLinks(h.db, a.townId), 0, 'the reserved link is free again'); }); test('trade: an offer expires after its ttl (divided by world speed) and returns the escrow exactly once', () => { for (const speed of [1, 4]) { const h = T.setup({ speed }); const a = T.addOperator(h, 'alice', { x: 5, y: 0 }); h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", a.townId); const start = stock(h, a.townId); const offer = h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'capital', giveAmount: 250, wantRes: 'fiber', wantAmount: 400, maxDistance: 20 }).offer; assert.equal(offer.expiresAt - h.clock.now(), D.TRADE.ttlHours * H / speed); h.advanceTo(offer.expiresAt - 1); assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'open'); h.advanceTo(offer.expiresAt); assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'expired'); assert.deepEqual(stock(h, a.townId), start); assert.equal(T.notes(h, a.userId, 'trade_expired').length, 1); // running the handler again (idempotence) does not pay twice require('../server/events/tradeExpire')(Object.assign(h.ctx(), { now: offer.expiresAt }), { id: 0, worldId: h.worldId, dueAt: offer.expiresAt, payload: { offerId: offer.id } }); assert.deepEqual(stock(h, a.townId), start); } }); test('trade: a delivery above the receiver\'s storage cap loses exactly the overflow (and says so); the rest is conserved', () => { const { h, a, b } = traders({ bInfra: { rack_hall: 1 } }); // cap 1000 h.db.run('UPDATE towns SET fiber = 900 WHERE id = ?', b.townId); const before = total(h); const offer = post(h, a, a.townId); const acc = h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId }); h.advanceTo(acc.arriveAt); assert.equal(stock(h, b.townId).fiber, 1000); const arrived = T.notes(h, b.userId, 'transport_arrived')[0]; assert.deepEqual(arrived.cargoLost, { fiber: 300 }); assert.equal(total(h) + 300, before, 'every unit is somewhere, except the 300 that did not fit and were reported lost'); assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'completed'); }); test('trade: a POP that changes hands voids its open offers; the escrow stays in the POP', () => { const { h, a, b } = traders(); const offer = post(h, a, a.townId); const before = total(h); const combat = require('../server/military/combat'); const town = require('../server/state').loadTown(h.db, a.townId); h.db.tx(() => combat.transferTown(h.ctx(), town, { id: b.opId, name: 'bob' }, { id: a.opId, name: 'alice' }, h.clock.now())); assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'void'); assert.equal(T.town(h, a.townId).owner_id, b.opId); assert.equal(T.town(h, a.townId).fiber, 4000, "the escrow is back in the POP, now bob's"); assert.equal(total(h), before, 'nothing created or lost'); assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'offer_closed'); assert.equal(h.db.get("SELECT status FROM events WHERE type = 'tradeExpire'").status, 'cancelled'); assert.equal(T.notes(h, a.userId, 'trade_void').length, 1); }); test('trade list: pages through offers that are out of reach (chunked read), cursor and filters stay right', () => { const saved = D.TRADE.scanChunk; D.TRADE.scanChunk = 2; try { const h = T.setup(); const p = T.addOperator(h, 'poster', { x: 5, y: 0, infra: { internet_exchange: 10 } }); const v = T.addOperator(h, 'viewer', { x: 9, y: 0 }); // 4 tiles away, exchange 3 (reach 30) for (const q of [p, v]) h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", q.townId); const ids = []; for (const [md, amt] of [[2, 10], [10, 20], [2, 30], [2, 40], [10, 50], [3, 60], [10, 70]]) ids.push(post(h, p, p.townId, { maxDistance: md, giveAmount: amt, wantAmount: amt }).id); const tq = createTradeQueries(h); const visible = [ids[1], ids[4], ids[6]]; // maxDistance >= 4 const p1 = tq.offers(v.userId, { limit: 2 }); assert.deepEqual(p1.items.map((o) => o.id), [visible[2], visible[1]]); assert.equal(p1.next, visible[1]); const p2 = tq.offers(v.userId, { limit: 2, after: p1.next }); assert.deepEqual(p2.items.map((o) => o.id), [visible[0]]); assert.equal(p2.next, null); assert.equal(tq.offers(v.userId, { limit: 10 }).items.length, 3); assert.deepEqual(tq.offers(v.userId, { limit: 10, give: 'capital' }).items, []); } finally { D.TRADE.scanChunk = saved; } });