BlueGit

timfa questward

Files

questward / server / src / market / service.js

service.js

service.js 26.6 KiB Download Raw
1import { randomUUID } from "node:crypto";
2import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
3import { BlockType } from "../../../shared/definitions/tiles.js";
4import { ItemId, itemDefinition, ITEM_DEFINITIONS, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";
5import {
6 addCoinsToSlots,
7 insertStack,
8 insertStackGrowable,
9 normalizeVault,
10 takeFromSlot,
11 cloneStack
12} from "../../../shared/items/inventory.js";
13import { assertMarketplaceSellable, canSellOnMarketplace } from "../../../shared/items/marketplace.js";
14import { attachOrigins, normalizeOrigins, splitOrigins, writtenOrigin } from "../../../shared/items/origin.js";
15import { undiscountedMarketValue } from "../../../shared/shop/pricing.js";
16import { CENTRAL_EXCHANGE_ORG } from "../../../shared/courier/systemLetters.js";
17import {
18 MARKET_ORDER_MAX_AGE_MS,
19 buyFilledLetterBody,
20 marketOrderListingFee,
21 midpointTradePrice,
22 orderExpiredLetterBody,
23 orderCancelledLetterBody,
24 pickExchangeClerk,
25 soldLetterBody
26} from "../../../shared/market/exchange.js";
27import { takeMarketFunds, resolveMarketSellListing, isFilledChequeEscrow } from "../../../shared/market/funds.js";
28import { decodeChunkBlob } from "../world/chunkData.js";
29import { withTransaction } from "../persistence/database.js";
30
31function userError (message)
32{
33 const error = new Error(message);
34 error.userFacing = true;
35 return error;
36}
37
38function chebyshev (ax, ay, bx, by)
39{
40 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
41}
42
43export class MarketService
44{
45 constructor ({ stateDb, worldDb, simulation })
46 {
47 this.stateDb = stateDb;
48 this.worldDb = worldDb;
49 this.simulation = simulation;
50 this.marketTiles = [];
51 /**
52 * Players holding a CE UI open at a staff station.
53 * key `${stationTileX},${stationTileY}` →
54 * { stationTileX, stationTileY, marketTileX, marketTileY, browsers: Map<characterId, sessionId> }
55 * @type {Map<string, object>}
56 */
57 this.stationAttendance = new Map();
58 /** @type {Map<number, object>} */
59 this.lastSales = new Map();
60 this.refreshIndex();
61 this.#loadLastSales();
62 this.#syncLastSalesToWorkers();
63 }
64
65 refreshIndex ()
66 {
67 const revisionId = this.worldDb.getActiveRevisionId();
68 const tiles = [];
69 for (const coord of this.worldDb.listChunkCoords(revisionId))
70 {
71 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
72 if (!row)
73 { continue; }
74 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y);
75 for (let localY = 0; localY < CHUNK_SIZE; localY++)
76 {
77 for (let localX = 0; localX < CHUNK_SIZE; localX++)
78 {
79 const block = data.blocks[localY * CHUNK_SIZE + localX];
80 if (block?.typeId !== BlockType.marketplace)
81 { continue; }
82 tiles.push({
83 tileX: coord.chunk_x * CHUNK_SIZE + localX,
84 tileY: coord.chunk_y * CHUNK_SIZE + localY
85 });
86 }
87 }
88 }
89 this.marketTiles = tiles;
90 }
91
92 nearestMarket (tileX, tileY)
93 {
94 if (!this.marketTiles.length)
95 { return null; }
96 let best = null;
97 let bestDist = Infinity;
98 for (const tile of this.marketTiles)
99 {
100 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
101 if (dist < bestDist)
102 {
103 bestDist = dist;
104 best = tile;
105 }
106 }
107 return best;
108 }
109
110 lastSaleFor (itemId)
111 {
112 return this.lastSales.get(itemId | 0) ?? null;
113 }
114
115 snapshot ()
116 {
117 const out = {};
118 for (const [itemId, sale] of this.lastSales.entries())
119 { out[String(itemId)] = sale; }
120 return out;
121 }
122
123 step (now = Date.now())
124 {
125 const events = [];
126 events.push(...this.#pruneStationAttendance());
127 const expired = this.stateDb.listExpiredMarketOrders(now - MARKET_ORDER_MAX_AGE_MS);
128 for (const order of expired)
129 {
130 try
131 {
132 events.push(...this.#expireOrder(order, now));
133 }
134 catch (error)
135 {
136 console.error("Market order expiry failed", order.orderId, error);
137 }
138 }
139 return events;
140 }
141
142 handleCommand (sessionId, command, now = Date.now())
143 {
144 switch (command.type)
145 {
146 case "open-market":
147 return this.openMarket(sessionId, command.characterId, now);
148 case "place-market-sell":
149 return this.placeSellOrder(
150 sessionId,
151 command.characterId,
152 command.slotIndex | 0,
153 command.quantity | 0 || 1,
154 command.minUnitPrice | 0,
155 now
156 );
157 case "place-market-buy":
158 return this.placeBuyOrder(
159 sessionId,
160 command.characterId,
161 command.itemId | 0,
162 command.quantity | 0 || 1,
163 command.maxUnitPrice | 0,
164 now
165 );
166 case "cancel-market-order":
167 return this.cancelOrder(sessionId, command.characterId, command.orderId | 0, now);
168 case "close-market":
169 return this.closeMarket(sessionId, command.characterId);
170 default:
171 return null;
172 }
173 }
174
175 openMarket (sessionId, characterId, now = Date.now())
176 {
177 const { position } = this.#requireAtMarket(characterId);
178 this.#attendStations(sessionId, characterId, position.tileX, position.tileY);
179 return {
180 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
181 };
182 }
183
184 closeMarket (sessionId, characterId)
185 {
186 this.leaveExchangeStations(characterId);
187 return {
188 events: [{ type: "market-closed", sessionId, characterId }]
189 };
190 }
191
192 /** Drop a character from every CE station (UI close / despawn). */
193 leaveExchangeStations (characterId)
194 {
195 const id = characterId | 0;
196 const emptyStations = [];
197 for (const [key, entry] of this.stationAttendance.entries())
198 {
199 if (!entry.browsers.has(id))
200 { continue; }
201 entry.browsers.delete(id);
202 if (entry.browsers.size === 0)
203 { emptyStations.push(key); }
204 }
205 for (const key of emptyStations)
206 { this.#releaseStation(key); }
207 }
208
209 placeSellOrder (sessionId, characterId, slotIndex, quantity, minUnitPrice, now = Date.now())
210 {
211 const { position } = this.#requireAtMarket(characterId);
212 const minPrice = Math.max(1, minUnitPrice | 0);
213 const bag = this.#loadBag(characterId);
214 const slot = bag.inventory?.[slotIndex];
215 if (!slot)
216 { throw userError("That slot is empty."); }
217 assertMarketplaceSellable(slot);
218 if ((slot.itemId | 0) === ItemId.coins)
219 { throw userError("Coins cannot be listed on the marketplace."); }
220
221 const listing = resolveMarketSellListing(slot);
222 if (!listing)
223 { throw userError("That item cannot be sold on the marketplace."); }
224
225 let escrowStack;
226 let orderQty;
227 if (listing.isCheque)
228 {
229 orderQty = listing.quantity;
230 const taken = takeFromSlot(bag.inventory, slotIndex, 1);
231 if (!taken.ok || !taken.taken)
232 { throw userError("That cheque is not available."); }
233 bag.inventory = taken.slots;
234 escrowStack = attachOrigins(taken.taken);
235 }
236 else
237 {
238 const qty = Math.max(1, Math.min(quantity | 0 || 1, listing.quantity));
239 orderQty = qty;
240 const taken = takeFromSlot(bag.inventory, slotIndex, qty);
241 if (!taken.ok || !taken.taken)
242 { throw userError("That item is not available."); }
243 bag.inventory = taken.slots;
244 escrowStack = attachOrigins(taken.taken);
245 }
246
247 const fee = marketOrderListingFee(minPrice, orderQty);
248 const paid = this.#payMarketFunds(bag, characterId, fee);
249 if (!paid.ok)
250 {
251 const restored = insertStack(
252 bag.inventory,
253 escrowStack,
254 itemDefinition(escrowStack.itemId)
255 );
256 bag.inventory = restored.slots;
257 throw userError(
258 fee > 0
259 ? `You need ${fee} coins for the listing fee.`
260 : "You cannot afford the listing fee."
261 );
262 }
263
264 const order = this.stateDb.insertMarketOrder({
265 characterId,
266 side: "sell",
267 itemId: listing.itemId,
268 quantity: orderQty,
269 limitUnitPrice: minPrice,
270 escrowCoins: 0,
271 escrowStack,
272 createdAt: now,
273 status: "open"
274 });
275 this.#persistBag(characterId, bag);
276 const matchEvents = this.#matchAfterInsert(order, now);
277 return {
278 events: [
279 this.#marketOpenEvent(sessionId, characterId, position, now),
280 ...matchEvents
281 ]
282 };
283 }
284
285 placeBuyOrder (sessionId, characterId, itemId, quantity, maxUnitPrice, now = Date.now())
286 {
287 const { position } = this.#requireAtMarket(characterId);
288 const maxPrice = Math.max(1, maxUnitPrice | 0);
289 const qty = Math.max(1, quantity | 0 || 1);
290 const def = itemDefinition(itemId);
291 if (!def || !canSellOnMarketplace({ itemId, quantity: 1 }))
292 { throw userError("That item cannot be bought on the marketplace."); }
293 if ((itemId | 0) === ItemId.coins)
294 { throw userError("Coins cannot be ordered on the marketplace."); }
295 const escrow = maxPrice * qty;
296 const fee = marketOrderListingFee(maxPrice, qty);
297 const bag = this.#loadBag(characterId);
298 const paid = this.#payMarketFunds(bag, characterId, escrow + fee);
299 if (!paid.ok)
300 {
301 throw userError(
302 `You need ${escrow + fee} coins (escrow ${escrow} + ${fee} listing fee).`
303 );
304 }
305 const order = this.stateDb.insertMarketOrder({
306 characterId,
307 side: "buy",
308 itemId: itemId | 0,
309 quantity: qty,
310 limitUnitPrice: maxPrice,
311 escrowCoins: escrow,
312 escrowStack: null,
313 createdAt: now,
314 status: "open"
315 });
316 this.#persistBag(characterId, bag);
317 const matchEvents = this.#matchAfterInsert(order, now);
318 return {
319 events: [
320 this.#marketOpenEvent(sessionId, characterId, position, now),
321 ...matchEvents
322 ]
323 };
324 }
325
326 cancelOrder (sessionId, characterId, orderId, now = Date.now())
327 {
328 const { position } = this.#requireAtMarket(characterId);
329 const order = this.stateDb.getMarketOrder(orderId);
330 if (!order || order.status !== "open")
331 { throw userError("That order is no longer open."); }
332 if (Number(order.characterId) !== Number(characterId))
333 { throw userError("That is not your order."); }
334 const clerkName = pickExchangeClerk();
335 this.#returnEscrowByPigeon(order, {
336 letterBody: orderCancelledLetterBody({
337 side: order.side,
338 itemName: itemDefinition(order.itemId)?.displayName ?? "item",
339 quantity: order.quantity,
340 escrowLabel: order.side === "buy"
341 ? "coins"
342 : (isFilledChequeEscrow(order.escrowStack)
343 ? "written cheque"
344 : (itemDefinition(order.itemId)?.displayName ?? "item")),
345 clerkName
346 }),
347 clerkName,
348 now
349 });
350 this.stateDb.updateMarketOrder({
351 ...order,
352 status: "cancelled",
353 quantity: 0,
354 escrowCoins: 0,
355 escrowStack: null
356 });
357 return {
358 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
359 };
360 }
361
362 #expireOrder (order, now)
363 {
364 const events = [];
365 const clerkName = pickExchangeClerk();
366 this.#returnEscrowByPigeon(order, {
367 letterBody: orderExpiredLetterBody({
368 side: order.side,
369 itemName: itemDefinition(order.itemId)?.displayName ?? "item",
370 quantity: order.quantity,
371 escrowLabel: order.side === "buy"
372 ? "coins"
373 : (isFilledChequeEscrow(order.escrowStack)
374 ? "written cheque"
375 : (itemDefinition(order.itemId)?.displayName ?? "item")),
376 clerkName
377 }),
378 clerkName,
379 now
380 });
381 this.stateDb.updateMarketOrder({
382 ...order,
383 status: "cancelled",
384 quantity: 0,
385 escrowCoins: 0,
386 escrowStack: null
387 });
388 events.push({
389 type: "market-order-expired",
390 orderId: order.orderId,
391 characterId: order.characterId
392 });
393 return events;
394 }
395
396 #matchAfterInsert (incoming, now)
397 {
398 const events = [];
399 let resting = this.stateDb.getMarketOrder(incoming.orderId);
400 if (!resting || resting.status !== "open")
401 { return events; }
402
403 const counterparts = resting.side === "sell"
404 ? this.stateDb.listOpenBuyOrdersForItem(resting.itemId)
405 : this.stateDb.listOpenSellOrdersForItem(resting.itemId);
406
407 for (const other of counterparts)
408 {
409 resting = this.stateDb.getMarketOrder(resting.orderId);
410 if (!resting || resting.status !== "open" || resting.quantity <= 0)
411 { break; }
412 const liveOther = this.stateDb.getMarketOrder(other.orderId);
413 if (!liveOther || liveOther.status !== "open" || liveOther.quantity <= 0)
414 { continue; }
415 if (Number(liveOther.characterId) === Number(resting.characterId))
416 { continue; }
417
418 const buy = resting.side === "buy" ? resting : liveOther;
419 const sell = resting.side === "sell" ? resting : liveOther;
420 if (buy.limitUnitPrice < sell.limitUnitPrice)
421 { continue; }
422
423 let fillQty = Math.min(buy.quantity, sell.quantity);
424 if (isFilledChequeEscrow(sell.escrowStack))
425 {
426 // Written cheques list as one indivisible lot.
427 if (fillQty < sell.quantity)
428 { continue; }
429 fillQty = sell.quantity;
430 }
431 if (fillQty <= 0)
432 { continue; }
433 const unitPrice = midpointTradePrice(buy.limitUnitPrice, sell.limitUnitPrice);
434 const tradeEvents = this.#settleMatch({
435 buy,
436 sell,
437 fillQty,
438 unitPrice,
439 triggeringSide: resting.side,
440 now
441 });
442 events.push(...tradeEvents);
443 }
444 return events;
445 }
446
447 #settleMatch ({ buy, sell, fillQty, unitPrice, triggeringSide, now })
448 {
449 const events = [];
450 const total = unitPrice * fillQty;
451 const itemName = itemDefinition(sell.itemId)?.displayName ?? "item";
452 const clerk = pickExchangeClerk();
453 const chequeEscrow = isFilledChequeEscrow(sell.escrowStack);
454
455 let goods;
456 let sellRemainOrigins = null;
457 if (chequeEscrow)
458 {
459 goods = this.#redeemSellChequeEscrow(sell.escrowStack);
460 if ((goods.quantity | 0) !== fillQty || (goods.itemId | 0) !== (sell.itemId | 0))
461 { throw userError("That cheque listing could not be settled."); }
462 }
463 else
464 {
465 const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty);
466 goods = attachOrigins({
467 itemId: sell.itemId,
468 quantity: fillQty,
469 origins: sellSplit.taken,
470 instance: sell.escrowStack?.instance ?? null
471 });
472 sellRemainOrigins = sellSplit.remain;
473 }
474
475 const buyRefund = (buy.limitUnitPrice - unitPrice) * fillQty;
476 const buyRemainingQty = buy.quantity - fillQty;
477 const sellRemainingQty = chequeEscrow ? 0 : sell.quantity - fillQty;
478
479 withTransaction(this.stateDb.db, () =>
480 {
481 this.stateDb.insertMarketTrade({
482 buyOrderId: buy.orderId,
483 sellOrderId: sell.orderId,
484 itemId: sell.itemId,
485 quantity: fillQty,
486 unitPrice,
487 buyerCharacterId: buy.characterId,
488 sellerCharacterId: sell.characterId,
489 createdAt: now
490 });
491
492 this.stateDb.updateMarketOrder({
493 ...buy,
494 quantity: buyRemainingQty,
495 escrowCoins: buy.limitUnitPrice * buyRemainingQty,
496 status: buyRemainingQty > 0 ? "open" : "filled"
497 });
498 this.stateDb.updateMarketOrder({
499 ...sell,
500 quantity: sellRemainingQty,
501 escrowStack: sellRemainingQty > 0
502 ? attachOrigins({
503 ...sell.escrowStack,
504 quantity: sellRemainingQty,
505 origins: sellRemainOrigins
506 })
507 : null,
508 status: sellRemainingQty > 0 ? "open" : "filled"
509 });
510 });
511
512 this.#recordLastSale(sell.itemId, unitPrice, now);
513
514 const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
515
516 if (triggeringSide === "buy")
517 {
518 this.#grantImmediate(buy.characterId, goods);
519 if (buyRefund > 0)
520 { this.#grantImmediateCoins(buy.characterId, buyRefund); }
521 this.#dispatchBankCargo(sell.characterId, origin, { kind: "money", amount: total });
522 this.#dispatchBankLetter(sell.characterId, origin, soldLetterBody({
523 itemName,
524 quantity: fillQty,
525 unitPrice,
526 clerkName: clerk
527 }), clerk);
528 }
529 else
530 {
531 this.#grantImmediateCoins(sell.characterId, total);
532 this.#dispatchBankCargo(buy.characterId, origin, { kind: "item", stack: goods });
533 if (buyRefund > 0)
534 { this.#dispatchBankCargo(buy.characterId, origin, { kind: "money", amount: buyRefund }); }
535 this.#dispatchBankLetter(buy.characterId, origin, buyFilledLetterBody({
536 itemName,
537 quantity: fillQty,
538 unitPrice,
539 clerkName: clerk
540 }), clerk);
541 }
542
543 events.push({
544 type: "market-trade",
545 itemId: sell.itemId,
546 quantity: fillQty,
547 unitPrice,
548 buyerCharacterId: buy.characterId,
549 sellerCharacterId: sell.characterId,
550 triggeringSide
551 });
552 return events;
553 }
554
555 /** Redeem a written-cheque sell escrow into the reserved goods stack. */
556 #redeemSellChequeEscrow (chequeStack)
557 {
558 const instance = chequeStack?.instance;
559 if (!instance || instance.kind !== "filled-cheque")
560 { throw userError("That cheque listing is invalid."); }
561 const issuerId = instance.issuerCharacterId | 0;
562 const release = this.simulation.releaseChequeReservation?.(issuerId, instance.chequeId, instance);
563 if (!release?.ok || !release.stack)
564 { throw userError(release?.error ?? "That cheque cannot be redeemed."); }
565 return attachOrigins(release.stack);
566 }
567
568 /**
569 * Charge coins (and whole coin-cheques) for escrow/fees. Mutates bag.inventory.
570 * Releases reservations for redeemed coin cheques.
571 */
572 #payMarketFunds (bag, payerCharacterId, amount)
573 {
574 const need = Math.max(0, amount | 0);
575 if (!need)
576 { return { ok: true }; }
577 const paid = takeMarketFunds(bag.inventory, need);
578 if (!paid.ok)
579 { return { ok: false }; }
580 bag.inventory = paid.slots;
581 for (const cheque of paid.redeemedCheques ?? [])
582 {
583 const instance = cheque.instance;
584 const issuerId = instance?.issuerCharacterId | 0;
585 const release = this.simulation.releaseChequeReservation?.(
586 issuerId,
587 instance.chequeId,
588 instance
589 );
590 if (!release?.ok)
591 {
592 // Restore cheque paper; leave other payments as-is (best-effort).
593 const restored = insertStack(bag.inventory, cheque, itemDefinition(ItemId.filledCheque));
594 bag.inventory = restored.slots;
595 return { ok: false };
596 }
597 }
598 if ((paid.change | 0) > 0)
599 {
600 const refunded = addCoinsToSlots(bag.inventory, paid.change | 0, { growable: false });
601 if (!refunded.ok)
602 {
603 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
604 const vaultPaid = addCoinsToSlots(vault.slots, paid.change | 0, { growable: true });
605 bag.inventory = refunded.slots;
606 bag.vault = vaultPaid.slots;
607 bag.vaultReserved = vault.reserved;
608 }
609 else
610 { bag.inventory = refunded.slots; }
611 }
612 void payerCharacterId;
613 return { ok: true };
614 }
615
616 #returnEscrowByPigeon (order, { letterBody, clerkName = null, now })
617 {
618 const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
619 if (order.side === "buy" && (order.escrowCoins | 0) > 0)
620 {
621 this.#dispatchBankCargo(order.characterId, origin, {
622 kind: "money",
623 amount: order.escrowCoins | 0
624 });
625 }
626 if (order.side === "sell" && order.escrowStack && (order.escrowStack.quantity | 0) > 0)
627 {
628 this.#dispatchBankCargo(order.characterId, origin, {
629 kind: "item",
630 stack: cloneStack(order.escrowStack)
631 });
632 }
633 this.#dispatchBankLetter(order.characterId, origin, letterBody, clerkName);
634 void now;
635 }
636
637 #dispatchBankLetter (characterId, origin, body, clerkName = null)
638 {
639 const trimmed = String(body ?? "").replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
640 const name = String(clerkName || pickExchangeClerk()).trim() || pickExchangeClerk();
641 const stack = attachOrigins({
642 itemId: ItemId.letter,
643 quantity: 1,
644 origins: [{ origin: writtenOrigin(name), quantity: 1 }],
645 instance: {
646 kind: "letter",
647 letterId: randomUUID(),
648 authorCharacterId: 0,
649 authorDisplayName: name,
650 authorOrganization: CENTRAL_EXCHANGE_ORG,
651 centralExchange: true,
652 body: trimmed,
653 opened: false,
654 writtenAt: Date.now()
655 }
656 });
657 this.simulation.courier.dispatchSystemLetter({
658 characterId,
659 originTileX: origin.tileX,
660 originTileY: origin.tileY,
661 stack
662 });
663 }
664
665 #dispatchBankCargo (characterId, origin, cargo)
666 {
667 this.simulation.courier.dispatchHeldCargo({
668 senderCharacterId: characterId,
669 originTileX: origin.tileX,
670 originTileY: origin.tileY,
671 destination: { kind: "bank" },
672 cargo
673 });
674 }
675
676 #grantImmediate (characterId, stack)
677 {
678 const bag = this.#loadBag(characterId);
679 const def = itemDefinition(stack.itemId);
680 const inserted = insertStack(bag.inventory ?? [], stack, def);
681 bag.inventory = inserted.slots;
682 if (inserted.remainder > 0)
683 {
684 const overflow = attachOrigins({
685 ...stack,
686 quantity: inserted.remainder,
687 origins: splitOrigins(normalizeOrigins(stack), stack.quantity - inserted.remainder).remain
688 });
689 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
690 const vaulted = insertStackGrowable(vault.slots, overflow, def);
691 bag.vault = vaulted.slots;
692 bag.vaultReserved = vault.reserved;
693 }
694 this.#persistBag(characterId, bag);
695 }
696
697 #grantImmediateCoins (characterId, amount)
698 {
699 const qty = Math.max(0, amount | 0);
700 if (qty <= 0)
701 { return; }
702 const bag = this.#loadBag(characterId);
703 const paid = addCoinsToSlots(bag.inventory ?? [], qty, { growable: false });
704 if (paid.ok && (paid.remainder | 0) === 0)
705 {
706 bag.inventory = paid.slots;
707 this.#persistBag(characterId, bag);
708 return;
709 }
710 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
711 const withInv = paid.ok ? paid.slots : bag.inventory;
712 const remainder = paid.ok ? (paid.remainder | 0) : qty;
713 bag.inventory = withInv;
714 const vaultPaid = addCoinsToSlots(vault.slots, remainder, { growable: true });
715 bag.vault = vaultPaid.slots;
716 bag.vaultReserved = vault.reserved;
717 this.#persistBag(characterId, bag);
718 }
719
720 #recordLastSale (itemId, unitPrice, now)
721 {
722 const previous = this.lastSales.get(itemId | 0) ?? null;
723 const priceFrom = undiscountedMarketValue(
724 itemId,
725 previous,
726 now,
727 this.simulation.settings?.shopPriceLerpDurationMs,
728 this.simulation.settings
729 );
730 const sale = {
731 itemId: itemId | 0,
732 lastTradePrice: unitPrice,
733 lastTradeAt: now,
734 priceFrom
735 };
736 this.lastSales.set(itemId | 0, sale);
737 this.stateDb.upsertItemLastSale(sale);
738 this.#syncLastSalesToWorkers();
739 }
740
741 #loadLastSales ()
742 {
743 for (const sale of this.stateDb.listItemLastSales())
744 { this.lastSales.set(sale.itemId | 0, sale); }
745 }
746
747 #syncLastSalesToWorkers ()
748 {
749 this.simulation.syncItemLastSales?.(this.lastSales);
750 }
751
752 #requireAtMarket (characterId)
753 {
754 const entityId = this.simulation.characterEntities.get(characterId);
755 const position = entityId ? this.simulation.positionOf(entityId) : null;
756 if (!position)
757 { throw userError("Enter the world before using the Central Exchange."); }
758 if (!this.marketTiles.length)
759 { throw userError("The Central Exchange is not open in this world yet."); }
760 const near = this.marketTiles.some((tile) =>
761 chebyshev(position.tileX, position.tileY, tile.tileX, tile.tileY) <= 1);
762 if (!near)
763 { throw userError("Stand next to the Central Exchange counter."); }
764 return { position, entityId };
765 }
766
767 #stationTargetsForPlayer (tileX, tileY)
768 {
769 const targets = [];
770 for (const tile of this.marketTiles)
771 {
772 if (chebyshev(tileX, tileY, tile.tileX, tile.tileY) > 1)
773 { continue; }
774 if (tile.tileX === tileX && tile.tileY === tileY)
775 { continue; }
776 const stationTileX = tile.tileX + (tile.tileX - tileX);
777 const stationTileY = tile.tileY + (tile.tileY - tileY);
778 if (stationTileX === tileX && stationTileY === tileY)
779 { continue; }
780 targets.push({
781 marketTileX: tile.tileX,
782 marketTileY: tile.tileY,
783 stationTileX,
784 stationTileY
785 });
786 }
787 return targets;
788 }
789
790 #stationKey (stationTileX, stationTileY)
791 {
792 return `${stationTileX | 0},${stationTileY | 0}`;
793 }
794
795 #attendStations (sessionId, characterId, tileX, tileY)
796 {
797 const id = characterId | 0;
798 for (const target of this.#stationTargetsForPlayer(tileX, tileY))
799 {
800 const key = this.#stationKey(target.stationTileX, target.stationTileY);
801 let entry = this.stationAttendance.get(key);
802 if (!entry)
803 {
804 entry = {
805 stationTileX: target.stationTileX,
806 stationTileY: target.stationTileY,
807 marketTileX: target.marketTileX,
808 marketTileY: target.marketTileY,
809 browsers: new Map()
810 };
811 this.stationAttendance.set(key, entry);
812 }
813 entry.browsers.set(id, sessionId);
814 entry.marketTileX = target.marketTileX;
815 entry.marketTileY = target.marketTileY;
816 this.simulation.stationExchangeClerk?.(target.stationTileX, target.stationTileY);
817 }
818 }
819
820 #characterStillAttending (characterId)
821 {
822 const id = characterId | 0;
823 for (const entry of this.stationAttendance.values())
824 {
825 if (entry.browsers.has(id))
826 { return true; }
827 }
828 return false;
829 }
830
831 #stillAtMarketCounter (characterId, marketTileX, marketTileY)
832 {
833 const entityId = this.simulation.characterEntities.get(characterId);
834 const position = entityId ? this.simulation.positionOf(entityId) : null;
835 if (!position)
836 { return false; }
837 return chebyshev(position.tileX, position.tileY, marketTileX, marketTileY) <= 1;
838 }
839
840 #releaseStation (key)
841 {
842 const entry = this.stationAttendance.get(key);
843 if (!entry)
844 { return; }
845 this.stationAttendance.delete(key);
846 this.simulation.releaseExchangeClerk?.(entry.stationTileX, entry.stationTileY);
847 }
848
849 /**
850 * Drop browsers who walked away from their counter; release clerks when a
851 * staff station has no remaining players.
852 */
853 #pruneStationAttendance ()
854 {
855 const events = [];
856 /** @type {Map<number, number>} characterId → sessionId */
857 const departed = new Map();
858 const emptyStations = [];
859 for (const [key, entry] of this.stationAttendance.entries())
860 {
861 for (const [characterId, sessionId] of [...entry.browsers.entries()])
862 {
863 if (this.#stillAtMarketCounter(characterId, entry.marketTileX, entry.marketTileY))
864 { continue; }
865 entry.browsers.delete(characterId);
866 departed.set(characterId, sessionId);
867 }
868 if (entry.browsers.size === 0)
869 { emptyStations.push(key); }
870 }
871 for (const key of emptyStations)
872 { this.#releaseStation(key); }
873 for (const [characterId, sessionId] of departed.entries())
874 {
875 if (this.#characterStillAttending(characterId))
876 { continue; }
877 events.push({ type: "market-closed", sessionId, characterId });
878 }
879 return events;
880 }
881
882 #marketOpenEvent (sessionId, characterId, position, now)
883 {
884 const orders = this.stateDb.listOpenMarketOrdersForCharacter(characterId).map((order) => ({
885 orderId: order.orderId,
886 side: order.side,
887 itemId: order.itemId,
888 displayName: itemDefinition(order.itemId)?.displayName ?? `Item ${order.itemId}`,
889 quantity: order.quantity,
890 limitUnitPrice: order.limitUnitPrice,
891 createdAt: order.createdAt
892 }));
893 const catalog = [];
894 for (const def of Object.values(ITEM_DEFINITIONS))
895 {
896 if (!canSellOnMarketplace({ itemId: def.itemId, quantity: 1 }))
897 { continue; }
898 if (def.itemId === ItemId.coins)
899 { continue; }
900 catalog.push({
901 itemId: def.itemId,
902 displayName: def.displayName,
903 hintPrice: undiscountedMarketValue(
904 def.itemId,
905 this.lastSaleFor(def.itemId),
906 now,
907 this.simulation.settings?.shopPriceLerpDurationMs,
908 this.simulation.settings
909 )
910 });
911 }
912 catalog.sort((a, b) => a.displayName.localeCompare(b.displayName));
913 return {
914 type: "market-open",
915 sessionId,
916 characterId,
917 displayName: "Central Exchange",
918 orders,
919 catalog,
920 tileX: position.tileX,
921 tileY: position.tileY
922 };
923 }
924
925 #loadBag (characterId)
926 {
927 const onlineId = this.simulation.characterEntities.get(characterId);
928 const bag = onlineId
929 ? this.simulation.bagOf(onlineId)
930 : this.stateDb.getBag(characterId);
931 if (!bag)
932 { throw userError("No bag."); }
933 return bag;
934 }
935
936 #persistBag (characterId, bag)
937 {
938 this.stateDb.saveBag(characterId, bag);
939 const onlineId = this.simulation.characterEntities.get(characterId);
940 if (onlineId)
941 {
942 this.simulation.applyBag(onlineId, bag);
943 this.simulation.pushInventory(characterId, bag);
944 }
945 }
946}