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