BlueGit

timfa questward

Files

questward / server / src / market / service.js

service.js

rweaks
timfa Tim Falken · pushed by timfa · 2 months ago
2b34e2dd History
service.js 22.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, ITEM_DEFINITIONS, 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 } from "../../../shared/items/origin.js";
15import { undiscountedMarketValue } from "../../../shared/shop/pricing.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 { decodeChunkBlob } from "../world/chunkData.js";
28import { withTransaction } from "../persistence/database.js";
29
30function userError (message)
31{
32 const error = new Error(message);
33 error.userFacing = true;
34 return error;
35}
36
37function chebyshev (ax, ay, bx, by)
38{
39 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
40}
41
42export class MarketService
43{
44 constructor ({ stateDb, worldDb, simulation })
45 {
46 this.stateDb = stateDb;
47 this.worldDb = worldDb;
48 this.simulation = simulation;
49 this.marketTiles = [];
50 /** @type {Map<number, object>} */
51 this.lastSales = new Map();
52 this.refreshIndex();
53 this.#loadLastSales();
54 this.#syncLastSalesToWorkers();
55 }
56
57 refreshIndex ()
58 {
59 const revisionId = this.worldDb.getActiveRevisionId();
60 const tiles = [];
61 for (const coord of this.worldDb.listChunkCoords(revisionId))
62 {
63 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
64 if (!row)
65 { continue; }
66 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId);
67 for (let localY = 0; localY < CHUNK_SIZE; localY++)
68 {
69 for (let localX = 0; localX < CHUNK_SIZE; localX++)
70 {
71 const block = data.blocks[localY * CHUNK_SIZE + localX];
72 if (block?.typeId !== BlockType.marketplace)
73 { continue; }
74 tiles.push({
75 tileX: coord.chunk_x * CHUNK_SIZE + localX,
76 tileY: coord.chunk_y * CHUNK_SIZE + localY
77 });
78 }
79 }
80 }
81 this.marketTiles = tiles;
82 }
83
84 nearestMarket (tileX, tileY)
85 {
86 if (!this.marketTiles.length)
87 { return null; }
88 let best = null;
89 let bestDist = Infinity;
90 for (const tile of this.marketTiles)
91 {
92 const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY);
93 if (dist < bestDist)
94 {
95 bestDist = dist;
96 best = tile;
97 }
98 }
99 return best;
100 }
101
102 lastSaleFor (itemId)
103 {
104 return this.lastSales.get(itemId | 0) ?? null;
105 }
106
107 snapshot ()
108 {
109 const out = {};
110 for (const [itemId, sale] of this.lastSales.entries())
111 { out[String(itemId)] = sale; }
112 return out;
113 }
114
115 step (now = Date.now())
116 {
117 const events = [];
118 const expired = this.stateDb.listExpiredMarketOrders(now - MARKET_ORDER_MAX_AGE_MS);
119 for (const order of expired)
120 {
121 try
122 {
123 events.push(...this.#expireOrder(order, now));
124 }
125 catch (error)
126 {
127 console.error("Market order expiry failed", order.orderId, error);
128 }
129 }
130 return events;
131 }
132
133 handleCommand (sessionId, command, now = Date.now())
134 {
135 switch (command.type)
136 {
137 case "open-market":
138 return this.openMarket(sessionId, command.characterId, now);
139 case "place-market-sell":
140 return this.placeSellOrder(
141 sessionId,
142 command.characterId,
143 command.slotIndex | 0,
144 command.quantity | 0 || 1,
145 command.minUnitPrice | 0,
146 now
147 );
148 case "place-market-buy":
149 return this.placeBuyOrder(
150 sessionId,
151 command.characterId,
152 command.itemId | 0,
153 command.quantity | 0 || 1,
154 command.maxUnitPrice | 0,
155 now
156 );
157 case "cancel-market-order":
158 return this.cancelOrder(sessionId, command.characterId, command.orderId | 0, now);
159 case "close-market":
160 return { events: [{ type: "market-closed", sessionId, characterId: command.characterId }] };
161 default:
162 return null;
163 }
164 }
165
166 openMarket (sessionId, characterId, now = Date.now())
167 {
168 const { position } = this.#requireAtMarket(characterId);
169 this.simulation.stationExchangeClerks?.(position.tileX, position.tileY);
170 return {
171 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
172 };
173 }
174
175 placeSellOrder (sessionId, characterId, slotIndex, quantity, minUnitPrice, now = Date.now())
176 {
177 const { position } = this.#requireAtMarket(characterId);
178 const minPrice = Math.max(1, minUnitPrice | 0);
179 const bag = this.#loadBag(characterId);
180 const slot = bag.inventory?.[slotIndex];
181 if (!slot)
182 { throw userError("That slot is empty."); }
183 assertMarketplaceSellable(slot);
184 if ((slot.itemId | 0) === ItemId.coins)
185 { throw userError("Coins cannot be listed on the marketplace."); }
186
187 const listing = resolveMarketSellListing(slot);
188 if (!listing)
189 { throw userError("That item cannot be sold on the marketplace."); }
190
191 let escrowStack;
192 let orderQty;
193 if (listing.isCheque)
194 {
195 orderQty = listing.quantity;
196 const taken = takeFromSlot(bag.inventory, slotIndex, 1);
197 if (!taken.ok || !taken.taken)
198 { throw userError("That cheque is not available."); }
199 bag.inventory = taken.slots;
200 escrowStack = attachOrigins(taken.taken);
201 }
202 else
203 {
204 const qty = Math.max(1, Math.min(quantity | 0 || 1, listing.quantity));
205 orderQty = qty;
206 const taken = takeFromSlot(bag.inventory, slotIndex, qty);
207 if (!taken.ok || !taken.taken)
208 { throw userError("That item is not available."); }
209 bag.inventory = taken.slots;
210 escrowStack = attachOrigins(taken.taken);
211 }
212
213 const fee = marketOrderListingFee(minPrice, orderQty);
214 const paid = this.#payMarketFunds(bag, characterId, fee);
215 if (!paid.ok)
216 {
217 const restored = insertStack(
218 bag.inventory,
219 escrowStack,
220 itemDefinition(escrowStack.itemId)
221 );
222 bag.inventory = restored.slots;
223 throw userError(
224 fee > 0
225 ? `You need ${fee} coins for the listing fee.`
226 : "You cannot afford the listing fee."
227 );
228 }
229
230 const order = this.stateDb.insertMarketOrder({
231 characterId,
232 side: "sell",
233 itemId: listing.itemId,
234 quantity: orderQty,
235 limitUnitPrice: minPrice,
236 escrowCoins: 0,
237 escrowStack,
238 createdAt: now,
239 status: "open"
240 });
241 this.#persistBag(characterId, bag);
242 const matchEvents = this.#matchAfterInsert(order, now);
243 return {
244 events: [
245 this.#marketOpenEvent(sessionId, characterId, position, now),
246 ...matchEvents
247 ]
248 };
249 }
250
251 placeBuyOrder (sessionId, characterId, itemId, quantity, maxUnitPrice, now = Date.now())
252 {
253 const { position } = this.#requireAtMarket(characterId);
254 const maxPrice = Math.max(1, maxUnitPrice | 0);
255 const qty = Math.max(1, quantity | 0 || 1);
256 const def = itemDefinition(itemId);
257 if (!def || !canSellOnMarketplace({ itemId, quantity: 1 }))
258 { throw userError("That item cannot be bought on the marketplace."); }
259 if ((itemId | 0) === ItemId.coins)
260 { throw userError("Coins cannot be ordered on the marketplace."); }
261 const escrow = maxPrice * qty;
262 const fee = marketOrderListingFee(maxPrice, qty);
263 const bag = this.#loadBag(characterId);
264 const paid = this.#payMarketFunds(bag, characterId, escrow + fee);
265 if (!paid.ok)
266 {
267 throw userError(
268 `You need ${escrow + fee} coins (escrow ${escrow} + ${fee} listing fee).`
269 );
270 }
271 const order = this.stateDb.insertMarketOrder({
272 characterId,
273 side: "buy",
274 itemId: itemId | 0,
275 quantity: qty,
276 limitUnitPrice: maxPrice,
277 escrowCoins: escrow,
278 escrowStack: null,
279 createdAt: now,
280 status: "open"
281 });
282 this.#persistBag(characterId, bag);
283 const matchEvents = this.#matchAfterInsert(order, now);
284 return {
285 events: [
286 this.#marketOpenEvent(sessionId, characterId, position, now),
287 ...matchEvents
288 ]
289 };
290 }
291
292 cancelOrder (sessionId, characterId, orderId, now = Date.now())
293 {
294 const { position } = this.#requireAtMarket(characterId);
295 const order = this.stateDb.getMarketOrder(orderId);
296 if (!order || order.status !== "open")
297 { throw userError("That order is no longer open."); }
298 if (Number(order.characterId) !== Number(characterId))
299 { throw userError("That is not your order."); }
300 this.#returnEscrowByPigeon(order, {
301 letterBody: orderCancelledLetterBody({
302 side: order.side,
303 itemName: itemDefinition(order.itemId)?.displayName ?? "item",
304 quantity: order.quantity,
305 escrowLabel: order.side === "buy"
306 ? "coins"
307 : (isFilledChequeEscrow(order.escrowStack)
308 ? "written cheque"
309 : (itemDefinition(order.itemId)?.displayName ?? "item")),
310 clerkName: pickExchangeClerk()
311 }),
312 now
313 });
314 this.stateDb.updateMarketOrder({
315 ...order,
316 status: "cancelled",
317 quantity: 0,
318 escrowCoins: 0,
319 escrowStack: null
320 });
321 return {
322 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
323 };
324 }
325
326 #expireOrder (order, now)
327 {
328 const events = [];
329 this.#returnEscrowByPigeon(order, {
330 letterBody: orderExpiredLetterBody({
331 side: order.side,
332 itemName: itemDefinition(order.itemId)?.displayName ?? "item",
333 quantity: order.quantity,
334 escrowLabel: order.side === "buy"
335 ? "coins"
336 : (isFilledChequeEscrow(order.escrowStack)
337 ? "written cheque"
338 : (itemDefinition(order.itemId)?.displayName ?? "item")),
339 clerkName: pickExchangeClerk()
340 }),
341 now
342 });
343 this.stateDb.updateMarketOrder({
344 ...order,
345 status: "cancelled",
346 quantity: 0,
347 escrowCoins: 0,
348 escrowStack: null
349 });
350 events.push({
351 type: "market-order-expired",
352 orderId: order.orderId,
353 characterId: order.characterId
354 });
355 return events;
356 }
357
358 #matchAfterInsert (incoming, now)
359 {
360 const events = [];
361 let resting = this.stateDb.getMarketOrder(incoming.orderId);
362 if (!resting || resting.status !== "open")
363 { return events; }
364
365 const counterparts = resting.side === "sell"
366 ? this.stateDb.listOpenBuyOrdersForItem(resting.itemId)
367 : this.stateDb.listOpenSellOrdersForItem(resting.itemId);
368
369 for (const other of counterparts)
370 {
371 resting = this.stateDb.getMarketOrder(resting.orderId);
372 if (!resting || resting.status !== "open" || resting.quantity <= 0)
373 { break; }
374 const liveOther = this.stateDb.getMarketOrder(other.orderId);
375 if (!liveOther || liveOther.status !== "open" || liveOther.quantity <= 0)
376 { continue; }
377 if (Number(liveOther.characterId) === Number(resting.characterId))
378 { continue; }
379
380 const buy = resting.side === "buy" ? resting : liveOther;
381 const sell = resting.side === "sell" ? resting : liveOther;
382 if (buy.limitUnitPrice < sell.limitUnitPrice)
383 { continue; }
384
385 let fillQty = Math.min(buy.quantity, sell.quantity);
386 if (isFilledChequeEscrow(sell.escrowStack))
387 {
388 // Written cheques list as one indivisible lot.
389 if (fillQty < sell.quantity)
390 { continue; }
391 fillQty = sell.quantity;
392 }
393 if (fillQty <= 0)
394 { continue; }
395 const unitPrice = midpointTradePrice(buy.limitUnitPrice, sell.limitUnitPrice);
396 const tradeEvents = this.#settleMatch({
397 buy,
398 sell,
399 fillQty,
400 unitPrice,
401 triggeringSide: resting.side,
402 now
403 });
404 events.push(...tradeEvents);
405 }
406 return events;
407 }
408
409 #settleMatch ({ buy, sell, fillQty, unitPrice, triggeringSide, now })
410 {
411 const events = [];
412 const total = unitPrice * fillQty;
413 const itemName = itemDefinition(sell.itemId)?.displayName ?? "item";
414 const clerk = pickExchangeClerk();
415 const chequeEscrow = isFilledChequeEscrow(sell.escrowStack);
416
417 let goods;
418 let sellRemainOrigins = null;
419 if (chequeEscrow)
420 {
421 goods = this.#redeemSellChequeEscrow(sell.escrowStack);
422 if ((goods.quantity | 0) !== fillQty || (goods.itemId | 0) !== (sell.itemId | 0))
423 { throw userError("That cheque listing could not be settled."); }
424 }
425 else
426 {
427 const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty);
428 goods = attachOrigins({
429 itemId: sell.itemId,
430 quantity: fillQty,
431 origins: sellSplit.taken,
432 instance: sell.escrowStack?.instance ?? null
433 });
434 sellRemainOrigins = sellSplit.remain;
435 }
436
437 const buyRefund = (buy.limitUnitPrice - unitPrice) * fillQty;
438 const buyRemainingQty = buy.quantity - fillQty;
439 const sellRemainingQty = chequeEscrow ? 0 : sell.quantity - fillQty;
440
441 withTransaction(this.stateDb.db, () =>
442 {
443 this.stateDb.insertMarketTrade({
444 buyOrderId: buy.orderId,
445 sellOrderId: sell.orderId,
446 itemId: sell.itemId,
447 quantity: fillQty,
448 unitPrice,
449 buyerCharacterId: buy.characterId,
450 sellerCharacterId: sell.characterId,
451 createdAt: now
452 });
453
454 this.stateDb.updateMarketOrder({
455 ...buy,
456 quantity: buyRemainingQty,
457 escrowCoins: buy.limitUnitPrice * buyRemainingQty,
458 status: buyRemainingQty > 0 ? "open" : "filled"
459 });
460 this.stateDb.updateMarketOrder({
461 ...sell,
462 quantity: sellRemainingQty,
463 escrowStack: sellRemainingQty > 0
464 ? attachOrigins({
465 ...sell.escrowStack,
466 quantity: sellRemainingQty,
467 origins: sellRemainOrigins
468 })
469 : null,
470 status: sellRemainingQty > 0 ? "open" : "filled"
471 });
472 });
473
474 this.#recordLastSale(sell.itemId, unitPrice, now);
475
476 const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
477
478 if (triggeringSide === "buy")
479 {
480 this.#grantImmediate(buy.characterId, goods);
481 if (buyRefund > 0)
482 { this.#grantImmediateCoins(buy.characterId, buyRefund); }
483 this.#dispatchBankCargo(sell.characterId, origin, { kind: "money", amount: total });
484 this.#dispatchBankLetter(sell.characterId, origin, soldLetterBody({
485 itemName,
486 quantity: fillQty,
487 unitPrice,
488 clerkName: clerk
489 }));
490 }
491 else
492 {
493 this.#grantImmediateCoins(sell.characterId, total);
494 this.#dispatchBankCargo(buy.characterId, origin, { kind: "item", stack: goods });
495 if (buyRefund > 0)
496 { this.#dispatchBankCargo(buy.characterId, origin, { kind: "money", amount: buyRefund }); }
497 this.#dispatchBankLetter(buy.characterId, origin, buyFilledLetterBody({
498 itemName,
499 quantity: fillQty,
500 unitPrice,
501 clerkName: clerk
502 }));
503 }
504
505 events.push({
506 type: "market-trade",
507 itemId: sell.itemId,
508 quantity: fillQty,
509 unitPrice,
510 buyerCharacterId: buy.characterId,
511 sellerCharacterId: sell.characterId,
512 triggeringSide
513 });
514 return events;
515 }
516
517 /** Redeem a written-cheque sell escrow into the reserved goods stack. */
518 #redeemSellChequeEscrow (chequeStack)
519 {
520 const instance = chequeStack?.instance;
521 if (!instance || instance.kind !== "filled-cheque")
522 { throw userError("That cheque listing is invalid."); }
523 const issuerId = instance.issuerCharacterId | 0;
524 const release = this.simulation.releaseChequeReservation?.(issuerId, instance.chequeId, instance);
525 if (!release?.ok || !release.stack)
526 { throw userError(release?.error ?? "That cheque cannot be redeemed."); }
527 return attachOrigins(release.stack);
528 }
529
530 /**
531 * Charge coins (and whole coin-cheques) for escrow/fees. Mutates bag.inventory.
532 * Releases reservations for redeemed coin cheques.
533 */
534 #payMarketFunds (bag, payerCharacterId, amount)
535 {
536 const need = Math.max(0, amount | 0);
537 if (!need)
538 { return { ok: true }; }
539 const paid = takeMarketFunds(bag.inventory, need);
540 if (!paid.ok)
541 { return { ok: false }; }
542 bag.inventory = paid.slots;
543 for (const cheque of paid.redeemedCheques ?? [])
544 {
545 const instance = cheque.instance;
546 const issuerId = instance?.issuerCharacterId | 0;
547 const release = this.simulation.releaseChequeReservation?.(
548 issuerId,
549 instance.chequeId,
550 instance
551 );
552 if (!release?.ok)
553 {
554 // Restore cheque paper; leave other payments as-is (best-effort).
555 const restored = insertStack(bag.inventory, cheque, itemDefinition(ItemId.filledCheque));
556 bag.inventory = restored.slots;
557 return { ok: false };
558 }
559 }
560 if ((paid.change | 0) > 0)
561 {
562 const refunded = addCoinsToSlots(bag.inventory, paid.change | 0, { growable: false });
563 if (!refunded.ok)
564 {
565 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
566 const vaultPaid = addCoinsToSlots(vault.slots, paid.change | 0, { growable: true });
567 bag.inventory = refunded.slots;
568 bag.vault = vaultPaid.slots;
569 bag.vaultReserved = vault.reserved;
570 }
571 else
572 { bag.inventory = refunded.slots; }
573 }
574 void payerCharacterId;
575 return { ok: true };
576 }
577
578 #returnEscrowByPigeon (order, { letterBody, now })
579 {
580 const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 };
581 if (order.side === "buy" && (order.escrowCoins | 0) > 0)
582 {
583 this.#dispatchBankCargo(order.characterId, origin, {
584 kind: "money",
585 amount: order.escrowCoins | 0
586 });
587 }
588 if (order.side === "sell" && order.escrowStack && (order.escrowStack.quantity | 0) > 0)
589 {
590 this.#dispatchBankCargo(order.characterId, origin, {
591 kind: "item",
592 stack: cloneStack(order.escrowStack)
593 });
594 }
595 this.#dispatchBankLetter(order.characterId, origin, letterBody);
596 void now;
597 }
598
599 #dispatchBankLetter (characterId, origin, body)
600 {
601 const trimmed = String(body ?? "").replace(/\r\n/g, "\n").trimEnd().slice(0, LETTER_MAX_BODY_CHARS);
602 const signed = /Signed,\n([^\n]+)\nCentral Exchange/.exec(trimmed);
603 const clerkName = signed?.[1] ?? pickExchangeClerk();
604 const stack = {
605 itemId: ItemId.letter,
606 quantity: 1,
607 instance: {
608 kind: "letter",
609 letterId: randomUUID(),
610 authorCharacterId: 0,
611 authorDisplayName: clerkName,
612 body: trimmed,
613 opened: false,
614 writtenAt: Date.now()
615 }
616 };
617 this.#dispatchBankCargo(characterId, origin, { kind: "item", stack });
618 }
619
620 #dispatchBankCargo (characterId, origin, cargo)
621 {
622 this.simulation.courier.dispatchHeldCargo({
623 senderCharacterId: characterId,
624 originTileX: origin.tileX,
625 originTileY: origin.tileY,
626 destination: { kind: "bank" },
627 cargo
628 });
629 }
630
631 #grantImmediate (characterId, stack)
632 {
633 const bag = this.#loadBag(characterId);
634 const def = itemDefinition(stack.itemId);
635 const inserted = insertStack(bag.inventory ?? [], stack, def);
636 bag.inventory = inserted.slots;
637 if (inserted.remainder > 0)
638 {
639 const overflow = attachOrigins({
640 ...stack,
641 quantity: inserted.remainder,
642 origins: splitOrigins(normalizeOrigins(stack), stack.quantity - inserted.remainder).remain
643 });
644 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
645 const vaulted = insertStackGrowable(vault.slots, overflow, def);
646 bag.vault = vaulted.slots;
647 bag.vaultReserved = vault.reserved;
648 }
649 this.#persistBag(characterId, bag);
650 }
651
652 #grantImmediateCoins (characterId, amount)
653 {
654 const qty = Math.max(0, amount | 0);
655 if (qty <= 0)
656 { return; }
657 const bag = this.#loadBag(characterId);
658 const paid = addCoinsToSlots(bag.inventory ?? [], qty, { growable: false });
659 if (paid.ok && (paid.remainder | 0) === 0)
660 {
661 bag.inventory = paid.slots;
662 this.#persistBag(characterId, bag);
663 return;
664 }
665 const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved });
666 const withInv = paid.ok ? paid.slots : bag.inventory;
667 const remainder = paid.ok ? (paid.remainder | 0) : qty;
668 bag.inventory = withInv;
669 const vaultPaid = addCoinsToSlots(vault.slots, remainder, { growable: true });
670 bag.vault = vaultPaid.slots;
671 bag.vaultReserved = vault.reserved;
672 this.#persistBag(characterId, bag);
673 }
674
675 #recordLastSale (itemId, unitPrice, now)
676 {
677 const previous = this.lastSales.get(itemId | 0) ?? null;
678 const priceFrom = undiscountedMarketValue(
679 itemId,
680 previous,
681 now,
682 this.simulation.settings?.shopPriceLerpDurationMs,
683 this.simulation.settings
684 );
685 const sale = {
686 itemId: itemId | 0,
687 lastTradePrice: unitPrice,
688 lastTradeAt: now,
689 priceFrom
690 };
691 this.lastSales.set(itemId | 0, sale);
692 this.stateDb.upsertItemLastSale(sale);
693 this.#syncLastSalesToWorkers();
694 }
695
696 #loadLastSales ()
697 {
698 for (const sale of this.stateDb.listItemLastSales())
699 { this.lastSales.set(sale.itemId | 0, sale); }
700 }
701
702 #syncLastSalesToWorkers ()
703 {
704 this.simulation.syncItemLastSales?.(this.lastSales);
705 }
706
707 #requireAtMarket (characterId)
708 {
709 const entityId = this.simulation.characterEntities.get(characterId);
710 const position = entityId ? this.simulation.positionOf(entityId) : null;
711 if (!position)
712 { throw userError("Enter the world before using the Central Exchange."); }
713 if (!this.marketTiles.length)
714 { throw userError("The Central Exchange is not open in this world yet."); }
715 const near = this.marketTiles.some((tile) =>
716 chebyshev(position.tileX, position.tileY, tile.tileX, tile.tileY) <= 1);
717 if (!near)
718 { throw userError("Stand next to the Central Exchange counter."); }
719 return { position, entityId };
720 }
721
722 #marketOpenEvent (sessionId, characterId, position, now)
723 {
724 const orders = this.stateDb.listOpenMarketOrdersForCharacter(characterId).map((order) => ({
725 orderId: order.orderId,
726 side: order.side,
727 itemId: order.itemId,
728 displayName: itemDefinition(order.itemId)?.displayName ?? `Item ${order.itemId}`,
729 quantity: order.quantity,
730 limitUnitPrice: order.limitUnitPrice,
731 createdAt: order.createdAt
732 }));
733 const catalog = [];
734 for (const def of Object.values(ITEM_DEFINITIONS))
735 {
736 if (!canSellOnMarketplace({ itemId: def.itemId, quantity: 1 }))
737 { continue; }
738 if (def.itemId === ItemId.coins)
739 { continue; }
740 catalog.push({
741 itemId: def.itemId,
742 displayName: def.displayName,
743 hintPrice: undiscountedMarketValue(
744 def.itemId,
745 this.lastSaleFor(def.itemId),
746 now,
747 this.simulation.settings?.shopPriceLerpDurationMs,
748 this.simulation.settings
749 )
750 });
751 }
752 catalog.sort((a, b) => a.displayName.localeCompare(b.displayName));
753 return {
754 type: "market-open",
755 sessionId,
756 characterId,
757 displayName: "Central Exchange",
758 orders,
759 catalog,
760 tileX: position.tileX,
761 tileY: position.tileY
762 };
763 }
764
765 #loadBag (characterId)
766 {
767 const onlineId = this.simulation.characterEntities.get(characterId);
768 const bag = onlineId
769 ? this.simulation.bagOf(onlineId)
770 : this.stateDb.getBag(characterId);
771 if (!bag)
772 { throw userError("No bag."); }
773 return bag;
774 }
775
776 #persistBag (characterId, bag)
777 {
778 this.stateDb.saveBag(characterId, bag);
779 const onlineId = this.simulation.characterEntities.get(characterId);
780 if (onlineId)
781 {
782 this.simulation.applyBag(onlineId, bag);
783 this.simulation.pushInventory(characterId, bag);
784 }
785 }
786}