BlueGit

timfa questward

Files

questward / server / src / market / service.js

service.js

service.js 26.9 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, undiscountedMarketCoins } 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 /** Keep CE attendance open but route private events to a new gateway session. */
210 reattachSession (characterId, sessionId)
211 {
212 const id = characterId | 0;
213 for (const entry of this.stationAttendance.values())
214 {
215 if (entry.browsers.has(id))
216 { entry.browsers.set(id, sessionId); }
217 }
218 }
219
220 placeSellOrder (sessionId, characterId, slotIndex, quantity, minUnitPrice, now = Date.now())
221 {
222 const { position } = this.#requireAtMarket(characterId);
223 const minPrice = Math.max(1, minUnitPrice | 0);
224 const bag = this.#loadBag(characterId);
225 const slot = bag.inventory?.[slotIndex];
226 if (!slot)
227 { throw userError("That slot is empty."); }
228 assertMarketplaceSellable(slot, characterId);
229 if ((slot.itemId | 0) === ItemId.coins)
230 { throw userError("Coins cannot be listed on the marketplace."); }
231
232 const listing = resolveMarketSellListing(slot);
233 if (!listing)
234 { throw userError("That item cannot be sold on the marketplace."); }
235
236 let escrowStack;
237 let orderQty;
238 if (listing.isCheque)
239 {
240 orderQty = listing.quantity;
241 const taken = takeFromSlot(bag.inventory, slotIndex, 1);
242 if (!taken.ok || !taken.taken)
243 { throw userError("That cheque is not available."); }
244 bag.inventory = taken.slots;
245 escrowStack = attachOrigins(taken.taken);
246 }
247 else
248 {
249 const qty = Math.max(1, Math.min(quantity | 0 || 1, listing.quantity));
250 orderQty = qty;
251 const taken = takeFromSlot(bag.inventory, slotIndex, qty);
252 if (!taken.ok || !taken.taken)
253 { throw userError("That item is not available."); }
254 bag.inventory = taken.slots;
255 escrowStack = attachOrigins(taken.taken);
256 }
257
258 const fee = marketOrderListingFee(minPrice, orderQty);
259 const paid = this.#payMarketFunds(bag, characterId, fee);
260 if (!paid.ok)
261 {
262 const restored = insertStack(
263 bag.inventory,
264 escrowStack,
265 itemDefinition(escrowStack.itemId)
266 );
267 bag.inventory = restored.slots;
268 throw userError(
269 fee > 0
270 ? `You need ${fee} coins for the listing fee.`
271 : "You cannot afford the listing fee."
272 );
273 }
274
275 const order = this.stateDb.insertMarketOrder({
276 characterId,
277 side: "sell",
278 itemId: listing.itemId,
279 quantity: orderQty,
280 limitUnitPrice: minPrice,
281 escrowCoins: 0,
282 escrowStack,
283 createdAt: now,
284 status: "open"
285 });
286 this.#persistBag(characterId, bag);
287 const matchEvents = this.#matchAfterInsert(order, now);
288 return {
289 events: [
290 this.#marketOpenEvent(sessionId, characterId, position, now),
291 ...matchEvents
292 ]
293 };
294 }
295
296 placeBuyOrder (sessionId, characterId, itemId, quantity, maxUnitPrice, now = Date.now())
297 {
298 const { position } = this.#requireAtMarket(characterId);
299 const maxPrice = Math.max(1, maxUnitPrice | 0);
300 const qty = Math.max(1, quantity | 0 || 1);
301 const def = itemDefinition(itemId);
302 if (!def || !canSellOnMarketplace({ itemId, quantity: 1 }))
303 { throw userError("That item cannot be bought on the marketplace."); }
304 if ((itemId | 0) === ItemId.coins)
305 { throw userError("Coins cannot be ordered on the marketplace."); }
306 const escrow = maxPrice * qty;
307 const fee = marketOrderListingFee(maxPrice, qty);
308 const bag = this.#loadBag(characterId);
309 const paid = this.#payMarketFunds(bag, characterId, escrow + fee);
310 if (!paid.ok)
311 {
312 throw userError(
313 `You need ${escrow + fee} coins (escrow ${escrow} + ${fee} listing fee).`
314 );
315 }
316 const order = this.stateDb.insertMarketOrder({
317 characterId,
318 side: "buy",
319 itemId: itemId | 0,
320 quantity: qty,
321 limitUnitPrice: maxPrice,
322 escrowCoins: escrow,
323 escrowStack: null,
324 createdAt: now,
325 status: "open"
326 });
327 this.#persistBag(characterId, bag);
328 const matchEvents = this.#matchAfterInsert(order, now);
329 return {
330 events: [
331 this.#marketOpenEvent(sessionId, characterId, position, now),
332 ...matchEvents
333 ]
334 };
335 }
336
337 cancelOrder (sessionId, characterId, orderId, now = Date.now())
338 {
339 const { position } = this.#requireAtMarket(characterId);
340 const order = this.stateDb.getMarketOrder(orderId);
341 if (!order || order.status !== "open")
342 { throw userError("That order is no longer open."); }
343 if (Number(order.characterId) !== Number(characterId))
344 { throw userError("That is not your order."); }
345 const clerkName = pickExchangeClerk();
346 this.#returnEscrowByPigeon(order, {
347 letterBody: orderCancelledLetterBody({
348 side: order.side,
349 itemName: itemDefinition(order.itemId)?.displayName ?? "item",
350 quantity: order.quantity,
351 escrowLabel: order.side === "buy"
352 ? "coins"
353 : (isFilledChequeEscrow(order.escrowStack)
354 ? "written cheque"
355 : (itemDefinition(order.itemId)?.displayName ?? "item")),
356 clerkName
357 }),
358 clerkName,
359 now
360 });
361 this.stateDb.updateMarketOrder({
362 ...order,
363 status: "cancelled",
364 quantity: 0,
365 escrowCoins: 0,
366 escrowStack: null
367 });
368 return {
369 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
370 };
371 }
372
373 #expireOrder (order, now)
374 {
375 const events = [];
376 const clerkName = pickExchangeClerk();
377 this.#returnEscrowByPigeon(order, {
378 letterBody: orderExpiredLetterBody({
379 side: order.side,
380 itemName: itemDefinition(order.itemId)?.displayName ?? "item",
381 quantity: order.quantity,
382 escrowLabel: order.side === "buy"
383 ? "coins"
384 : (isFilledChequeEscrow(order.escrowStack)
385 ? "written cheque"
386 : (itemDefinition(order.itemId)?.displayName ?? "item")),
387 clerkName
388 }),
389 clerkName,
390 now
391 });
392 this.stateDb.updateMarketOrder({
393 ...order,
394 status: "cancelled",
395 quantity: 0,
396 escrowCoins: 0,
397 escrowStack: null
398 });
399 events.push({
400 type: "market-order-expired",
401 orderId: order.orderId,
402 characterId: order.characterId
403 });
404 return events;
405 }
406
407 #matchAfterInsert (incoming, now)
408 {
409 const events = [];
410 let resting = this.stateDb.getMarketOrder(incoming.orderId);
411 if (!resting || resting.status !== "open")
412 { return events; }
413
414 const counterparts = resting.side === "sell"
415 ? this.stateDb.listOpenBuyOrdersForItem(resting.itemId)
416 : this.stateDb.listOpenSellOrdersForItem(resting.itemId);
417
418 for (const other of counterparts)
419 {
420 resting = this.stateDb.getMarketOrder(resting.orderId);
421 if (!resting || resting.status !== "open" || resting.quantity <= 0)
422 { break; }
423 const liveOther = this.stateDb.getMarketOrder(other.orderId);
424 if (!liveOther || liveOther.status !== "open" || liveOther.quantity <= 0)
425 { continue; }
426 if (Number(liveOther.characterId) === Number(resting.characterId))
427 { continue; }
428
429 const buy = resting.side === "buy" ? resting : liveOther;
430 const sell = resting.side === "sell" ? resting : liveOther;
431 if (buy.limitUnitPrice < sell.limitUnitPrice)
432 { continue; }
433
434 let fillQty = Math.min(buy.quantity, sell.quantity);
435 if (isFilledChequeEscrow(sell.escrowStack))
436 {
437 // Written cheques list as one indivisible lot.
438 if (fillQty < sell.quantity)
439 { continue; }
440 fillQty = sell.quantity;
441 }
442 if (fillQty <= 0)
443 { continue; }
444 const unitPrice = midpointTradePrice(buy.limitUnitPrice, sell.limitUnitPrice);
445 const tradeEvents = this.#settleMatch({
446 buy,
447 sell,
448 fillQty,
449 unitPrice,
450 triggeringSide: resting.side,
451 now
452 });
453 events.push(...tradeEvents);
454 }
455 return events;
456 }
457
458 #settleMatch ({ buy, sell, fillQty, unitPrice, triggeringSide, now })
459 {
460 const events = [];
461 const total = unitPrice * fillQty;
462 const itemName = itemDefinition(sell.itemId)?.displayName ?? "item";
463 const clerk = pickExchangeClerk();
464 const chequeEscrow = isFilledChequeEscrow(sell.escrowStack);
465
466 let goods;
467 let sellRemainOrigins = null;
468 if (chequeEscrow)
469 {
470 goods = this.#redeemSellChequeEscrow(sell.escrowStack);
471 if ((goods.quantity | 0) !== fillQty || (goods.itemId | 0) !== (sell.itemId | 0))
472 { throw userError("That cheque listing could not be settled."); }
473 }
474 else
475 {
476 const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty);
477 goods = attachOrigins({
478 itemId: sell.itemId,
479 quantity: fillQty,
480 origins: sellSplit.taken,
481 instance: sell.escrowStack?.instance ?? null
482 });
483 sellRemainOrigins = sellSplit.remain;
484 }
485
486 const buyRefund = (buy.limitUnitPrice - unitPrice) * fillQty;
487 const buyRemainingQty = buy.quantity - fillQty;
488 const sellRemainingQty = chequeEscrow ? 0 : sell.quantity - fillQty;
489
490 withTransaction(this.stateDb.db, () =>
491 {
492 this.stateDb.insertMarketTrade({
493 buyOrderId: buy.orderId,
494 sellOrderId: sell.orderId,
495 itemId: sell.itemId,
496 quantity: fillQty,
497 unitPrice,
498 buyerCharacterId: buy.characterId,
499 sellerCharacterId: sell.characterId,
500 createdAt: now
501 });
502
503 this.stateDb.updateMarketOrder({
504 ...buy,
505 quantity: buyRemainingQty,
506 escrowCoins: buy.limitUnitPrice * buyRemainingQty,
507 status: buyRemainingQty > 0 ? "open" : "filled"
508 });
509 this.stateDb.updateMarketOrder({
510 ...sell,
511 quantity: sellRemainingQty,
512 escrowStack: sellRemainingQty > 0
513 ? attachOrigins({
514 ...sell.escrowStack,
515 quantity: sellRemainingQty,
516 origins: sellRemainOrigins
517 })
518 : null,
519 status: sellRemainingQty > 0 ? "open" : "filled"
520 });
521 });
522
523 this.#recordLastSale(sell.itemId, unitPrice, now);
524
525 const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
526
527 if (triggeringSide === "buy")
528 {
529 this.#grantImmediate(buy.characterId, goods);
530 if (buyRefund > 0)
531 { this.#grantImmediateCoins(buy.characterId, buyRefund); }
532 this.#dispatchBankCargo(sell.characterId, origin, { kind: "money", amount: total });
533 this.#dispatchBankLetter(sell.characterId, origin, soldLetterBody({
534 itemName,
535 quantity: fillQty,
536 unitPrice,
537 clerkName: clerk
538 }), clerk);
539 }
540 else
541 {
542 this.#grantImmediateCoins(sell.characterId, total);
543 this.#dispatchBankCargo(buy.characterId, origin, { kind: "item", stack: goods });
544 if (buyRefund > 0)
545 { this.#dispatchBankCargo(buy.characterId, origin, { kind: "money", amount: buyRefund }); }
546 this.#dispatchBankLetter(buy.characterId, origin, buyFilledLetterBody({
547 itemName,
548 quantity: fillQty,
549 unitPrice,
550 clerkName: clerk
551 }), clerk);
552 }
553
554 events.push({
555 type: "market-trade",
556 itemId: sell.itemId,
557 quantity: fillQty,
558 unitPrice,
559 buyerCharacterId: buy.characterId,
560 sellerCharacterId: sell.characterId,
561 triggeringSide
562 });
563 return events;
564 }
565
566 /** Redeem a written-cheque sell escrow into the reserved goods stack. */
567 #redeemSellChequeEscrow (chequeStack)
568 {
569 const instance = chequeStack?.instance;
570 if (!instance || instance.kind !== "filled-cheque")
571 { throw userError("That cheque listing is invalid."); }
572 const issuerId = instance.issuerCharacterId | 0;
573 const release = this.simulation.releaseChequeReservation?.(issuerId, instance.chequeId, instance);
574 if (!release?.ok || !release.stack)
575 { throw userError(release?.error ?? "That cheque cannot be redeemed."); }
576 return attachOrigins(release.stack);
577 }
578
579 /**
580 * Charge coins (and whole coin-cheques) for escrow/fees. Mutates bag.inventory.
581 * Releases reservations for redeemed coin cheques.
582 */
583 #payMarketFunds (bag, payerCharacterId, amount)
584 {
585 const need = Math.max(0, amount | 0);
586 if (!need)
587 { return { ok: true }; }
588 const paid = takeMarketFunds(bag.inventory, need);
589 if (!paid.ok)
590 { return { ok: false }; }
591 bag.inventory = paid.slots;
592 for (const cheque of paid.redeemedCheques ?? [])
593 {
594 const instance = cheque.instance;
595 const issuerId = instance?.issuerCharacterId | 0;
596 const release = this.simulation.releaseChequeReservation?.(
597 issuerId,
598 instance.chequeId,
599 instance
600 );
601 if (!release?.ok)
602 {
603 // Restore cheque paper; leave other payments as-is (best-effort).
604 const restored = insertStack(bag.inventory, cheque, itemDefinition(ItemId.filledCheque));
605 bag.inventory = restored.slots;
606 return { ok: false };
607 }
608 }
609 if ((paid.change | 0) > 0)
610 {
611 const refunded = addCoinsToSlots(bag.inventory, paid.change | 0, { growable: false });
612 if (!refunded.ok)
613 {
614 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
615 const vaultPaid = addCoinsToSlots(vault.slots, paid.change | 0, { growable: true });
616 bag.inventory = refunded.slots;
617 bag.vault = vaultPaid.slots;
618 bag.vaultReserved = vault.reserved;
619 }
620 else
621 { bag.inventory = refunded.slots; }
622 }
623 void payerCharacterId;
624 return { ok: true };
625 }
626
627 #returnEscrowByPigeon (order, { letterBody, clerkName = null, now })
628 {
629 const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
630 if (order.side === "buy" && (order.escrowCoins | 0) > 0)
631 {
632 this.#dispatchBankCargo(order.characterId, origin, {
633 kind: "money",
634 amount: order.escrowCoins | 0
635 });
636 }
637 if (order.side === "sell" && order.escrowStack && (order.escrowStack.quantity | 0) > 0)
638 {
639 this.#dispatchBankCargo(order.characterId, origin, {
640 kind: "item",
641 stack: cloneStack(order.escrowStack)
642 });
643 }
644 this.#dispatchBankLetter(order.characterId, origin, letterBody, clerkName);
645 void now;
646 }
647
648 #dispatchBankLetter (characterId, origin, body, clerkName = null)
649 {
650 const trimmed = String(body ?? "").replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
651 const name = String(clerkName || pickExchangeClerk()).trim() || pickExchangeClerk();
652 const stack = attachOrigins({
653 itemId: ItemId.letter,
654 quantity: 1,
655 origins: [{ origin: writtenOrigin(name), quantity: 1 }],
656 instance: {
657 kind: "letter",
658 letterId: randomUUID(),
659 authorCharacterId: 0,
660 authorDisplayName: name,
661 authorOrganization: CENTRAL_EXCHANGE_ORG,
662 centralExchange: true,
663 body: trimmed,
664 opened: false,
665 writtenAt: Date.now()
666 }
667 });
668 this.simulation.courier.dispatchSystemLetter({
669 characterId,
670 originTileX: origin.tileX,
671 originTileY: origin.tileY,
672 stack
673 });
674 }
675
676 #dispatchBankCargo (characterId, origin, cargo)
677 {
678 this.simulation.courier.dispatchHeldCargo({
679 senderCharacterId: characterId,
680 originTileX: origin.tileX,
681 originTileY: origin.tileY,
682 destination: { kind: "bank" },
683 cargo
684 });
685 }
686
687 #grantImmediate (characterId, stack)
688 {
689 const bag = this.#loadBag(characterId);
690 const def = itemDefinition(stack.itemId);
691 const inserted = insertStack(bag.inventory ?? [], stack, def);
692 bag.inventory = inserted.slots;
693 if (inserted.remainder > 0)
694 {
695 const overflow = attachOrigins({
696 ...stack,
697 quantity: inserted.remainder,
698 origins: splitOrigins(normalizeOrigins(stack), stack.quantity - inserted.remainder).remain
699 });
700 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
701 const vaulted = insertStackGrowable(vault.slots, overflow, def);
702 bag.vault = vaulted.slots;
703 bag.vaultReserved = vault.reserved;
704 }
705 this.#persistBag(characterId, bag);
706 }
707
708 #grantImmediateCoins (characterId, amount)
709 {
710 const qty = Math.max(0, amount | 0);
711 if (qty <= 0)
712 { return; }
713 const bag = this.#loadBag(characterId);
714 const paid = addCoinsToSlots(bag.inventory ?? [], qty, { growable: false });
715 if (paid.ok && (paid.remainder | 0) === 0)
716 {
717 bag.inventory = paid.slots;
718 this.#persistBag(characterId, bag);
719 return;
720 }
721 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
722 const withInv = paid.ok ? paid.slots : bag.inventory;
723 const remainder = paid.ok ? (paid.remainder | 0) : qty;
724 bag.inventory = withInv;
725 const vaultPaid = addCoinsToSlots(vault.slots, remainder, { growable: true });
726 bag.vault = vaultPaid.slots;
727 bag.vaultReserved = vault.reserved;
728 this.#persistBag(characterId, bag);
729 }
730
731 #recordLastSale (itemId, unitPrice, now)
732 {
733 const previous = this.lastSales.get(itemId | 0) ?? null;
734 const priceFrom = undiscountedMarketValue(
735 itemId,
736 previous,
737 now,
738 this.simulation.settings?.shopPriceLerpDurationMs,
739 this.simulation.settings
740 );
741 const sale = {
742 itemId: itemId | 0,
743 lastTradePrice: unitPrice,
744 lastTradeAt: now,
745 priceFrom
746 };
747 this.lastSales.set(itemId | 0, sale);
748 this.stateDb.upsertItemLastSale(sale);
749 this.#syncLastSalesToWorkers();
750 }
751
752 #loadLastSales ()
753 {
754 for (const sale of this.stateDb.listItemLastSales())
755 { this.lastSales.set(sale.itemId | 0, sale); }
756 }
757
758 #syncLastSalesToWorkers ()
759 {
760 this.simulation.syncItemLastSales?.(this.lastSales);
761 }
762
763 #requireAtMarket (characterId)
764 {
765 const entityId = this.simulation.characterEntities.get(characterId);
766 const position = entityId ? this.simulation.positionOf(entityId) : null;
767 if (!position)
768 { throw userError("Enter the world before using the Central Exchange."); }
769 if (!this.marketTiles.length)
770 { throw userError("The Central Exchange is not open in this world yet."); }
771 const near = this.marketTiles.some((tile) =>
772 chebyshev(position.tileX, position.tileY, tile.tileX, tile.tileY) <= 1);
773 if (!near)
774 { throw userError("Stand next to the Central Exchange counter."); }
775 return { position, entityId };
776 }
777
778 #stationTargetsForPlayer (tileX, tileY)
779 {
780 const targets = [];
781 for (const tile of this.marketTiles)
782 {
783 if (chebyshev(tileX, tileY, tile.tileX, tile.tileY) > 1)
784 { continue; }
785 if (tile.tileX === tileX && tile.tileY === tileY)
786 { continue; }
787 const stationTileX = tile.tileX + (tile.tileX - tileX);
788 const stationTileY = tile.tileY + (tile.tileY - tileY);
789 if (stationTileX === tileX && stationTileY === tileY)
790 { continue; }
791 targets.push({
792 marketTileX: tile.tileX,
793 marketTileY: tile.tileY,
794 stationTileX,
795 stationTileY
796 });
797 }
798 return targets;
799 }
800
801 #stationKey (stationTileX, stationTileY)
802 {
803 return `${stationTileX | 0},${stationTileY | 0}`;
804 }
805
806 #attendStations (sessionId, characterId, tileX, tileY)
807 {
808 const id = characterId | 0;
809 for (const target of this.#stationTargetsForPlayer(tileX, tileY))
810 {
811 const key = this.#stationKey(target.stationTileX, target.stationTileY);
812 let entry = this.stationAttendance.get(key);
813 if (!entry)
814 {
815 entry = {
816 stationTileX: target.stationTileX,
817 stationTileY: target.stationTileY,
818 marketTileX: target.marketTileX,
819 marketTileY: target.marketTileY,
820 browsers: new Map()
821 };
822 this.stationAttendance.set(key, entry);
823 }
824 entry.browsers.set(id, sessionId);
825 entry.marketTileX = target.marketTileX;
826 entry.marketTileY = target.marketTileY;
827 this.simulation.stationExchangeClerk?.(target.stationTileX, target.stationTileY);
828 }
829 }
830
831 #characterStillAttending (characterId)
832 {
833 const id = characterId | 0;
834 for (const entry of this.stationAttendance.values())
835 {
836 if (entry.browsers.has(id))
837 { return true; }
838 }
839 return false;
840 }
841
842 #stillAtMarketCounter (characterId, marketTileX, marketTileY)
843 {
844 const entityId = this.simulation.characterEntities.get(characterId);
845 const position = entityId ? this.simulation.positionOf(entityId) : null;
846 if (!position)
847 { return false; }
848 return chebyshev(position.tileX, position.tileY, marketTileX, marketTileY) <= 1;
849 }
850
851 #releaseStation (key)
852 {
853 const entry = this.stationAttendance.get(key);
854 if (!entry)
855 { return; }
856 this.stationAttendance.delete(key);
857 this.simulation.releaseExchangeClerk?.(entry.stationTileX, entry.stationTileY);
858 }
859
860 /**
861 * Drop browsers who walked away from their counter; release clerks when a
862 * staff station has no remaining players.
863 */
864 #pruneStationAttendance ()
865 {
866 const events = [];
867 /** @type {Map<number, number>} characterId → sessionId */
868 const departed = new Map();
869 const emptyStations = [];
870 for (const [key, entry] of this.stationAttendance.entries())
871 {
872 for (const [characterId, sessionId] of [...entry.browsers.entries()])
873 {
874 if (this.#stillAtMarketCounter(characterId, entry.marketTileX, entry.marketTileY))
875 { continue; }
876 entry.browsers.delete(characterId);
877 departed.set(characterId, sessionId);
878 }
879 if (entry.browsers.size === 0)
880 { emptyStations.push(key); }
881 }
882 for (const key of emptyStations)
883 { this.#releaseStation(key); }
884 for (const [characterId, sessionId] of departed.entries())
885 {
886 if (this.#characterStillAttending(characterId))
887 { continue; }
888 events.push({ type: "market-closed", sessionId, characterId });
889 }
890 return events;
891 }
892
893 #marketOpenEvent (sessionId, characterId, position, now)
894 {
895 const orders = this.stateDb.listOpenMarketOrdersForCharacter(characterId).map((order) => ({
896 orderId: order.orderId,
897 side: order.side,
898 itemId: order.itemId,
899 displayName: itemDefinition(order.itemId)?.displayName ?? `Item ${order.itemId}`,
900 quantity: order.quantity,
901 limitUnitPrice: order.limitUnitPrice,
902 createdAt: order.createdAt
903 }));
904 const catalog = [];
905 for (const def of Object.values(ITEM_DEFINITIONS))
906 {
907 if (!canSellOnMarketplace({ itemId: def.itemId, quantity: 1 }))
908 { continue; }
909 if (def.itemId === ItemId.coins)
910 { continue; }
911 catalog.push({
912 itemId: def.itemId,
913 displayName: def.displayName,
914 hintPrice: undiscountedMarketCoins(
915 def.itemId,
916 this.lastSaleFor(def.itemId),
917 now,
918 this.simulation.settings?.shopPriceLerpDurationMs,
919 this.simulation.settings
920 )
921 });
922 }
923 catalog.sort((a, b) => a.displayName.localeCompare(b.displayName));
924 return {
925 type: "market-open",
926 sessionId,
927 characterId,
928 displayName: "Central Exchange",
929 orders,
930 catalog,
931 tileX: position.tileX,
932 tileY: position.tileY
933 };
934 }
935
936 #loadBag (characterId)
937 {
938 const onlineId = this.simulation.characterEntities.get(characterId);
939 const bag = onlineId
940 ? this.simulation.bagOf(onlineId)
941 : this.stateDb.getBag(characterId);
942 if (!bag)
943 { throw userError("No bag."); }
944 return bag;
945 }
946
947 #persistBag (characterId, bag)
948 {
949 this.stateDb.saveBag(characterId, bag);
950 const onlineId = this.simulation.characterEntities.get(characterId);
951 if (onlineId)
952 {
953 this.simulation.applyBag(onlineId, bag);
954 this.simulation.pushInventory(characterId, bag);
955 }
956 }
957}