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