BlueGit

timfa questward

Files

questward / server / src / market / service.js

service.js

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