import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { BlockType } from "../../../shared/definitions/tiles.js"; import { ItemId, itemDefinition } from "../../../shared/definitions/items.js"; import { addCoinsToSlots, insertStack, insertStackGrowable, normalizeVault, takeFromSlot, cloneStack } from "../../../shared/items/inventory.js"; import { assertMarketplaceSellable, canSellOnMarketplace } from "../../../shared/items/marketplace.js"; import { attachOrigins, normalizeOrigins, splitOrigins } from "../../../shared/items/origin.js"; import { undiscountedMarketValue, undiscountedMarketCoins } from "../../../shared/shop/pricing.js"; import { CENTRAL_EXCHANGE_ORG } from "../../../shared/courier/systemLetters.js"; import { MARKET_ORDER_MAX_AGE_MS, buyFilledLetterBody, marketOrderListingFee, midpointTradePrice, orderExpiredLetterBody, orderCancelledLetterBody, pickExchangeClerk, soldLetterBody } from "../../../shared/market/exchange.js"; import { takeMarketFunds, resolveMarketSellListing, isFilledChequeEscrow } from "../../../shared/market/funds.js"; import { buildMarketCatalogEntries, listingKeyFromOrder, listingKeyFromStack, marketBuyListingKeyError, marketBuyRequiresListingKey, marketOrderDisplayName, marketOrdersCompatible, normalizeBuyListingKey } from "../../../shared/market/listingKey.js"; import { decodeChunkBlob } from "../world/chunkData.js"; import { withTransaction } from "../persistence/database.js"; import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js"; function userError (message) { const error = new Error(message); error.userFacing = true; return error; } import { isAdjacentTile } from "../../../shared/navigation/adjacency.js"; export class MarketService { constructor ({ stateDb, worldDb, simulation }) { this.stateDb = stateDb; this.worldDb = worldDb; this.simulation = simulation; this.marketTiles = []; /** * Players holding a CE UI open at a staff station. * key `${dimensionId}:${stationTileX},${stationTileY}` → * { stationTileX, stationTileY, marketTileX, marketTileY, dimensionId, browsers: Map } * @type {Map} */ this.stationAttendance = new Map(); /** @type {Map} */ this.lastSales = new Map(); this.refreshIndex(); this.#loadLastSales(); this.#syncLastSalesToWorkers(); } refreshIndex () { const revisionId = this.worldDb.getActiveRevisionId(); const tiles = []; for (const coord of this.worldDb.listChunkCoords(revisionId)) { const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID); const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId, dim); if (!row) { continue; } const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId, coord.chunk_x, coord.chunk_y); for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const block = data.blocks[localY * CHUNK_SIZE + localX]; if (block?.typeId !== BlockType.marketplace) { continue; } tiles.push({ tileX: coord.chunk_x * CHUNK_SIZE + localX, tileY: coord.chunk_y * CHUNK_SIZE + localY, dimensionId: dim }); } } } this.marketTiles = tiles; } nearestMarket (tileX, tileY, dimensionId = null) { if (!this.marketTiles.length) { return null; } const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : null; let best = null; let bestDist = Infinity; for (const tile of this.marketTiles) { if (dim != null && normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim) { continue; } const dist = Math.hypot(tile.tileX - tileX, tile.tileY - tileY); if (dist < bestDist) { bestDist = dist; best = tile; } } return best; } lastSaleFor (itemId) { return this.lastSales.get(itemId | 0) ?? null; } snapshot () { const out = {}; for (const [itemId, sale] of this.lastSales.entries()) { out[String(itemId)] = sale; } return out; } step (now = Date.now()) { const events = []; events.push(...this.#pruneStationAttendance()); const expired = this.stateDb.listExpiredMarketOrders(now - MARKET_ORDER_MAX_AGE_MS); for (const order of expired) { try { events.push(...this.#expireOrder(order, now)); } catch (error) { console.error("Market order expiry failed", order.orderId, error); } } return events; } handleCommand (sessionId, command, now = Date.now()) { switch (command.type) { case "open-market": return this.openMarket(sessionId, command.characterId, now); case "place-market-sell": return this.placeSellOrder( sessionId, command.characterId, command.slotIndex | 0, command.quantity | 0 || 1, command.minUnitPrice | 0, now ); case "place-market-buy": return this.placeBuyOrder( sessionId, command.characterId, command.itemId | 0, command.quantity | 0 || 1, command.maxUnitPrice | 0, command.listingKey ?? null, now ); case "cancel-market-order": return this.cancelOrder(sessionId, command.characterId, command.orderId | 0, now); case "close-market": return this.closeMarket(sessionId, command.characterId); default: return null; } } openMarket (sessionId, characterId, now = Date.now()) { const { position } = this.#requireAtMarket(characterId); const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); this.#attendStations(sessionId, characterId, position.tileX, position.tileY, dim); return { events: [this.#marketOpenEvent(sessionId, characterId, position, now)] }; } closeMarket (sessionId, characterId) { this.leaveExchangeStations(characterId); return { events: [{ type: "market-closed", sessionId, characterId }] }; } /** Drop a character from every CE station (UI close / despawn). */ leaveExchangeStations (characterId) { const id = characterId | 0; const emptyStations = []; for (const [key, entry] of this.stationAttendance.entries()) { if (!entry.browsers.has(id)) { continue; } entry.browsers.delete(id); if (entry.browsers.size === 0) { emptyStations.push(key); } } for (const key of emptyStations) { this.#releaseStation(key); } } /** Keep CE attendance open but route private events to a new gateway session. */ reattachSession (characterId, sessionId) { const id = characterId | 0; for (const entry of this.stationAttendance.values()) { if (entry.browsers.has(id)) { entry.browsers.set(id, sessionId); } } } placeSellOrder (sessionId, characterId, slotIndex, quantity, minUnitPrice, now = Date.now()) { const { position } = this.#requireAtMarket(characterId); const minPrice = Math.max(1, minUnitPrice | 0); const bag = this.#loadBag(characterId); const slot = bag.inventory?.[slotIndex]; if (!slot) { throw userError("That slot is empty."); } assertMarketplaceSellable(slot, characterId); if ((slot.itemId | 0) === ItemId.coins) { throw userError("Coins cannot be listed on the marketplace."); } const listing = resolveMarketSellListing(slot); if (!listing) { throw userError("That item cannot be sold on the marketplace."); } let escrowStack; let orderQty; if (listing.isCheque) { orderQty = listing.quantity; const taken = takeFromSlot(bag.inventory, slotIndex, 1); if (!taken.ok || !taken.taken) { throw userError("That cheque is not available."); } bag.inventory = taken.slots; escrowStack = attachOrigins(taken.taken); } else { const qty = Math.max(1, Math.min(quantity | 0 || 1, listing.quantity)); orderQty = qty; const taken = takeFromSlot(bag.inventory, slotIndex, qty); if (!taken.ok || !taken.taken) { throw userError("That item is not available."); } bag.inventory = taken.slots; escrowStack = attachOrigins(taken.taken); } const fee = marketOrderListingFee(minPrice, orderQty); const paid = this.#payMarketFunds(bag, characterId, fee); if (!paid.ok) { const restored = insertStack( bag.inventory, escrowStack, itemDefinition(escrowStack.itemId) ); bag.inventory = restored.slots; throw userError( fee > 0 ? `You need ${fee} coins for the listing fee.` : "You cannot afford the listing fee." ); } const order = this.stateDb.insertMarketOrder({ characterId, side: "sell", itemId: listing.itemId, listingKey: listing.listingKey ?? listingKeyFromStack(escrowStack), quantity: orderQty, limitUnitPrice: minPrice, escrowCoins: 0, escrowStack, createdAt: now, status: "open" }); this.#persistBag(characterId, bag); const matchEvents = this.#matchAfterInsert(order, now); return { events: [ this.#marketOpenEvent(sessionId, characterId, position, now), ...matchEvents ] }; } placeBuyOrder (sessionId, characterId, itemId, quantity, maxUnitPrice, listingKey, now = Date.now()) { const { position } = this.#requireAtMarket(characterId); const maxPrice = Math.max(1, maxUnitPrice | 0); const qty = Math.max(1, quantity | 0 || 1); const def = itemDefinition(itemId); if (!def || !canSellOnMarketplace({ itemId, quantity: 1 })) { throw userError("That item cannot be bought on the marketplace."); } if ((itemId | 0) === ItemId.coins) { throw userError("Coins cannot be ordered on the marketplace."); } const normalizedListingKey = normalizeBuyListingKey(itemId, listingKey); if (marketBuyRequiresListingKey(itemId) && !normalizedListingKey) { throw userError(marketBuyListingKeyError(itemId)); } const rawListingKey = String(listingKey ?? "").trim(); if (rawListingKey && !normalizedListingKey) { throw userError("That listing is not available."); } const escrow = maxPrice * qty; const fee = marketOrderListingFee(maxPrice, qty); const bag = this.#loadBag(characterId); const paid = this.#payMarketFunds(bag, characterId, escrow + fee); if (!paid.ok) { throw userError( `You need ${escrow + fee} coins (escrow ${escrow} + ${fee} listing fee).` ); } const order = this.stateDb.insertMarketOrder({ characterId, side: "buy", itemId: itemId | 0, listingKey: normalizedListingKey, quantity: qty, limitUnitPrice: maxPrice, escrowCoins: escrow, escrowStack: null, createdAt: now, status: "open" }); this.#persistBag(characterId, bag); const matchEvents = this.#matchAfterInsert(order, now); return { events: [ this.#marketOpenEvent(sessionId, characterId, position, now), ...matchEvents ] }; } cancelOrder (sessionId, characterId, orderId, now = Date.now()) { const { position } = this.#requireAtMarket(characterId); const order = this.stateDb.getMarketOrder(orderId); if (!order || order.status !== "open") { throw userError("That order is no longer open."); } if (Number(order.characterId) !== Number(characterId)) { throw userError("That is not your order."); } const clerkName = pickExchangeClerk(); this.#returnEscrowByPigeon(order, { letterBody: orderCancelledLetterBody({ side: order.side, itemName: marketOrderDisplayName(order), quantity: order.quantity, escrowLabel: order.side === "buy" ? "coins" : (isFilledChequeEscrow(order.escrowStack) ? "written cheque" : marketOrderDisplayName(order)), clerkName }), clerkName, now }); this.stateDb.updateMarketOrder({ ...order, status: "cancelled", quantity: 0, escrowCoins: 0, escrowStack: null }); return { events: [this.#marketOpenEvent(sessionId, characterId, position, now)] }; } #expireOrder (order, now) { const events = []; const clerkName = pickExchangeClerk(); this.#returnEscrowByPigeon(order, { letterBody: orderExpiredLetterBody({ side: order.side, itemName: marketOrderDisplayName(order), quantity: order.quantity, escrowLabel: order.side === "buy" ? "coins" : (isFilledChequeEscrow(order.escrowStack) ? "written cheque" : marketOrderDisplayName(order)), clerkName }), clerkName, now }); this.stateDb.updateMarketOrder({ ...order, status: "cancelled", quantity: 0, escrowCoins: 0, escrowStack: null }); events.push({ type: "market-order-expired", orderId: order.orderId, characterId: order.characterId }); return events; } #matchAfterInsert (incoming, now) { const events = []; let resting = this.stateDb.getMarketOrder(incoming.orderId); if (!resting || resting.status !== "open") { return events; } const restingKey = listingKeyFromOrder(resting); const counterparts = resting.side === "sell" ? this.stateDb.listOpenBuyOrdersForItem(resting.itemId, restingKey) : this.stateDb.listOpenSellOrdersForItem(resting.itemId, restingKey); for (const other of counterparts) { resting = this.stateDb.getMarketOrder(resting.orderId); if (!resting || resting.status !== "open" || resting.quantity <= 0) { break; } const liveOther = this.stateDb.getMarketOrder(other.orderId); if (!liveOther || liveOther.status !== "open" || liveOther.quantity <= 0) { continue; } if (Number(liveOther.characterId) === Number(resting.characterId)) { continue; } const buy = resting.side === "buy" ? resting : liveOther; const sell = resting.side === "sell" ? resting : liveOther; if (!marketOrdersCompatible(buy, sell)) { continue; } if (buy.limitUnitPrice < sell.limitUnitPrice) { continue; } let fillQty = Math.min(buy.quantity, sell.quantity); if (isFilledChequeEscrow(sell.escrowStack)) { // Written cheques list as one indivisible lot. if (fillQty < sell.quantity) { continue; } fillQty = sell.quantity; } if (fillQty <= 0) { continue; } const unitPrice = midpointTradePrice(buy.limitUnitPrice, sell.limitUnitPrice); const tradeEvents = this.#settleMatch({ buy, sell, fillQty, unitPrice, triggeringSide: resting.side, now }); events.push(...tradeEvents); } return events; } #settleMatch ({ buy, sell, fillQty, unitPrice, triggeringSide, now }) { const events = []; const total = unitPrice * fillQty; const itemName = marketOrderDisplayName(sell); const clerk = pickExchangeClerk(); const chequeEscrow = isFilledChequeEscrow(sell.escrowStack); let goods; let sellRemainOrigins = null; if (chequeEscrow) { goods = this.#redeemSellChequeEscrow(sell.escrowStack); if ((goods.quantity | 0) !== fillQty || (goods.itemId | 0) !== (sell.itemId | 0)) { throw userError("That cheque listing could not be settled."); } } else { const sellSplit = splitOrigins(normalizeOrigins(sell.escrowStack), fillQty); goods = attachOrigins({ itemId: sell.itemId, quantity: fillQty, origins: sellSplit.taken, instance: sell.escrowStack?.instance ?? null }); sellRemainOrigins = sellSplit.remain; } const buyRefund = (buy.limitUnitPrice - unitPrice) * fillQty; const buyRemainingQty = buy.quantity - fillQty; const sellRemainingQty = chequeEscrow ? 0 : sell.quantity - fillQty; withTransaction(this.stateDb.db, () => { this.stateDb.insertMarketTrade({ buyOrderId: buy.orderId, sellOrderId: sell.orderId, itemId: sell.itemId, quantity: fillQty, unitPrice, buyerCharacterId: buy.characterId, sellerCharacterId: sell.characterId, createdAt: now }); this.stateDb.updateMarketOrder({ ...buy, quantity: buyRemainingQty, escrowCoins: buy.limitUnitPrice * buyRemainingQty, status: buyRemainingQty > 0 ? "open" : "filled" }); this.stateDb.updateMarketOrder({ ...sell, quantity: sellRemainingQty, escrowStack: sellRemainingQty > 0 ? attachOrigins({ ...sell.escrowStack, quantity: sellRemainingQty, origins: sellRemainOrigins }) : null, status: sellRemainingQty > 0 ? "open" : "filled" }); }); this.#recordLastSale(sell.itemId, unitPrice, now); const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 }; if (triggeringSide === "buy") { this.#grantImmediate(buy.characterId, goods); if (buyRefund > 0) { this.#grantImmediateCoins(buy.characterId, buyRefund); } this.#dispatchBankCargo(sell.characterId, origin, { kind: "money", amount: total }); this.#dispatchBankLetter(sell.characterId, origin, soldLetterBody({ itemName, quantity: fillQty, unitPrice, clerkName: clerk }), clerk); } else { this.#grantImmediateCoins(sell.characterId, total); this.#dispatchBankCargo(buy.characterId, origin, { kind: "item", stack: goods }); if (buyRefund > 0) { this.#dispatchBankCargo(buy.characterId, origin, { kind: "money", amount: buyRefund }); } this.#dispatchBankLetter(buy.characterId, origin, buyFilledLetterBody({ itemName, quantity: fillQty, unitPrice, clerkName: clerk }), clerk); } events.push({ type: "market-trade", itemId: sell.itemId, quantity: fillQty, unitPrice, buyerCharacterId: buy.characterId, sellerCharacterId: sell.characterId, triggeringSide }); return events; } /** Redeem a written-cheque sell escrow into the reserved goods stack. */ #redeemSellChequeEscrow (chequeStack) { const instance = chequeStack?.instance; if (!instance || instance.kind !== "filled-cheque") { throw userError("That cheque listing is invalid."); } const issuerId = instance.issuerCharacterId | 0; const release = this.simulation.releaseChequeReservation?.(issuerId, instance.chequeId, instance); if (!release?.ok || !release.stack) { throw userError(release?.error ?? "That cheque cannot be redeemed."); } return attachOrigins(release.stack); } /** * Charge coins (and whole coin-cheques) for escrow/fees. Mutates bag.inventory. * Releases reservations for redeemed coin cheques. */ #payMarketFunds (bag, payerCharacterId, amount) { const need = Math.max(0, amount | 0); if (!need) { return { ok: true }; } const paid = takeMarketFunds(bag.inventory, need); if (!paid.ok) { return { ok: false }; } bag.inventory = paid.slots; for (const cheque of paid.redeemedCheques ?? []) { const instance = cheque.instance; const issuerId = instance?.issuerCharacterId | 0; const release = this.simulation.releaseChequeReservation?.( issuerId, instance.chequeId, instance ); if (!release?.ok) { // Restore cheque paper; leave other payments as-is (best-effort). const restored = insertStack(bag.inventory, cheque, itemDefinition(ItemId.filledCheque)); bag.inventory = restored.slots; return { ok: false }; } } if ((paid.change | 0) > 0) { const refunded = addCoinsToSlots(bag.inventory, paid.change | 0, { growable: false }); if (!refunded.ok) { const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); const vaultPaid = addCoinsToSlots(vault.slots, paid.change | 0, { growable: true }); bag.inventory = refunded.slots; bag.vault = vaultPaid.slots; bag.vaultReserved = vault.reserved; } else { bag.inventory = refunded.slots; } } void payerCharacterId; return { ok: true }; } #returnEscrowByPigeon (order, { letterBody, clerkName = null, now }) { const origin = this.nearestMarket(0, 0) ?? { tileX: 8, tileY: 8 }; if (order.side === "buy" && (order.escrowCoins | 0) > 0) { this.#dispatchBankCargo(order.characterId, origin, { kind: "money", amount: order.escrowCoins | 0 }); } if (order.side === "sell" && order.escrowStack && (order.escrowStack.quantity | 0) > 0) { this.#dispatchBankCargo(order.characterId, origin, { kind: "item", stack: cloneStack(order.escrowStack) }); } this.#dispatchBankLetter(order.characterId, origin, letterBody, clerkName); void now; } #dispatchBankLetter (characterId, origin, body, clerkName = null) { const name = String(clerkName || pickExchangeClerk()).trim() || pickExchangeClerk(); this.simulation.courier.enqueueSystemLetter({ characterId, originTileX: origin.tileX, originTileY: origin.tileY, originDimensionId: origin.dimensionId, authorDisplayName: name, authorOrganization: CENTRAL_EXCHANGE_ORG, body, centralExchange: true }); } #dispatchBankCargo (characterId, origin, cargo) { this.simulation.courier.dispatchHeldCargo({ senderCharacterId: characterId, originTileX: origin.tileX, originTileY: origin.tileY, originDimensionId: origin.dimensionId, destination: { kind: "bank" }, cargo }); } #grantImmediate (characterId, stack) { const bag = this.#loadBag(characterId); const def = itemDefinition(stack.itemId); const inserted = insertStack(bag.inventory ?? [], stack, def); bag.inventory = inserted.slots; if (inserted.remainder > 0) { const overflow = attachOrigins({ ...stack, quantity: inserted.remainder, origins: splitOrigins(normalizeOrigins(stack), stack.quantity - inserted.remainder).remain }); const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); const vaulted = insertStackGrowable(vault.slots, overflow, def); bag.vault = vaulted.slots; bag.vaultReserved = vault.reserved; } this.#persistBag(characterId, bag); } #grantImmediateCoins (characterId, amount) { const qty = Math.max(0, amount | 0); if (qty <= 0) { return; } const bag = this.#loadBag(characterId); const paid = addCoinsToSlots(bag.inventory ?? [], qty, { growable: false }); if (paid.ok && (paid.remainder | 0) === 0) { bag.inventory = paid.slots; this.#persistBag(characterId, bag); return; } const vault = normalizeVault({ slots: bag.vault, reserved: bag.vaultReserved }); const withInv = paid.ok ? paid.slots : bag.inventory; const remainder = paid.ok ? (paid.remainder | 0) : qty; bag.inventory = withInv; const vaultPaid = addCoinsToSlots(vault.slots, remainder, { growable: true }); bag.vault = vaultPaid.slots; bag.vaultReserved = vault.reserved; this.#persistBag(characterId, bag); } #recordLastSale (itemId, unitPrice, now) { const previous = this.lastSales.get(itemId | 0) ?? null; const priceFrom = undiscountedMarketValue( itemId, previous, now, this.simulation.settings?.shopPriceLerpDurationMs, this.simulation.settings ); const sale = { itemId: itemId | 0, lastTradePrice: unitPrice, lastTradeAt: now, priceFrom }; this.lastSales.set(itemId | 0, sale); this.stateDb.upsertItemLastSale(sale); this.#syncLastSalesToWorkers(); } #loadLastSales () { for (const sale of this.stateDb.listItemLastSales()) { this.lastSales.set(sale.itemId | 0, sale); } } #syncLastSalesToWorkers () { this.simulation.syncItemLastSales?.(this.lastSales); } #requireAtMarket (characterId) { const entityId = this.simulation.characterEntities.get(characterId); const position = entityId ? this.simulation.positionOf(entityId) : null; if (!position) { throw userError("Enter the world before using the Central Exchange."); } if (!this.marketTiles.length) { throw userError("The Central Exchange is not open in this world yet."); } const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); const near = this.marketTiles.some((tile) => normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) === dim && isAdjacentTile(position.tileX, position.tileY, tile.tileX, tile.tileY)); if (!near) { throw userError("Stand next to the Central Exchange counter."); } return { position, entityId }; } #stationTargetsForPlayer (tileX, tileY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); const targets = []; for (const tile of this.marketTiles) { if (normalizeDimensionId(tile.dimensionId ?? OVERWORLD_ID) !== dim) { continue; } if (!isAdjacentTile(tileX, tileY, tile.tileX, tile.tileY)) { continue; } if (tile.tileX === tileX && tile.tileY === tileY) { continue; } const stationTileX = tile.tileX + (tile.tileX - tileX); const stationTileY = tile.tileY + (tile.tileY - tileY); if (stationTileX === tileX && stationTileY === tileY) { continue; } targets.push({ marketTileX: tile.tileX, marketTileY: tile.tileY, stationTileX, stationTileY, dimensionId: dim }); } return targets; } #stationKey (stationTileX, stationTileY, dimensionId = OVERWORLD_ID) { const dim = normalizeDimensionId(dimensionId); return `${dim}:${stationTileX | 0},${stationTileY | 0}`; } #attendStations (sessionId, characterId, tileX, tileY, dimensionId = OVERWORLD_ID) { const id = characterId | 0; const dim = normalizeDimensionId(dimensionId); for (const target of this.#stationTargetsForPlayer(tileX, tileY, dim)) { const key = this.#stationKey(target.stationTileX, target.stationTileY, dim); let entry = this.stationAttendance.get(key); if (!entry) { entry = { stationTileX: target.stationTileX, stationTileY: target.stationTileY, marketTileX: target.marketTileX, marketTileY: target.marketTileY, dimensionId: dim, browsers: new Map() }; this.stationAttendance.set(key, entry); } entry.browsers.set(id, sessionId); entry.marketTileX = target.marketTileX; entry.marketTileY = target.marketTileY; entry.dimensionId = dim; this.simulation.stationExchangeClerk?.( target.stationTileX, target.stationTileY, dim ); } } #characterStillAttending (characterId) { const id = characterId | 0; for (const entry of this.stationAttendance.values()) { if (entry.browsers.has(id)) { return true; } } return false; } #stillAtMarketCounter (characterId, marketTileX, marketTileY, dimensionId = OVERWORLD_ID) { const entityId = this.simulation.characterEntities.get(characterId); const position = entityId ? this.simulation.positionOf(entityId) : null; if (!position) { return false; } const dim = normalizeDimensionId(dimensionId); if (normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID) !== dim) { return false; } return isAdjacentTile(position.tileX, position.tileY, marketTileX, marketTileY); } #releaseStation (key) { const entry = this.stationAttendance.get(key); if (!entry) { return; } this.stationAttendance.delete(key); this.simulation.releaseExchangeClerk?.( entry.stationTileX, entry.stationTileY, normalizeDimensionId(entry.dimensionId ?? OVERWORLD_ID) ); } /** * Drop browsers who walked away from their counter; release clerks when a * staff station has no remaining players. */ #pruneStationAttendance () { const events = []; /** @type {Map} characterId → sessionId */ const departed = new Map(); const emptyStations = []; for (const [key, entry] of this.stationAttendance.entries()) { for (const [characterId, sessionId] of [...entry.browsers.entries()]) { if (this.#stillAtMarketCounter( characterId, entry.marketTileX, entry.marketTileY, entry.dimensionId ?? OVERWORLD_ID )) { continue; } entry.browsers.delete(characterId); departed.set(characterId, sessionId); } if (entry.browsers.size === 0) { emptyStations.push(key); } } for (const key of emptyStations) { this.#releaseStation(key); } for (const [characterId, sessionId] of departed.entries()) { if (this.#characterStillAttending(characterId)) { continue; } events.push({ type: "market-closed", sessionId, characterId }); } return events; } #marketOpenEvent (sessionId, characterId, position, now) { const orders = this.stateDb.listOpenMarketOrdersForCharacter(characterId).map((order) => ({ orderId: order.orderId, side: order.side, itemId: order.itemId, listingKey: listingKeyFromOrder(order), displayName: marketOrderDisplayName(order), quantity: order.quantity, limitUnitPrice: order.limitUnitPrice, createdAt: order.createdAt })); const catalog = buildMarketCatalogEntries({ lastSaleFor: (itemId) => this.lastSaleFor(itemId), undiscountedMarketCoins, now, lerpDurationMs: this.simulation.settings?.shopPriceLerpDurationMs, settings: this.simulation.settings }); return { type: "market-open", sessionId, characterId, displayName: "Central Exchange", orders, catalog, tileX: position.tileX, tileY: position.tileY }; } #loadBag (characterId) { const onlineId = this.simulation.characterEntities.get(characterId); const bag = onlineId ? this.simulation.bagOf(onlineId) : this.stateDb.getBag(characterId); if (!bag) { throw userError("No bag."); } return bag; } #persistBag (characterId, bag) { this.stateDb.saveBag(characterId, bag); const onlineId = this.simulation.characterEntities.get(characterId); if (onlineId) { this.simulation.applyBag(onlineId, bag); this.simulation.pushInventory(characterId, bag); } } }