Match CE recipe paper orders and search by specific potion recipe.
Each alchemy recipe gets its own catalog entry and listing key so buy/sell orders only match the same written recipe.
@@ -46,6 +46,7 @@ export function initMarket ({
46
46
let searchHits = [];
47
47
let selectedSellSlot = null;
48
48
let selectedBuyItemId = null;
49
let selectedBuyListingKey = null;
49
50
let activeTab = "orders";
50
51
let sellQtyLocked = false;
51
52
@@ -67,7 +68,7 @@ export function initMarket ({
67
68
const slots = getInventorySlots?.() ?? [];
68
69
const slot = selectedSellSlot == null ? null : slots[selectedSellSlot];
69
70
const listing = slot ? resolveMarketSellListing(slot) : null;
70
updateSellSuggest(listing?.itemId ?? null);
71
updateSellSuggest(listing?.itemId ?? null, listing?.listingKey ?? null);
71
72
}
72
73
if (tab === "buy")
73
74
{ updateBuyFee(); }
@@ -108,6 +109,24 @@ export function initMarket ({
108
109
sellQty?.addEventListener("input", () => updateSellFee());
109
110
sellMin?.addEventListener("input", () => updateSellFee());
110
111
112
function catalogEntryMatches (entry)
113
{
114
return (entry.itemId | 0) === (selectedBuyItemId | 0)
115
&& (entry.listingKey ?? null) === (selectedBuyListingKey ?? null);
116
}
117
118
function selectBuyEntry (entry)
119
{
120
selectedBuyItemId = entry.itemId;
121
selectedBuyListingKey = entry.listingKey ?? null;
122
if (buyItem)
123
{ buyItem.textContent = entry.displayName; }
124
if (buyMax && !(buyMax.valueAsNumber > 0))
125
{ buyMax.value = String(entry.hintPrice); }
126
renderCatalog();
127
updateBuyFee();
128
}
129
111
130
document.getElementById("market-buy-confirm")?.addEventListener("click", () =>
112
131
{
113
132
if (selectedBuyItemId == null)
@@ -115,6 +134,7 @@ export function initMarket ({
115
134
socket.send({
116
135
type: MessageType.placeMarketBuy,
117
136
itemId: selectedBuyItemId,
137
listingKey: selectedBuyListingKey,
118
138
quantity: Math.max(1, buyQty?.valueAsNumber || 1),
119
139
maxUnitPrice: Math.max(1, buyMax?.valueAsNumber || 1)
120
140
});
@@ -157,6 +177,7 @@ export function initMarket ({
157
177
{
158
178
const needle = String(query ?? "").trim().toLowerCase();
159
179
selectedBuyItemId = null;
180
selectedBuyListingKey = null;
160
181
if (buyItem)
161
182
{ buyItem.textContent = needle ? "Select an item" : "Search and select an item"; }
162
183
if (!needle)
@@ -200,20 +221,21 @@ export function initMarket ({
200
221
}
201
222
}
202
223
203
function hintPriceForItem (itemId)
224
function hintPriceForItem (itemId, listingKey = null)
204
225
{
205
const entry = catalog.find((row) => (row.itemId | 0) === (itemId | 0));
226
const entry = catalog.find((row) => (row.itemId | 0) === (itemId | 0)
227
&& (row.listingKey ?? null) === (listingKey ?? null));
206
228
const price = entry?.hintPrice;
207
229
if (price == null || !(Number(price) > 0))
208
230
{ return null; }
209
231
return Math.max(1, Math.ceil(Number(price)));
210
232
}
211
233
212
function updateSellSuggest (itemId = null)
234
function updateSellSuggest (itemId = null, listingKey = null)
213
235
{
214
236
if (!sellSuggest)
215
237
{ return; }
216
const price = itemId == null ? null : hintPriceForItem(itemId);
238
const price = itemId == null ? null : hintPriceForItem(itemId, listingKey);
217
239
if (price == null)
218
240
{
219
241
sellSuggest.hidden = true;
@@ -280,19 +302,10 @@ export function initMarket ({
280
302
const row = document.createElement("button");
281
303
row.type = "button";
282
304
row.className = "market-catalog-row";
283
if (selectedBuyItemId === entry.itemId)
305
if (catalogEntryMatches(entry))
284
306
{ row.classList.add("selected"); }
285
307
row.textContent = `${entry.displayName} (~${entry.hintPrice})`;
286
row.addEventListener("click", () =>
287
{
288
selectedBuyItemId = entry.itemId;
289
if (buyItem)
290
{ buyItem.textContent = entry.displayName; }
291
if (buyMax && !(buyMax.valueAsNumber > 0))
292
{ buyMax.value = String(entry.hintPrice); }
293
renderCatalog();
294
updateBuyFee();
295
});
308
row.addEventListener("click", () => selectBuyEntry(entry));
296
309
catalogEl.append(row);
297
310
}
298
311
}
@@ -319,7 +332,7 @@ export function initMarket ({
319
332
? `Selling cheque for ${listing.quantity}× ${listing.displayName}.`
320
333
: `Selling ${itemDisplayName(slot)}`;
321
334
}
322
updateSellSuggest(listing.itemId);
335
updateSellSuggest(listing.itemId, listing.listingKey ?? null);
323
336
renderSellables();
324
337
updateSellFee();
325
338
}
@@ -396,6 +409,7 @@ export function initMarket ({
396
409
searchHits = [];
397
410
selectedSellSlot = null;
398
411
selectedBuyItemId = null;
412
selectedBuyListingKey = null;
399
413
sellQtyLocked = false;
400
414
updateSellSuggest(null);
401
415
if (sellQty)
@@ -46,6 +46,7 @@ export function initMarket ({46
let searchHits = [];46
let searchHits = [];47
let selectedSellSlot = null;47
let selectedSellSlot = null;48
let selectedBuyItemId = null;48
let selectedBuyItemId = null;49
let selectedBuyListingKey = null;49
let activeTab = "orders";50
let activeTab = "orders";50
let sellQtyLocked = false;51
let sellQtyLocked = false;51
52
@@ -67,7 +68,7 @@ export function initMarket ({67
const slots = getInventorySlots?.() ?? [];68
const slots = getInventorySlots?.() ?? [];68
const slot = selectedSellSlot == null ? null : slots[selectedSellSlot];69
const slot = selectedSellSlot == null ? null : slots[selectedSellSlot];69
const listing = slot ? resolveMarketSellListing(slot) : null;70
const listing = slot ? resolveMarketSellListing(slot) : null;70
updateSellSuggest(listing?.itemId ?? null);71
updateSellSuggest(listing?.itemId ?? null, listing?.listingKey ?? null);71
}72
}72
if (tab === "buy")73
if (tab === "buy")73
{ updateBuyFee(); }74
{ updateBuyFee(); }@@ -108,6 +109,24 @@ export function initMarket ({108
sellQty?.addEventListener("input", () => updateSellFee());109
sellQty?.addEventListener("input", () => updateSellFee());109
sellMin?.addEventListener("input", () => updateSellFee());110
sellMin?.addEventListener("input", () => updateSellFee());110
111
112
function catalogEntryMatches (entry)113
{114
return (entry.itemId | 0) === (selectedBuyItemId | 0)115
&& (entry.listingKey ?? null) === (selectedBuyListingKey ?? null);116
}117
118
function selectBuyEntry (entry)119
{120
selectedBuyItemId = entry.itemId;121
selectedBuyListingKey = entry.listingKey ?? null;122
if (buyItem)123
{ buyItem.textContent = entry.displayName; }124
if (buyMax && !(buyMax.valueAsNumber > 0))125
{ buyMax.value = String(entry.hintPrice); }126
renderCatalog();127
updateBuyFee();128
}129
111
document.getElementById("market-buy-confirm")?.addEventListener("click", () =>130
document.getElementById("market-buy-confirm")?.addEventListener("click", () =>112
{131
{113
if (selectedBuyItemId == null)132
if (selectedBuyItemId == null)@@ -115,6 +134,7 @@ export function initMarket ({115
socket.send({134
socket.send({116
type: MessageType.placeMarketBuy,135
type: MessageType.placeMarketBuy,117
itemId: selectedBuyItemId,136
itemId: selectedBuyItemId,137
listingKey: selectedBuyListingKey,118
quantity: Math.max(1, buyQty?.valueAsNumber || 1),138
quantity: Math.max(1, buyQty?.valueAsNumber || 1),119
maxUnitPrice: Math.max(1, buyMax?.valueAsNumber || 1)139
maxUnitPrice: Math.max(1, buyMax?.valueAsNumber || 1)120
});140
});@@ -157,6 +177,7 @@ export function initMarket ({157
{177
{158
const needle = String(query ?? "").trim().toLowerCase();178
const needle = String(query ?? "").trim().toLowerCase();159
selectedBuyItemId = null;179
selectedBuyItemId = null;180
selectedBuyListingKey = null;160
if (buyItem)181
if (buyItem)161
{ buyItem.textContent = needle ? "Select an item" : "Search and select an item"; }182
{ buyItem.textContent = needle ? "Select an item" : "Search and select an item"; }162
if (!needle)183
if (!needle)@@ -200,20 +221,21 @@ export function initMarket ({200
}221
}201
}222
}202
223
203
function hintPriceForItem (itemId)224
function hintPriceForItem (itemId, listingKey = null)204
{225
{205
const entry = catalog.find((row) => (row.itemId | 0) === (itemId | 0));226
const entry = catalog.find((row) => (row.itemId | 0) === (itemId | 0)227
&& (row.listingKey ?? null) === (listingKey ?? null));206
const price = entry?.hintPrice;228
const price = entry?.hintPrice;207
if (price == null || !(Number(price) > 0))229
if (price == null || !(Number(price) > 0))208
{ return null; }230
{ return null; }209
return Math.max(1, Math.ceil(Number(price)));231
return Math.max(1, Math.ceil(Number(price)));210
}232
}211
233
212
function updateSellSuggest (itemId = null)234
function updateSellSuggest (itemId = null, listingKey = null)213
{235
{214
if (!sellSuggest)236
if (!sellSuggest)215
{ return; }237
{ return; }216
const price = itemId == null ? null : hintPriceForItem(itemId);238
const price = itemId == null ? null : hintPriceForItem(itemId, listingKey);217
if (price == null)239
if (price == null)218
{240
{219
sellSuggest.hidden = true;241
sellSuggest.hidden = true;@@ -280,19 +302,10 @@ export function initMarket ({280
const row = document.createElement("button");302
const row = document.createElement("button");281
row.type = "button";303
row.type = "button";282
row.className = "market-catalog-row";304
row.className = "market-catalog-row";283
if (selectedBuyItemId === entry.itemId)305
if (catalogEntryMatches(entry))284
{ row.classList.add("selected"); }306
{ row.classList.add("selected"); }285
row.textContent = `${entry.displayName} (~${entry.hintPrice})`;307
row.textContent = `${entry.displayName} (~${entry.hintPrice})`;286
row.addEventListener("click", () =>308
row.addEventListener("click", () => selectBuyEntry(entry));287
{288
selectedBuyItemId = entry.itemId;289
if (buyItem)290
{ buyItem.textContent = entry.displayName; }291
if (buyMax && !(buyMax.valueAsNumber > 0))292
{ buyMax.value = String(entry.hintPrice); }293
renderCatalog();294
updateBuyFee();295
});296
catalogEl.append(row);309
catalogEl.append(row);297
}310
}298
}311
}@@ -319,7 +332,7 @@ export function initMarket ({319
? `Selling cheque for ${listing.quantity}× ${listing.displayName}.`332
? `Selling cheque for ${listing.quantity}× ${listing.displayName}.`320
: `Selling ${itemDisplayName(slot)}`;333
: `Selling ${itemDisplayName(slot)}`;321
}334
}322
updateSellSuggest(listing.itemId);335
updateSellSuggest(listing.itemId, listing.listingKey ?? null);323
renderSellables();336
renderSellables();324
updateSellFee();337
updateSellFee();325
}338
}@@ -396,6 +409,7 @@ export function initMarket ({396
searchHits = [];409
searchHits = [];397
selectedSellSlot = null;410
selectedSellSlot = null;398
selectedBuyItemId = null;411
selectedBuyItemId = null;412
selectedBuyListingKey = null;399
sellQtyLocked = false;413
sellQtyLocked = false;400
updateSellSuggest(null);414
updateSellSuggest(null);401
if (sellQty)415
if (sellQty)@@ -767,6 +767,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
767
767
type: "place-market-buy",
768
768
characterId: session.characterId,
769
769
itemId: message.itemId | 0,
770
listingKey: message.listingKey ?? null,
770
771
quantity: message.quantity | 0 || 1,
771
772
maxUnitPrice: message.maxUnitPrice | 0
772
773
});
@@ -767,6 +767,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,767
type: "place-market-buy",767
type: "place-market-buy",768
characterId: session.characterId,768
characterId: session.characterId,769
itemId: message.itemId | 0,769
itemId: message.itemId | 0,770
listingKey: message.listingKey ?? null,770
quantity: message.quantity | 0 || 1,771
quantity: message.quantity | 0 || 1,771
maxUnitPrice: message.maxUnitPrice | 0772
maxUnitPrice: message.maxUnitPrice | 0772
});773
});@@ -1,7 +1,7 @@
1
1
import { randomUUID } from "node:crypto";
2
2
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
3
3
import { BlockType } from "../../../shared/definitions/tiles.js";
4
import { ItemId, itemDefinition, ITEM_DEFINITIONS, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";
4
import { ItemId, itemDefinition, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";
5
5
import {
6
6
addCoinsToSlots,
7
7
insertStack,
@@ -25,6 +25,14 @@ import {
25
25
soldLetterBody
26
26
} from "../../../shared/market/exchange.js";
27
27
import { takeMarketFunds, resolveMarketSellListing, isFilledChequeEscrow } from "../../../shared/market/funds.js";
28
import {
29
buildMarketCatalogEntries,
30
listingKeyFromOrder,
31
listingKeyFromStack,
32
marketOrderDisplayName,
33
marketOrdersCompatible,
34
normalizeBuyListingKey
35
} from "../../../shared/market/listingKey.js";
28
36
import { decodeChunkBlob } from "../world/chunkData.js";
29
37
import { withTransaction } from "../persistence/database.js";
30
38
@@ -161,6 +169,7 @@ export class MarketService
161
169
command.itemId | 0,
162
170
command.quantity | 0 || 1,
163
171
command.maxUnitPrice | 0,
172
command.listingKey ?? null,
164
173
now
165
174
);
166
175
case "cancel-market-order":
@@ -276,6 +285,7 @@ export class MarketService
276
285
characterId,
277
286
side: "sell",
278
287
itemId: listing.itemId,
288
listingKey: listing.listingKey ?? listingKeyFromStack(escrowStack),
279
289
quantity: orderQty,
280
290
limitUnitPrice: minPrice,
281
291
escrowCoins: 0,
@@ -293,7 +303,7 @@ export class MarketService
293
303
};
294
304
}
295
305
296
placeBuyOrder (sessionId, characterId, itemId, quantity, maxUnitPrice, now = Date.now())
306
placeBuyOrder (sessionId, characterId, itemId, quantity, maxUnitPrice, listingKey, now = Date.now())
297
307
{
298
308
const { position } = this.#requireAtMarket(characterId);
299
309
const maxPrice = Math.max(1, maxUnitPrice | 0);
@@ -303,6 +313,9 @@ export class MarketService
303
313
{ throw userError("That item cannot be bought on the marketplace."); }
304
314
if ((itemId | 0) === ItemId.coins)
305
315
{ throw userError("Coins cannot be ordered on the marketplace."); }
316
const normalizedListingKey = normalizeBuyListingKey(itemId, listingKey);
317
if ((itemId | 0) === ItemId.recipePaper && !normalizedListingKey)
318
{ throw userError("Choose which recipe to buy."); }
306
319
const escrow = maxPrice * qty;
307
320
const fee = marketOrderListingFee(maxPrice, qty);
308
321
const bag = this.#loadBag(characterId);
@@ -317,6 +330,7 @@ export class MarketService
317
330
characterId,
318
331
side: "buy",
319
332
itemId: itemId | 0,
333
listingKey: normalizedListingKey,
320
334
quantity: qty,
321
335
limitUnitPrice: maxPrice,
322
336
escrowCoins: escrow,
@@ -346,13 +360,13 @@ export class MarketService
346
360
this.#returnEscrowByPigeon(order, {
347
361
letterBody: orderCancelledLetterBody({
348
362
side: order.side,
349
itemName: itemDefinition(order.itemId)?.displayName ?? "item",
363
itemName: marketOrderDisplayName(order),
350
364
quantity: order.quantity,
351
365
escrowLabel: order.side === "buy"
352
366
? "coins"
353
367
: (isFilledChequeEscrow(order.escrowStack)
354
368
? "written cheque"
355
: (itemDefinition(order.itemId)?.displayName ?? "item")),
369
: marketOrderDisplayName(order)),
356
370
clerkName
357
371
}),
358
372
clerkName,
@@ -377,13 +391,13 @@ export class MarketService
377
391
this.#returnEscrowByPigeon(order, {
378
392
letterBody: orderExpiredLetterBody({
379
393
side: order.side,
380
itemName: itemDefinition(order.itemId)?.displayName ?? "item",
394
itemName: marketOrderDisplayName(order),
381
395
quantity: order.quantity,
382
396
escrowLabel: order.side === "buy"
383
397
? "coins"
384
398
: (isFilledChequeEscrow(order.escrowStack)
385
399
? "written cheque"
386
: (itemDefinition(order.itemId)?.displayName ?? "item")),
400
: marketOrderDisplayName(order)),
387
401
clerkName
388
402
}),
389
403
clerkName,
@@ -411,9 +425,10 @@ export class MarketService
411
425
if (!resting || resting.status !== "open")
412
426
{ return events; }
413
427
428
const restingKey = listingKeyFromOrder(resting);
414
429
const counterparts = resting.side === "sell"
415
? this.stateDb.listOpenBuyOrdersForItem(resting.itemId)
416
: this.stateDb.listOpenSellOrdersForItem(resting.itemId);
430
? this.stateDb.listOpenBuyOrdersForItem(resting.itemId, restingKey)
431
: this.stateDb.listOpenSellOrdersForItem(resting.itemId, restingKey);
417
432
418
433
for (const other of counterparts)
419
434
{
@@ -428,6 +443,8 @@ export class MarketService
428
443
429
444
const buy = resting.side === "buy" ? resting : liveOther;
430
445
const sell = resting.side === "sell" ? resting : liveOther;
446
if (!marketOrdersCompatible(buy, sell))
447
{ continue; }
431
448
if (buy.limitUnitPrice < sell.limitUnitPrice)
432
449
{ continue; }
433
450
@@ -459,7 +476,7 @@ export class MarketService
459
476
{
460
477
const events = [];
461
478
const total = unitPrice * fillQty;
462
const itemName = itemDefinition(sell.itemId)?.displayName ?? "item";
479
const itemName = marketOrderDisplayName(sell);
463
480
const clerk = pickExchangeClerk();
464
481
const chequeEscrow = isFilledChequeEscrow(sell.escrowStack);
465
482
@@ -896,31 +913,19 @@ export class MarketService
896
913
orderId: order.orderId,
897
914
side: order.side,
898
915
itemId: order.itemId,
899
displayName: itemDefinition(order.itemId)?.displayName ?? `Item ${order.itemId}`,
916
listingKey: listingKeyFromOrder(order),
917
displayName: marketOrderDisplayName(order),
900
918
quantity: order.quantity,
901
919
limitUnitPrice: order.limitUnitPrice,
902
920
createdAt: order.createdAt
903
921
}));
904
const catalog = [];
905
for (const def of Object.values(ITEM_DEFINITIONS))
906
{
907
if (!canSellOnMarketplace({ itemId: def.itemId, quantity: 1 }))
908
{ continue; }
909
if (def.itemId === ItemId.coins)
910
{ continue; }
911
catalog.push({
912
itemId: def.itemId,
913
displayName: def.displayName,
914
hintPrice: undiscountedMarketCoins(
915
def.itemId,
916
this.lastSaleFor(def.itemId),
917
now,
918
this.simulation.settings?.shopPriceLerpDurationMs,
919
this.simulation.settings
920
)
921
});
922
}
923
catalog.sort((a, b) => a.displayName.localeCompare(b.displayName));
922
const catalog = buildMarketCatalogEntries({
923
lastSaleFor: (itemId) => this.lastSaleFor(itemId),
924
undiscountedMarketCoins,
925
now,
926
lerpDurationMs: this.simulation.settings?.shopPriceLerpDurationMs,
927
settings: this.simulation.settings
928
});
924
929
return {
925
930
type: "market-open",
926
931
sessionId,
@@ -1,7 +1,7 @@1
import { randomUUID } from "node:crypto";1
import { randomUUID } from "node:crypto";2
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";2
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";3
import { BlockType } from "../../../shared/definitions/tiles.js";3
import { BlockType } from "../../../shared/definitions/tiles.js";4
import { ItemId, itemDefinition, ITEM_DEFINITIONS, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";4
import { ItemId, itemDefinition, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";5
import {5
import {6
addCoinsToSlots,6
addCoinsToSlots,7
insertStack,7
insertStack,@@ -25,6 +25,14 @@ import {25
soldLetterBody25
soldLetterBody26
} from "../../../shared/market/exchange.js";26
} from "../../../shared/market/exchange.js";27
import { takeMarketFunds, resolveMarketSellListing, isFilledChequeEscrow } from "../../../shared/market/funds.js";27
import { takeMarketFunds, resolveMarketSellListing, isFilledChequeEscrow } from "../../../shared/market/funds.js";28
import {29
buildMarketCatalogEntries,30
listingKeyFromOrder,31
listingKeyFromStack,32
marketOrderDisplayName,33
marketOrdersCompatible,34
normalizeBuyListingKey35
} from "../../../shared/market/listingKey.js";28
import { decodeChunkBlob } from "../world/chunkData.js";36
import { decodeChunkBlob } from "../world/chunkData.js";29
import { withTransaction } from "../persistence/database.js";37
import { withTransaction } from "../persistence/database.js";30
38
@@ -161,6 +169,7 @@ export class MarketService161
command.itemId | 0,169
command.itemId | 0,162
command.quantity | 0 || 1,170
command.quantity | 0 || 1,163
command.maxUnitPrice | 0,171
command.maxUnitPrice | 0,172
command.listingKey ?? null,164
now173
now165
);174
);166
case "cancel-market-order":175
case "cancel-market-order":@@ -276,6 +285,7 @@ export class MarketService276
characterId,285
characterId,277
side: "sell",286
side: "sell",278
itemId: listing.itemId,287
itemId: listing.itemId,288
listingKey: listing.listingKey ?? listingKeyFromStack(escrowStack),279
quantity: orderQty,289
quantity: orderQty,280
limitUnitPrice: minPrice,290
limitUnitPrice: minPrice,281
escrowCoins: 0,291
escrowCoins: 0,@@ -293,7 +303,7 @@ export class MarketService293
};303
};294
}304
}295
305
296
placeBuyOrder (sessionId, characterId, itemId, quantity, maxUnitPrice, now = Date.now())306
placeBuyOrder (sessionId, characterId, itemId, quantity, maxUnitPrice, listingKey, now = Date.now())297
{307
{298
const { position } = this.#requireAtMarket(characterId);308
const { position } = this.#requireAtMarket(characterId);299
const maxPrice = Math.max(1, maxUnitPrice | 0);309
const maxPrice = Math.max(1, maxUnitPrice | 0);@@ -303,6 +313,9 @@ export class MarketService303
{ throw userError("That item cannot be bought on the marketplace."); }313
{ throw userError("That item cannot be bought on the marketplace."); }304
if ((itemId | 0) === ItemId.coins)314
if ((itemId | 0) === ItemId.coins)305
{ throw userError("Coins cannot be ordered on the marketplace."); }315
{ throw userError("Coins cannot be ordered on the marketplace."); }316
const normalizedListingKey = normalizeBuyListingKey(itemId, listingKey);317
if ((itemId | 0) === ItemId.recipePaper && !normalizedListingKey)318
{ throw userError("Choose which recipe to buy."); }306
const escrow = maxPrice * qty;319
const escrow = maxPrice * qty;307
const fee = marketOrderListingFee(maxPrice, qty);320
const fee = marketOrderListingFee(maxPrice, qty);308
const bag = this.#loadBag(characterId);321
const bag = this.#loadBag(characterId);@@ -317,6 +330,7 @@ export class MarketService317
characterId,330
characterId,318
side: "buy",331
side: "buy",319
itemId: itemId | 0,332
itemId: itemId | 0,333
listingKey: normalizedListingKey,320
quantity: qty,334
quantity: qty,321
limitUnitPrice: maxPrice,335
limitUnitPrice: maxPrice,322
escrowCoins: escrow,336
escrowCoins: escrow,@@ -346,13 +360,13 @@ export class MarketService346
this.#returnEscrowByPigeon(order, {360
this.#returnEscrowByPigeon(order, {347
letterBody: orderCancelledLetterBody({361
letterBody: orderCancelledLetterBody({348
side: order.side,362
side: order.side,349
itemName: itemDefinition(order.itemId)?.displayName ?? "item",363
itemName: marketOrderDisplayName(order),350
quantity: order.quantity,364
quantity: order.quantity,351
escrowLabel: order.side === "buy"365
escrowLabel: order.side === "buy"352
? "coins"366
? "coins"353
: (isFilledChequeEscrow(order.escrowStack)367
: (isFilledChequeEscrow(order.escrowStack)354
? "written cheque"368
? "written cheque"355
: (itemDefinition(order.itemId)?.displayName ?? "item")),369
: marketOrderDisplayName(order)),356
clerkName370
clerkName357
}),371
}),358
clerkName,372
clerkName,@@ -377,13 +391,13 @@ export class MarketService377
this.#returnEscrowByPigeon(order, {391
this.#returnEscrowByPigeon(order, {378
letterBody: orderExpiredLetterBody({392
letterBody: orderExpiredLetterBody({379
side: order.side,393
side: order.side,380
itemName: itemDefinition(order.itemId)?.displayName ?? "item",394
itemName: marketOrderDisplayName(order),381
quantity: order.quantity,395
quantity: order.quantity,382
escrowLabel: order.side === "buy"396
escrowLabel: order.side === "buy"383
? "coins"397
? "coins"384
: (isFilledChequeEscrow(order.escrowStack)398
: (isFilledChequeEscrow(order.escrowStack)385
? "written cheque"399
? "written cheque"386
: (itemDefinition(order.itemId)?.displayName ?? "item")),400
: marketOrderDisplayName(order)),387
clerkName401
clerkName388
}),402
}),389
clerkName,403
clerkName,@@ -411,9 +425,10 @@ export class MarketService411
if (!resting || resting.status !== "open")425
if (!resting || resting.status !== "open")412
{ return events; }426
{ return events; }413
427
428
const restingKey = listingKeyFromOrder(resting);414
const counterparts = resting.side === "sell"429
const counterparts = resting.side === "sell"415
? this.stateDb.listOpenBuyOrdersForItem(resting.itemId)430
? this.stateDb.listOpenBuyOrdersForItem(resting.itemId, restingKey)416
: this.stateDb.listOpenSellOrdersForItem(resting.itemId);431
: this.stateDb.listOpenSellOrdersForItem(resting.itemId, restingKey);417
432
418
for (const other of counterparts)433
for (const other of counterparts)419
{434
{@@ -428,6 +443,8 @@ export class MarketService428
443
429
const buy = resting.side === "buy" ? resting : liveOther;444
const buy = resting.side === "buy" ? resting : liveOther;430
const sell = resting.side === "sell" ? resting : liveOther;445
const sell = resting.side === "sell" ? resting : liveOther;446
if (!marketOrdersCompatible(buy, sell))447
{ continue; }431
if (buy.limitUnitPrice < sell.limitUnitPrice)448
if (buy.limitUnitPrice < sell.limitUnitPrice)432
{ continue; }449
{ continue; }433
450
@@ -459,7 +476,7 @@ export class MarketService459
{476
{460
const events = [];477
const events = [];461
const total = unitPrice * fillQty;478
const total = unitPrice * fillQty;462
const itemName = itemDefinition(sell.itemId)?.displayName ?? "item";479
const itemName = marketOrderDisplayName(sell);463
const clerk = pickExchangeClerk();480
const clerk = pickExchangeClerk();464
const chequeEscrow = isFilledChequeEscrow(sell.escrowStack);481
const chequeEscrow = isFilledChequeEscrow(sell.escrowStack);465
482
@@ -896,31 +913,19 @@ export class MarketService896
orderId: order.orderId,913
orderId: order.orderId,897
side: order.side,914
side: order.side,898
itemId: order.itemId,915
itemId: order.itemId,899
displayName: itemDefinition(order.itemId)?.displayName ?? `Item ${order.itemId}`,916
listingKey: listingKeyFromOrder(order),917
displayName: marketOrderDisplayName(order),900
quantity: order.quantity,918
quantity: order.quantity,901
limitUnitPrice: order.limitUnitPrice,919
limitUnitPrice: order.limitUnitPrice,902
createdAt: order.createdAt920
createdAt: order.createdAt903
}));921
}));904
const catalog = [];922
const catalog = buildMarketCatalogEntries({905
for (const def of Object.values(ITEM_DEFINITIONS))923
lastSaleFor: (itemId) => this.lastSaleFor(itemId),906
{924
undiscountedMarketCoins,907
if (!canSellOnMarketplace({ itemId: def.itemId, quantity: 1 }))925
now,908
{ continue; }926
lerpDurationMs: this.simulation.settings?.shopPriceLerpDurationMs,909
if (def.itemId === ItemId.coins)927
settings: this.simulation.settings910
{ continue; }928
});911
catalog.push({912
itemId: def.itemId,913
displayName: def.displayName,914
hintPrice: undiscountedMarketCoins(915
def.itemId,916
this.lastSaleFor(def.itemId),917
now,918
this.simulation.settings?.shopPriceLerpDurationMs,919
this.simulation.settings920
)921
});922
}923
catalog.sort((a, b) => a.displayName.localeCompare(b.displayName));924
return {929
return {925
type: "market-open",930
type: "market-open",926
sessionId,931
sessionId,@@ -113,6 +113,7 @@ CREATE TABLE IF NOT EXISTS market_orders (
113
113
limit_unit_price INTEGER NOT NULL,
114
114
escrow_coins INTEGER NOT NULL DEFAULT 0,
115
115
escrow_stack_blob TEXT,
116
listing_key TEXT,
116
117
created_at INTEGER NOT NULL,
117
118
status TEXT NOT NULL
118
119
);
@@ -259,6 +260,9 @@ export class StateDatabase
259
260
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter REAL NOT NULL DEFAULT 0"); }
260
261
if (!characterColumns.some((column) => column.name === "kill_counter_at"))
261
262
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }
263
const marketColumns = this.db.prepare("PRAGMA table_info(market_orders)").all();
264
if (!marketColumns.some((column) => column.name === "listing_key"))
265
{ this.db.exec("ALTER TABLE market_orders ADD COLUMN listing_key TEXT"); }
262
266
this.db.exec(`
263
267
CREATE TABLE IF NOT EXISTS account_friend_requests (
264
268
request_id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -1574,8 +1578,8 @@ export class StateDatabase
1574
1578
const result = this.db.prepare(`
1575
1579
INSERT INTO market_orders (
1576
1580
character_id, side, item_id, quantity, limit_unit_price,
1577
escrow_coins, escrow_stack_blob, created_at, status
1578
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1581
escrow_coins, escrow_stack_blob, listing_key, created_at, status
1582
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1579
1583
`).run(
1580
1584
order.characterId,
1581
1585
order.side,
@@ -1584,6 +1588,7 @@ export class StateDatabase
1584
1588
order.limitUnitPrice | 0,
1585
1589
order.escrowCoins | 0 || 0,
1586
1590
order.escrowStack ? JSON.stringify(order.escrowStack) : null,
1591
order.listingKey ?? null,
1587
1592
order.createdAt ?? Date.now(),
1588
1593
order.status ?? "open"
1589
1594
);
@@ -1621,20 +1626,38 @@ export class StateDatabase
1621
1626
`).all(characterId).map(parseMarketOrder);
1622
1627
}
1623
1628
1624
listOpenBuyOrdersForItem (itemId)
1629
listOpenBuyOrdersForItem (itemId, listingKey = null)
1625
1630
{
1631
if (listingKey)
1632
{
1633
return this.db.prepare(`
1634
SELECT * FROM market_orders
1635
WHERE status = 'open' AND side = 'buy' AND item_id = ? AND listing_key = ?
1636
ORDER BY limit_unit_price DESC, created_at ASC, order_id ASC
1637
`).all(itemId | 0, listingKey).map(parseMarketOrder);
1638
}
1626
1639
return this.db.prepare(`
1627
1640
SELECT * FROM market_orders
1628
1641
WHERE status = 'open' AND side = 'buy' AND item_id = ?
1642
AND (listing_key IS NULL OR listing_key = '')
1629
1643
ORDER BY limit_unit_price DESC, created_at ASC, order_id ASC
1630
1644
`).all(itemId | 0).map(parseMarketOrder);
1631
1645
}
1632
1646
1633
listOpenSellOrdersForItem (itemId)
1647
listOpenSellOrdersForItem (itemId, listingKey = null)
1634
1648
{
1649
if (listingKey)
1650
{
1651
return this.db.prepare(`
1652
SELECT * FROM market_orders
1653
WHERE status = 'open' AND side = 'sell' AND item_id = ? AND listing_key = ?
1654
ORDER BY limit_unit_price ASC, created_at ASC, order_id ASC
1655
`).all(itemId | 0, listingKey).map(parseMarketOrder);
1656
}
1635
1657
return this.db.prepare(`
1636
1658
SELECT * FROM market_orders
1637
1659
WHERE status = 'open' AND side = 'sell' AND item_id = ?
1660
AND (listing_key IS NULL OR listing_key = '')
1638
1661
ORDER BY limit_unit_price ASC, created_at ASC, order_id ASC
1639
1662
`).all(itemId | 0).map(parseMarketOrder);
1640
1663
}
@@ -1736,6 +1759,7 @@ function parseMarketOrder (row)
1736
1759
limitUnitPrice: row.limit_unit_price,
1737
1760
escrowCoins: row.escrow_coins | 0,
1738
1761
escrowStack: row.escrow_stack_blob ? JSON.parse(row.escrow_stack_blob) : null,
1762
listingKey: row.listing_key ?? null,
1739
1763
createdAt: row.created_at,
1740
1764
status: row.status
1741
1765
};
@@ -113,6 +113,7 @@ CREATE TABLE IF NOT EXISTS market_orders (113
limit_unit_price INTEGER NOT NULL,113
limit_unit_price INTEGER NOT NULL,114
escrow_coins INTEGER NOT NULL DEFAULT 0,114
escrow_coins INTEGER NOT NULL DEFAULT 0,115
escrow_stack_blob TEXT,115
escrow_stack_blob TEXT,116
listing_key TEXT,116
created_at INTEGER NOT NULL,117
created_at INTEGER NOT NULL,117
status TEXT NOT NULL118
status TEXT NOT NULL118
);119
);@@ -259,6 +260,9 @@ export class StateDatabase259
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter REAL NOT NULL DEFAULT 0"); }260
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter REAL NOT NULL DEFAULT 0"); }260
if (!characterColumns.some((column) => column.name === "kill_counter_at"))261
if (!characterColumns.some((column) => column.name === "kill_counter_at"))261
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }262
{ this.db.exec("ALTER TABLE characters ADD COLUMN kill_counter_at INTEGER"); }263
const marketColumns = this.db.prepare("PRAGMA table_info(market_orders)").all();264
if (!marketColumns.some((column) => column.name === "listing_key"))265
{ this.db.exec("ALTER TABLE market_orders ADD COLUMN listing_key TEXT"); }262
this.db.exec(`266
this.db.exec(`263
CREATE TABLE IF NOT EXISTS account_friend_requests (267
CREATE TABLE IF NOT EXISTS account_friend_requests (264
request_id INTEGER PRIMARY KEY AUTOINCREMENT,268
request_id INTEGER PRIMARY KEY AUTOINCREMENT,@@ -1574,8 +1578,8 @@ export class StateDatabase1574
const result = this.db.prepare(`1578
const result = this.db.prepare(`1575
INSERT INTO market_orders (1579
INSERT INTO market_orders (1576
character_id, side, item_id, quantity, limit_unit_price,1580
character_id, side, item_id, quantity, limit_unit_price,1577
escrow_coins, escrow_stack_blob, created_at, status1581
escrow_coins, escrow_stack_blob, listing_key, created_at, status1578
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)1582
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)1579
`).run(1583
`).run(1580
order.characterId,1584
order.characterId,1581
order.side,1585
order.side,@@ -1584,6 +1588,7 @@ export class StateDatabase1584
order.limitUnitPrice | 0,1588
order.limitUnitPrice | 0,1585
order.escrowCoins | 0 || 0,1589
order.escrowCoins | 0 || 0,1586
order.escrowStack ? JSON.stringify(order.escrowStack) : null,1590
order.escrowStack ? JSON.stringify(order.escrowStack) : null,1591
order.listingKey ?? null,1587
order.createdAt ?? Date.now(),1592
order.createdAt ?? Date.now(),1588
order.status ?? "open"1593
order.status ?? "open"1589
);1594
);@@ -1621,20 +1626,38 @@ export class StateDatabase1621
`).all(characterId).map(parseMarketOrder);1626
`).all(characterId).map(parseMarketOrder);1622
}1627
}1623
1628
1624
listOpenBuyOrdersForItem (itemId)1629
listOpenBuyOrdersForItem (itemId, listingKey = null)1625
{1630
{1631
if (listingKey)1632
{1633
return this.db.prepare(`1634
SELECT * FROM market_orders1635
WHERE status = 'open' AND side = 'buy' AND item_id = ? AND listing_key = ?1636
ORDER BY limit_unit_price DESC, created_at ASC, order_id ASC1637
`).all(itemId | 0, listingKey).map(parseMarketOrder);1638
}1626
return this.db.prepare(`1639
return this.db.prepare(`1627
SELECT * FROM market_orders1640
SELECT * FROM market_orders1628
WHERE status = 'open' AND side = 'buy' AND item_id = ?1641
WHERE status = 'open' AND side = 'buy' AND item_id = ?1642
AND (listing_key IS NULL OR listing_key = '')1629
ORDER BY limit_unit_price DESC, created_at ASC, order_id ASC1643
ORDER BY limit_unit_price DESC, created_at ASC, order_id ASC1630
`).all(itemId | 0).map(parseMarketOrder);1644
`).all(itemId | 0).map(parseMarketOrder);1631
}1645
}1632
1646
1633
listOpenSellOrdersForItem (itemId)1647
listOpenSellOrdersForItem (itemId, listingKey = null)1634
{1648
{1649
if (listingKey)1650
{1651
return this.db.prepare(`1652
SELECT * FROM market_orders1653
WHERE status = 'open' AND side = 'sell' AND item_id = ? AND listing_key = ?1654
ORDER BY limit_unit_price ASC, created_at ASC, order_id ASC1655
`).all(itemId | 0, listingKey).map(parseMarketOrder);1656
}1635
return this.db.prepare(`1657
return this.db.prepare(`1636
SELECT * FROM market_orders1658
SELECT * FROM market_orders1637
WHERE status = 'open' AND side = 'sell' AND item_id = ?1659
WHERE status = 'open' AND side = 'sell' AND item_id = ?1660
AND (listing_key IS NULL OR listing_key = '')1638
ORDER BY limit_unit_price ASC, created_at ASC, order_id ASC1661
ORDER BY limit_unit_price ASC, created_at ASC, order_id ASC1639
`).all(itemId | 0).map(parseMarketOrder);1662
`).all(itemId | 0).map(parseMarketOrder);1640
}1663
}@@ -1736,6 +1759,7 @@ function parseMarketOrder (row)1736
limitUnitPrice: row.limit_unit_price,1759
limitUnitPrice: row.limit_unit_price,1737
escrowCoins: row.escrow_coins | 0,1760
escrowCoins: row.escrow_coins | 0,1738
escrowStack: row.escrow_stack_blob ? JSON.parse(row.escrow_stack_blob) : null,1761
escrowStack: row.escrow_stack_blob ? JSON.parse(row.escrow_stack_blob) : null,1762
listingKey: row.listing_key ?? null,1739
createdAt: row.created_at,1763
createdAt: row.created_at,1740
status: row.status1764
status: row.status1741
};1765
};@@ -10,6 +10,12 @@ import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody, marketOrde
10
10
import { formatLetterSignature, CENTRAL_EXCHANGE_ORG } from "../../shared/courier/systemLetters.js";
11
11
import { writtenOrigin, originLabel, CraftOriginVerb } from "../../shared/items/origin.js";
12
12
import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js";
13
import {
14
buildMarketCatalogEntries,
15
marketOrdersCompatible,
16
recipeListingKey,
17
recipePaperDisplayName
18
} from "../../shared/market/listingKey.js";
13
19
import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
14
20
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
15
21
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
@@ -225,6 +231,190 @@ function placePlaza (worldDb)
225
231
worldDb.saveChunkVersion(0, 0, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
226
232
}
227
233
234
function recipePaperStack (potionKey, displayName)
235
{
236
return {
237
itemId: ItemId.recipePaper,
238
quantity: 1,
239
instance: {
240
kind: "recipe-paper",
241
recipeId: `test-${potionKey}`,
242
potionKey,
243
displayName: displayName ?? recipePaperDisplayName(potionKey)
244
}
245
};
246
}
247
248
test("market catalog lists each alchemy recipe paper separately", () =>
249
{
250
const catalog = buildMarketCatalogEntries({
251
lastSaleFor: () => null,
252
undiscountedMarketCoins: (itemId) => (itemId === ItemId.recipePaper ? 5 : 10),
253
now: Date.now(),
254
lerpDurationMs: 0,
255
settings: {}
256
});
257
const recipes = catalog.filter((entry) => entry.itemId === ItemId.recipePaper);
258
assert.ok(recipes.length > 1);
259
assert.ok(recipes.some((entry) => entry.listingKey === recipeListingKey("lesserHealthTonic")));
260
assert.ok(recipes.some((entry) => entry.displayName.toLowerCase().includes("lesser health tonic")));
261
assert.equal(recipes.some((entry) => !entry.listingKey), false);
262
});
263
264
test("recipe paper sell listings carry listing keys", () =>
265
{
266
const stack = recipePaperStack("lesserHealthTonic");
267
const listing = resolveMarketSellListing(stack);
268
assert.ok(listing);
269
assert.equal(listing.listingKey, recipeListingKey("lesserHealthTonic"));
270
assert.match(listing.displayName.toLowerCase(), /lesser health tonic recipe/);
271
assert.equal(listing.quantityLocked, true);
272
});
273
274
test("recipe paper buy and sell orders only match the same recipe", () =>
275
{
276
const lesserBuy = {
277
itemId: ItemId.recipePaper,
278
listingKey: recipeListingKey("lesserHealthTonic")
279
};
280
const lesserSell = {
281
itemId: ItemId.recipePaper,
282
listingKey: recipeListingKey("lesserHealthTonic"),
283
escrowStack: recipePaperStack("lesserHealthTonic")
284
};
285
const claritySell = {
286
itemId: ItemId.recipePaper,
287
listingKey: recipeListingKey("clarityPotion"),
288
escrowStack: recipePaperStack("clarityPotion")
289
};
290
assert.equal(marketOrdersCompatible(lesserBuy, lesserSell), true);
291
assert.equal(marketOrdersCompatible(lesserBuy, claritySell), false);
292
});
293
294
test("matching recipe paper buy and sell orders trade the specific recipe", () =>
295
{
296
const harness = makeSimulation({ workerCount: 1 });
297
try
298
{
299
placePlaza(harness.worldDb);
300
harness.simulation.reloadWorld();
301
302
const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Scribe", lastName: "One" });
303
const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buyer", lastName: "Two" });
304
const sellerBag = addCoinsToSlots(emptySlots(), 5);
305
assert.equal(sellerBag.ok, true);
306
sellerBag.slots[1] = recipePaperStack("lesserHealthTonic");
307
harness.stateDb.saveBag(seller.character_id, {
308
inventory: sellerBag.slots,
309
equipment: emptyEquipment(),
310
vault: [],
311
vaultReserved: []
312
});
313
const buyerBag = addCoinsToSlots(emptySlots(), 100);
314
assert.equal(buyerBag.ok, true);
315
harness.stateDb.saveBag(buyer.character_id, {
316
inventory: buyerBag.slots,
317
equipment: emptyEquipment(),
318
vault: [],
319
vaultReserved: []
320
});
321
322
harness.simulation.spawnCharacter(1, seller);
323
harness.simulation.spawnCharacter(2, buyer);
324
harness.simulation.step();
325
326
harness.simulation.enqueue(1, {
327
type: "place-market-sell",
328
characterId: seller.character_id,
329
slotIndex: 1,
330
quantity: 1,
331
minUnitPrice: 8
332
});
333
const sellResult = harness.simulation.step();
334
assert.equal(sellResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(sellResult.events));
335
336
harness.simulation.enqueue(2, {
337
type: "place-market-buy",
338
characterId: buyer.character_id,
339
itemId: ItemId.recipePaper,
340
listingKey: recipeListingKey("lesserHealthTonic"),
341
quantity: 1,
342
maxUnitPrice: 12
343
});
344
const buyResult = harness.simulation.step();
345
assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));
346
const trade = buyResult.events.find((event) => event.type === "market-trade");
347
assert.ok(trade, JSON.stringify(buyResult.events));
348
assert.equal(trade.quantity, 1);
349
350
const buyerBagNow = harness.simulation.bagOf(2);
351
const recipe = (buyerBagNow.inventory ?? []).find((slot) => slot?.itemId === ItemId.recipePaper);
352
assert.ok(recipe);
353
assert.equal(recipe.instance?.potionKey, "lesserHealthTonic");
354
}
355
finally
356
{ harness.close(); }
357
});
358
359
test("recipe paper buy orders for a different recipe do not match", () =>
360
{
361
const harness = makeSimulation({ workerCount: 1 });
362
try
363
{
364
placePlaza(harness.worldDb);
365
harness.simulation.reloadWorld();
366
367
const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
368
const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
369
const sellerBag = addCoinsToSlots(emptySlots(), 5);
370
assert.equal(sellerBag.ok, true);
371
sellerBag.slots[1] = recipePaperStack("lesserHealthTonic");
372
harness.stateDb.saveBag(seller.character_id, {
373
inventory: sellerBag.slots,
374
equipment: emptyEquipment(),
375
vault: [],
376
vaultReserved: []
377
});
378
const buyerBag = addCoinsToSlots(emptySlots(), 100);
379
assert.equal(buyerBag.ok, true);
380
harness.stateDb.saveBag(buyer.character_id, {
381
inventory: buyerBag.slots,
382
equipment: emptyEquipment(),
383
vault: [],
384
vaultReserved: []
385
});
386
387
harness.simulation.spawnCharacter(1, seller);
388
harness.simulation.spawnCharacter(2, buyer);
389
harness.simulation.step();
390
391
harness.simulation.enqueue(1, {
392
type: "place-market-sell",
393
characterId: seller.character_id,
394
slotIndex: 1,
395
quantity: 1,
396
minUnitPrice: 8
397
});
398
harness.simulation.step();
399
400
harness.simulation.enqueue(2, {
401
type: "place-market-buy",
402
characterId: buyer.character_id,
403
itemId: ItemId.recipePaper,
404
listingKey: recipeListingKey("clarityPotion"),
405
quantity: 1,
406
maxUnitPrice: 12
407
});
408
const buyResult = harness.simulation.step();
409
assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));
410
assert.equal(buyResult.events.some((event) => event.type === "market-trade"), false);
411
assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(seller.character_id).length, 1);
412
assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(buyer.character_id).length, 1);
413
}
414
finally
415
{ harness.close(); }
416
});
417
228
418
test("sell then buy at Central Exchange matches at midpoint and pays seller by pigeon letter", () =>
229
419
{
230
420
const harness = makeSimulation({ workerCount: 1 });
@@ -10,6 +10,12 @@ import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody, marketOrde10
import { formatLetterSignature, CENTRAL_EXCHANGE_ORG } from "../../shared/courier/systemLetters.js";10
import { formatLetterSignature, CENTRAL_EXCHANGE_ORG } from "../../shared/courier/systemLetters.js";11
import { writtenOrigin, originLabel, CraftOriginVerb } from "../../shared/items/origin.js";11
import { writtenOrigin, originLabel, CraftOriginVerb } from "../../shared/items/origin.js";12
import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js";12
import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js";13
import {14
buildMarketCatalogEntries,15
marketOrdersCompatible,16
recipeListingKey,17
recipePaperDisplayName18
} from "../../shared/market/listingKey.js";13
import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";19
import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";14
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";20
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";15
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";21
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";@@ -225,6 +231,190 @@ function placePlaza (worldDb)225
worldDb.saveChunkVersion(0, 0, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));231
worldDb.saveChunkVersion(0, 0, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));226
}232
}227
233
234
function recipePaperStack (potionKey, displayName)235
{236
return {237
itemId: ItemId.recipePaper,238
quantity: 1,239
instance: {240
kind: "recipe-paper",241
recipeId: `test-${potionKey}`,242
potionKey,243
displayName: displayName ?? recipePaperDisplayName(potionKey)244
}245
};246
}247
248
test("market catalog lists each alchemy recipe paper separately", () =>249
{250
const catalog = buildMarketCatalogEntries({251
lastSaleFor: () => null,252
undiscountedMarketCoins: (itemId) => (itemId === ItemId.recipePaper ? 5 : 10),253
now: Date.now(),254
lerpDurationMs: 0,255
settings: {}256
});257
const recipes = catalog.filter((entry) => entry.itemId === ItemId.recipePaper);258
assert.ok(recipes.length > 1);259
assert.ok(recipes.some((entry) => entry.listingKey === recipeListingKey("lesserHealthTonic")));260
assert.ok(recipes.some((entry) => entry.displayName.toLowerCase().includes("lesser health tonic")));261
assert.equal(recipes.some((entry) => !entry.listingKey), false);262
});263
264
test("recipe paper sell listings carry listing keys", () =>265
{266
const stack = recipePaperStack("lesserHealthTonic");267
const listing = resolveMarketSellListing(stack);268
assert.ok(listing);269
assert.equal(listing.listingKey, recipeListingKey("lesserHealthTonic"));270
assert.match(listing.displayName.toLowerCase(), /lesser health tonic recipe/);271
assert.equal(listing.quantityLocked, true);272
});273
274
test("recipe paper buy and sell orders only match the same recipe", () =>275
{276
const lesserBuy = {277
itemId: ItemId.recipePaper,278
listingKey: recipeListingKey("lesserHealthTonic")279
};280
const lesserSell = {281
itemId: ItemId.recipePaper,282
listingKey: recipeListingKey("lesserHealthTonic"),283
escrowStack: recipePaperStack("lesserHealthTonic")284
};285
const claritySell = {286
itemId: ItemId.recipePaper,287
listingKey: recipeListingKey("clarityPotion"),288
escrowStack: recipePaperStack("clarityPotion")289
};290
assert.equal(marketOrdersCompatible(lesserBuy, lesserSell), true);291
assert.equal(marketOrdersCompatible(lesserBuy, claritySell), false);292
});293
294
test("matching recipe paper buy and sell orders trade the specific recipe", () =>295
{296
const harness = makeSimulation({ workerCount: 1 });297
try298
{299
placePlaza(harness.worldDb);300
harness.simulation.reloadWorld();301
302
const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Scribe", lastName: "One" });303
const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buyer", lastName: "Two" });304
const sellerBag = addCoinsToSlots(emptySlots(), 5);305
assert.equal(sellerBag.ok, true);306
sellerBag.slots[1] = recipePaperStack("lesserHealthTonic");307
harness.stateDb.saveBag(seller.character_id, {308
inventory: sellerBag.slots,309
equipment: emptyEquipment(),310
vault: [],311
vaultReserved: []312
});313
const buyerBag = addCoinsToSlots(emptySlots(), 100);314
assert.equal(buyerBag.ok, true);315
harness.stateDb.saveBag(buyer.character_id, {316
inventory: buyerBag.slots,317
equipment: emptyEquipment(),318
vault: [],319
vaultReserved: []320
});321
322
harness.simulation.spawnCharacter(1, seller);323
harness.simulation.spawnCharacter(2, buyer);324
harness.simulation.step();325
326
harness.simulation.enqueue(1, {327
type: "place-market-sell",328
characterId: seller.character_id,329
slotIndex: 1,330
quantity: 1,331
minUnitPrice: 8332
});333
const sellResult = harness.simulation.step();334
assert.equal(sellResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(sellResult.events));335
336
harness.simulation.enqueue(2, {337
type: "place-market-buy",338
characterId: buyer.character_id,339
itemId: ItemId.recipePaper,340
listingKey: recipeListingKey("lesserHealthTonic"),341
quantity: 1,342
maxUnitPrice: 12343
});344
const buyResult = harness.simulation.step();345
assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));346
const trade = buyResult.events.find((event) => event.type === "market-trade");347
assert.ok(trade, JSON.stringify(buyResult.events));348
assert.equal(trade.quantity, 1);349
350
const buyerBagNow = harness.simulation.bagOf(2);351
const recipe = (buyerBagNow.inventory ?? []).find((slot) => slot?.itemId === ItemId.recipePaper);352
assert.ok(recipe);353
assert.equal(recipe.instance?.potionKey, "lesserHealthTonic");354
}355
finally356
{ harness.close(); }357
});358
359
test("recipe paper buy orders for a different recipe do not match", () =>360
{361
const harness = makeSimulation({ workerCount: 1 });362
try363
{364
placePlaza(harness.worldDb);365
harness.simulation.reloadWorld();366
367
const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });368
const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });369
const sellerBag = addCoinsToSlots(emptySlots(), 5);370
assert.equal(sellerBag.ok, true);371
sellerBag.slots[1] = recipePaperStack("lesserHealthTonic");372
harness.stateDb.saveBag(seller.character_id, {373
inventory: sellerBag.slots,374
equipment: emptyEquipment(),375
vault: [],376
vaultReserved: []377
});378
const buyerBag = addCoinsToSlots(emptySlots(), 100);379
assert.equal(buyerBag.ok, true);380
harness.stateDb.saveBag(buyer.character_id, {381
inventory: buyerBag.slots,382
equipment: emptyEquipment(),383
vault: [],384
vaultReserved: []385
});386
387
harness.simulation.spawnCharacter(1, seller);388
harness.simulation.spawnCharacter(2, buyer);389
harness.simulation.step();390
391
harness.simulation.enqueue(1, {392
type: "place-market-sell",393
characterId: seller.character_id,394
slotIndex: 1,395
quantity: 1,396
minUnitPrice: 8397
});398
harness.simulation.step();399
400
harness.simulation.enqueue(2, {401
type: "place-market-buy",402
characterId: buyer.character_id,403
itemId: ItemId.recipePaper,404
listingKey: recipeListingKey("clarityPotion"),405
quantity: 1,406
maxUnitPrice: 12407
});408
const buyResult = harness.simulation.step();409
assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));410
assert.equal(buyResult.events.some((event) => event.type === "market-trade"), false);411
assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(seller.character_id).length, 1);412
assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(buyer.character_id).length, 1);413
}414
finally415
{ harness.close(); }416
});417
228
test("sell then buy at Central Exchange matches at midpoint and pays seller by pigeon letter", () =>418
test("sell then buy at Central Exchange matches at midpoint and pays seller by pigeon letter", () =>229
{419
{230
const harness = makeSimulation({ workerCount: 1 });420
const harness = makeSimulation({ workerCount: 1 });