BlueGit

timfa questward

Files

questward / server / src / market / service.js

service.js

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