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