BlueGit

timfa questward

Files

questward / server / tests / marketplace.test.js

marketplace.test.js

marketplace.test.js 19.9 KiB Download Raw
1import test from "node:test";
2import assert from "node:assert/strict";
3import { ItemId } from "../../shared/definitions/items.js";
4import { CraftingItemId, tinderboxItemInstance } from "../../shared/definitions/craftingItems.js";
5import { dyeItemInstance } from "../../shared/definitions/dyes.js";
6import { potionItemInstance } from "../../shared/alchemy/recipes.js";
7import { BlockType } from "../../shared/definitions/tiles.js";
8import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
9import { midpointTradePrice, MARKET_ORDER_MAX_AGE_MS, soldLetterBody, marketOrderListingFee, orderCancelledLetterBody, orderExpiredLetterBody } from "../../shared/market/exchange.js";
10import { formatLetterSignature, CENTRAL_EXCHANGE_ORG } from "../../shared/courier/systemLetters.js";
11import { writtenOrigin, originLabel, CraftOriginVerb } from "../../shared/items/origin.js";
12import { takeMarketFunds, resolveMarketSellListing } from "../../shared/market/funds.js";
13import {
14 buildMarketCatalogEntries,
15 marketOrdersCompatible,
16 recipeListingKey,
17 recipePaperDisplayName
18} from "../../shared/market/listingKey.js";
19import { emptyEquipment, emptySlots, addCoinsToSlots, countCoinsInSlots } from "../../shared/items/inventory.js";
20import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
21import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
22import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
23
24test("blank cheques cannot be listed on the marketplace", () =>
25{
26 const stack = { itemId: ItemId.blankCheque, quantity: 1 };
27 assert.equal(canSellOnMarketplace(stack), false);
28 assert.throws(
29 () => assertMarketplaceSellable(stack),
30 (err) => err.message === "Blank cheques cannot be sold on the marketplace."
31 );
32});
33
34test("written cheques can be listed on the marketplace", () =>
35{
36 const stack = {
37 itemId: ItemId.filledCheque,
38 quantity: 1,
39 instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 2 }
40 };
41 assert.equal(canSellOnMarketplace(stack), true);
42 assert.doesNotThrow(() => assertMarketplaceSellable(stack));
43});
44
45test("normal items are marketplace sellable by default", () =>
46{
47 assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);
48});
49
50test("fully charged tinderbox can list on CE; worn cannot", () =>
51{
52 const fresh = {
53 itemId: CraftingItemId.tinderbox,
54 quantity: 1,
55 instance: tinderboxItemInstance(6)
56 };
57 const worn = {
58 itemId: CraftingItemId.tinderbox,
59 quantity: 1,
60 instance: tinderboxItemInstance(1)
61 };
62 assert.equal(canSellOnMarketplace(fresh), true);
63 assert.equal(canSellOnMarketplace(worn), false);
64 assert.throws(
65 () => assertMarketplaceSellable(worn),
66 (err) => /partially used/i.test(err.message)
67 );
68});
69
70test("full potions and dyes can list on CE; sipped or used cannot", () =>
71{
72 const fullPotion = {
73 itemId: ItemId.potion,
74 quantity: 1,
75 instance: potionItemInstance({
76 potionKey: "lesserHealthTonic",
77 displayName: "Lesser health tonic",
78 color: { r: 0.95, g: 0.38, b: 0.32 },
79 fillLevel: 4,
80 effect: { type: "health-regen", amountPerSecond: 1, durationMs: 10_000 },
81 effectKey: "health-regen"
82 })
83 };
84 const sipped = {
85 ...fullPotion,
86 instance: { ...fullPotion.instance, fillLevel: 3 }
87 };
88 const fullDye = {
89 itemId: ItemId.dye,
90 quantity: 1,
91 instance: dyeItemInstance({ r: 0.8, g: 0.1, b: 0.1 }, 4)
92 };
93 const usedDye = {
94 itemId: ItemId.dye,
95 quantity: 1,
96 instance: dyeItemInstance({ r: 0.8, g: 0.1, b: 0.1 }, 2)
97 };
98 const unstableFull = {
99 itemId: ItemId.potion,
100 quantity: 1,
101 instance: potionItemInstance({
102 potionKey: "unstable:glow",
103 unstable: true,
104 displayName: "Unstable draught",
105 color: { r: 0.95, g: 0.9, b: 0.45 },
106 fillLevel: 3,
107 effectKey: "glow",
108 effect: { type: "glow", lightRadiusTiles: 2, durationMs: 10_000 }
109 })
110 };
111 const unstableSipped = {
112 ...unstableFull,
113 instance: { ...unstableFull.instance, fillLevel: 2 }
114 };
115 assert.equal(canSellOnMarketplace(fullPotion), true);
116 assert.equal(canSellOnMarketplace(sipped), false);
117 assert.equal(canSellOnMarketplace(fullDye), true);
118 assert.equal(canSellOnMarketplace(usedDye), false);
119 assert.equal(canSellOnMarketplace(unstableFull), true);
120 assert.equal(canSellOnMarketplace(unstableSipped), false);
121});
122
123test("letters cannot be listed on the marketplace", () =>
124{
125 const own = {
126 itemId: ItemId.letter,
127 quantity: 1,
128 instance: {
129 kind: "letter",
130 letterId: "x",
131 authorCharacterId: 1,
132 authorDisplayName: "Ada",
133 body: "Hi",
134 opened: true
135 }
136 };
137 const received = {
138 ...own,
139 instance: { ...own.instance, authorCharacterId: 2, authorDisplayName: "Bob" }
140 };
141 assert.equal(canSellOnMarketplace(own, 1), false);
142 assert.equal(canSellOnMarketplace(received, 1), false);
143 assert.throws(
144 () => assertMarketplaceSellable(own, 1),
145 (err) => /letters cannot be sold on the marketplace/i.test(err.message)
146 );
147});
148
149test("midpoint trade price rounds half units deterministically", () =>
150{
151 assert.equal(midpointTradePrice(100, 80), 90);
152 assert.equal(midpointTradePrice(101, 80), 91);
153 assert.equal(midpointTradePrice(80, 100), 90);
154});
155
156test("listing fee is 3% of notional rounded up", () =>
157{
158 assert.equal(marketOrderListingFee(100, 1), 3);
159 assert.equal(marketOrderListingFee(10, 1), 1);
160 assert.equal(marketOrderListingFee(8, 2), 1);
161 assert.equal(marketOrderListingFee(0, 5), 0);
162});
163
164test("cancel and expiry letters use side-specific escrow copy", () =>
165{
166 const buyCancel = orderCancelledLetterBody({
167 side: "buy",
168 itemName: "Flower",
169 quantity: 1,
170 escrowLabel: "coins",
171 clerkName: "Ada Ledger"
172 });
173 assert.match(buyCancel, /buy order for 1× Flower was cancelled/);
174 assert.match(buyCancel, /coins have been returned/);
175 assert.doesNotMatch(buyCancel, /coins has been returned/);
176
177 const sellCancel = orderCancelledLetterBody({
178 side: "sell",
179 itemName: "Apple",
180 quantity: 2,
181 escrowLabel: "Apple",
182 clerkName: "Ada Ledger"
183 });
184 assert.match(sellCancel, /sell order for 2× Apple was cancelled/);
185 assert.match(sellCancel, /listed goods have been returned/);
186
187 const buyExpired = orderExpiredLetterBody({
188 side: "buy",
189 itemName: "Flower",
190 quantity: 1,
191 escrowLabel: "coins",
192 clerkName: "Ada Ledger"
193 });
194 assert.match(buyExpired, /coins have been returned/);
195});
196
197test("market funds spend whole coin cheques and return change", () =>
198{
199 const slots = emptySlots();
200 slots[0] = {
201 itemId: ItemId.filledCheque,
202 quantity: 1,
203 instance: { kind: "filled-cheque", chequeId: "c1", issuerCharacterId: 1, itemId: ItemId.coins, quantity: 40 }
204 };
205 const paid = takeMarketFunds(slots, 25);
206 assert.equal(paid.ok, true);
207 assert.equal(paid.change, 15);
208 assert.equal(paid.redeemedCheques.length, 1);
209 assert.equal(paid.slots.every((slot) => !slot || slot.itemId !== ItemId.filledCheque), true);
210});
211
212test("written cheque sell listing locks quantity to reserved goods", () =>
213{
214 const listing = resolveMarketSellListing({
215 itemId: ItemId.filledCheque,
216 quantity: 1,
217 instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 7 }
218 });
219 assert.equal(listing.isCheque, true);
220 assert.equal(listing.itemId, ItemId.apple);
221 assert.equal(listing.quantity, 7);
222 assert.equal(listing.quantityLocked, true);
223});
224
225function placePlaza (worldDb)
226{
227 const data = createEmptyChunkData();
228 data.open = true;
229 data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: null };
230 data.blocks[8 * CHUNK_SIZE + 10] = { typeId: BlockType.bank, state: null };
231 worldDb.saveChunkVersion(0, 0, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
232}
233
234function 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
248test("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
264test("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
274test("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
294test("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
359test("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
418test("sell then buy at Central Exchange matches at midpoint and pays seller by pigeon letter", () =>
419{
420 const harness = makeSimulation({ workerCount: 1 });
421 try
422 {
423 placePlaza(harness.worldDb);
424 harness.simulation.reloadWorld();
425
426 const seller = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8, firstName: "Sel", lastName: "Ler" });
427 const buyer = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9, firstName: "Buy", lastName: "Er" });
428 const sellerBag = addCoinsToSlots(emptySlots(), 5);
429 assert.equal(sellerBag.ok, true);
430 sellerBag.slots[1] = { itemId: ItemId.apple, quantity: 2 };
431 harness.stateDb.saveBag(seller.character_id, {
432 inventory: sellerBag.slots,
433 equipment: emptyEquipment(),
434 vault: [],
435 vaultReserved: []
436 });
437 const buyerBag = addCoinsToSlots(emptySlots(), 100);
438 assert.equal(buyerBag.ok, true);
439 harness.stateDb.saveBag(buyer.character_id, {
440 inventory: buyerBag.slots,
441 equipment: emptyEquipment(),
442 vault: [],
443 vaultReserved: []
444 });
445
446 const sellerId = harness.simulation.spawnCharacter(1, seller);
447 const buyerId = harness.simulation.spawnCharacter(2, buyer);
448 harness.simulation.step();
449
450 harness.simulation.enqueue(1, {
451 type: "place-market-sell",
452 characterId: seller.character_id,
453 slotIndex: 1,
454 quantity: 2,
455 minUnitPrice: 8
456 });
457 const sellResult = harness.simulation.step();
458 assert.equal(sellResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(sellResult.events));
459 assert.ok(sellResult.events.some((event) => event.type === "market-open"));
460
461 harness.simulation.enqueue(2, {
462 type: "place-market-buy",
463 characterId: buyer.character_id,
464 itemId: ItemId.apple,
465 quantity: 2,
466 maxUnitPrice: 12
467 });
468 const buyResult = harness.simulation.step();
469 assert.equal(buyResult.events.some((event) => event.type === "command-error"), false, JSON.stringify(buyResult.events));
470 const trade = buyResult.events.find((event) => event.type === "market-trade");
471 assert.ok(trade, JSON.stringify(buyResult.events));
472 assert.equal(trade.unitPrice, 10);
473 assert.equal(trade.quantity, 2);
474
475 const buyerBagNow = harness.simulation.bagOf(buyerId);
476 assert.equal((buyerBagNow.inventory ?? []).some((slot) => slot?.itemId === ItemId.apple), true);
477
478 // Coins go to bank; letter goes to the online seller's inventory.
479 for (let i = 0; i < 500; i++)
480 {
481 harness.advance(1000);
482 harness.simulation.step();
483 const sellerVault = harness.stateDb.getBag(seller.character_id);
484 const sellerBag = harness.simulation.bagOf(sellerId);
485 const coins = countCoinsInSlots(sellerVault.vault ?? []);
486 const letter = (sellerBag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter)
487 ?? (sellerVault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
488 if (coins >= 20 && letter)
489 {
490 assert.match(letter.instance.body, /sold|filled|proceeds/i);
491 assert.doesNotMatch(letter.instance.body, /Signed,/);
492 assert.equal(letter.instance.authorOrganization, "Central Exchange");
493 assert.ok(letter.instance.authorDisplayName);
494 assert.equal(letter.origins?.[0]?.origin?.verb, "Written");
495 assert.equal(letter.origins?.[0]?.origin?.displayName, letter.instance.authorDisplayName);
496 assert.equal(harness.simulation.market.lastSaleFor(ItemId.apple)?.lastTradePrice, 10);
497 return;
498 }
499 }
500 assert.fail("Seller did not receive coins in vault and letter");
501 }
502 finally
503 { harness.close(); }
504});
505
506test("orders older than one month auto-cancel and return escrow to bank", () =>
507{
508 const harness = makeSimulation({ workerCount: 1 });
509 try
510 {
511 placePlaza(harness.worldDb);
512 harness.simulation.reloadWorld();
513
514 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
515 const bag = addCoinsToSlots(emptySlots(), 50);
516 assert.equal(bag.ok, true);
517 harness.stateDb.saveBag(character.character_id, {
518 inventory: bag.slots,
519 equipment: emptyEquipment(),
520 vault: [],
521 vaultReserved: []
522 });
523 harness.simulation.spawnCharacter(1, character);
524 harness.simulation.step();
525
526 harness.simulation.enqueue(1, {
527 type: "place-market-buy",
528 characterId: character.character_id,
529 itemId: ItemId.apple,
530 quantity: 1,
531 maxUnitPrice: 10
532 });
533 const placed = harness.simulation.step();
534 assert.equal(placed.events.some((event) => event.type === "command-error"), false, JSON.stringify(placed.events));
535 const open = harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id);
536 assert.equal(open.length, 1);
537
538 const order = open[0];
539 harness.stateDb.db.prepare("UPDATE market_orders SET created_at = ? WHERE order_id = ?")
540 .run(Date.now() - MARKET_ORDER_MAX_AGE_MS - 1000, order.orderId);
541
542 const expired = harness.simulation.market.step(Date.now());
543 assert.ok(expired.some((event) => event.type === "market-order-expired"));
544 assert.equal(harness.stateDb.listOpenMarketOrdersForCharacter(character.character_id).length, 0);
545
546 for (let i = 0; i < 500; i++)
547 {
548 harness.advance(1000);
549 harness.simulation.step();
550 const vault = harness.stateDb.getBag(character.character_id);
551 const bag = harness.simulation.bagOf(1);
552 const coins = countCoinsInSlots(vault.vault ?? []);
553 const letter = (bag?.inventory ?? []).find((slot) => slot?.itemId === ItemId.letter)
554 ?? (vault.vault ?? []).find((slot) => slot?.itemId === ItemId.letter);
555 if (coins >= 10 && letter)
556 {
557 assert.match(letter.instance.body, /one month/i);
558 assert.doesNotMatch(letter.instance.body, /Signed,/);
559 assert.equal(letter.instance.authorOrganization, "Central Exchange");
560 return;
561 }
562 }
563 assert.fail("Expired order did not return escrow letter");
564 }
565 finally
566 { harness.close(); }
567});
568
569test("exchange letter instance carries Central Exchange signature fields", () =>
570{
571 const body = soldLetterBody({
572 itemName: "Apple",
573 quantity: 1,
574 unitPrice: 5,
575 clerkName: "Bobby Pennies"
576 });
577 assert.doesNotMatch(body, /Signed,/);
578 assert.doesNotMatch(body, /Bobby Pennies/);
579 assert.doesNotMatch(body, /Central Exchange/);
580 assert.match(body, /filled at 5 coins/);
581 assert.equal(
582 formatLetterSignature({
583 authorDisplayName: "Bobby Pennies",
584 authorOrganization: CENTRAL_EXCHANGE_ORG
585 }),
586 "Signed:\nBobby Pennies\nCentral Exchange"
587 );
588 assert.equal(
589 formatLetterSignature({ authorDisplayName: "The Bank" }),
590 "Signed:\nThe Bank"
591 );
592});
593
594test("written origin labels match letter author", () =>
595{
596 assert.equal(originLabel(writtenOrigin("Marge Tally")), "Written by Marge Tally");
597 assert.equal(CraftOriginVerb.written, "Written");
598});