BlueGit

timfa questward

Files

questward / server / src / market / service.js

service.js

service.js 28.2 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 authorDisplayName: name,
681 authorOrganization: CENTRAL_EXCHANGE_ORG,
682 body,
683 centralExchange: true
684 });
685 }
686
687 #dispatchBankCargo (characterId, origin, cargo)
688 {
689 this.simulation.courier.dispatchHeldCargo({
690 senderCharacterId: characterId,
691 originTileX: origin.tileX,
692 originTileY: origin.tileY,
693 destination: { kind: "bank" },
694 cargo
695 });
696 }
697
698 #grantImmediate (characterId, stack)
699 {
700 const bag = this.#loadBag(characterId);
701 const def = itemDefinition(stack.itemId);
702 const inserted = insertStack(bag.inventory ?? [], stack, def);
703 bag.inventory = inserted.slots;
704 if (inserted.remainder > 0)
705 {
706 const overflow = attachOrigins({
707 ...stack,
708 quantity: inserted.remainder,
709 origins: splitOrigins(normalizeOrigins(stack), stack.quantity - inserted.remainder).remain
710 });
711 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
712 const vaulted = insertStackGrowable(vault.slots, overflow, def);
713 bag.vault = vaulted.slots;
714 bag.vaultReserved = vault.reserved;
715 }
716 this.#persistBag(characterId, bag);
717 }
718
719 #grantImmediateCoins (characterId, amount)
720 {
721 const qty = Math.max(0, amount | 0);
722 if (qty <= 0)
723 { return; }
724 const bag = this.#loadBag(characterId);
725 const paid = addCoinsToSlots(bag.inventory ?? [], qty, { growable: false });
726 if (paid.ok && (paid.remainder | 0) === 0)
727 {
728 bag.inventory = paid.slots;
729 this.#persistBag(characterId, bag);
730 return;
731 }
732 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
733 const withInv = paid.ok ? paid.slots : bag.inventory;
734 const remainder = paid.ok ? (paid.remainder | 0) : qty;
735 bag.inventory = withInv;
736 const vaultPaid = addCoinsToSlots(vault.slots, remainder, { growable: true });
737 bag.vault = vaultPaid.slots;
738 bag.vaultReserved = vault.reserved;
739 this.#persistBag(characterId, bag);
740 }
741
742 #recordLastSale (itemId, unitPrice, now)
743 {
744 const previous = this.lastSales.get(itemId | 0) ?? null;
745 const priceFrom = undiscountedMarketValue(
746 itemId,
747 previous,
748 now,
749 this.simulation.settings?.shopPriceLerpDurationMs,
750 this.simulation.settings
751 );
752 const sale = {
753 itemId: itemId | 0,
754 lastTradePrice: unitPrice,
755 lastTradeAt: now,
756 priceFrom
757 };
758 this.lastSales.set(itemId | 0, sale);
759 this.stateDb.upsertItemLastSale(sale);
760 this.#syncLastSalesToWorkers();
761 }
762
763 #loadLastSales ()
764 {
765 for (const sale of this.stateDb.listItemLastSales())
766 { this.lastSales.set(sale.itemId | 0, sale); }
767 }
768
769 #syncLastSalesToWorkers ()
770 {
771 this.simulation.syncItemLastSales?.(this.lastSales);
772 }
773
774 #requireAtMarket (characterId)
775 {
776 const entityId = this.simulation.characterEntities.get(characterId);
777 const position = entityId ? this.simulation.positionOf(entityId) : null;
778 if (!position)
779 { throw userError("Enter the world before using the Central Exchange."); }
780 if (!this.marketTiles.length)
781 { throw userError("The Central Exchange is not open in this world yet."); }
782 const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
783 const near = this.marketTiles.some((tile) =>
784 normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) === dim
785 && isAdjacentTile(position.tileX, position.tileY, tile.tileX, tile.tileY));
786 if (!near)
787 { throw userError("Stand next to the Central Exchange counter."); }
788 return { position, entityId };
789 }
790
791 #stationTargetsForPlayer (tileX, tileY, dimensionId = OVERWORLD_ID)
792 {
793 const dim = normalizeDimensionId(dimensionId);
794 const targets = [];
795 for (const tile of this.marketTiles)
796 {
797 if (normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim)
798 { continue; }
799 if (!isAdjacentTile(tileX, tileY, tile.tileX, tile.tileY))
800 { continue; }
801 if (tile.tileX === tileX && tile.tileY === tileY)
802 { continue; }
803 const stationTileX = tile.tileX + (tile.tileX - tileX);
804 const stationTileY = tile.tileY + (tile.tileY - tileY);
805 if (stationTileX === tileX && stationTileY === tileY)
806 { continue; }
807 targets.push({
808 marketTileX: tile.tileX,
809 marketTileY: tile.tileY,
810 stationTileX,
811 stationTileY,
812 dimensionId: dim
813 });
814 }
815 return targets;
816 }
817
818 #stationKey (stationTileX, stationTileY, dimensionId = OVERWORLD_ID)
819 {
820 const dim = normalizeDimensionId(dimensionId);
821 return `${dim}:${stationTileX | 0},${stationTileY | 0}`;
822 }
823
824 #attendStations (sessionId, characterId, tileX, tileY, dimensionId = OVERWORLD_ID)
825 {
826 const id = characterId | 0;
827 const dim = normalizeDimensionId(dimensionId);
828 for (const target of this.#stationTargetsForPlayer(tileX, tileY, dim))
829 {
830 const key = this.#stationKey(target.stationTileX, target.stationTileY, dim);
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 dimensionId: dim,
840 browsers: new Map()
841 };
842 this.stationAttendance.set(key, entry);
843 }
844 entry.browsers.set(id, sessionId);
845 entry.marketTileX = target.marketTileX;
846 entry.marketTileY = target.marketTileY;
847 entry.dimensionId = dim;
848 this.simulation.stationExchangeClerk?.(
849 target.stationTileX,
850 target.stationTileY,
851 dim
852 );
853 }
854 }
855
856 #characterStillAttending (characterId)
857 {
858 const id = characterId | 0;
859 for (const entry of this.stationAttendance.values())
860 {
861 if (entry.browsers.has(id))
862 { return true; }
863 }
864 return false;
865 }
866
867 #stillAtMarketCounter (characterId, marketTileX, marketTileY, dimensionId = OVERWORLD_ID)
868 {
869 const entityId = this.simulation.characterEntities.get(characterId);
870 const position = entityId ? this.simulation.positionOf(entityId) : null;
871 if (!position)
872 { return false; }
873 const dim = normalizeDimensionId(dimensionId);
874 if (normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID) !== dim)
875 { return false; }
876 return isAdjacentTile(position.tileX, position.tileY, marketTileX, marketTileY);
877 }
878
879 #releaseStation (key)
880 {
881 const entry = this.stationAttendance.get(key);
882 if (!entry)
883 { return; }
884 this.stationAttendance.delete(key);
885 this.simulation.releaseExchangeClerk?.(
886 entry.stationTileX,
887 entry.stationTileY,
888 normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID)
889 );
890 }
891
892 /**
893 * Drop browsers who walked away from their counter; release clerks when a
894 * staff station has no remaining players.
895 */
896 #pruneStationAttendance ()
897 {
898 const events = [];
899 /** @type {Map<number, number>} characterId → sessionId */
900 const departed = new Map();
901 const emptyStations = [];
902 for (const [key, entry] of this.stationAttendance.entries())
903 {
904 for (const [characterId, sessionId] of [...entry.browsers.entries()])
905 {
906 if (this.#stillAtMarketCounter(
907 characterId,
908 entry.marketTileX,
909 entry.marketTileY,
910 entry.dimensionId ?? OVERWORLD_ID
911 ))
912 { continue; }
913 entry.browsers.delete(characterId);
914 departed.set(characterId, sessionId);
915 }
916 if (entry.browsers.size === 0)
917 { emptyStations.push(key); }
918 }
919 for (const key of emptyStations)
920 { this.#releaseStation(key); }
921 for (const [characterId, sessionId] of departed.entries())
922 {
923 if (this.#characterStillAttending(characterId))
924 { continue; }
925 events.push({ type: "market-closed", sessionId, characterId });
926 }
927 return events;
928 }
929
930 #marketOpenEvent (sessionId, characterId, position, now)
931 {
932 const orders = this.stateDb.listOpenMarketOrdersForCharacter(characterId).map((order) => ({
933 orderId: order.orderId,
934 side: order.side,
935 itemId: order.itemId,
936 listingKey: listingKeyFromOrder(order),
937 displayName: marketOrderDisplayName(order),
938 quantity: order.quantity,
939 limitUnitPrice: order.limitUnitPrice,
940 createdAt: order.createdAt
941 }));
942 const catalog = buildMarketCatalogEntries({
943 lastSaleFor: (itemId) => this.lastSaleFor(itemId),
944 undiscountedMarketCoins,
945 now,
946 lerpDurationMs: this.simulation.settings?.shopPriceLerpDurationMs,
947 settings: this.simulation.settings
948 });
949 return {
950 type: "market-open",
951 sessionId,
952 characterId,
953 displayName: "Central Exchange",
954 orders,
955 catalog,
956 tileX: position.tileX,
957 tileY: position.tileY
958 };
959 }
960
961 #loadBag (characterId)
962 {
963 const onlineId = this.simulation.characterEntities.get(characterId);
964 const bag = onlineId
965 ? this.simulation.bagOf(onlineId)
966 : this.stateDb.getBag(characterId);
967 if (!bag)
968 { throw userError("No bag."); }
969 return bag;
970 }
971
972 #persistBag (characterId, bag)
973 {
974 this.stateDb.saveBag(characterId, bag);
975 const onlineId = this.simulation.characterEntities.get(characterId);
976 if (onlineId)
977 {
978 this.simulation.applyBag(onlineId, bag);
979 this.simulation.pushInventory(characterId, bag);
980 }
981 }
982}