'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 };