BlueGit

timfa questward

Files

questward / server / src / market / service.js

service.js

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