BlueGit

timfa questward

Files

questward / server / src / market / service.js

service.js

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