BlueGit

timfa questward

Files

questward / server / src / market / service.js

service.js

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